Installing a breakpoint on top of a dprintf makes GDB lose control.
[external/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 "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include <string.h>
40 #include "gdb-demangle.h"
41 #include "filenames.h"
42 #include "annotate.h"
43 #include "symfile.h"
44 #include "objfiles.h"
45 #include "source.h"
46 #include "linespec.h"
47 #include "completer.h"
48 #include "gdb.h"
49 #include "ui-out.h"
50 #include "cli/cli-script.h"
51 #include "gdb_assert.h"
52 #include "block.h"
53 #include "solib.h"
54 #include "solist.h"
55 #include "observer.h"
56 #include "exceptions.h"
57 #include "memattr.h"
58 #include "ada-lang.h"
59 #include "top.h"
60 #include "valprint.h"
61 #include "jit.h"
62 #include "xml-syscall.h"
63 #include "parser-defs.h"
64 #include "gdb_regex.h"
65 #include "probe.h"
66 #include "cli/cli-utils.h"
67 #include "continuations.h"
68 #include "stack.h"
69 #include "skip.h"
70 #include "ax-gdb.h"
71 #include "dummy-frame.h"
72
73 #include "format.h"
74
75 /* readline include files */
76 #include "readline/readline.h"
77 #include "readline/history.h"
78
79 /* readline defines this.  */
80 #undef savestring
81
82 #include "mi/mi-common.h"
83 #include "extension.h"
84
85 /* Enums for exception-handling support.  */
86 enum exception_event_kind
87 {
88   EX_EVENT_THROW,
89   EX_EVENT_RETHROW,
90   EX_EVENT_CATCH
91 };
92
93 /* Prototypes for local functions.  */
94
95 static void enable_delete_command (char *, int);
96
97 static void enable_once_command (char *, int);
98
99 static void enable_count_command (char *, int);
100
101 static void disable_command (char *, int);
102
103 static void enable_command (char *, int);
104
105 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
106                                                       void *),
107                                     void *);
108
109 static void ignore_command (char *, int);
110
111 static int breakpoint_re_set_one (void *);
112
113 static void breakpoint_re_set_default (struct breakpoint *);
114
115 static void create_sals_from_address_default (char **,
116                                               struct linespec_result *,
117                                               enum bptype, char *,
118                                               char **);
119
120 static void create_breakpoints_sal_default (struct gdbarch *,
121                                             struct linespec_result *,
122                                             char *, char *, enum bptype,
123                                             enum bpdisp, int, int,
124                                             int,
125                                             const struct breakpoint_ops *,
126                                             int, int, int, unsigned);
127
128 static void decode_linespec_default (struct breakpoint *, char **,
129                                      struct symtabs_and_lines *);
130
131 static void clear_command (char *, int);
132
133 static void catch_command (char *, int);
134
135 static int can_use_hardware_watchpoint (struct value *);
136
137 static void break_command_1 (char *, int, int);
138
139 static void mention (struct breakpoint *);
140
141 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
142                                                                enum bptype,
143                                                                const struct breakpoint_ops *);
144 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
145                                                        const struct symtab_and_line *);
146
147 /* This function is used in gdbtk sources and thus can not be made
148    static.  */
149 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
150                                        struct symtab_and_line,
151                                        enum bptype,
152                                        const struct breakpoint_ops *);
153
154 static struct breakpoint *
155   momentary_breakpoint_from_master (struct breakpoint *orig,
156                                     enum bptype type,
157                                     const struct breakpoint_ops *ops);
158
159 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
160
161 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
162                                             CORE_ADDR bpaddr,
163                                             enum bptype bptype);
164
165 static void describe_other_breakpoints (struct gdbarch *,
166                                         struct program_space *, CORE_ADDR,
167                                         struct obj_section *, int);
168
169 static int watchpoint_locations_match (struct bp_location *loc1,
170                                        struct bp_location *loc2);
171
172 static int breakpoint_location_address_match (struct bp_location *bl,
173                                               struct address_space *aspace,
174                                               CORE_ADDR addr);
175
176 static void breakpoints_info (char *, int);
177
178 static void watchpoints_info (char *, int);
179
180 static int breakpoint_1 (char *, int, 
181                          int (*) (const struct breakpoint *));
182
183 static int breakpoint_cond_eval (void *);
184
185 static void cleanup_executing_breakpoints (void *);
186
187 static void commands_command (char *, int);
188
189 static void condition_command (char *, int);
190
191 typedef enum
192   {
193     mark_inserted,
194     mark_uninserted
195   }
196 insertion_state_t;
197
198 static int remove_breakpoint (struct bp_location *, insertion_state_t);
199 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
200
201 static enum print_stop_action print_bp_stop_message (bpstat bs);
202
203 static int watchpoint_check (void *);
204
205 static void maintenance_info_breakpoints (char *, int);
206
207 static int hw_breakpoint_used_count (void);
208
209 static int hw_watchpoint_use_count (struct breakpoint *);
210
211 static int hw_watchpoint_used_count_others (struct breakpoint *except,
212                                             enum bptype type,
213                                             int *other_type_used);
214
215 static void hbreak_command (char *, int);
216
217 static void thbreak_command (char *, int);
218
219 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
220                                     int count);
221
222 static void stop_command (char *arg, int from_tty);
223
224 static void stopin_command (char *arg, int from_tty);
225
226 static void stopat_command (char *arg, int from_tty);
227
228 static void tcatch_command (char *arg, int from_tty);
229
230 static void detach_single_step_breakpoints (void);
231
232 static void free_bp_location (struct bp_location *loc);
233 static void incref_bp_location (struct bp_location *loc);
234 static void decref_bp_location (struct bp_location **loc);
235
236 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
237
238 static void update_global_location_list (int);
239
240 static void update_global_location_list_nothrow (int);
241
242 static int is_hardware_watchpoint (const struct breakpoint *bpt);
243
244 static void insert_breakpoint_locations (void);
245
246 static int syscall_catchpoint_p (struct breakpoint *b);
247
248 static void tracepoints_info (char *, int);
249
250 static void delete_trace_command (char *, int);
251
252 static void enable_trace_command (char *, int);
253
254 static void disable_trace_command (char *, int);
255
256 static void trace_pass_command (char *, int);
257
258 static void set_tracepoint_count (int num);
259
260 static int is_masked_watchpoint (const struct breakpoint *b);
261
262 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
263
264 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
265    otherwise.  */
266
267 static int strace_marker_p (struct breakpoint *b);
268
269 /* The abstract base class all breakpoint_ops structures inherit
270    from.  */
271 struct breakpoint_ops base_breakpoint_ops;
272
273 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
274    that are implemented on top of software or hardware breakpoints
275    (user breakpoints, internal and momentary breakpoints, etc.).  */
276 static struct breakpoint_ops bkpt_base_breakpoint_ops;
277
278 /* Internal breakpoints class type.  */
279 static struct breakpoint_ops internal_breakpoint_ops;
280
281 /* Momentary breakpoints class type.  */
282 static struct breakpoint_ops momentary_breakpoint_ops;
283
284 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
285 static struct breakpoint_ops longjmp_breakpoint_ops;
286
287 /* The breakpoint_ops structure to be used in regular user created
288    breakpoints.  */
289 struct breakpoint_ops bkpt_breakpoint_ops;
290
291 /* Breakpoints set on probes.  */
292 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
293
294 /* Dynamic printf class type.  */
295 struct breakpoint_ops dprintf_breakpoint_ops;
296
297 /* One (or perhaps two) breakpoints used for software single
298    stepping.  */
299
300 static void *single_step_breakpoints[2];
301 static struct gdbarch *single_step_gdbarch[2];
302
303 /* The style in which to perform a dynamic printf.  This is a user
304    option because different output options have different tradeoffs;
305    if GDB does the printing, there is better error handling if there
306    is a problem with any of the arguments, but using an inferior
307    function lets you have special-purpose printers and sending of
308    output to the same place as compiled-in print functions.  */
309
310 static const char dprintf_style_gdb[] = "gdb";
311 static const char dprintf_style_call[] = "call";
312 static const char dprintf_style_agent[] = "agent";
313 static const char *const dprintf_style_enums[] = {
314   dprintf_style_gdb,
315   dprintf_style_call,
316   dprintf_style_agent,
317   NULL
318 };
319 static const char *dprintf_style = dprintf_style_gdb;
320
321 /* The function to use for dynamic printf if the preferred style is to
322    call into the inferior.  The value is simply a string that is
323    copied into the command, so it can be anything that GDB can
324    evaluate to a callable address, not necessarily a function name.  */
325
326 static char *dprintf_function = "";
327
328 /* The channel to use for dynamic printf if the preferred style is to
329    call into the inferior; if a nonempty string, it will be passed to
330    the call as the first argument, with the format string as the
331    second.  As with the dprintf function, this can be anything that
332    GDB knows how to evaluate, so in addition to common choices like
333    "stderr", this could be an app-specific expression like
334    "mystreams[curlogger]".  */
335
336 static char *dprintf_channel = "";
337
338 /* True if dprintf commands should continue to operate even if GDB
339    has disconnected.  */
340 static int disconnected_dprintf = 1;
341
342 /* A reference-counted struct command_line.  This lets multiple
343    breakpoints share a single command list.  */
344 struct counted_command_line
345 {
346   /* The reference count.  */
347   int refc;
348
349   /* The command list.  */
350   struct command_line *commands;
351 };
352
353 struct command_line *
354 breakpoint_commands (struct breakpoint *b)
355 {
356   return b->commands ? b->commands->commands : NULL;
357 }
358
359 /* Flag indicating that a command has proceeded the inferior past the
360    current breakpoint.  */
361
362 static int breakpoint_proceeded;
363
364 const char *
365 bpdisp_text (enum bpdisp disp)
366 {
367   /* NOTE: the following values are a part of MI protocol and
368      represent values of 'disp' field returned when inferior stops at
369      a breakpoint.  */
370   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
371
372   return bpdisps[(int) disp];
373 }
374
375 /* Prototypes for exported functions.  */
376 /* If FALSE, gdb will not use hardware support for watchpoints, even
377    if such is available.  */
378 static int can_use_hw_watchpoints;
379
380 static void
381 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
382                              struct cmd_list_element *c,
383                              const char *value)
384 {
385   fprintf_filtered (file,
386                     _("Debugger's willingness to use "
387                       "watchpoint hardware is %s.\n"),
388                     value);
389 }
390
391 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
392    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
393    for unrecognized breakpoint locations.
394    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
395 static enum auto_boolean pending_break_support;
396 static void
397 show_pending_break_support (struct ui_file *file, int from_tty,
398                             struct cmd_list_element *c,
399                             const char *value)
400 {
401   fprintf_filtered (file,
402                     _("Debugger's behavior regarding "
403                       "pending breakpoints is %s.\n"),
404                     value);
405 }
406
407 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
408    set with "break" but falling in read-only memory.
409    If 0, gdb will warn about such breakpoints, but won't automatically
410    use hardware breakpoints.  */
411 static int automatic_hardware_breakpoints;
412 static void
413 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
414                                      struct cmd_list_element *c,
415                                      const char *value)
416 {
417   fprintf_filtered (file,
418                     _("Automatic usage of hardware breakpoints is %s.\n"),
419                     value);
420 }
421
422 /* If on, gdb will keep breakpoints inserted even as inferior is
423    stopped, and immediately insert any new breakpoints.  If off, gdb
424    will insert breakpoints into inferior only when resuming it, and
425    will remove breakpoints upon stop.  If auto, GDB will behave as ON
426    if in non-stop mode, and as OFF if all-stop mode.*/
427
428 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
429
430 static void
431 show_always_inserted_mode (struct ui_file *file, int from_tty,
432                      struct cmd_list_element *c, const char *value)
433 {
434   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
435     fprintf_filtered (file,
436                       _("Always inserted breakpoint "
437                         "mode is %s (currently %s).\n"),
438                       value,
439                       breakpoints_always_inserted_mode () ? "on" : "off");
440   else
441     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
442                       value);
443 }
444
445 int
446 breakpoints_always_inserted_mode (void)
447 {
448   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
449           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
450 }
451
452 static const char condition_evaluation_both[] = "host or target";
453
454 /* Modes for breakpoint condition evaluation.  */
455 static const char condition_evaluation_auto[] = "auto";
456 static const char condition_evaluation_host[] = "host";
457 static const char condition_evaluation_target[] = "target";
458 static const char *const condition_evaluation_enums[] = {
459   condition_evaluation_auto,
460   condition_evaluation_host,
461   condition_evaluation_target,
462   NULL
463 };
464
465 /* Global that holds the current mode for breakpoint condition evaluation.  */
466 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
467
468 /* Global that we use to display information to the user (gets its value from
469    condition_evaluation_mode_1.  */
470 static const char *condition_evaluation_mode = condition_evaluation_auto;
471
472 /* Translate a condition evaluation mode MODE into either "host"
473    or "target".  This is used mostly to translate from "auto" to the
474    real setting that is being used.  It returns the translated
475    evaluation mode.  */
476
477 static const char *
478 translate_condition_evaluation_mode (const char *mode)
479 {
480   if (mode == condition_evaluation_auto)
481     {
482       if (target_supports_evaluation_of_breakpoint_conditions ())
483         return condition_evaluation_target;
484       else
485         return condition_evaluation_host;
486     }
487   else
488     return mode;
489 }
490
491 /* Discovers what condition_evaluation_auto translates to.  */
492
493 static const char *
494 breakpoint_condition_evaluation_mode (void)
495 {
496   return translate_condition_evaluation_mode (condition_evaluation_mode);
497 }
498
499 /* Return true if GDB should evaluate breakpoint conditions or false
500    otherwise.  */
501
502 static int
503 gdb_evaluates_breakpoint_condition_p (void)
504 {
505   const char *mode = breakpoint_condition_evaluation_mode ();
506
507   return (mode == condition_evaluation_host);
508 }
509
510 void _initialize_breakpoint (void);
511
512 /* Are we executing breakpoint commands?  */
513 static int executing_breakpoint_commands;
514
515 /* Are overlay event breakpoints enabled? */
516 static int overlay_events_enabled;
517
518 /* See description in breakpoint.h. */
519 int target_exact_watchpoints = 0;
520
521 /* Walk the following statement or block through all breakpoints.
522    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
523    current breakpoint.  */
524
525 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
526
527 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
528         for (B = breakpoint_chain;      \
529              B ? (TMP=B->next, 1): 0;   \
530              B = TMP)
531
532 /* Similar iterator for the low-level breakpoints.  SAFE variant is
533    not provided so update_global_location_list must not be called
534    while executing the block of ALL_BP_LOCATIONS.  */
535
536 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
537         for (BP_TMP = bp_location;                                      \
538              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
539              BP_TMP++)
540
541 /* Iterates through locations with address ADDRESS for the currently selected
542    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
543    to where the loop should start from.
544    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
545    appropriate location to start with.  */
546
547 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
548         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
549              BP_LOCP_TMP = BP_LOCP_START;                               \
550              BP_LOCP_START                                              \
551              && (BP_LOCP_TMP < bp_location + bp_location_count          \
552              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
553              BP_LOCP_TMP++)
554
555 /* Iterator for tracepoints only.  */
556
557 #define ALL_TRACEPOINTS(B)  \
558   for (B = breakpoint_chain; B; B = B->next)  \
559     if (is_tracepoint (B))
560
561 /* Chains of all breakpoints defined.  */
562
563 struct breakpoint *breakpoint_chain;
564
565 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
566
567 static struct bp_location **bp_location;
568
569 /* Number of elements of BP_LOCATION.  */
570
571 static unsigned bp_location_count;
572
573 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
574    ADDRESS for the current elements of BP_LOCATION which get a valid
575    result from bp_location_has_shadow.  You can use it for roughly
576    limiting the subrange of BP_LOCATION to scan for shadow bytes for
577    an address you need to read.  */
578
579 static CORE_ADDR bp_location_placed_address_before_address_max;
580
581 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
582    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
583    BP_LOCATION which get a valid result from bp_location_has_shadow.
584    You can use it for roughly limiting the subrange of BP_LOCATION to
585    scan for shadow bytes for an address you need to read.  */
586
587 static CORE_ADDR bp_location_shadow_len_after_address_max;
588
589 /* The locations that no longer correspond to any breakpoint, unlinked
590    from bp_location array, but for which a hit may still be reported
591    by a target.  */
592 VEC(bp_location_p) *moribund_locations = NULL;
593
594 /* Number of last breakpoint made.  */
595
596 static int breakpoint_count;
597
598 /* The value of `breakpoint_count' before the last command that
599    created breakpoints.  If the last (break-like) command created more
600    than one breakpoint, then the difference between BREAKPOINT_COUNT
601    and PREV_BREAKPOINT_COUNT is more than one.  */
602 static int prev_breakpoint_count;
603
604 /* Number of last tracepoint made.  */
605
606 static int tracepoint_count;
607
608 static struct cmd_list_element *breakpoint_set_cmdlist;
609 static struct cmd_list_element *breakpoint_show_cmdlist;
610 struct cmd_list_element *save_cmdlist;
611
612 /* Return whether a breakpoint is an active enabled breakpoint.  */
613 static int
614 breakpoint_enabled (struct breakpoint *b)
615 {
616   return (b->enable_state == bp_enabled);
617 }
618
619 /* Set breakpoint count to NUM.  */
620
621 static void
622 set_breakpoint_count (int num)
623 {
624   prev_breakpoint_count = breakpoint_count;
625   breakpoint_count = num;
626   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
627 }
628
629 /* Used by `start_rbreak_breakpoints' below, to record the current
630    breakpoint count before "rbreak" creates any breakpoint.  */
631 static int rbreak_start_breakpoint_count;
632
633 /* Called at the start an "rbreak" command to record the first
634    breakpoint made.  */
635
636 void
637 start_rbreak_breakpoints (void)
638 {
639   rbreak_start_breakpoint_count = breakpoint_count;
640 }
641
642 /* Called at the end of an "rbreak" command to record the last
643    breakpoint made.  */
644
645 void
646 end_rbreak_breakpoints (void)
647 {
648   prev_breakpoint_count = rbreak_start_breakpoint_count;
649 }
650
651 /* Used in run_command to zero the hit count when a new run starts.  */
652
653 void
654 clear_breakpoint_hit_counts (void)
655 {
656   struct breakpoint *b;
657
658   ALL_BREAKPOINTS (b)
659     b->hit_count = 0;
660 }
661
662 /* Allocate a new counted_command_line with reference count of 1.
663    The new structure owns COMMANDS.  */
664
665 static struct counted_command_line *
666 alloc_counted_command_line (struct command_line *commands)
667 {
668   struct counted_command_line *result
669     = xmalloc (sizeof (struct counted_command_line));
670
671   result->refc = 1;
672   result->commands = commands;
673   return result;
674 }
675
676 /* Increment reference count.  This does nothing if CMD is NULL.  */
677
678 static void
679 incref_counted_command_line (struct counted_command_line *cmd)
680 {
681   if (cmd)
682     ++cmd->refc;
683 }
684
685 /* Decrement reference count.  If the reference count reaches 0,
686    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
687    nothing if *CMDP is NULL.  */
688
689 static void
690 decref_counted_command_line (struct counted_command_line **cmdp)
691 {
692   if (*cmdp)
693     {
694       if (--(*cmdp)->refc == 0)
695         {
696           free_command_lines (&(*cmdp)->commands);
697           xfree (*cmdp);
698         }
699       *cmdp = NULL;
700     }
701 }
702
703 /* A cleanup function that calls decref_counted_command_line.  */
704
705 static void
706 do_cleanup_counted_command_line (void *arg)
707 {
708   decref_counted_command_line (arg);
709 }
710
711 /* Create a cleanup that calls decref_counted_command_line on the
712    argument.  */
713
714 static struct cleanup *
715 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
716 {
717   return make_cleanup (do_cleanup_counted_command_line, cmdp);
718 }
719
720 \f
721 /* Return the breakpoint with the specified number, or NULL
722    if the number does not refer to an existing breakpoint.  */
723
724 struct breakpoint *
725 get_breakpoint (int num)
726 {
727   struct breakpoint *b;
728
729   ALL_BREAKPOINTS (b)
730     if (b->number == num)
731       return b;
732   
733   return NULL;
734 }
735
736 \f
737
738 /* Mark locations as "conditions have changed" in case the target supports
739    evaluating conditions on its side.  */
740
741 static void
742 mark_breakpoint_modified (struct breakpoint *b)
743 {
744   struct bp_location *loc;
745
746   /* This is only meaningful if the target is
747      evaluating conditions and if the user has
748      opted for condition evaluation on the target's
749      side.  */
750   if (gdb_evaluates_breakpoint_condition_p ()
751       || !target_supports_evaluation_of_breakpoint_conditions ())
752     return;
753
754   if (!is_breakpoint (b))
755     return;
756
757   for (loc = b->loc; loc; loc = loc->next)
758     loc->condition_changed = condition_modified;
759 }
760
761 /* Mark location as "conditions have changed" in case the target supports
762    evaluating conditions on its side.  */
763
764 static void
765 mark_breakpoint_location_modified (struct bp_location *loc)
766 {
767   /* This is only meaningful if the target is
768      evaluating conditions and if the user has
769      opted for condition evaluation on the target's
770      side.  */
771   if (gdb_evaluates_breakpoint_condition_p ()
772       || !target_supports_evaluation_of_breakpoint_conditions ())
773
774     return;
775
776   if (!is_breakpoint (loc->owner))
777     return;
778
779   loc->condition_changed = condition_modified;
780 }
781
782 /* Sets the condition-evaluation mode using the static global
783    condition_evaluation_mode.  */
784
785 static void
786 set_condition_evaluation_mode (char *args, int from_tty,
787                                struct cmd_list_element *c)
788 {
789   const char *old_mode, *new_mode;
790
791   if ((condition_evaluation_mode_1 == condition_evaluation_target)
792       && !target_supports_evaluation_of_breakpoint_conditions ())
793     {
794       condition_evaluation_mode_1 = condition_evaluation_mode;
795       warning (_("Target does not support breakpoint condition evaluation.\n"
796                  "Using host evaluation mode instead."));
797       return;
798     }
799
800   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
801   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
802
803   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
804      settings was "auto".  */
805   condition_evaluation_mode = condition_evaluation_mode_1;
806
807   /* Only update the mode if the user picked a different one.  */
808   if (new_mode != old_mode)
809     {
810       struct bp_location *loc, **loc_tmp;
811       /* If the user switched to a different evaluation mode, we
812          need to synch the changes with the target as follows:
813
814          "host" -> "target": Send all (valid) conditions to the target.
815          "target" -> "host": Remove all the conditions from the target.
816       */
817
818       if (new_mode == condition_evaluation_target)
819         {
820           /* Mark everything modified and synch conditions with the
821              target.  */
822           ALL_BP_LOCATIONS (loc, loc_tmp)
823             mark_breakpoint_location_modified (loc);
824         }
825       else
826         {
827           /* Manually mark non-duplicate locations to synch conditions
828              with the target.  We do this to remove all the conditions the
829              target knows about.  */
830           ALL_BP_LOCATIONS (loc, loc_tmp)
831             if (is_breakpoint (loc->owner) && loc->inserted)
832               loc->needs_update = 1;
833         }
834
835       /* Do the update.  */
836       update_global_location_list (1);
837     }
838
839   return;
840 }
841
842 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
843    what "auto" is translating to.  */
844
845 static void
846 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
847                                 struct cmd_list_element *c, const char *value)
848 {
849   if (condition_evaluation_mode == condition_evaluation_auto)
850     fprintf_filtered (file,
851                       _("Breakpoint condition evaluation "
852                         "mode is %s (currently %s).\n"),
853                       value,
854                       breakpoint_condition_evaluation_mode ());
855   else
856     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
857                       value);
858 }
859
860 /* A comparison function for bp_location AP and BP that is used by
861    bsearch.  This comparison function only cares about addresses, unlike
862    the more general bp_location_compare function.  */
863
864 static int
865 bp_location_compare_addrs (const void *ap, const void *bp)
866 {
867   struct bp_location *a = *(void **) ap;
868   struct bp_location *b = *(void **) bp;
869
870   if (a->address == b->address)
871     return 0;
872   else
873     return ((a->address > b->address) - (a->address < b->address));
874 }
875
876 /* Helper function to skip all bp_locations with addresses
877    less than ADDRESS.  It returns the first bp_location that
878    is greater than or equal to ADDRESS.  If none is found, just
879    return NULL.  */
880
881 static struct bp_location **
882 get_first_locp_gte_addr (CORE_ADDR address)
883 {
884   struct bp_location dummy_loc;
885   struct bp_location *dummy_locp = &dummy_loc;
886   struct bp_location **locp_found = NULL;
887
888   /* Initialize the dummy location's address field.  */
889   memset (&dummy_loc, 0, sizeof (struct bp_location));
890   dummy_loc.address = address;
891
892   /* Find a close match to the first location at ADDRESS.  */
893   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
894                         sizeof (struct bp_location **),
895                         bp_location_compare_addrs);
896
897   /* Nothing was found, nothing left to do.  */
898   if (locp_found == NULL)
899     return NULL;
900
901   /* We may have found a location that is at ADDRESS but is not the first in the
902      location's list.  Go backwards (if possible) and locate the first one.  */
903   while ((locp_found - 1) >= bp_location
904          && (*(locp_found - 1))->address == address)
905     locp_found--;
906
907   return locp_found;
908 }
909
910 void
911 set_breakpoint_condition (struct breakpoint *b, char *exp,
912                           int from_tty)
913 {
914   xfree (b->cond_string);
915   b->cond_string = NULL;
916
917   if (is_watchpoint (b))
918     {
919       struct watchpoint *w = (struct watchpoint *) b;
920
921       xfree (w->cond_exp);
922       w->cond_exp = NULL;
923     }
924   else
925     {
926       struct bp_location *loc;
927
928       for (loc = b->loc; loc; loc = loc->next)
929         {
930           xfree (loc->cond);
931           loc->cond = NULL;
932
933           /* No need to free the condition agent expression
934              bytecode (if we have one).  We will handle this
935              when we go through update_global_location_list.  */
936         }
937     }
938
939   if (*exp == 0)
940     {
941       if (from_tty)
942         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
943     }
944   else
945     {
946       const char *arg = exp;
947
948       /* I don't know if it matters whether this is the string the user
949          typed in or the decompiled expression.  */
950       b->cond_string = xstrdup (arg);
951       b->condition_not_parsed = 0;
952
953       if (is_watchpoint (b))
954         {
955           struct watchpoint *w = (struct watchpoint *) b;
956
957           innermost_block = NULL;
958           arg = exp;
959           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
960           if (*arg)
961             error (_("Junk at end of expression"));
962           w->cond_exp_valid_block = innermost_block;
963         }
964       else
965         {
966           struct bp_location *loc;
967
968           for (loc = b->loc; loc; loc = loc->next)
969             {
970               arg = exp;
971               loc->cond =
972                 parse_exp_1 (&arg, loc->address,
973                              block_for_pc (loc->address), 0);
974               if (*arg)
975                 error (_("Junk at end of expression"));
976             }
977         }
978     }
979   mark_breakpoint_modified (b);
980
981   observer_notify_breakpoint_modified (b);
982 }
983
984 /* Completion for the "condition" command.  */
985
986 static VEC (char_ptr) *
987 condition_completer (struct cmd_list_element *cmd,
988                      const char *text, const char *word)
989 {
990   const char *space;
991
992   text = skip_spaces_const (text);
993   space = skip_to_space_const (text);
994   if (*space == '\0')
995     {
996       int len;
997       struct breakpoint *b;
998       VEC (char_ptr) *result = NULL;
999
1000       if (text[0] == '$')
1001         {
1002           /* We don't support completion of history indices.  */
1003           if (isdigit (text[1]))
1004             return NULL;
1005           return complete_internalvar (&text[1]);
1006         }
1007
1008       /* We're completing the breakpoint number.  */
1009       len = strlen (text);
1010
1011       ALL_BREAKPOINTS (b)
1012         {
1013           char number[50];
1014
1015           xsnprintf (number, sizeof (number), "%d", b->number);
1016
1017           if (strncmp (number, text, len) == 0)
1018             VEC_safe_push (char_ptr, result, xstrdup (number));
1019         }
1020
1021       return result;
1022     }
1023
1024   /* We're completing the expression part.  */
1025   text = skip_spaces_const (space);
1026   return expression_completer (cmd, text, word);
1027 }
1028
1029 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1030
1031 static void
1032 condition_command (char *arg, int from_tty)
1033 {
1034   struct breakpoint *b;
1035   char *p;
1036   int bnum;
1037
1038   if (arg == 0)
1039     error_no_arg (_("breakpoint number"));
1040
1041   p = arg;
1042   bnum = get_number (&p);
1043   if (bnum == 0)
1044     error (_("Bad breakpoint argument: '%s'"), arg);
1045
1046   ALL_BREAKPOINTS (b)
1047     if (b->number == bnum)
1048       {
1049         /* Check if this breakpoint has a "stop" method implemented in an
1050            extension language.  This method and conditions entered into GDB
1051            from the CLI are mutually exclusive.  */
1052         const struct extension_language_defn *extlang
1053           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1054
1055         if (extlang != NULL)
1056           {
1057             error (_("Only one stop condition allowed.  There is currently"
1058                      " a %s stop condition defined for this breakpoint."),
1059                    ext_lang_capitalized_name (extlang));
1060           }
1061         set_breakpoint_condition (b, p, from_tty);
1062
1063         if (is_breakpoint (b))
1064           update_global_location_list (1);
1065
1066         return;
1067       }
1068
1069   error (_("No breakpoint number %d."), bnum);
1070 }
1071
1072 /* Check that COMMAND do not contain commands that are suitable
1073    only for tracepoints and not suitable for ordinary breakpoints.
1074    Throw if any such commands is found.  */
1075
1076 static void
1077 check_no_tracepoint_commands (struct command_line *commands)
1078 {
1079   struct command_line *c;
1080
1081   for (c = commands; c; c = c->next)
1082     {
1083       int i;
1084
1085       if (c->control_type == while_stepping_control)
1086         error (_("The 'while-stepping' command can "
1087                  "only be used for tracepoints"));
1088
1089       for (i = 0; i < c->body_count; ++i)
1090         check_no_tracepoint_commands ((c->body_list)[i]);
1091
1092       /* Not that command parsing removes leading whitespace and comment
1093          lines and also empty lines.  So, we only need to check for
1094          command directly.  */
1095       if (strstr (c->line, "collect ") == c->line)
1096         error (_("The 'collect' command can only be used for tracepoints"));
1097
1098       if (strstr (c->line, "teval ") == c->line)
1099         error (_("The 'teval' command can only be used for tracepoints"));
1100     }
1101 }
1102
1103 /* Encapsulate tests for different types of tracepoints.  */
1104
1105 static int
1106 is_tracepoint_type (enum bptype type)
1107 {
1108   return (type == bp_tracepoint
1109           || type == bp_fast_tracepoint
1110           || type == bp_static_tracepoint);
1111 }
1112
1113 int
1114 is_tracepoint (const struct breakpoint *b)
1115 {
1116   return is_tracepoint_type (b->type);
1117 }
1118
1119 /* A helper function that validates that COMMANDS are valid for a
1120    breakpoint.  This function will throw an exception if a problem is
1121    found.  */
1122
1123 static void
1124 validate_commands_for_breakpoint (struct breakpoint *b,
1125                                   struct command_line *commands)
1126 {
1127   if (is_tracepoint (b))
1128     {
1129       struct tracepoint *t = (struct tracepoint *) b;
1130       struct command_line *c;
1131       struct command_line *while_stepping = 0;
1132
1133       /* Reset the while-stepping step count.  The previous commands
1134          might have included a while-stepping action, while the new
1135          ones might not.  */
1136       t->step_count = 0;
1137
1138       /* We need to verify that each top-level element of commands is
1139          valid for tracepoints, that there's at most one
1140          while-stepping element, and that the while-stepping's body
1141          has valid tracing commands excluding nested while-stepping.
1142          We also need to validate the tracepoint action line in the
1143          context of the tracepoint --- validate_actionline actually
1144          has side effects, like setting the tracepoint's
1145          while-stepping STEP_COUNT, in addition to checking if the
1146          collect/teval actions parse and make sense in the
1147          tracepoint's context.  */
1148       for (c = commands; c; c = c->next)
1149         {
1150           if (c->control_type == while_stepping_control)
1151             {
1152               if (b->type == bp_fast_tracepoint)
1153                 error (_("The 'while-stepping' command "
1154                          "cannot be used for fast tracepoint"));
1155               else if (b->type == bp_static_tracepoint)
1156                 error (_("The 'while-stepping' command "
1157                          "cannot be used for static tracepoint"));
1158
1159               if (while_stepping)
1160                 error (_("The 'while-stepping' command "
1161                          "can be used only once"));
1162               else
1163                 while_stepping = c;
1164             }
1165
1166           validate_actionline (c->line, b);
1167         }
1168       if (while_stepping)
1169         {
1170           struct command_line *c2;
1171
1172           gdb_assert (while_stepping->body_count == 1);
1173           c2 = while_stepping->body_list[0];
1174           for (; c2; c2 = c2->next)
1175             {
1176               if (c2->control_type == while_stepping_control)
1177                 error (_("The 'while-stepping' command cannot be nested"));
1178             }
1179         }
1180     }
1181   else
1182     {
1183       check_no_tracepoint_commands (commands);
1184     }
1185 }
1186
1187 /* Return a vector of all the static tracepoints set at ADDR.  The
1188    caller is responsible for releasing the vector.  */
1189
1190 VEC(breakpoint_p) *
1191 static_tracepoints_here (CORE_ADDR addr)
1192 {
1193   struct breakpoint *b;
1194   VEC(breakpoint_p) *found = 0;
1195   struct bp_location *loc;
1196
1197   ALL_BREAKPOINTS (b)
1198     if (b->type == bp_static_tracepoint)
1199       {
1200         for (loc = b->loc; loc; loc = loc->next)
1201           if (loc->address == addr)
1202             VEC_safe_push(breakpoint_p, found, b);
1203       }
1204
1205   return found;
1206 }
1207
1208 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1209    validate that only allowed commands are included.  */
1210
1211 void
1212 breakpoint_set_commands (struct breakpoint *b, 
1213                          struct command_line *commands)
1214 {
1215   validate_commands_for_breakpoint (b, commands);
1216
1217   decref_counted_command_line (&b->commands);
1218   b->commands = alloc_counted_command_line (commands);
1219   observer_notify_breakpoint_modified (b);
1220 }
1221
1222 /* Set the internal `silent' flag on the breakpoint.  Note that this
1223    is not the same as the "silent" that may appear in the breakpoint's
1224    commands.  */
1225
1226 void
1227 breakpoint_set_silent (struct breakpoint *b, int silent)
1228 {
1229   int old_silent = b->silent;
1230
1231   b->silent = silent;
1232   if (old_silent != silent)
1233     observer_notify_breakpoint_modified (b);
1234 }
1235
1236 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1237    breakpoint work for any thread.  */
1238
1239 void
1240 breakpoint_set_thread (struct breakpoint *b, int thread)
1241 {
1242   int old_thread = b->thread;
1243
1244   b->thread = thread;
1245   if (old_thread != thread)
1246     observer_notify_breakpoint_modified (b);
1247 }
1248
1249 /* Set the task for this breakpoint.  If TASK is 0, make the
1250    breakpoint work for any task.  */
1251
1252 void
1253 breakpoint_set_task (struct breakpoint *b, int task)
1254 {
1255   int old_task = b->task;
1256
1257   b->task = task;
1258   if (old_task != task)
1259     observer_notify_breakpoint_modified (b);
1260 }
1261
1262 void
1263 check_tracepoint_command (char *line, void *closure)
1264 {
1265   struct breakpoint *b = closure;
1266
1267   validate_actionline (line, b);
1268 }
1269
1270 /* A structure used to pass information through
1271    map_breakpoint_numbers.  */
1272
1273 struct commands_info
1274 {
1275   /* True if the command was typed at a tty.  */
1276   int from_tty;
1277
1278   /* The breakpoint range spec.  */
1279   char *arg;
1280
1281   /* Non-NULL if the body of the commands are being read from this
1282      already-parsed command.  */
1283   struct command_line *control;
1284
1285   /* The command lines read from the user, or NULL if they have not
1286      yet been read.  */
1287   struct counted_command_line *cmd;
1288 };
1289
1290 /* A callback for map_breakpoint_numbers that sets the commands for
1291    commands_command.  */
1292
1293 static void
1294 do_map_commands_command (struct breakpoint *b, void *data)
1295 {
1296   struct commands_info *info = data;
1297
1298   if (info->cmd == NULL)
1299     {
1300       struct command_line *l;
1301
1302       if (info->control != NULL)
1303         l = copy_command_lines (info->control->body_list[0]);
1304       else
1305         {
1306           struct cleanup *old_chain;
1307           char *str;
1308
1309           str = xstrprintf (_("Type commands for breakpoint(s) "
1310                               "%s, one per line."),
1311                             info->arg);
1312
1313           old_chain = make_cleanup (xfree, str);
1314
1315           l = read_command_lines (str,
1316                                   info->from_tty, 1,
1317                                   (is_tracepoint (b)
1318                                    ? check_tracepoint_command : 0),
1319                                   b);
1320
1321           do_cleanups (old_chain);
1322         }
1323
1324       info->cmd = alloc_counted_command_line (l);
1325     }
1326
1327   /* If a breakpoint was on the list more than once, we don't need to
1328      do anything.  */
1329   if (b->commands != info->cmd)
1330     {
1331       validate_commands_for_breakpoint (b, info->cmd->commands);
1332       incref_counted_command_line (info->cmd);
1333       decref_counted_command_line (&b->commands);
1334       b->commands = info->cmd;
1335       observer_notify_breakpoint_modified (b);
1336     }
1337 }
1338
1339 static void
1340 commands_command_1 (char *arg, int from_tty, 
1341                     struct command_line *control)
1342 {
1343   struct cleanup *cleanups;
1344   struct commands_info info;
1345
1346   info.from_tty = from_tty;
1347   info.control = control;
1348   info.cmd = NULL;
1349   /* If we read command lines from the user, then `info' will hold an
1350      extra reference to the commands that we must clean up.  */
1351   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1352
1353   if (arg == NULL || !*arg)
1354     {
1355       if (breakpoint_count - prev_breakpoint_count > 1)
1356         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1357                           breakpoint_count);
1358       else if (breakpoint_count > 0)
1359         arg = xstrprintf ("%d", breakpoint_count);
1360       else
1361         {
1362           /* So that we don't try to free the incoming non-NULL
1363              argument in the cleanup below.  Mapping breakpoint
1364              numbers will fail in this case.  */
1365           arg = NULL;
1366         }
1367     }
1368   else
1369     /* The command loop has some static state, so we need to preserve
1370        our argument.  */
1371     arg = xstrdup (arg);
1372
1373   if (arg != NULL)
1374     make_cleanup (xfree, arg);
1375
1376   info.arg = arg;
1377
1378   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1379
1380   if (info.cmd == NULL)
1381     error (_("No breakpoints specified."));
1382
1383   do_cleanups (cleanups);
1384 }
1385
1386 static void
1387 commands_command (char *arg, int from_tty)
1388 {
1389   commands_command_1 (arg, from_tty, NULL);
1390 }
1391
1392 /* Like commands_command, but instead of reading the commands from
1393    input stream, takes them from an already parsed command structure.
1394
1395    This is used by cli-script.c to DTRT with breakpoint commands
1396    that are part of if and while bodies.  */
1397 enum command_control_type
1398 commands_from_control_command (char *arg, struct command_line *cmd)
1399 {
1400   commands_command_1 (arg, 0, cmd);
1401   return simple_control;
1402 }
1403
1404 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1405
1406 static int
1407 bp_location_has_shadow (struct bp_location *bl)
1408 {
1409   if (bl->loc_type != bp_loc_software_breakpoint)
1410     return 0;
1411   if (!bl->inserted)
1412     return 0;
1413   if (bl->target_info.shadow_len == 0)
1414     /* BL isn't valid, or doesn't shadow memory.  */
1415     return 0;
1416   return 1;
1417 }
1418
1419 /* Update BUF, which is LEN bytes read from the target address
1420    MEMADDR, by replacing a memory breakpoint with its shadowed
1421    contents.
1422
1423    If READBUF is not NULL, this buffer must not overlap with the of
1424    the breakpoint location's shadow_contents buffer.  Otherwise, a
1425    failed assertion internal error will be raised.  */
1426
1427 static void
1428 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1429                             const gdb_byte *writebuf_org,
1430                             ULONGEST memaddr, LONGEST len,
1431                             struct bp_target_info *target_info,
1432                             struct gdbarch *gdbarch)
1433 {
1434   /* Now do full processing of the found relevant range of elements.  */
1435   CORE_ADDR bp_addr = 0;
1436   int bp_size = 0;
1437   int bptoffset = 0;
1438
1439   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1440                                  current_program_space->aspace, 0))
1441     {
1442       /* The breakpoint is inserted in a different address space.  */
1443       return;
1444     }
1445
1446   /* Addresses and length of the part of the breakpoint that
1447      we need to copy.  */
1448   bp_addr = target_info->placed_address;
1449   bp_size = target_info->shadow_len;
1450
1451   if (bp_addr + bp_size <= memaddr)
1452     {
1453       /* The breakpoint is entirely before the chunk of memory we are
1454          reading.  */
1455       return;
1456     }
1457
1458   if (bp_addr >= memaddr + len)
1459     {
1460       /* The breakpoint is entirely after the chunk of memory we are
1461          reading.  */
1462       return;
1463     }
1464
1465   /* Offset within shadow_contents.  */
1466   if (bp_addr < memaddr)
1467     {
1468       /* Only copy the second part of the breakpoint.  */
1469       bp_size -= memaddr - bp_addr;
1470       bptoffset = memaddr - bp_addr;
1471       bp_addr = memaddr;
1472     }
1473
1474   if (bp_addr + bp_size > memaddr + len)
1475     {
1476       /* Only copy the first part of the breakpoint.  */
1477       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1478     }
1479
1480   if (readbuf != NULL)
1481     {
1482       /* Verify that the readbuf buffer does not overlap with the
1483          shadow_contents buffer.  */
1484       gdb_assert (target_info->shadow_contents >= readbuf + len
1485                   || readbuf >= (target_info->shadow_contents
1486                                  + target_info->shadow_len));
1487
1488       /* Update the read buffer with this inserted breakpoint's
1489          shadow.  */
1490       memcpy (readbuf + bp_addr - memaddr,
1491               target_info->shadow_contents + bptoffset, bp_size);
1492     }
1493   else
1494     {
1495       const unsigned char *bp;
1496       CORE_ADDR placed_address = target_info->placed_address;
1497       int placed_size = target_info->placed_size;
1498
1499       /* Update the shadow with what we want to write to memory.  */
1500       memcpy (target_info->shadow_contents + bptoffset,
1501               writebuf_org + bp_addr - memaddr, bp_size);
1502
1503       /* Determine appropriate breakpoint contents and size for this
1504          address.  */
1505       bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1506
1507       /* Update the final write buffer with this inserted
1508          breakpoint's INSN.  */
1509       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1510     }
1511 }
1512
1513 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1514    by replacing any memory breakpoints with their shadowed contents.
1515
1516    If READBUF is not NULL, this buffer must not overlap with any of
1517    the breakpoint location's shadow_contents buffers.  Otherwise,
1518    a failed assertion internal error will be raised.
1519
1520    The range of shadowed area by each bp_location is:
1521      bl->address - bp_location_placed_address_before_address_max
1522      up to bl->address + bp_location_shadow_len_after_address_max
1523    The range we were requested to resolve shadows for is:
1524      memaddr ... memaddr + len
1525    Thus the safe cutoff boundaries for performance optimization are
1526      memaddr + len <= (bl->address
1527                        - bp_location_placed_address_before_address_max)
1528    and:
1529      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1530
1531 void
1532 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1533                         const gdb_byte *writebuf_org,
1534                         ULONGEST memaddr, LONGEST len)
1535 {
1536   /* Left boundary, right boundary and median element of our binary
1537      search.  */
1538   unsigned bc_l, bc_r, bc;
1539   size_t i;
1540
1541   /* Find BC_L which is a leftmost element which may affect BUF
1542      content.  It is safe to report lower value but a failure to
1543      report higher one.  */
1544
1545   bc_l = 0;
1546   bc_r = bp_location_count;
1547   while (bc_l + 1 < bc_r)
1548     {
1549       struct bp_location *bl;
1550
1551       bc = (bc_l + bc_r) / 2;
1552       bl = bp_location[bc];
1553
1554       /* Check first BL->ADDRESS will not overflow due to the added
1555          constant.  Then advance the left boundary only if we are sure
1556          the BC element can in no way affect the BUF content (MEMADDR
1557          to MEMADDR + LEN range).
1558
1559          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1560          offset so that we cannot miss a breakpoint with its shadow
1561          range tail still reaching MEMADDR.  */
1562
1563       if ((bl->address + bp_location_shadow_len_after_address_max
1564            >= bl->address)
1565           && (bl->address + bp_location_shadow_len_after_address_max
1566               <= memaddr))
1567         bc_l = bc;
1568       else
1569         bc_r = bc;
1570     }
1571
1572   /* Due to the binary search above, we need to make sure we pick the
1573      first location that's at BC_L's address.  E.g., if there are
1574      multiple locations at the same address, BC_L may end up pointing
1575      at a duplicate location, and miss the "master"/"inserted"
1576      location.  Say, given locations L1, L2 and L3 at addresses A and
1577      B:
1578
1579       L1@A, L2@A, L3@B, ...
1580
1581      BC_L could end up pointing at location L2, while the "master"
1582      location could be L1.  Since the `loc->inserted' flag is only set
1583      on "master" locations, we'd forget to restore the shadow of L1
1584      and L2.  */
1585   while (bc_l > 0
1586          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1587     bc_l--;
1588
1589   /* Now do full processing of the found relevant range of elements.  */
1590
1591   for (bc = bc_l; bc < bp_location_count; bc++)
1592   {
1593     struct bp_location *bl = bp_location[bc];
1594     CORE_ADDR bp_addr = 0;
1595     int bp_size = 0;
1596     int bptoffset = 0;
1597
1598     /* bp_location array has BL->OWNER always non-NULL.  */
1599     if (bl->owner->type == bp_none)
1600       warning (_("reading through apparently deleted breakpoint #%d?"),
1601                bl->owner->number);
1602
1603     /* Performance optimization: any further element can no longer affect BUF
1604        content.  */
1605
1606     if (bl->address >= bp_location_placed_address_before_address_max
1607         && memaddr + len <= (bl->address
1608                              - bp_location_placed_address_before_address_max))
1609       break;
1610
1611     if (!bp_location_has_shadow (bl))
1612       continue;
1613
1614     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1615                                 memaddr, len, &bl->target_info, bl->gdbarch);
1616   }
1617
1618   /* Now process single-step breakpoints.  These are not found in the
1619      bp_location array.  */
1620   for (i = 0; i < 2; i++)
1621     {
1622       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
1623
1624       if (bp_tgt != NULL)
1625         {
1626           struct gdbarch *gdbarch = single_step_gdbarch[i];
1627
1628           one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1629                                       memaddr, len, bp_tgt, gdbarch);
1630         }
1631     }
1632 }
1633
1634 \f
1635
1636 /* Return true if BPT is either a software breakpoint or a hardware
1637    breakpoint.  */
1638
1639 int
1640 is_breakpoint (const struct breakpoint *bpt)
1641 {
1642   return (bpt->type == bp_breakpoint
1643           || bpt->type == bp_hardware_breakpoint
1644           || bpt->type == bp_dprintf);
1645 }
1646
1647 /* Return true if BPT is of any hardware watchpoint kind.  */
1648
1649 static int
1650 is_hardware_watchpoint (const struct breakpoint *bpt)
1651 {
1652   return (bpt->type == bp_hardware_watchpoint
1653           || bpt->type == bp_read_watchpoint
1654           || bpt->type == bp_access_watchpoint);
1655 }
1656
1657 /* Return true if BPT is of any watchpoint kind, hardware or
1658    software.  */
1659
1660 int
1661 is_watchpoint (const struct breakpoint *bpt)
1662 {
1663   return (is_hardware_watchpoint (bpt)
1664           || bpt->type == bp_watchpoint);
1665 }
1666
1667 /* Returns true if the current thread and its running state are safe
1668    to evaluate or update watchpoint B.  Watchpoints on local
1669    expressions need to be evaluated in the context of the thread that
1670    was current when the watchpoint was created, and, that thread needs
1671    to be stopped to be able to select the correct frame context.
1672    Watchpoints on global expressions can be evaluated on any thread,
1673    and in any state.  It is presently left to the target allowing
1674    memory accesses when threads are running.  */
1675
1676 static int
1677 watchpoint_in_thread_scope (struct watchpoint *b)
1678 {
1679   return (b->base.pspace == current_program_space
1680           && (ptid_equal (b->watchpoint_thread, null_ptid)
1681               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1682                   && !is_executing (inferior_ptid))));
1683 }
1684
1685 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1686    associated bp_watchpoint_scope breakpoint.  */
1687
1688 static void
1689 watchpoint_del_at_next_stop (struct watchpoint *w)
1690 {
1691   struct breakpoint *b = &w->base;
1692
1693   if (b->related_breakpoint != b)
1694     {
1695       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1696       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1697       b->related_breakpoint->disposition = disp_del_at_next_stop;
1698       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1699       b->related_breakpoint = b;
1700     }
1701   b->disposition = disp_del_at_next_stop;
1702 }
1703
1704 /* Assuming that B is a watchpoint:
1705    - Reparse watchpoint expression, if REPARSE is non-zero
1706    - Evaluate expression and store the result in B->val
1707    - Evaluate the condition if there is one, and store the result
1708      in b->loc->cond.
1709    - Update the list of values that must be watched in B->loc.
1710
1711    If the watchpoint disposition is disp_del_at_next_stop, then do
1712    nothing.  If this is local watchpoint that is out of scope, delete
1713    it.
1714
1715    Even with `set breakpoint always-inserted on' the watchpoints are
1716    removed + inserted on each stop here.  Normal breakpoints must
1717    never be removed because they might be missed by a running thread
1718    when debugging in non-stop mode.  On the other hand, hardware
1719    watchpoints (is_hardware_watchpoint; processed here) are specific
1720    to each LWP since they are stored in each LWP's hardware debug
1721    registers.  Therefore, such LWP must be stopped first in order to
1722    be able to modify its hardware watchpoints.
1723
1724    Hardware watchpoints must be reset exactly once after being
1725    presented to the user.  It cannot be done sooner, because it would
1726    reset the data used to present the watchpoint hit to the user.  And
1727    it must not be done later because it could display the same single
1728    watchpoint hit during multiple GDB stops.  Note that the latter is
1729    relevant only to the hardware watchpoint types bp_read_watchpoint
1730    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1731    not user-visible - its hit is suppressed if the memory content has
1732    not changed.
1733
1734    The following constraints influence the location where we can reset
1735    hardware watchpoints:
1736
1737    * target_stopped_by_watchpoint and target_stopped_data_address are
1738      called several times when GDB stops.
1739
1740    [linux] 
1741    * Multiple hardware watchpoints can be hit at the same time,
1742      causing GDB to stop.  GDB only presents one hardware watchpoint
1743      hit at a time as the reason for stopping, and all the other hits
1744      are presented later, one after the other, each time the user
1745      requests the execution to be resumed.  Execution is not resumed
1746      for the threads still having pending hit event stored in
1747      LWP_INFO->STATUS.  While the watchpoint is already removed from
1748      the inferior on the first stop the thread hit event is kept being
1749      reported from its cached value by linux_nat_stopped_data_address
1750      until the real thread resume happens after the watchpoint gets
1751      presented and thus its LWP_INFO->STATUS gets reset.
1752
1753    Therefore the hardware watchpoint hit can get safely reset on the
1754    watchpoint removal from inferior.  */
1755
1756 static void
1757 update_watchpoint (struct watchpoint *b, int reparse)
1758 {
1759   int within_current_scope;
1760   struct frame_id saved_frame_id;
1761   int frame_saved;
1762
1763   /* If this is a local watchpoint, we only want to check if the
1764      watchpoint frame is in scope if the current thread is the thread
1765      that was used to create the watchpoint.  */
1766   if (!watchpoint_in_thread_scope (b))
1767     return;
1768
1769   if (b->base.disposition == disp_del_at_next_stop)
1770     return;
1771  
1772   frame_saved = 0;
1773
1774   /* Determine if the watchpoint is within scope.  */
1775   if (b->exp_valid_block == NULL)
1776     within_current_scope = 1;
1777   else
1778     {
1779       struct frame_info *fi = get_current_frame ();
1780       struct gdbarch *frame_arch = get_frame_arch (fi);
1781       CORE_ADDR frame_pc = get_frame_pc (fi);
1782
1783       /* If we're in a function epilogue, unwinding may not work
1784          properly, so do not attempt to recreate locations at this
1785          point.  See similar comments in watchpoint_check.  */
1786       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1787         return;
1788
1789       /* Save the current frame's ID so we can restore it after
1790          evaluating the watchpoint expression on its own frame.  */
1791       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1792          took a frame parameter, so that we didn't have to change the
1793          selected frame.  */
1794       frame_saved = 1;
1795       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1796
1797       fi = frame_find_by_id (b->watchpoint_frame);
1798       within_current_scope = (fi != NULL);
1799       if (within_current_scope)
1800         select_frame (fi);
1801     }
1802
1803   /* We don't free locations.  They are stored in the bp_location array
1804      and update_global_location_list will eventually delete them and
1805      remove breakpoints if needed.  */
1806   b->base.loc = NULL;
1807
1808   if (within_current_scope && reparse)
1809     {
1810       const char *s;
1811
1812       if (b->exp)
1813         {
1814           xfree (b->exp);
1815           b->exp = NULL;
1816         }
1817       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1818       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1819       /* If the meaning of expression itself changed, the old value is
1820          no longer relevant.  We don't want to report a watchpoint hit
1821          to the user when the old value and the new value may actually
1822          be completely different objects.  */
1823       value_free (b->val);
1824       b->val = NULL;
1825       b->val_valid = 0;
1826
1827       /* Note that unlike with breakpoints, the watchpoint's condition
1828          expression is stored in the breakpoint object, not in the
1829          locations (re)created below.  */
1830       if (b->base.cond_string != NULL)
1831         {
1832           if (b->cond_exp != NULL)
1833             {
1834               xfree (b->cond_exp);
1835               b->cond_exp = NULL;
1836             }
1837
1838           s = b->base.cond_string;
1839           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1840         }
1841     }
1842
1843   /* If we failed to parse the expression, for example because
1844      it refers to a global variable in a not-yet-loaded shared library,
1845      don't try to insert watchpoint.  We don't automatically delete
1846      such watchpoint, though, since failure to parse expression
1847      is different from out-of-scope watchpoint.  */
1848   if (!target_has_execution)
1849     {
1850       /* Without execution, memory can't change.  No use to try and
1851          set watchpoint locations.  The watchpoint will be reset when
1852          the target gains execution, through breakpoint_re_set.  */
1853       if (!can_use_hw_watchpoints)
1854         {
1855           if (b->base.ops->works_in_software_mode (&b->base))
1856             b->base.type = bp_watchpoint;
1857           else
1858             error (_("Can't set read/access watchpoint when "
1859                      "hardware watchpoints are disabled."));
1860         }
1861     }
1862   else if (within_current_scope && b->exp)
1863     {
1864       int pc = 0;
1865       struct value *val_chain, *v, *result, *next;
1866       struct program_space *frame_pspace;
1867
1868       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1869
1870       /* Avoid setting b->val if it's already set.  The meaning of
1871          b->val is 'the last value' user saw, and we should update
1872          it only if we reported that last value to user.  As it
1873          happens, the code that reports it updates b->val directly.
1874          We don't keep track of the memory value for masked
1875          watchpoints.  */
1876       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1877         {
1878           b->val = v;
1879           b->val_valid = 1;
1880         }
1881
1882       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1883
1884       /* Look at each value on the value chain.  */
1885       for (v = val_chain; v; v = value_next (v))
1886         {
1887           /* If it's a memory location, and GDB actually needed
1888              its contents to evaluate the expression, then we
1889              must watch it.  If the first value returned is
1890              still lazy, that means an error occurred reading it;
1891              watch it anyway in case it becomes readable.  */
1892           if (VALUE_LVAL (v) == lval_memory
1893               && (v == val_chain || ! value_lazy (v)))
1894             {
1895               struct type *vtype = check_typedef (value_type (v));
1896
1897               /* We only watch structs and arrays if user asked
1898                  for it explicitly, never if they just happen to
1899                  appear in the middle of some value chain.  */
1900               if (v == result
1901                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1902                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1903                 {
1904                   CORE_ADDR addr;
1905                   int type;
1906                   struct bp_location *loc, **tmp;
1907
1908                   addr = value_address (v);
1909                   type = hw_write;
1910                   if (b->base.type == bp_read_watchpoint)
1911                     type = hw_read;
1912                   else if (b->base.type == bp_access_watchpoint)
1913                     type = hw_access;
1914
1915                   loc = allocate_bp_location (&b->base);
1916                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1917                     ;
1918                   *tmp = loc;
1919                   loc->gdbarch = get_type_arch (value_type (v));
1920
1921                   loc->pspace = frame_pspace;
1922                   loc->address = addr;
1923                   loc->length = TYPE_LENGTH (value_type (v));
1924                   loc->watchpoint_type = type;
1925                 }
1926             }
1927         }
1928
1929       /* Change the type of breakpoint between hardware assisted or
1930          an ordinary watchpoint depending on the hardware support
1931          and free hardware slots.  REPARSE is set when the inferior
1932          is started.  */
1933       if (reparse)
1934         {
1935           int reg_cnt;
1936           enum bp_loc_type loc_type;
1937           struct bp_location *bl;
1938
1939           reg_cnt = can_use_hardware_watchpoint (val_chain);
1940
1941           if (reg_cnt)
1942             {
1943               int i, target_resources_ok, other_type_used;
1944               enum bptype type;
1945
1946               /* Use an exact watchpoint when there's only one memory region to be
1947                  watched, and only one debug register is needed to watch it.  */
1948               b->exact = target_exact_watchpoints && reg_cnt == 1;
1949
1950               /* We need to determine how many resources are already
1951                  used for all other hardware watchpoints plus this one
1952                  to see if we still have enough resources to also fit
1953                  this watchpoint in as well.  */
1954
1955               /* If this is a software watchpoint, we try to turn it
1956                  to a hardware one -- count resources as if B was of
1957                  hardware watchpoint type.  */
1958               type = b->base.type;
1959               if (type == bp_watchpoint)
1960                 type = bp_hardware_watchpoint;
1961
1962               /* This watchpoint may or may not have been placed on
1963                  the list yet at this point (it won't be in the list
1964                  if we're trying to create it for the first time,
1965                  through watch_command), so always account for it
1966                  manually.  */
1967
1968               /* Count resources used by all watchpoints except B.  */
1969               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1970
1971               /* Add in the resources needed for B.  */
1972               i += hw_watchpoint_use_count (&b->base);
1973
1974               target_resources_ok
1975                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1976               if (target_resources_ok <= 0)
1977                 {
1978                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1979
1980                   if (target_resources_ok == 0 && !sw_mode)
1981                     error (_("Target does not support this type of "
1982                              "hardware watchpoint."));
1983                   else if (target_resources_ok < 0 && !sw_mode)
1984                     error (_("There are not enough available hardware "
1985                              "resources for this watchpoint."));
1986
1987                   /* Downgrade to software watchpoint.  */
1988                   b->base.type = bp_watchpoint;
1989                 }
1990               else
1991                 {
1992                   /* If this was a software watchpoint, we've just
1993                      found we have enough resources to turn it to a
1994                      hardware watchpoint.  Otherwise, this is a
1995                      nop.  */
1996                   b->base.type = type;
1997                 }
1998             }
1999           else if (!b->base.ops->works_in_software_mode (&b->base))
2000             {
2001               if (!can_use_hw_watchpoints)
2002                 error (_("Can't set read/access watchpoint when "
2003                          "hardware watchpoints are disabled."));
2004               else
2005                 error (_("Expression cannot be implemented with "
2006                          "read/access watchpoint."));
2007             }
2008           else
2009             b->base.type = bp_watchpoint;
2010
2011           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2012                       : bp_loc_hardware_watchpoint);
2013           for (bl = b->base.loc; bl; bl = bl->next)
2014             bl->loc_type = loc_type;
2015         }
2016
2017       for (v = val_chain; v; v = next)
2018         {
2019           next = value_next (v);
2020           if (v != b->val)
2021             value_free (v);
2022         }
2023
2024       /* If a software watchpoint is not watching any memory, then the
2025          above left it without any location set up.  But,
2026          bpstat_stop_status requires a location to be able to report
2027          stops, so make sure there's at least a dummy one.  */
2028       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2029         {
2030           struct breakpoint *base = &b->base;
2031           base->loc = allocate_bp_location (base);
2032           base->loc->pspace = frame_pspace;
2033           base->loc->address = -1;
2034           base->loc->length = -1;
2035           base->loc->watchpoint_type = -1;
2036         }
2037     }
2038   else if (!within_current_scope)
2039     {
2040       printf_filtered (_("\
2041 Watchpoint %d deleted because the program has left the block\n\
2042 in which its expression is valid.\n"),
2043                        b->base.number);
2044       watchpoint_del_at_next_stop (b);
2045     }
2046
2047   /* Restore the selected frame.  */
2048   if (frame_saved)
2049     select_frame (frame_find_by_id (saved_frame_id));
2050 }
2051
2052
2053 /* Returns 1 iff breakpoint location should be
2054    inserted in the inferior.  We don't differentiate the type of BL's owner
2055    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2056    breakpoint_ops is not defined, because in insert_bp_location,
2057    tracepoint's insert_location will not be called.  */
2058 static int
2059 should_be_inserted (struct bp_location *bl)
2060 {
2061   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2062     return 0;
2063
2064   if (bl->owner->disposition == disp_del_at_next_stop)
2065     return 0;
2066
2067   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2068     return 0;
2069
2070   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2071     return 0;
2072
2073   /* This is set for example, when we're attached to the parent of a
2074      vfork, and have detached from the child.  The child is running
2075      free, and we expect it to do an exec or exit, at which point the
2076      OS makes the parent schedulable again (and the target reports
2077      that the vfork is done).  Until the child is done with the shared
2078      memory region, do not insert breakpoints in the parent, otherwise
2079      the child could still trip on the parent's breakpoints.  Since
2080      the parent is blocked anyway, it won't miss any breakpoint.  */
2081   if (bl->pspace->breakpoints_not_allowed)
2082     return 0;
2083
2084   /* Don't insert a breakpoint if we're trying to step past its
2085      location.  */
2086   if ((bl->loc_type == bp_loc_software_breakpoint
2087        || bl->loc_type == bp_loc_hardware_breakpoint)
2088       && stepping_past_instruction_at (bl->pspace->aspace,
2089                                        bl->address))
2090     return 0;
2091
2092   return 1;
2093 }
2094
2095 /* Same as should_be_inserted but does the check assuming
2096    that the location is not duplicated.  */
2097
2098 static int
2099 unduplicated_should_be_inserted (struct bp_location *bl)
2100 {
2101   int result;
2102   const int save_duplicate = bl->duplicate;
2103
2104   bl->duplicate = 0;
2105   result = should_be_inserted (bl);
2106   bl->duplicate = save_duplicate;
2107   return result;
2108 }
2109
2110 /* Parses a conditional described by an expression COND into an
2111    agent expression bytecode suitable for evaluation
2112    by the bytecode interpreter.  Return NULL if there was
2113    any error during parsing.  */
2114
2115 static struct agent_expr *
2116 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2117 {
2118   struct agent_expr *aexpr = NULL;
2119   volatile struct gdb_exception ex;
2120
2121   if (!cond)
2122     return NULL;
2123
2124   /* We don't want to stop processing, so catch any errors
2125      that may show up.  */
2126   TRY_CATCH (ex, RETURN_MASK_ERROR)
2127     {
2128       aexpr = gen_eval_for_expr (scope, cond);
2129     }
2130
2131   if (ex.reason < 0)
2132     {
2133       /* If we got here, it means the condition could not be parsed to a valid
2134          bytecode expression and thus can't be evaluated on the target's side.
2135          It's no use iterating through the conditions.  */
2136       return NULL;
2137     }
2138
2139   /* We have a valid agent expression.  */
2140   return aexpr;
2141 }
2142
2143 /* Based on location BL, create a list of breakpoint conditions to be
2144    passed on to the target.  If we have duplicated locations with different
2145    conditions, we will add such conditions to the list.  The idea is that the
2146    target will evaluate the list of conditions and will only notify GDB when
2147    one of them is true.  */
2148
2149 static void
2150 build_target_condition_list (struct bp_location *bl)
2151 {
2152   struct bp_location **locp = NULL, **loc2p;
2153   int null_condition_or_parse_error = 0;
2154   int modified = bl->needs_update;
2155   struct bp_location *loc;
2156
2157   /* Release conditions left over from a previous insert.  */
2158   VEC_free (agent_expr_p, bl->target_info.conditions);
2159
2160   /* This is only meaningful if the target is
2161      evaluating conditions and if the user has
2162      opted for condition evaluation on the target's
2163      side.  */
2164   if (gdb_evaluates_breakpoint_condition_p ()
2165       || !target_supports_evaluation_of_breakpoint_conditions ())
2166     return;
2167
2168   /* Do a first pass to check for locations with no assigned
2169      conditions or conditions that fail to parse to a valid agent expression
2170      bytecode.  If any of these happen, then it's no use to send conditions
2171      to the target since this location will always trigger and generate a
2172      response back to GDB.  */
2173   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2174     {
2175       loc = (*loc2p);
2176       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2177         {
2178           if (modified)
2179             {
2180               struct agent_expr *aexpr;
2181
2182               /* Re-parse the conditions since something changed.  In that
2183                  case we already freed the condition bytecodes (see
2184                  force_breakpoint_reinsertion).  We just
2185                  need to parse the condition to bytecodes again.  */
2186               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2187               loc->cond_bytecode = aexpr;
2188
2189               /* Check if we managed to parse the conditional expression
2190                  correctly.  If not, we will not send this condition
2191                  to the target.  */
2192               if (aexpr)
2193                 continue;
2194             }
2195
2196           /* If we have a NULL bytecode expression, it means something
2197              went wrong or we have a null condition expression.  */
2198           if (!loc->cond_bytecode)
2199             {
2200               null_condition_or_parse_error = 1;
2201               break;
2202             }
2203         }
2204     }
2205
2206   /* If any of these happened, it means we will have to evaluate the conditions
2207      for the location's address on gdb's side.  It is no use keeping bytecodes
2208      for all the other duplicate locations, thus we free all of them here.
2209
2210      This is so we have a finer control over which locations' conditions are
2211      being evaluated by GDB or the remote stub.  */
2212   if (null_condition_or_parse_error)
2213     {
2214       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2215         {
2216           loc = (*loc2p);
2217           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2218             {
2219               /* Only go as far as the first NULL bytecode is
2220                  located.  */
2221               if (!loc->cond_bytecode)
2222                 return;
2223
2224               free_agent_expr (loc->cond_bytecode);
2225               loc->cond_bytecode = NULL;
2226             }
2227         }
2228     }
2229
2230   /* No NULL conditions or failed bytecode generation.  Build a condition list
2231      for this location's address.  */
2232   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2233     {
2234       loc = (*loc2p);
2235       if (loc->cond
2236           && is_breakpoint (loc->owner)
2237           && loc->pspace->num == bl->pspace->num
2238           && loc->owner->enable_state == bp_enabled
2239           && loc->enabled)
2240         /* Add the condition to the vector.  This will be used later to send the
2241            conditions to the target.  */
2242         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2243                        loc->cond_bytecode);
2244     }
2245
2246   return;
2247 }
2248
2249 /* Parses a command described by string CMD into an agent expression
2250    bytecode suitable for evaluation by the bytecode interpreter.
2251    Return NULL if there was any error during parsing.  */
2252
2253 static struct agent_expr *
2254 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2255 {
2256   struct cleanup *old_cleanups = 0;
2257   struct expression *expr, **argvec;
2258   struct agent_expr *aexpr = NULL;
2259   volatile struct gdb_exception ex;
2260   const char *cmdrest;
2261   const char *format_start, *format_end;
2262   struct format_piece *fpieces;
2263   int nargs;
2264   struct gdbarch *gdbarch = get_current_arch ();
2265
2266   if (!cmd)
2267     return NULL;
2268
2269   cmdrest = cmd;
2270
2271   if (*cmdrest == ',')
2272     ++cmdrest;
2273   cmdrest = skip_spaces_const (cmdrest);
2274
2275   if (*cmdrest++ != '"')
2276     error (_("No format string following the location"));
2277
2278   format_start = cmdrest;
2279
2280   fpieces = parse_format_string (&cmdrest);
2281
2282   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2283
2284   format_end = cmdrest;
2285
2286   if (*cmdrest++ != '"')
2287     error (_("Bad format string, non-terminated '\"'."));
2288   
2289   cmdrest = skip_spaces_const (cmdrest);
2290
2291   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2292     error (_("Invalid argument syntax"));
2293
2294   if (*cmdrest == ',')
2295     cmdrest++;
2296   cmdrest = skip_spaces_const (cmdrest);
2297
2298   /* For each argument, make an expression.  */
2299
2300   argvec = (struct expression **) alloca (strlen (cmd)
2301                                          * sizeof (struct expression *));
2302
2303   nargs = 0;
2304   while (*cmdrest != '\0')
2305     {
2306       const char *cmd1;
2307
2308       cmd1 = cmdrest;
2309       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2310       argvec[nargs++] = expr;
2311       cmdrest = cmd1;
2312       if (*cmdrest == ',')
2313         ++cmdrest;
2314     }
2315
2316   /* We don't want to stop processing, so catch any errors
2317      that may show up.  */
2318   TRY_CATCH (ex, RETURN_MASK_ERROR)
2319     {
2320       aexpr = gen_printf (scope, gdbarch, 0, 0,
2321                           format_start, format_end - format_start,
2322                           fpieces, nargs, argvec);
2323     }
2324
2325   do_cleanups (old_cleanups);
2326
2327   if (ex.reason < 0)
2328     {
2329       /* If we got here, it means the command could not be parsed to a valid
2330          bytecode expression and thus can't be evaluated on the target's side.
2331          It's no use iterating through the other commands.  */
2332       return NULL;
2333     }
2334
2335   /* We have a valid agent expression, return it.  */
2336   return aexpr;
2337 }
2338
2339 /* Based on location BL, create a list of breakpoint commands to be
2340    passed on to the target.  If we have duplicated locations with
2341    different commands, we will add any such to the list.  */
2342
2343 static void
2344 build_target_command_list (struct bp_location *bl)
2345 {
2346   struct bp_location **locp = NULL, **loc2p;
2347   int null_command_or_parse_error = 0;
2348   int modified = bl->needs_update;
2349   struct bp_location *loc;
2350
2351   /* Release commands left over from a previous insert.  */
2352   VEC_free (agent_expr_p, bl->target_info.tcommands);
2353
2354   if (!target_can_run_breakpoint_commands ())
2355     return;
2356
2357   /* For now, limit to agent-style dprintf breakpoints.  */
2358   if (dprintf_style != dprintf_style_agent)
2359     return;
2360
2361   /* For now, if we have any duplicate location that isn't a dprintf,
2362      don't install the target-side commands, as that would make the
2363      breakpoint not be reported to the core, and we'd lose
2364      control.  */
2365   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2366     {
2367       loc = (*loc2p);
2368       if (is_breakpoint (loc->owner)
2369           && loc->pspace->num == bl->pspace->num
2370           && loc->owner->type != bp_dprintf)
2371         return;
2372     }
2373
2374   /* Do a first pass to check for locations with no assigned
2375      conditions or conditions that fail to parse to a valid agent expression
2376      bytecode.  If any of these happen, then it's no use to send conditions
2377      to the target since this location will always trigger and generate a
2378      response back to GDB.  */
2379   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2380     {
2381       loc = (*loc2p);
2382       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2383         {
2384           if (modified)
2385             {
2386               struct agent_expr *aexpr;
2387
2388               /* Re-parse the commands since something changed.  In that
2389                  case we already freed the command bytecodes (see
2390                  force_breakpoint_reinsertion).  We just
2391                  need to parse the command to bytecodes again.  */
2392               aexpr = parse_cmd_to_aexpr (bl->address,
2393                                           loc->owner->extra_string);
2394               loc->cmd_bytecode = aexpr;
2395
2396               if (!aexpr)
2397                 continue;
2398             }
2399
2400           /* If we have a NULL bytecode expression, it means something
2401              went wrong or we have a null command expression.  */
2402           if (!loc->cmd_bytecode)
2403             {
2404               null_command_or_parse_error = 1;
2405               break;
2406             }
2407         }
2408     }
2409
2410   /* If anything failed, then we're not doing target-side commands,
2411      and so clean up.  */
2412   if (null_command_or_parse_error)
2413     {
2414       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2415         {
2416           loc = (*loc2p);
2417           if (is_breakpoint (loc->owner)
2418               && loc->pspace->num == bl->pspace->num)
2419             {
2420               /* Only go as far as the first NULL bytecode is
2421                  located.  */
2422               if (loc->cmd_bytecode == NULL)
2423                 return;
2424
2425               free_agent_expr (loc->cmd_bytecode);
2426               loc->cmd_bytecode = NULL;
2427             }
2428         }
2429     }
2430
2431   /* No NULL commands or failed bytecode generation.  Build a command list
2432      for this location's address.  */
2433   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2434     {
2435       loc = (*loc2p);
2436       if (loc->owner->extra_string
2437           && is_breakpoint (loc->owner)
2438           && loc->pspace->num == bl->pspace->num
2439           && loc->owner->enable_state == bp_enabled
2440           && loc->enabled)
2441         /* Add the command to the vector.  This will be used later
2442            to send the commands to the target.  */
2443         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2444                        loc->cmd_bytecode);
2445     }
2446
2447   bl->target_info.persist = 0;
2448   /* Maybe flag this location as persistent.  */
2449   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2450     bl->target_info.persist = 1;
2451 }
2452
2453 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2454    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2455    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2456    Returns 0 for success, 1 if the bp_location type is not supported or
2457    -1 for failure.
2458
2459    NOTE drow/2003-09-09: This routine could be broken down to an
2460    object-style method for each breakpoint or catchpoint type.  */
2461 static int
2462 insert_bp_location (struct bp_location *bl,
2463                     struct ui_file *tmp_error_stream,
2464                     int *disabled_breaks,
2465                     int *hw_breakpoint_error,
2466                     int *hw_bp_error_explained_already)
2467 {
2468   enum errors bp_err = GDB_NO_ERROR;
2469   const char *bp_err_message = NULL;
2470   volatile struct gdb_exception e;
2471
2472   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2473     return 0;
2474
2475   /* Note we don't initialize bl->target_info, as that wipes out
2476      the breakpoint location's shadow_contents if the breakpoint
2477      is still inserted at that location.  This in turn breaks
2478      target_read_memory which depends on these buffers when
2479      a memory read is requested at the breakpoint location:
2480      Once the target_info has been wiped, we fail to see that
2481      we have a breakpoint inserted at that address and thus
2482      read the breakpoint instead of returning the data saved in
2483      the breakpoint location's shadow contents.  */
2484   bl->target_info.placed_address = bl->address;
2485   bl->target_info.placed_address_space = bl->pspace->aspace;
2486   bl->target_info.length = bl->length;
2487
2488   /* When working with target-side conditions, we must pass all the conditions
2489      for the same breakpoint address down to the target since GDB will not
2490      insert those locations.  With a list of breakpoint conditions, the target
2491      can decide when to stop and notify GDB.  */
2492
2493   if (is_breakpoint (bl->owner))
2494     {
2495       build_target_condition_list (bl);
2496       build_target_command_list (bl);
2497       /* Reset the modification marker.  */
2498       bl->needs_update = 0;
2499     }
2500
2501   if (bl->loc_type == bp_loc_software_breakpoint
2502       || bl->loc_type == bp_loc_hardware_breakpoint)
2503     {
2504       if (bl->owner->type != bp_hardware_breakpoint)
2505         {
2506           /* If the explicitly specified breakpoint type
2507              is not hardware breakpoint, check the memory map to see
2508              if the breakpoint address is in read only memory or not.
2509
2510              Two important cases are:
2511              - location type is not hardware breakpoint, memory
2512              is readonly.  We change the type of the location to
2513              hardware breakpoint.
2514              - location type is hardware breakpoint, memory is
2515              read-write.  This means we've previously made the
2516              location hardware one, but then the memory map changed,
2517              so we undo.
2518              
2519              When breakpoints are removed, remove_breakpoints will use
2520              location types we've just set here, the only possible
2521              problem is that memory map has changed during running
2522              program, but it's not going to work anyway with current
2523              gdb.  */
2524           struct mem_region *mr 
2525             = lookup_mem_region (bl->target_info.placed_address);
2526           
2527           if (mr)
2528             {
2529               if (automatic_hardware_breakpoints)
2530                 {
2531                   enum bp_loc_type new_type;
2532                   
2533                   if (mr->attrib.mode != MEM_RW)
2534                     new_type = bp_loc_hardware_breakpoint;
2535                   else 
2536                     new_type = bp_loc_software_breakpoint;
2537                   
2538                   if (new_type != bl->loc_type)
2539                     {
2540                       static int said = 0;
2541
2542                       bl->loc_type = new_type;
2543                       if (!said)
2544                         {
2545                           fprintf_filtered (gdb_stdout,
2546                                             _("Note: automatically using "
2547                                               "hardware breakpoints for "
2548                                               "read-only addresses.\n"));
2549                           said = 1;
2550                         }
2551                     }
2552                 }
2553               else if (bl->loc_type == bp_loc_software_breakpoint
2554                        && mr->attrib.mode != MEM_RW)        
2555                 warning (_("cannot set software breakpoint "
2556                            "at readonly address %s"),
2557                          paddress (bl->gdbarch, bl->address));
2558             }
2559         }
2560         
2561       /* First check to see if we have to handle an overlay.  */
2562       if (overlay_debugging == ovly_off
2563           || bl->section == NULL
2564           || !(section_is_overlay (bl->section)))
2565         {
2566           /* No overlay handling: just set the breakpoint.  */
2567           TRY_CATCH (e, RETURN_MASK_ALL)
2568             {
2569               int val;
2570
2571               val = bl->owner->ops->insert_location (bl);
2572               if (val)
2573                 bp_err = GENERIC_ERROR;
2574             }
2575           if (e.reason < 0)
2576             {
2577               bp_err = e.error;
2578               bp_err_message = e.message;
2579             }
2580         }
2581       else
2582         {
2583           /* This breakpoint is in an overlay section.
2584              Shall we set a breakpoint at the LMA?  */
2585           if (!overlay_events_enabled)
2586             {
2587               /* Yes -- overlay event support is not active, 
2588                  so we must try to set a breakpoint at the LMA.
2589                  This will not work for a hardware breakpoint.  */
2590               if (bl->loc_type == bp_loc_hardware_breakpoint)
2591                 warning (_("hardware breakpoint %d not supported in overlay!"),
2592                          bl->owner->number);
2593               else
2594                 {
2595                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2596                                                              bl->section);
2597                   /* Set a software (trap) breakpoint at the LMA.  */
2598                   bl->overlay_target_info = bl->target_info;
2599                   bl->overlay_target_info.placed_address = addr;
2600
2601                   /* No overlay handling: just set the breakpoint.  */
2602                   TRY_CATCH (e, RETURN_MASK_ALL)
2603                     {
2604                       int val;
2605
2606                       val = target_insert_breakpoint (bl->gdbarch,
2607                                                       &bl->overlay_target_info);
2608                       if (val)
2609                         bp_err = GENERIC_ERROR;
2610                     }
2611                   if (e.reason < 0)
2612                     {
2613                       bp_err = e.error;
2614                       bp_err_message = e.message;
2615                     }
2616
2617                   if (bp_err != GDB_NO_ERROR)
2618                     fprintf_unfiltered (tmp_error_stream,
2619                                         "Overlay breakpoint %d "
2620                                         "failed: in ROM?\n",
2621                                         bl->owner->number);
2622                 }
2623             }
2624           /* Shall we set a breakpoint at the VMA? */
2625           if (section_is_mapped (bl->section))
2626             {
2627               /* Yes.  This overlay section is mapped into memory.  */
2628               TRY_CATCH (e, RETURN_MASK_ALL)
2629                 {
2630                   int val;
2631
2632                   val = bl->owner->ops->insert_location (bl);
2633                   if (val)
2634                     bp_err = GENERIC_ERROR;
2635                 }
2636               if (e.reason < 0)
2637                 {
2638                   bp_err = e.error;
2639                   bp_err_message = e.message;
2640                 }
2641             }
2642           else
2643             {
2644               /* No.  This breakpoint will not be inserted.  
2645                  No error, but do not mark the bp as 'inserted'.  */
2646               return 0;
2647             }
2648         }
2649
2650       if (bp_err != GDB_NO_ERROR)
2651         {
2652           /* Can't set the breakpoint.  */
2653
2654           /* In some cases, we might not be able to insert a
2655              breakpoint in a shared library that has already been
2656              removed, but we have not yet processed the shlib unload
2657              event.  Unfortunately, some targets that implement
2658              breakpoint insertion themselves can't tell why the
2659              breakpoint insertion failed (e.g., the remote target
2660              doesn't define error codes), so we must treat generic
2661              errors as memory errors.  */
2662           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2663               && bl->loc_type == bp_loc_software_breakpoint
2664               && (solib_name_from_address (bl->pspace, bl->address)
2665                   || userloaded_objfile_contains_address_p (bl->pspace,
2666                                                             bl->address)))
2667             {
2668               /* See also: disable_breakpoints_in_shlibs.  */
2669               bl->shlib_disabled = 1;
2670               observer_notify_breakpoint_modified (bl->owner);
2671               if (!*disabled_breaks)
2672                 {
2673                   fprintf_unfiltered (tmp_error_stream, 
2674                                       "Cannot insert breakpoint %d.\n", 
2675                                       bl->owner->number);
2676                   fprintf_unfiltered (tmp_error_stream, 
2677                                       "Temporarily disabling shared "
2678                                       "library breakpoints:\n");
2679                 }
2680               *disabled_breaks = 1;
2681               fprintf_unfiltered (tmp_error_stream,
2682                                   "breakpoint #%d\n", bl->owner->number);
2683               return 0;
2684             }
2685           else
2686             {
2687               if (bl->loc_type == bp_loc_hardware_breakpoint)
2688                 {
2689                   *hw_breakpoint_error = 1;
2690                   *hw_bp_error_explained_already = bp_err_message != NULL;
2691                   fprintf_unfiltered (tmp_error_stream,
2692                                       "Cannot insert hardware breakpoint %d%s",
2693                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2694                   if (bp_err_message != NULL)
2695                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2696                 }
2697               else
2698                 {
2699                   if (bp_err_message == NULL)
2700                     {
2701                       char *message
2702                         = memory_error_message (TARGET_XFER_E_IO,
2703                                                 bl->gdbarch, bl->address);
2704                       struct cleanup *old_chain = make_cleanup (xfree, message);
2705
2706                       fprintf_unfiltered (tmp_error_stream,
2707                                           "Cannot insert breakpoint %d.\n"
2708                                           "%s\n",
2709                                           bl->owner->number, message);
2710                       do_cleanups (old_chain);
2711                     }
2712                   else
2713                     {
2714                       fprintf_unfiltered (tmp_error_stream,
2715                                           "Cannot insert breakpoint %d: %s\n",
2716                                           bl->owner->number,
2717                                           bp_err_message);
2718                     }
2719                 }
2720               return 1;
2721
2722             }
2723         }
2724       else
2725         bl->inserted = 1;
2726
2727       return 0;
2728     }
2729
2730   else if (bl->loc_type == bp_loc_hardware_watchpoint
2731            /* NOTE drow/2003-09-08: This state only exists for removing
2732               watchpoints.  It's not clear that it's necessary...  */
2733            && bl->owner->disposition != disp_del_at_next_stop)
2734     {
2735       int val;
2736
2737       gdb_assert (bl->owner->ops != NULL
2738                   && bl->owner->ops->insert_location != NULL);
2739
2740       val = bl->owner->ops->insert_location (bl);
2741
2742       /* If trying to set a read-watchpoint, and it turns out it's not
2743          supported, try emulating one with an access watchpoint.  */
2744       if (val == 1 && bl->watchpoint_type == hw_read)
2745         {
2746           struct bp_location *loc, **loc_temp;
2747
2748           /* But don't try to insert it, if there's already another
2749              hw_access location that would be considered a duplicate
2750              of this one.  */
2751           ALL_BP_LOCATIONS (loc, loc_temp)
2752             if (loc != bl
2753                 && loc->watchpoint_type == hw_access
2754                 && watchpoint_locations_match (bl, loc))
2755               {
2756                 bl->duplicate = 1;
2757                 bl->inserted = 1;
2758                 bl->target_info = loc->target_info;
2759                 bl->watchpoint_type = hw_access;
2760                 val = 0;
2761                 break;
2762               }
2763
2764           if (val == 1)
2765             {
2766               bl->watchpoint_type = hw_access;
2767               val = bl->owner->ops->insert_location (bl);
2768
2769               if (val)
2770                 /* Back to the original value.  */
2771                 bl->watchpoint_type = hw_read;
2772             }
2773         }
2774
2775       bl->inserted = (val == 0);
2776     }
2777
2778   else if (bl->owner->type == bp_catchpoint)
2779     {
2780       int val;
2781
2782       gdb_assert (bl->owner->ops != NULL
2783                   && bl->owner->ops->insert_location != NULL);
2784
2785       val = bl->owner->ops->insert_location (bl);
2786       if (val)
2787         {
2788           bl->owner->enable_state = bp_disabled;
2789
2790           if (val == 1)
2791             warning (_("\
2792 Error inserting catchpoint %d: Your system does not support this type\n\
2793 of catchpoint."), bl->owner->number);
2794           else
2795             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2796         }
2797
2798       bl->inserted = (val == 0);
2799
2800       /* We've already printed an error message if there was a problem
2801          inserting this catchpoint, and we've disabled the catchpoint,
2802          so just return success.  */
2803       return 0;
2804     }
2805
2806   return 0;
2807 }
2808
2809 /* This function is called when program space PSPACE is about to be
2810    deleted.  It takes care of updating breakpoints to not reference
2811    PSPACE anymore.  */
2812
2813 void
2814 breakpoint_program_space_exit (struct program_space *pspace)
2815 {
2816   struct breakpoint *b, *b_temp;
2817   struct bp_location *loc, **loc_temp;
2818
2819   /* Remove any breakpoint that was set through this program space.  */
2820   ALL_BREAKPOINTS_SAFE (b, b_temp)
2821     {
2822       if (b->pspace == pspace)
2823         delete_breakpoint (b);
2824     }
2825
2826   /* Breakpoints set through other program spaces could have locations
2827      bound to PSPACE as well.  Remove those.  */
2828   ALL_BP_LOCATIONS (loc, loc_temp)
2829     {
2830       struct bp_location *tmp;
2831
2832       if (loc->pspace == pspace)
2833         {
2834           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2835           if (loc->owner->loc == loc)
2836             loc->owner->loc = loc->next;
2837           else
2838             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2839               if (tmp->next == loc)
2840                 {
2841                   tmp->next = loc->next;
2842                   break;
2843                 }
2844         }
2845     }
2846
2847   /* Now update the global location list to permanently delete the
2848      removed locations above.  */
2849   update_global_location_list (0);
2850 }
2851
2852 /* Make sure all breakpoints are inserted in inferior.
2853    Throws exception on any error.
2854    A breakpoint that is already inserted won't be inserted
2855    again, so calling this function twice is safe.  */
2856 void
2857 insert_breakpoints (void)
2858 {
2859   struct breakpoint *bpt;
2860
2861   ALL_BREAKPOINTS (bpt)
2862     if (is_hardware_watchpoint (bpt))
2863       {
2864         struct watchpoint *w = (struct watchpoint *) bpt;
2865
2866         update_watchpoint (w, 0 /* don't reparse.  */);
2867       }
2868
2869   update_global_location_list (1);
2870
2871   /* update_global_location_list does not insert breakpoints when
2872      always_inserted_mode is not enabled.  Explicitly insert them
2873      now.  */
2874   if (!breakpoints_always_inserted_mode ())
2875     insert_breakpoint_locations ();
2876 }
2877
2878 /* Invoke CALLBACK for each of bp_location.  */
2879
2880 void
2881 iterate_over_bp_locations (walk_bp_location_callback callback)
2882 {
2883   struct bp_location *loc, **loc_tmp;
2884
2885   ALL_BP_LOCATIONS (loc, loc_tmp)
2886     {
2887       callback (loc, NULL);
2888     }
2889 }
2890
2891 /* This is used when we need to synch breakpoint conditions between GDB and the
2892    target.  It is the case with deleting and disabling of breakpoints when using
2893    always-inserted mode.  */
2894
2895 static void
2896 update_inserted_breakpoint_locations (void)
2897 {
2898   struct bp_location *bl, **blp_tmp;
2899   int error_flag = 0;
2900   int val = 0;
2901   int disabled_breaks = 0;
2902   int hw_breakpoint_error = 0;
2903   int hw_bp_details_reported = 0;
2904
2905   struct ui_file *tmp_error_stream = mem_fileopen ();
2906   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2907
2908   /* Explicitly mark the warning -- this will only be printed if
2909      there was an error.  */
2910   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2911
2912   save_current_space_and_thread ();
2913
2914   ALL_BP_LOCATIONS (bl, blp_tmp)
2915     {
2916       /* We only want to update software breakpoints and hardware
2917          breakpoints.  */
2918       if (!is_breakpoint (bl->owner))
2919         continue;
2920
2921       /* We only want to update locations that are already inserted
2922          and need updating.  This is to avoid unwanted insertion during
2923          deletion of breakpoints.  */
2924       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2925         continue;
2926
2927       switch_to_program_space_and_thread (bl->pspace);
2928
2929       /* For targets that support global breakpoints, there's no need
2930          to select an inferior to insert breakpoint to.  In fact, even
2931          if we aren't attached to any process yet, we should still
2932          insert breakpoints.  */
2933       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2934           && ptid_equal (inferior_ptid, null_ptid))
2935         continue;
2936
2937       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2938                                     &hw_breakpoint_error, &hw_bp_details_reported);
2939       if (val)
2940         error_flag = val;
2941     }
2942
2943   if (error_flag)
2944     {
2945       target_terminal_ours_for_output ();
2946       error_stream (tmp_error_stream);
2947     }
2948
2949   do_cleanups (cleanups);
2950 }
2951
2952 /* Used when starting or continuing the program.  */
2953
2954 static void
2955 insert_breakpoint_locations (void)
2956 {
2957   struct breakpoint *bpt;
2958   struct bp_location *bl, **blp_tmp;
2959   int error_flag = 0;
2960   int val = 0;
2961   int disabled_breaks = 0;
2962   int hw_breakpoint_error = 0;
2963   int hw_bp_error_explained_already = 0;
2964
2965   struct ui_file *tmp_error_stream = mem_fileopen ();
2966   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2967   
2968   /* Explicitly mark the warning -- this will only be printed if
2969      there was an error.  */
2970   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2971
2972   save_current_space_and_thread ();
2973
2974   ALL_BP_LOCATIONS (bl, blp_tmp)
2975     {
2976       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2977         continue;
2978
2979       /* There is no point inserting thread-specific breakpoints if
2980          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2981          has BL->OWNER always non-NULL.  */
2982       if (bl->owner->thread != -1
2983           && !valid_thread_id (bl->owner->thread))
2984         continue;
2985
2986       switch_to_program_space_and_thread (bl->pspace);
2987
2988       /* For targets that support global breakpoints, there's no need
2989          to select an inferior to insert breakpoint to.  In fact, even
2990          if we aren't attached to any process yet, we should still
2991          insert breakpoints.  */
2992       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2993           && ptid_equal (inferior_ptid, null_ptid))
2994         continue;
2995
2996       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2997                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2998       if (val)
2999         error_flag = val;
3000     }
3001
3002   /* If we failed to insert all locations of a watchpoint, remove
3003      them, as half-inserted watchpoint is of limited use.  */
3004   ALL_BREAKPOINTS (bpt)  
3005     {
3006       int some_failed = 0;
3007       struct bp_location *loc;
3008
3009       if (!is_hardware_watchpoint (bpt))
3010         continue;
3011
3012       if (!breakpoint_enabled (bpt))
3013         continue;
3014
3015       if (bpt->disposition == disp_del_at_next_stop)
3016         continue;
3017       
3018       for (loc = bpt->loc; loc; loc = loc->next)
3019         if (!loc->inserted && should_be_inserted (loc))
3020           {
3021             some_failed = 1;
3022             break;
3023           }
3024       if (some_failed)
3025         {
3026           for (loc = bpt->loc; loc; loc = loc->next)
3027             if (loc->inserted)
3028               remove_breakpoint (loc, mark_uninserted);
3029
3030           hw_breakpoint_error = 1;
3031           fprintf_unfiltered (tmp_error_stream,
3032                               "Could not insert hardware watchpoint %d.\n", 
3033                               bpt->number);
3034           error_flag = -1;
3035         }
3036     }
3037
3038   if (error_flag)
3039     {
3040       /* If a hardware breakpoint or watchpoint was inserted, add a
3041          message about possibly exhausted resources.  */
3042       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3043         {
3044           fprintf_unfiltered (tmp_error_stream, 
3045                               "Could not insert hardware breakpoints:\n\
3046 You may have requested too many hardware breakpoints/watchpoints.\n");
3047         }
3048       target_terminal_ours_for_output ();
3049       error_stream (tmp_error_stream);
3050     }
3051
3052   do_cleanups (cleanups);
3053 }
3054
3055 /* Used when the program stops.
3056    Returns zero if successful, or non-zero if there was a problem
3057    removing a breakpoint location.  */
3058
3059 int
3060 remove_breakpoints (void)
3061 {
3062   struct bp_location *bl, **blp_tmp;
3063   int val = 0;
3064
3065   ALL_BP_LOCATIONS (bl, blp_tmp)
3066   {
3067     if (bl->inserted && !is_tracepoint (bl->owner))
3068       val |= remove_breakpoint (bl, mark_uninserted);
3069   }
3070   return val;
3071 }
3072
3073 /* When a thread exits, remove breakpoints that are related to
3074    that thread.  */
3075
3076 static void
3077 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3078 {
3079   struct breakpoint *b, *b_tmp;
3080
3081   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3082     {
3083       if (b->thread == tp->num && user_breakpoint_p (b))
3084         {
3085           b->disposition = disp_del_at_next_stop;
3086
3087           printf_filtered (_("\
3088 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3089                           b->number, tp->num);
3090
3091           /* Hide it from the user.  */
3092           b->number = 0;
3093        }
3094     }
3095 }
3096
3097 /* Remove breakpoints of process PID.  */
3098
3099 int
3100 remove_breakpoints_pid (int pid)
3101 {
3102   struct bp_location *bl, **blp_tmp;
3103   int val;
3104   struct inferior *inf = find_inferior_pid (pid);
3105
3106   ALL_BP_LOCATIONS (bl, blp_tmp)
3107   {
3108     if (bl->pspace != inf->pspace)
3109       continue;
3110
3111     if (bl->owner->type == bp_dprintf)
3112       continue;
3113
3114     if (bl->inserted)
3115       {
3116         val = remove_breakpoint (bl, mark_uninserted);
3117         if (val != 0)
3118           return val;
3119       }
3120   }
3121   return 0;
3122 }
3123
3124 int
3125 reattach_breakpoints (int pid)
3126 {
3127   struct cleanup *old_chain;
3128   struct bp_location *bl, **blp_tmp;
3129   int val;
3130   struct ui_file *tmp_error_stream;
3131   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3132   struct inferior *inf;
3133   struct thread_info *tp;
3134
3135   tp = any_live_thread_of_process (pid);
3136   if (tp == NULL)
3137     return 1;
3138
3139   inf = find_inferior_pid (pid);
3140   old_chain = save_inferior_ptid ();
3141
3142   inferior_ptid = tp->ptid;
3143
3144   tmp_error_stream = mem_fileopen ();
3145   make_cleanup_ui_file_delete (tmp_error_stream);
3146
3147   ALL_BP_LOCATIONS (bl, blp_tmp)
3148   {
3149     if (bl->pspace != inf->pspace)
3150       continue;
3151
3152     if (bl->inserted)
3153       {
3154         bl->inserted = 0;
3155         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3156         if (val != 0)
3157           {
3158             do_cleanups (old_chain);
3159             return val;
3160           }
3161       }
3162   }
3163   do_cleanups (old_chain);
3164   return 0;
3165 }
3166
3167 static int internal_breakpoint_number = -1;
3168
3169 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3170    If INTERNAL is non-zero, the breakpoint number will be populated
3171    from internal_breakpoint_number and that variable decremented.
3172    Otherwise the breakpoint number will be populated from
3173    breakpoint_count and that value incremented.  Internal breakpoints
3174    do not set the internal var bpnum.  */
3175 static void
3176 set_breakpoint_number (int internal, struct breakpoint *b)
3177 {
3178   if (internal)
3179     b->number = internal_breakpoint_number--;
3180   else
3181     {
3182       set_breakpoint_count (breakpoint_count + 1);
3183       b->number = breakpoint_count;
3184     }
3185 }
3186
3187 static struct breakpoint *
3188 create_internal_breakpoint (struct gdbarch *gdbarch,
3189                             CORE_ADDR address, enum bptype type,
3190                             const struct breakpoint_ops *ops)
3191 {
3192   struct symtab_and_line sal;
3193   struct breakpoint *b;
3194
3195   init_sal (&sal);              /* Initialize to zeroes.  */
3196
3197   sal.pc = address;
3198   sal.section = find_pc_overlay (sal.pc);
3199   sal.pspace = current_program_space;
3200
3201   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3202   b->number = internal_breakpoint_number--;
3203   b->disposition = disp_donttouch;
3204
3205   return b;
3206 }
3207
3208 static const char *const longjmp_names[] =
3209   {
3210     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3211   };
3212 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3213
3214 /* Per-objfile data private to breakpoint.c.  */
3215 struct breakpoint_objfile_data
3216 {
3217   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3218   struct bound_minimal_symbol overlay_msym;
3219
3220   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3221   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3222
3223   /* True if we have looked for longjmp probes.  */
3224   int longjmp_searched;
3225
3226   /* SystemTap probe points for longjmp (if any).  */
3227   VEC (probe_p) *longjmp_probes;
3228
3229   /* Minimal symbol for "std::terminate()" (if any).  */
3230   struct bound_minimal_symbol terminate_msym;
3231
3232   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3233   struct bound_minimal_symbol exception_msym;
3234
3235   /* True if we have looked for exception probes.  */
3236   int exception_searched;
3237
3238   /* SystemTap probe points for unwinding (if any).  */
3239   VEC (probe_p) *exception_probes;
3240 };
3241
3242 static const struct objfile_data *breakpoint_objfile_key;
3243
3244 /* Minimal symbol not found sentinel.  */
3245 static struct minimal_symbol msym_not_found;
3246
3247 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3248
3249 static int
3250 msym_not_found_p (const struct minimal_symbol *msym)
3251 {
3252   return msym == &msym_not_found;
3253 }
3254
3255 /* Return per-objfile data needed by breakpoint.c.
3256    Allocate the data if necessary.  */
3257
3258 static struct breakpoint_objfile_data *
3259 get_breakpoint_objfile_data (struct objfile *objfile)
3260 {
3261   struct breakpoint_objfile_data *bp_objfile_data;
3262
3263   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3264   if (bp_objfile_data == NULL)
3265     {
3266       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3267                                        sizeof (*bp_objfile_data));
3268
3269       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3270       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3271     }
3272   return bp_objfile_data;
3273 }
3274
3275 static void
3276 free_breakpoint_probes (struct objfile *obj, void *data)
3277 {
3278   struct breakpoint_objfile_data *bp_objfile_data = data;
3279
3280   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3281   VEC_free (probe_p, bp_objfile_data->exception_probes);
3282 }
3283
3284 static void
3285 create_overlay_event_breakpoint (void)
3286 {
3287   struct objfile *objfile;
3288   const char *const func_name = "_ovly_debug_event";
3289
3290   ALL_OBJFILES (objfile)
3291     {
3292       struct breakpoint *b;
3293       struct breakpoint_objfile_data *bp_objfile_data;
3294       CORE_ADDR addr;
3295
3296       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3297
3298       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3299         continue;
3300
3301       if (bp_objfile_data->overlay_msym.minsym == NULL)
3302         {
3303           struct bound_minimal_symbol m;
3304
3305           m = lookup_minimal_symbol_text (func_name, objfile);
3306           if (m.minsym == NULL)
3307             {
3308               /* Avoid future lookups in this objfile.  */
3309               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3310               continue;
3311             }
3312           bp_objfile_data->overlay_msym = m;
3313         }
3314
3315       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3316       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3317                                       bp_overlay_event,
3318                                       &internal_breakpoint_ops);
3319       b->addr_string = xstrdup (func_name);
3320
3321       if (overlay_debugging == ovly_auto)
3322         {
3323           b->enable_state = bp_enabled;
3324           overlay_events_enabled = 1;
3325         }
3326       else
3327        {
3328          b->enable_state = bp_disabled;
3329          overlay_events_enabled = 0;
3330        }
3331     }
3332   update_global_location_list (1);
3333 }
3334
3335 static void
3336 create_longjmp_master_breakpoint (void)
3337 {
3338   struct program_space *pspace;
3339   struct cleanup *old_chain;
3340
3341   old_chain = save_current_program_space ();
3342
3343   ALL_PSPACES (pspace)
3344   {
3345     struct objfile *objfile;
3346
3347     set_current_program_space (pspace);
3348
3349     ALL_OBJFILES (objfile)
3350     {
3351       int i;
3352       struct gdbarch *gdbarch;
3353       struct breakpoint_objfile_data *bp_objfile_data;
3354
3355       gdbarch = get_objfile_arch (objfile);
3356
3357       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3358
3359       if (!bp_objfile_data->longjmp_searched)
3360         {
3361           VEC (probe_p) *ret;
3362
3363           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3364           if (ret != NULL)
3365             {
3366               /* We are only interested in checking one element.  */
3367               struct probe *p = VEC_index (probe_p, ret, 0);
3368
3369               if (!can_evaluate_probe_arguments (p))
3370                 {
3371                   /* We cannot use the probe interface here, because it does
3372                      not know how to evaluate arguments.  */
3373                   VEC_free (probe_p, ret);
3374                   ret = NULL;
3375                 }
3376             }
3377           bp_objfile_data->longjmp_probes = ret;
3378           bp_objfile_data->longjmp_searched = 1;
3379         }
3380
3381       if (bp_objfile_data->longjmp_probes != NULL)
3382         {
3383           int i;
3384           struct probe *probe;
3385           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3386
3387           for (i = 0;
3388                VEC_iterate (probe_p,
3389                             bp_objfile_data->longjmp_probes,
3390                             i, probe);
3391                ++i)
3392             {
3393               struct breakpoint *b;
3394
3395               b = create_internal_breakpoint (gdbarch,
3396                                               get_probe_address (probe,
3397                                                                  objfile),
3398                                               bp_longjmp_master,
3399                                               &internal_breakpoint_ops);
3400               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3401               b->enable_state = bp_disabled;
3402             }
3403
3404           continue;
3405         }
3406
3407       if (!gdbarch_get_longjmp_target_p (gdbarch))
3408         continue;
3409
3410       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3411         {
3412           struct breakpoint *b;
3413           const char *func_name;
3414           CORE_ADDR addr;
3415
3416           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3417             continue;
3418
3419           func_name = longjmp_names[i];
3420           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3421             {
3422               struct bound_minimal_symbol m;
3423
3424               m = lookup_minimal_symbol_text (func_name, objfile);
3425               if (m.minsym == NULL)
3426                 {
3427                   /* Prevent future lookups in this objfile.  */
3428                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3429                   continue;
3430                 }
3431               bp_objfile_data->longjmp_msym[i] = m;
3432             }
3433
3434           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3435           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3436                                           &internal_breakpoint_ops);
3437           b->addr_string = xstrdup (func_name);
3438           b->enable_state = bp_disabled;
3439         }
3440     }
3441   }
3442   update_global_location_list (1);
3443
3444   do_cleanups (old_chain);
3445 }
3446
3447 /* Create a master std::terminate breakpoint.  */
3448 static void
3449 create_std_terminate_master_breakpoint (void)
3450 {
3451   struct program_space *pspace;
3452   struct cleanup *old_chain;
3453   const char *const func_name = "std::terminate()";
3454
3455   old_chain = save_current_program_space ();
3456
3457   ALL_PSPACES (pspace)
3458   {
3459     struct objfile *objfile;
3460     CORE_ADDR addr;
3461
3462     set_current_program_space (pspace);
3463
3464     ALL_OBJFILES (objfile)
3465     {
3466       struct breakpoint *b;
3467       struct breakpoint_objfile_data *bp_objfile_data;
3468
3469       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3470
3471       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3472         continue;
3473
3474       if (bp_objfile_data->terminate_msym.minsym == NULL)
3475         {
3476           struct bound_minimal_symbol m;
3477
3478           m = lookup_minimal_symbol (func_name, NULL, objfile);
3479           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3480                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3481             {
3482               /* Prevent future lookups in this objfile.  */
3483               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3484               continue;
3485             }
3486           bp_objfile_data->terminate_msym = m;
3487         }
3488
3489       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3490       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3491                                       bp_std_terminate_master,
3492                                       &internal_breakpoint_ops);
3493       b->addr_string = xstrdup (func_name);
3494       b->enable_state = bp_disabled;
3495     }
3496   }
3497
3498   update_global_location_list (1);
3499
3500   do_cleanups (old_chain);
3501 }
3502
3503 /* Install a master breakpoint on the unwinder's debug hook.  */
3504
3505 static void
3506 create_exception_master_breakpoint (void)
3507 {
3508   struct objfile *objfile;
3509   const char *const func_name = "_Unwind_DebugHook";
3510
3511   ALL_OBJFILES (objfile)
3512     {
3513       struct breakpoint *b;
3514       struct gdbarch *gdbarch;
3515       struct breakpoint_objfile_data *bp_objfile_data;
3516       CORE_ADDR addr;
3517
3518       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3519
3520       /* We prefer the SystemTap probe point if it exists.  */
3521       if (!bp_objfile_data->exception_searched)
3522         {
3523           VEC (probe_p) *ret;
3524
3525           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3526
3527           if (ret != NULL)
3528             {
3529               /* We are only interested in checking one element.  */
3530               struct probe *p = VEC_index (probe_p, ret, 0);
3531
3532               if (!can_evaluate_probe_arguments (p))
3533                 {
3534                   /* We cannot use the probe interface here, because it does
3535                      not know how to evaluate arguments.  */
3536                   VEC_free (probe_p, ret);
3537                   ret = NULL;
3538                 }
3539             }
3540           bp_objfile_data->exception_probes = ret;
3541           bp_objfile_data->exception_searched = 1;
3542         }
3543
3544       if (bp_objfile_data->exception_probes != NULL)
3545         {
3546           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3547           int i;
3548           struct probe *probe;
3549
3550           for (i = 0;
3551                VEC_iterate (probe_p,
3552                             bp_objfile_data->exception_probes,
3553                             i, probe);
3554                ++i)
3555             {
3556               struct breakpoint *b;
3557
3558               b = create_internal_breakpoint (gdbarch,
3559                                               get_probe_address (probe,
3560                                                                  objfile),
3561                                               bp_exception_master,
3562                                               &internal_breakpoint_ops);
3563               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3564               b->enable_state = bp_disabled;
3565             }
3566
3567           continue;
3568         }
3569
3570       /* Otherwise, try the hook function.  */
3571
3572       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3573         continue;
3574
3575       gdbarch = get_objfile_arch (objfile);
3576
3577       if (bp_objfile_data->exception_msym.minsym == NULL)
3578         {
3579           struct bound_minimal_symbol debug_hook;
3580
3581           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3582           if (debug_hook.minsym == NULL)
3583             {
3584               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3585               continue;
3586             }
3587
3588           bp_objfile_data->exception_msym = debug_hook;
3589         }
3590
3591       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3592       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3593                                                  &current_target);
3594       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3595                                       &internal_breakpoint_ops);
3596       b->addr_string = xstrdup (func_name);
3597       b->enable_state = bp_disabled;
3598     }
3599
3600   update_global_location_list (1);
3601 }
3602
3603 void
3604 update_breakpoints_after_exec (void)
3605 {
3606   struct breakpoint *b, *b_tmp;
3607   struct bp_location *bploc, **bplocp_tmp;
3608
3609   /* We're about to delete breakpoints from GDB's lists.  If the
3610      INSERTED flag is true, GDB will try to lift the breakpoints by
3611      writing the breakpoints' "shadow contents" back into memory.  The
3612      "shadow contents" are NOT valid after an exec, so GDB should not
3613      do that.  Instead, the target is responsible from marking
3614      breakpoints out as soon as it detects an exec.  We don't do that
3615      here instead, because there may be other attempts to delete
3616      breakpoints after detecting an exec and before reaching here.  */
3617   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3618     if (bploc->pspace == current_program_space)
3619       gdb_assert (!bploc->inserted);
3620
3621   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3622   {
3623     if (b->pspace != current_program_space)
3624       continue;
3625
3626     /* Solib breakpoints must be explicitly reset after an exec().  */
3627     if (b->type == bp_shlib_event)
3628       {
3629         delete_breakpoint (b);
3630         continue;
3631       }
3632
3633     /* JIT breakpoints must be explicitly reset after an exec().  */
3634     if (b->type == bp_jit_event)
3635       {
3636         delete_breakpoint (b);
3637         continue;
3638       }
3639
3640     /* Thread event breakpoints must be set anew after an exec(),
3641        as must overlay event and longjmp master breakpoints.  */
3642     if (b->type == bp_thread_event || b->type == bp_overlay_event
3643         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3644         || b->type == bp_exception_master)
3645       {
3646         delete_breakpoint (b);
3647         continue;
3648       }
3649
3650     /* Step-resume breakpoints are meaningless after an exec().  */
3651     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3652       {
3653         delete_breakpoint (b);
3654         continue;
3655       }
3656
3657     /* Longjmp and longjmp-resume breakpoints are also meaningless
3658        after an exec.  */
3659     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3660         || b->type == bp_longjmp_call_dummy
3661         || b->type == bp_exception || b->type == bp_exception_resume)
3662       {
3663         delete_breakpoint (b);
3664         continue;
3665       }
3666
3667     if (b->type == bp_catchpoint)
3668       {
3669         /* For now, none of the bp_catchpoint breakpoints need to
3670            do anything at this point.  In the future, if some of
3671            the catchpoints need to something, we will need to add
3672            a new method, and call this method from here.  */
3673         continue;
3674       }
3675
3676     /* bp_finish is a special case.  The only way we ought to be able
3677        to see one of these when an exec() has happened, is if the user
3678        caught a vfork, and then said "finish".  Ordinarily a finish just
3679        carries them to the call-site of the current callee, by setting
3680        a temporary bp there and resuming.  But in this case, the finish
3681        will carry them entirely through the vfork & exec.
3682
3683        We don't want to allow a bp_finish to remain inserted now.  But
3684        we can't safely delete it, 'cause finish_command has a handle to
3685        the bp on a bpstat, and will later want to delete it.  There's a
3686        chance (and I've seen it happen) that if we delete the bp_finish
3687        here, that its storage will get reused by the time finish_command
3688        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3689        We really must allow finish_command to delete a bp_finish.
3690
3691        In the absence of a general solution for the "how do we know
3692        it's safe to delete something others may have handles to?"
3693        problem, what we'll do here is just uninsert the bp_finish, and
3694        let finish_command delete it.
3695
3696        (We know the bp_finish is "doomed" in the sense that it's
3697        momentary, and will be deleted as soon as finish_command sees
3698        the inferior stopped.  So it doesn't matter that the bp's
3699        address is probably bogus in the new a.out, unlike e.g., the
3700        solib breakpoints.)  */
3701
3702     if (b->type == bp_finish)
3703       {
3704         continue;
3705       }
3706
3707     /* Without a symbolic address, we have little hope of the
3708        pre-exec() address meaning the same thing in the post-exec()
3709        a.out.  */
3710     if (b->addr_string == NULL)
3711       {
3712         delete_breakpoint (b);
3713         continue;
3714       }
3715   }
3716   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3717   create_overlay_event_breakpoint ();
3718   create_longjmp_master_breakpoint ();
3719   create_std_terminate_master_breakpoint ();
3720   create_exception_master_breakpoint ();
3721 }
3722
3723 int
3724 detach_breakpoints (ptid_t ptid)
3725 {
3726   struct bp_location *bl, **blp_tmp;
3727   int val = 0;
3728   struct cleanup *old_chain = save_inferior_ptid ();
3729   struct inferior *inf = current_inferior ();
3730
3731   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3732     error (_("Cannot detach breakpoints of inferior_ptid"));
3733
3734   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3735   inferior_ptid = ptid;
3736   ALL_BP_LOCATIONS (bl, blp_tmp)
3737   {
3738     if (bl->pspace != inf->pspace)
3739       continue;
3740
3741     /* This function must physically remove breakpoints locations
3742        from the specified ptid, without modifying the breakpoint
3743        package's state.  Locations of type bp_loc_other are only
3744        maintained at GDB side.  So, there is no need to remove
3745        these bp_loc_other locations.  Moreover, removing these
3746        would modify the breakpoint package's state.  */
3747     if (bl->loc_type == bp_loc_other)
3748       continue;
3749
3750     if (bl->inserted)
3751       val |= remove_breakpoint_1 (bl, mark_inserted);
3752   }
3753
3754   /* Detach single-step breakpoints as well.  */
3755   detach_single_step_breakpoints ();
3756
3757   do_cleanups (old_chain);
3758   return val;
3759 }
3760
3761 /* Remove the breakpoint location BL from the current address space.
3762    Note that this is used to detach breakpoints from a child fork.
3763    When we get here, the child isn't in the inferior list, and neither
3764    do we have objects to represent its address space --- we should
3765    *not* look at bl->pspace->aspace here.  */
3766
3767 static int
3768 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3769 {
3770   int val;
3771
3772   /* BL is never in moribund_locations by our callers.  */
3773   gdb_assert (bl->owner != NULL);
3774
3775   if (bl->owner->enable_state == bp_permanent)
3776     /* Permanent breakpoints cannot be inserted or removed.  */
3777     return 0;
3778
3779   /* The type of none suggests that owner is actually deleted.
3780      This should not ever happen.  */
3781   gdb_assert (bl->owner->type != bp_none);
3782
3783   if (bl->loc_type == bp_loc_software_breakpoint
3784       || bl->loc_type == bp_loc_hardware_breakpoint)
3785     {
3786       /* "Normal" instruction breakpoint: either the standard
3787          trap-instruction bp (bp_breakpoint), or a
3788          bp_hardware_breakpoint.  */
3789
3790       /* First check to see if we have to handle an overlay.  */
3791       if (overlay_debugging == ovly_off
3792           || bl->section == NULL
3793           || !(section_is_overlay (bl->section)))
3794         {
3795           /* No overlay handling: just remove the breakpoint.  */
3796
3797           /* If we're trying to uninsert a memory breakpoint that we
3798              know is set in a dynamic object that is marked
3799              shlib_disabled, then either the dynamic object was
3800              removed with "remove-symbol-file" or with
3801              "nosharedlibrary".  In the former case, we don't know
3802              whether another dynamic object might have loaded over the
3803              breakpoint's address -- the user might well let us know
3804              about it next with add-symbol-file (the whole point of
3805              OBJF_USERLOADED is letting the user manually maintain a
3806              list of dynamically loaded objects).  If we have the
3807              breakpoint's shadow memory, that is, this is a software
3808              breakpoint managed by GDB, check whether the breakpoint
3809              is still inserted in memory, to avoid overwriting wrong
3810              code with stale saved shadow contents.  Note that HW
3811              breakpoints don't have shadow memory, as they're
3812              implemented using a mechanism that is not dependent on
3813              being able to modify the target's memory, and as such
3814              they should always be removed.  */
3815           if (bl->shlib_disabled
3816               && bl->target_info.shadow_len != 0
3817               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3818             val = 0;
3819           else
3820             val = bl->owner->ops->remove_location (bl);
3821         }
3822       else
3823         {
3824           /* This breakpoint is in an overlay section.
3825              Did we set a breakpoint at the LMA?  */
3826           if (!overlay_events_enabled)
3827               {
3828                 /* Yes -- overlay event support is not active, so we
3829                    should have set a breakpoint at the LMA.  Remove it.  
3830                 */
3831                 /* Ignore any failures: if the LMA is in ROM, we will
3832                    have already warned when we failed to insert it.  */
3833                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3834                   target_remove_hw_breakpoint (bl->gdbarch,
3835                                                &bl->overlay_target_info);
3836                 else
3837                   target_remove_breakpoint (bl->gdbarch,
3838                                             &bl->overlay_target_info);
3839               }
3840           /* Did we set a breakpoint at the VMA? 
3841              If so, we will have marked the breakpoint 'inserted'.  */
3842           if (bl->inserted)
3843             {
3844               /* Yes -- remove it.  Previously we did not bother to
3845                  remove the breakpoint if the section had been
3846                  unmapped, but let's not rely on that being safe.  We
3847                  don't know what the overlay manager might do.  */
3848
3849               /* However, we should remove *software* breakpoints only
3850                  if the section is still mapped, or else we overwrite
3851                  wrong code with the saved shadow contents.  */
3852               if (bl->loc_type == bp_loc_hardware_breakpoint
3853                   || section_is_mapped (bl->section))
3854                 val = bl->owner->ops->remove_location (bl);
3855               else
3856                 val = 0;
3857             }
3858           else
3859             {
3860               /* No -- not inserted, so no need to remove.  No error.  */
3861               val = 0;
3862             }
3863         }
3864
3865       /* In some cases, we might not be able to remove a breakpoint in
3866          a shared library that has already been removed, but we have
3867          not yet processed the shlib unload event.  Similarly for an
3868          unloaded add-symbol-file object - the user might not yet have
3869          had the chance to remove-symbol-file it.  shlib_disabled will
3870          be set if the library/object has already been removed, but
3871          the breakpoint hasn't been uninserted yet, e.g., after
3872          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3873          always-inserted mode.  */
3874       if (val
3875           && (bl->loc_type == bp_loc_software_breakpoint
3876               && (bl->shlib_disabled
3877                   || solib_name_from_address (bl->pspace, bl->address)
3878                   || userloaded_objfile_contains_address_p (bl->pspace,
3879                                                             bl->address))))
3880         val = 0;
3881
3882       if (val)
3883         return val;
3884       bl->inserted = (is == mark_inserted);
3885     }
3886   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3887     {
3888       gdb_assert (bl->owner->ops != NULL
3889                   && bl->owner->ops->remove_location != NULL);
3890
3891       bl->inserted = (is == mark_inserted);
3892       bl->owner->ops->remove_location (bl);
3893
3894       /* Failure to remove any of the hardware watchpoints comes here.  */
3895       if ((is == mark_uninserted) && (bl->inserted))
3896         warning (_("Could not remove hardware watchpoint %d."),
3897                  bl->owner->number);
3898     }
3899   else if (bl->owner->type == bp_catchpoint
3900            && breakpoint_enabled (bl->owner)
3901            && !bl->duplicate)
3902     {
3903       gdb_assert (bl->owner->ops != NULL
3904                   && bl->owner->ops->remove_location != NULL);
3905
3906       val = bl->owner->ops->remove_location (bl);
3907       if (val)
3908         return val;
3909
3910       bl->inserted = (is == mark_inserted);
3911     }
3912
3913   return 0;
3914 }
3915
3916 static int
3917 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3918 {
3919   int ret;
3920   struct cleanup *old_chain;
3921
3922   /* BL is never in moribund_locations by our callers.  */
3923   gdb_assert (bl->owner != NULL);
3924
3925   if (bl->owner->enable_state == bp_permanent)
3926     /* Permanent breakpoints cannot be inserted or removed.  */
3927     return 0;
3928
3929   /* The type of none suggests that owner is actually deleted.
3930      This should not ever happen.  */
3931   gdb_assert (bl->owner->type != bp_none);
3932
3933   old_chain = save_current_space_and_thread ();
3934
3935   switch_to_program_space_and_thread (bl->pspace);
3936
3937   ret = remove_breakpoint_1 (bl, is);
3938
3939   do_cleanups (old_chain);
3940   return ret;
3941 }
3942
3943 /* Clear the "inserted" flag in all breakpoints.  */
3944
3945 void
3946 mark_breakpoints_out (void)
3947 {
3948   struct bp_location *bl, **blp_tmp;
3949
3950   ALL_BP_LOCATIONS (bl, blp_tmp)
3951     if (bl->pspace == current_program_space)
3952       bl->inserted = 0;
3953 }
3954
3955 /* Clear the "inserted" flag in all breakpoints and delete any
3956    breakpoints which should go away between runs of the program.
3957
3958    Plus other such housekeeping that has to be done for breakpoints
3959    between runs.
3960
3961    Note: this function gets called at the end of a run (by
3962    generic_mourn_inferior) and when a run begins (by
3963    init_wait_for_inferior).  */
3964
3965
3966
3967 void
3968 breakpoint_init_inferior (enum inf_context context)
3969 {
3970   struct breakpoint *b, *b_tmp;
3971   struct bp_location *bl, **blp_tmp;
3972   int ix;
3973   struct program_space *pspace = current_program_space;
3974
3975   /* If breakpoint locations are shared across processes, then there's
3976      nothing to do.  */
3977   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3978     return;
3979
3980   ALL_BP_LOCATIONS (bl, blp_tmp)
3981   {
3982     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3983     if (bl->pspace == pspace
3984         && bl->owner->enable_state != bp_permanent)
3985       bl->inserted = 0;
3986   }
3987
3988   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3989   {
3990     if (b->loc && b->loc->pspace != pspace)
3991       continue;
3992
3993     switch (b->type)
3994       {
3995       case bp_call_dummy:
3996       case bp_longjmp_call_dummy:
3997
3998         /* If the call dummy breakpoint is at the entry point it will
3999            cause problems when the inferior is rerun, so we better get
4000            rid of it.  */
4001
4002       case bp_watchpoint_scope:
4003
4004         /* Also get rid of scope breakpoints.  */
4005
4006       case bp_shlib_event:
4007
4008         /* Also remove solib event breakpoints.  Their addresses may
4009            have changed since the last time we ran the program.
4010            Actually we may now be debugging against different target;
4011            and so the solib backend that installed this breakpoint may
4012            not be used in by the target.  E.g.,
4013
4014            (gdb) file prog-linux
4015            (gdb) run               # native linux target
4016            ...
4017            (gdb) kill
4018            (gdb) file prog-win.exe
4019            (gdb) tar rem :9999     # remote Windows gdbserver.
4020         */
4021
4022       case bp_step_resume:
4023
4024         /* Also remove step-resume breakpoints.  */
4025
4026         delete_breakpoint (b);
4027         break;
4028
4029       case bp_watchpoint:
4030       case bp_hardware_watchpoint:
4031       case bp_read_watchpoint:
4032       case bp_access_watchpoint:
4033         {
4034           struct watchpoint *w = (struct watchpoint *) b;
4035
4036           /* Likewise for watchpoints on local expressions.  */
4037           if (w->exp_valid_block != NULL)
4038             delete_breakpoint (b);
4039           else if (context == inf_starting)
4040             {
4041               /* Reset val field to force reread of starting value in
4042                  insert_breakpoints.  */
4043               if (w->val)
4044                 value_free (w->val);
4045               w->val = NULL;
4046               w->val_valid = 0;
4047           }
4048         }
4049         break;
4050       default:
4051         break;
4052       }
4053   }
4054
4055   /* Get rid of the moribund locations.  */
4056   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4057     decref_bp_location (&bl);
4058   VEC_free (bp_location_p, moribund_locations);
4059 }
4060
4061 /* These functions concern about actual breakpoints inserted in the
4062    target --- to e.g. check if we need to do decr_pc adjustment or if
4063    we need to hop over the bkpt --- so we check for address space
4064    match, not program space.  */
4065
4066 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4067    exists at PC.  It returns ordinary_breakpoint_here if it's an
4068    ordinary breakpoint, or permanent_breakpoint_here if it's a
4069    permanent breakpoint.
4070    - When continuing from a location with an ordinary breakpoint, we
4071      actually single step once before calling insert_breakpoints.
4072    - When continuing from a location with a permanent breakpoint, we
4073      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4074      the target, to advance the PC past the breakpoint.  */
4075
4076 enum breakpoint_here
4077 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4078 {
4079   struct bp_location *bl, **blp_tmp;
4080   int any_breakpoint_here = 0;
4081
4082   ALL_BP_LOCATIONS (bl, blp_tmp)
4083     {
4084       if (bl->loc_type != bp_loc_software_breakpoint
4085           && bl->loc_type != bp_loc_hardware_breakpoint)
4086         continue;
4087
4088       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4089       if ((breakpoint_enabled (bl->owner)
4090            || bl->owner->enable_state == bp_permanent)
4091           && breakpoint_location_address_match (bl, aspace, pc))
4092         {
4093           if (overlay_debugging 
4094               && section_is_overlay (bl->section)
4095               && !section_is_mapped (bl->section))
4096             continue;           /* unmapped overlay -- can't be a match */
4097           else if (bl->owner->enable_state == bp_permanent)
4098             return permanent_breakpoint_here;
4099           else
4100             any_breakpoint_here = 1;
4101         }
4102     }
4103
4104   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4105 }
4106
4107 /* Return true if there's a moribund breakpoint at PC.  */
4108
4109 int
4110 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4111 {
4112   struct bp_location *loc;
4113   int ix;
4114
4115   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4116     if (breakpoint_location_address_match (loc, aspace, pc))
4117       return 1;
4118
4119   return 0;
4120 }
4121
4122 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4123    inserted using regular breakpoint_chain / bp_location array
4124    mechanism.  This does not check for single-step breakpoints, which
4125    are inserted and removed using direct target manipulation.  */
4126
4127 int
4128 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4129                                     CORE_ADDR pc)
4130 {
4131   struct bp_location *bl, **blp_tmp;
4132
4133   ALL_BP_LOCATIONS (bl, blp_tmp)
4134     {
4135       if (bl->loc_type != bp_loc_software_breakpoint
4136           && bl->loc_type != bp_loc_hardware_breakpoint)
4137         continue;
4138
4139       if (bl->inserted
4140           && breakpoint_location_address_match (bl, aspace, pc))
4141         {
4142           if (overlay_debugging 
4143               && section_is_overlay (bl->section)
4144               && !section_is_mapped (bl->section))
4145             continue;           /* unmapped overlay -- can't be a match */
4146           else
4147             return 1;
4148         }
4149     }
4150   return 0;
4151 }
4152
4153 /* Returns non-zero iff there's either regular breakpoint
4154    or a single step breakpoint inserted at PC.  */
4155
4156 int
4157 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4158 {
4159   if (regular_breakpoint_inserted_here_p (aspace, pc))
4160     return 1;
4161
4162   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4163     return 1;
4164
4165   return 0;
4166 }
4167
4168 /* This function returns non-zero iff there is a software breakpoint
4169    inserted at PC.  */
4170
4171 int
4172 software_breakpoint_inserted_here_p (struct address_space *aspace,
4173                                      CORE_ADDR pc)
4174 {
4175   struct bp_location *bl, **blp_tmp;
4176
4177   ALL_BP_LOCATIONS (bl, blp_tmp)
4178     {
4179       if (bl->loc_type != bp_loc_software_breakpoint)
4180         continue;
4181
4182       if (bl->inserted
4183           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4184                                        aspace, pc))
4185         {
4186           if (overlay_debugging 
4187               && section_is_overlay (bl->section)
4188               && !section_is_mapped (bl->section))
4189             continue;           /* unmapped overlay -- can't be a match */
4190           else
4191             return 1;
4192         }
4193     }
4194
4195   /* Also check for software single-step breakpoints.  */
4196   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4197     return 1;
4198
4199   return 0;
4200 }
4201
4202 int
4203 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4204                                        CORE_ADDR addr, ULONGEST len)
4205 {
4206   struct breakpoint *bpt;
4207
4208   ALL_BREAKPOINTS (bpt)
4209     {
4210       struct bp_location *loc;
4211
4212       if (bpt->type != bp_hardware_watchpoint
4213           && bpt->type != bp_access_watchpoint)
4214         continue;
4215
4216       if (!breakpoint_enabled (bpt))
4217         continue;
4218
4219       for (loc = bpt->loc; loc; loc = loc->next)
4220         if (loc->pspace->aspace == aspace && loc->inserted)
4221           {
4222             CORE_ADDR l, h;
4223
4224             /* Check for intersection.  */
4225             l = max (loc->address, addr);
4226             h = min (loc->address + loc->length, addr + len);
4227             if (l < h)
4228               return 1;
4229           }
4230     }
4231   return 0;
4232 }
4233
4234 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4235    PC is valid for process/thread PTID.  */
4236
4237 int
4238 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4239                          ptid_t ptid)
4240 {
4241   struct bp_location *bl, **blp_tmp;
4242   /* The thread and task IDs associated to PTID, computed lazily.  */
4243   int thread = -1;
4244   int task = 0;
4245   
4246   ALL_BP_LOCATIONS (bl, blp_tmp)
4247     {
4248       if (bl->loc_type != bp_loc_software_breakpoint
4249           && bl->loc_type != bp_loc_hardware_breakpoint)
4250         continue;
4251
4252       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4253       if (!breakpoint_enabled (bl->owner)
4254           && bl->owner->enable_state != bp_permanent)
4255         continue;
4256
4257       if (!breakpoint_location_address_match (bl, aspace, pc))
4258         continue;
4259
4260       if (bl->owner->thread != -1)
4261         {
4262           /* This is a thread-specific breakpoint.  Check that ptid
4263              matches that thread.  If thread hasn't been computed yet,
4264              it is now time to do so.  */
4265           if (thread == -1)
4266             thread = pid_to_thread_id (ptid);
4267           if (bl->owner->thread != thread)
4268             continue;
4269         }
4270
4271       if (bl->owner->task != 0)
4272         {
4273           /* This is a task-specific breakpoint.  Check that ptid
4274              matches that task.  If task hasn't been computed yet,
4275              it is now time to do so.  */
4276           if (task == 0)
4277             task = ada_get_task_number (ptid);
4278           if (bl->owner->task != task)
4279             continue;
4280         }
4281
4282       if (overlay_debugging 
4283           && section_is_overlay (bl->section)
4284           && !section_is_mapped (bl->section))
4285         continue;           /* unmapped overlay -- can't be a match */
4286
4287       return 1;
4288     }
4289
4290   return 0;
4291 }
4292 \f
4293
4294 /* bpstat stuff.  External routines' interfaces are documented
4295    in breakpoint.h.  */
4296
4297 int
4298 is_catchpoint (struct breakpoint *ep)
4299 {
4300   return (ep->type == bp_catchpoint);
4301 }
4302
4303 /* Frees any storage that is part of a bpstat.  Does not walk the
4304    'next' chain.  */
4305
4306 static void
4307 bpstat_free (bpstat bs)
4308 {
4309   if (bs->old_val != NULL)
4310     value_free (bs->old_val);
4311   decref_counted_command_line (&bs->commands);
4312   decref_bp_location (&bs->bp_location_at);
4313   xfree (bs);
4314 }
4315
4316 /* Clear a bpstat so that it says we are not at any breakpoint.
4317    Also free any storage that is part of a bpstat.  */
4318
4319 void
4320 bpstat_clear (bpstat *bsp)
4321 {
4322   bpstat p;
4323   bpstat q;
4324
4325   if (bsp == 0)
4326     return;
4327   p = *bsp;
4328   while (p != NULL)
4329     {
4330       q = p->next;
4331       bpstat_free (p);
4332       p = q;
4333     }
4334   *bsp = NULL;
4335 }
4336
4337 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4338    is part of the bpstat is copied as well.  */
4339
4340 bpstat
4341 bpstat_copy (bpstat bs)
4342 {
4343   bpstat p = NULL;
4344   bpstat tmp;
4345   bpstat retval = NULL;
4346
4347   if (bs == NULL)
4348     return bs;
4349
4350   for (; bs != NULL; bs = bs->next)
4351     {
4352       tmp = (bpstat) xmalloc (sizeof (*tmp));
4353       memcpy (tmp, bs, sizeof (*tmp));
4354       incref_counted_command_line (tmp->commands);
4355       incref_bp_location (tmp->bp_location_at);
4356       if (bs->old_val != NULL)
4357         {
4358           tmp->old_val = value_copy (bs->old_val);
4359           release_value (tmp->old_val);
4360         }
4361
4362       if (p == NULL)
4363         /* This is the first thing in the chain.  */
4364         retval = tmp;
4365       else
4366         p->next = tmp;
4367       p = tmp;
4368     }
4369   p->next = NULL;
4370   return retval;
4371 }
4372
4373 /* Find the bpstat associated with this breakpoint.  */
4374
4375 bpstat
4376 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4377 {
4378   if (bsp == NULL)
4379     return NULL;
4380
4381   for (; bsp != NULL; bsp = bsp->next)
4382     {
4383       if (bsp->breakpoint_at == breakpoint)
4384         return bsp;
4385     }
4386   return NULL;
4387 }
4388
4389 /* See breakpoint.h.  */
4390
4391 int
4392 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4393 {
4394   for (; bsp != NULL; bsp = bsp->next)
4395     {
4396       if (bsp->breakpoint_at == NULL)
4397         {
4398           /* A moribund location can never explain a signal other than
4399              GDB_SIGNAL_TRAP.  */
4400           if (sig == GDB_SIGNAL_TRAP)
4401             return 1;
4402         }
4403       else
4404         {
4405           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4406                                                         sig))
4407             return 1;
4408         }
4409     }
4410
4411   return 0;
4412 }
4413
4414 /* Put in *NUM the breakpoint number of the first breakpoint we are
4415    stopped at.  *BSP upon return is a bpstat which points to the
4416    remaining breakpoints stopped at (but which is not guaranteed to be
4417    good for anything but further calls to bpstat_num).
4418
4419    Return 0 if passed a bpstat which does not indicate any breakpoints.
4420    Return -1 if stopped at a breakpoint that has been deleted since
4421    we set it.
4422    Return 1 otherwise.  */
4423
4424 int
4425 bpstat_num (bpstat *bsp, int *num)
4426 {
4427   struct breakpoint *b;
4428
4429   if ((*bsp) == NULL)
4430     return 0;                   /* No more breakpoint values */
4431
4432   /* We assume we'll never have several bpstats that correspond to a
4433      single breakpoint -- otherwise, this function might return the
4434      same number more than once and this will look ugly.  */
4435   b = (*bsp)->breakpoint_at;
4436   *bsp = (*bsp)->next;
4437   if (b == NULL)
4438     return -1;                  /* breakpoint that's been deleted since */
4439
4440   *num = b->number;             /* We have its number */
4441   return 1;
4442 }
4443
4444 /* See breakpoint.h.  */
4445
4446 void
4447 bpstat_clear_actions (void)
4448 {
4449   struct thread_info *tp;
4450   bpstat bs;
4451
4452   if (ptid_equal (inferior_ptid, null_ptid))
4453     return;
4454
4455   tp = find_thread_ptid (inferior_ptid);
4456   if (tp == NULL)
4457     return;
4458
4459   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4460     {
4461       decref_counted_command_line (&bs->commands);
4462
4463       if (bs->old_val != NULL)
4464         {
4465           value_free (bs->old_val);
4466           bs->old_val = NULL;
4467         }
4468     }
4469 }
4470
4471 /* Called when a command is about to proceed the inferior.  */
4472
4473 static void
4474 breakpoint_about_to_proceed (void)
4475 {
4476   if (!ptid_equal (inferior_ptid, null_ptid))
4477     {
4478       struct thread_info *tp = inferior_thread ();
4479
4480       /* Allow inferior function calls in breakpoint commands to not
4481          interrupt the command list.  When the call finishes
4482          successfully, the inferior will be standing at the same
4483          breakpoint as if nothing happened.  */
4484       if (tp->control.in_infcall)
4485         return;
4486     }
4487
4488   breakpoint_proceeded = 1;
4489 }
4490
4491 /* Stub for cleaning up our state if we error-out of a breakpoint
4492    command.  */
4493 static void
4494 cleanup_executing_breakpoints (void *ignore)
4495 {
4496   executing_breakpoint_commands = 0;
4497 }
4498
4499 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4500    or its equivalent.  */
4501
4502 static int
4503 command_line_is_silent (struct command_line *cmd)
4504 {
4505   return cmd && (strcmp ("silent", cmd->line) == 0
4506                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4507 }
4508
4509 /* Execute all the commands associated with all the breakpoints at
4510    this location.  Any of these commands could cause the process to
4511    proceed beyond this point, etc.  We look out for such changes by
4512    checking the global "breakpoint_proceeded" after each command.
4513
4514    Returns true if a breakpoint command resumed the inferior.  In that
4515    case, it is the caller's responsibility to recall it again with the
4516    bpstat of the current thread.  */
4517
4518 static int
4519 bpstat_do_actions_1 (bpstat *bsp)
4520 {
4521   bpstat bs;
4522   struct cleanup *old_chain;
4523   int again = 0;
4524
4525   /* Avoid endless recursion if a `source' command is contained
4526      in bs->commands.  */
4527   if (executing_breakpoint_commands)
4528     return 0;
4529
4530   executing_breakpoint_commands = 1;
4531   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4532
4533   prevent_dont_repeat ();
4534
4535   /* This pointer will iterate over the list of bpstat's.  */
4536   bs = *bsp;
4537
4538   breakpoint_proceeded = 0;
4539   for (; bs != NULL; bs = bs->next)
4540     {
4541       struct counted_command_line *ccmd;
4542       struct command_line *cmd;
4543       struct cleanup *this_cmd_tree_chain;
4544
4545       /* Take ownership of the BSP's command tree, if it has one.
4546
4547          The command tree could legitimately contain commands like
4548          'step' and 'next', which call clear_proceed_status, which
4549          frees stop_bpstat's command tree.  To make sure this doesn't
4550          free the tree we're executing out from under us, we need to
4551          take ownership of the tree ourselves.  Since a given bpstat's
4552          commands are only executed once, we don't need to copy it; we
4553          can clear the pointer in the bpstat, and make sure we free
4554          the tree when we're done.  */
4555       ccmd = bs->commands;
4556       bs->commands = NULL;
4557       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4558       cmd = ccmd ? ccmd->commands : NULL;
4559       if (command_line_is_silent (cmd))
4560         {
4561           /* The action has been already done by bpstat_stop_status.  */
4562           cmd = cmd->next;
4563         }
4564
4565       while (cmd != NULL)
4566         {
4567           execute_control_command (cmd);
4568
4569           if (breakpoint_proceeded)
4570             break;
4571           else
4572             cmd = cmd->next;
4573         }
4574
4575       /* We can free this command tree now.  */
4576       do_cleanups (this_cmd_tree_chain);
4577
4578       if (breakpoint_proceeded)
4579         {
4580           if (target_can_async_p ())
4581             /* If we are in async mode, then the target might be still
4582                running, not stopped at any breakpoint, so nothing for
4583                us to do here -- just return to the event loop.  */
4584             ;
4585           else
4586             /* In sync mode, when execute_control_command returns
4587                we're already standing on the next breakpoint.
4588                Breakpoint commands for that stop were not run, since
4589                execute_command does not run breakpoint commands --
4590                only command_line_handler does, but that one is not
4591                involved in execution of breakpoint commands.  So, we
4592                can now execute breakpoint commands.  It should be
4593                noted that making execute_command do bpstat actions is
4594                not an option -- in this case we'll have recursive
4595                invocation of bpstat for each breakpoint with a
4596                command, and can easily blow up GDB stack.  Instead, we
4597                return true, which will trigger the caller to recall us
4598                with the new stop_bpstat.  */
4599             again = 1;
4600           break;
4601         }
4602     }
4603   do_cleanups (old_chain);
4604   return again;
4605 }
4606
4607 void
4608 bpstat_do_actions (void)
4609 {
4610   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4611
4612   /* Do any commands attached to breakpoint we are stopped at.  */
4613   while (!ptid_equal (inferior_ptid, null_ptid)
4614          && target_has_execution
4615          && !is_exited (inferior_ptid)
4616          && !is_executing (inferior_ptid))
4617     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4618        and only return when it is stopped at the next breakpoint, we
4619        keep doing breakpoint actions until it returns false to
4620        indicate the inferior was not resumed.  */
4621     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4622       break;
4623
4624   discard_cleanups (cleanup_if_error);
4625 }
4626
4627 /* Print out the (old or new) value associated with a watchpoint.  */
4628
4629 static void
4630 watchpoint_value_print (struct value *val, struct ui_file *stream)
4631 {
4632   if (val == NULL)
4633     fprintf_unfiltered (stream, _("<unreadable>"));
4634   else
4635     {
4636       struct value_print_options opts;
4637       get_user_print_options (&opts);
4638       value_print (val, stream, &opts);
4639     }
4640 }
4641
4642 /* Generic routine for printing messages indicating why we
4643    stopped.  The behavior of this function depends on the value
4644    'print_it' in the bpstat structure.  Under some circumstances we
4645    may decide not to print anything here and delegate the task to
4646    normal_stop().  */
4647
4648 static enum print_stop_action
4649 print_bp_stop_message (bpstat bs)
4650 {
4651   switch (bs->print_it)
4652     {
4653     case print_it_noop:
4654       /* Nothing should be printed for this bpstat entry.  */
4655       return PRINT_UNKNOWN;
4656       break;
4657
4658     case print_it_done:
4659       /* We still want to print the frame, but we already printed the
4660          relevant messages.  */
4661       return PRINT_SRC_AND_LOC;
4662       break;
4663
4664     case print_it_normal:
4665       {
4666         struct breakpoint *b = bs->breakpoint_at;
4667
4668         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4669            which has since been deleted.  */
4670         if (b == NULL)
4671           return PRINT_UNKNOWN;
4672
4673         /* Normal case.  Call the breakpoint's print_it method.  */
4674         return b->ops->print_it (bs);
4675       }
4676       break;
4677
4678     default:
4679       internal_error (__FILE__, __LINE__,
4680                       _("print_bp_stop_message: unrecognized enum value"));
4681       break;
4682     }
4683 }
4684
4685 /* A helper function that prints a shared library stopped event.  */
4686
4687 static void
4688 print_solib_event (int is_catchpoint)
4689 {
4690   int any_deleted
4691     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4692   int any_added
4693     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4694
4695   if (!is_catchpoint)
4696     {
4697       if (any_added || any_deleted)
4698         ui_out_text (current_uiout,
4699                      _("Stopped due to shared library event:\n"));
4700       else
4701         ui_out_text (current_uiout,
4702                      _("Stopped due to shared library event (no "
4703                        "libraries added or removed)\n"));
4704     }
4705
4706   if (ui_out_is_mi_like_p (current_uiout))
4707     ui_out_field_string (current_uiout, "reason",
4708                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4709
4710   if (any_deleted)
4711     {
4712       struct cleanup *cleanup;
4713       char *name;
4714       int ix;
4715
4716       ui_out_text (current_uiout, _("  Inferior unloaded "));
4717       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4718                                                     "removed");
4719       for (ix = 0;
4720            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4721                         ix, name);
4722            ++ix)
4723         {
4724           if (ix > 0)
4725             ui_out_text (current_uiout, "    ");
4726           ui_out_field_string (current_uiout, "library", name);
4727           ui_out_text (current_uiout, "\n");
4728         }
4729
4730       do_cleanups (cleanup);
4731     }
4732
4733   if (any_added)
4734     {
4735       struct so_list *iter;
4736       int ix;
4737       struct cleanup *cleanup;
4738
4739       ui_out_text (current_uiout, _("  Inferior loaded "));
4740       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4741                                                     "added");
4742       for (ix = 0;
4743            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4744                         ix, iter);
4745            ++ix)
4746         {
4747           if (ix > 0)
4748             ui_out_text (current_uiout, "    ");
4749           ui_out_field_string (current_uiout, "library", iter->so_name);
4750           ui_out_text (current_uiout, "\n");
4751         }
4752
4753       do_cleanups (cleanup);
4754     }
4755 }
4756
4757 /* Print a message indicating what happened.  This is called from
4758    normal_stop().  The input to this routine is the head of the bpstat
4759    list - a list of the eventpoints that caused this stop.  KIND is
4760    the target_waitkind for the stopping event.  This
4761    routine calls the generic print routine for printing a message
4762    about reasons for stopping.  This will print (for example) the
4763    "Breakpoint n," part of the output.  The return value of this
4764    routine is one of:
4765
4766    PRINT_UNKNOWN: Means we printed nothing.
4767    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4768    code to print the location.  An example is 
4769    "Breakpoint 1, " which should be followed by
4770    the location.
4771    PRINT_SRC_ONLY: Means we printed something, but there is no need
4772    to also print the location part of the message.
4773    An example is the catch/throw messages, which
4774    don't require a location appended to the end.
4775    PRINT_NOTHING: We have done some printing and we don't need any 
4776    further info to be printed.  */
4777
4778 enum print_stop_action
4779 bpstat_print (bpstat bs, int kind)
4780 {
4781   int val;
4782
4783   /* Maybe another breakpoint in the chain caused us to stop.
4784      (Currently all watchpoints go on the bpstat whether hit or not.
4785      That probably could (should) be changed, provided care is taken
4786      with respect to bpstat_explains_signal).  */
4787   for (; bs; bs = bs->next)
4788     {
4789       val = print_bp_stop_message (bs);
4790       if (val == PRINT_SRC_ONLY 
4791           || val == PRINT_SRC_AND_LOC 
4792           || val == PRINT_NOTHING)
4793         return val;
4794     }
4795
4796   /* If we had hit a shared library event breakpoint,
4797      print_bp_stop_message would print out this message.  If we hit an
4798      OS-level shared library event, do the same thing.  */
4799   if (kind == TARGET_WAITKIND_LOADED)
4800     {
4801       print_solib_event (0);
4802       return PRINT_NOTHING;
4803     }
4804
4805   /* We reached the end of the chain, or we got a null BS to start
4806      with and nothing was printed.  */
4807   return PRINT_UNKNOWN;
4808 }
4809
4810 /* Evaluate the expression EXP and return 1 if value is zero.
4811    This returns the inverse of the condition because it is called
4812    from catch_errors which returns 0 if an exception happened, and if an
4813    exception happens we want execution to stop.
4814    The argument is a "struct expression *" that has been cast to a
4815    "void *" to make it pass through catch_errors.  */
4816
4817 static int
4818 breakpoint_cond_eval (void *exp)
4819 {
4820   struct value *mark = value_mark ();
4821   int i = !value_true (evaluate_expression ((struct expression *) exp));
4822
4823   value_free_to_mark (mark);
4824   return i;
4825 }
4826
4827 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4828
4829 static bpstat
4830 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4831 {
4832   bpstat bs;
4833
4834   bs = (bpstat) xmalloc (sizeof (*bs));
4835   bs->next = NULL;
4836   **bs_link_pointer = bs;
4837   *bs_link_pointer = &bs->next;
4838   bs->breakpoint_at = bl->owner;
4839   bs->bp_location_at = bl;
4840   incref_bp_location (bl);
4841   /* If the condition is false, etc., don't do the commands.  */
4842   bs->commands = NULL;
4843   bs->old_val = NULL;
4844   bs->print_it = print_it_normal;
4845   return bs;
4846 }
4847 \f
4848 /* The target has stopped with waitstatus WS.  Check if any hardware
4849    watchpoints have triggered, according to the target.  */
4850
4851 int
4852 watchpoints_triggered (struct target_waitstatus *ws)
4853 {
4854   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4855   CORE_ADDR addr;
4856   struct breakpoint *b;
4857
4858   if (!stopped_by_watchpoint)
4859     {
4860       /* We were not stopped by a watchpoint.  Mark all watchpoints
4861          as not triggered.  */
4862       ALL_BREAKPOINTS (b)
4863         if (is_hardware_watchpoint (b))
4864           {
4865             struct watchpoint *w = (struct watchpoint *) b;
4866
4867             w->watchpoint_triggered = watch_triggered_no;
4868           }
4869
4870       return 0;
4871     }
4872
4873   if (!target_stopped_data_address (&current_target, &addr))
4874     {
4875       /* We were stopped by a watchpoint, but we don't know where.
4876          Mark all watchpoints as unknown.  */
4877       ALL_BREAKPOINTS (b)
4878         if (is_hardware_watchpoint (b))
4879           {
4880             struct watchpoint *w = (struct watchpoint *) b;
4881
4882             w->watchpoint_triggered = watch_triggered_unknown;
4883           }
4884
4885       return 1;
4886     }
4887
4888   /* The target could report the data address.  Mark watchpoints
4889      affected by this data address as triggered, and all others as not
4890      triggered.  */
4891
4892   ALL_BREAKPOINTS (b)
4893     if (is_hardware_watchpoint (b))
4894       {
4895         struct watchpoint *w = (struct watchpoint *) b;
4896         struct bp_location *loc;
4897
4898         w->watchpoint_triggered = watch_triggered_no;
4899         for (loc = b->loc; loc; loc = loc->next)
4900           {
4901             if (is_masked_watchpoint (b))
4902               {
4903                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4904                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4905
4906                 if (newaddr == start)
4907                   {
4908                     w->watchpoint_triggered = watch_triggered_yes;
4909                     break;
4910                   }
4911               }
4912             /* Exact match not required.  Within range is sufficient.  */
4913             else if (target_watchpoint_addr_within_range (&current_target,
4914                                                          addr, loc->address,
4915                                                          loc->length))
4916               {
4917                 w->watchpoint_triggered = watch_triggered_yes;
4918                 break;
4919               }
4920           }
4921       }
4922
4923   return 1;
4924 }
4925
4926 /* Possible return values for watchpoint_check (this can't be an enum
4927    because of check_errors).  */
4928 /* The watchpoint has been deleted.  */
4929 #define WP_DELETED 1
4930 /* The value has changed.  */
4931 #define WP_VALUE_CHANGED 2
4932 /* The value has not changed.  */
4933 #define WP_VALUE_NOT_CHANGED 3
4934 /* Ignore this watchpoint, no matter if the value changed or not.  */
4935 #define WP_IGNORE 4
4936
4937 #define BP_TEMPFLAG 1
4938 #define BP_HARDWAREFLAG 2
4939
4940 /* Evaluate watchpoint condition expression and check if its value
4941    changed.
4942
4943    P should be a pointer to struct bpstat, but is defined as a void *
4944    in order for this function to be usable with catch_errors.  */
4945
4946 static int
4947 watchpoint_check (void *p)
4948 {
4949   bpstat bs = (bpstat) p;
4950   struct watchpoint *b;
4951   struct frame_info *fr;
4952   int within_current_scope;
4953
4954   /* BS is built from an existing struct breakpoint.  */
4955   gdb_assert (bs->breakpoint_at != NULL);
4956   b = (struct watchpoint *) bs->breakpoint_at;
4957
4958   /* If this is a local watchpoint, we only want to check if the
4959      watchpoint frame is in scope if the current thread is the thread
4960      that was used to create the watchpoint.  */
4961   if (!watchpoint_in_thread_scope (b))
4962     return WP_IGNORE;
4963
4964   if (b->exp_valid_block == NULL)
4965     within_current_scope = 1;
4966   else
4967     {
4968       struct frame_info *frame = get_current_frame ();
4969       struct gdbarch *frame_arch = get_frame_arch (frame);
4970       CORE_ADDR frame_pc = get_frame_pc (frame);
4971
4972       /* in_function_epilogue_p() returns a non-zero value if we're
4973          still in the function but the stack frame has already been
4974          invalidated.  Since we can't rely on the values of local
4975          variables after the stack has been destroyed, we are treating
4976          the watchpoint in that state as `not changed' without further
4977          checking.  Don't mark watchpoints as changed if the current
4978          frame is in an epilogue - even if they are in some other
4979          frame, our view of the stack is likely to be wrong and
4980          frame_find_by_id could error out.  */
4981       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4982         return WP_IGNORE;
4983
4984       fr = frame_find_by_id (b->watchpoint_frame);
4985       within_current_scope = (fr != NULL);
4986
4987       /* If we've gotten confused in the unwinder, we might have
4988          returned a frame that can't describe this variable.  */
4989       if (within_current_scope)
4990         {
4991           struct symbol *function;
4992
4993           function = get_frame_function (fr);
4994           if (function == NULL
4995               || !contained_in (b->exp_valid_block,
4996                                 SYMBOL_BLOCK_VALUE (function)))
4997             within_current_scope = 0;
4998         }
4999
5000       if (within_current_scope)
5001         /* If we end up stopping, the current frame will get selected
5002            in normal_stop.  So this call to select_frame won't affect
5003            the user.  */
5004         select_frame (fr);
5005     }
5006
5007   if (within_current_scope)
5008     {
5009       /* We use value_{,free_to_}mark because it could be a *long*
5010          time before we return to the command level and call
5011          free_all_values.  We can't call free_all_values because we
5012          might be in the middle of evaluating a function call.  */
5013
5014       int pc = 0;
5015       struct value *mark;
5016       struct value *new_val;
5017
5018       if (is_masked_watchpoint (&b->base))
5019         /* Since we don't know the exact trigger address (from
5020            stopped_data_address), just tell the user we've triggered
5021            a mask watchpoint.  */
5022         return WP_VALUE_CHANGED;
5023
5024       mark = value_mark ();
5025       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5026
5027       /* We use value_equal_contents instead of value_equal because
5028          the latter coerces an array to a pointer, thus comparing just
5029          the address of the array instead of its contents.  This is
5030          not what we want.  */
5031       if ((b->val != NULL) != (new_val != NULL)
5032           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5033         {
5034           if (new_val != NULL)
5035             {
5036               release_value (new_val);
5037               value_free_to_mark (mark);
5038             }
5039           bs->old_val = b->val;
5040           b->val = new_val;
5041           b->val_valid = 1;
5042           return WP_VALUE_CHANGED;
5043         }
5044       else
5045         {
5046           /* Nothing changed.  */
5047           value_free_to_mark (mark);
5048           return WP_VALUE_NOT_CHANGED;
5049         }
5050     }
5051   else
5052     {
5053       struct ui_out *uiout = current_uiout;
5054
5055       /* This seems like the only logical thing to do because
5056          if we temporarily ignored the watchpoint, then when
5057          we reenter the block in which it is valid it contains
5058          garbage (in the case of a function, it may have two
5059          garbage values, one before and one after the prologue).
5060          So we can't even detect the first assignment to it and
5061          watch after that (since the garbage may or may not equal
5062          the first value assigned).  */
5063       /* We print all the stop information in
5064          breakpoint_ops->print_it, but in this case, by the time we
5065          call breakpoint_ops->print_it this bp will be deleted
5066          already.  So we have no choice but print the information
5067          here.  */
5068       if (ui_out_is_mi_like_p (uiout))
5069         ui_out_field_string
5070           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5071       ui_out_text (uiout, "\nWatchpoint ");
5072       ui_out_field_int (uiout, "wpnum", b->base.number);
5073       ui_out_text (uiout,
5074                    " deleted because the program has left the block in\n\
5075 which its expression is valid.\n");     
5076
5077       /* Make sure the watchpoint's commands aren't executed.  */
5078       decref_counted_command_line (&b->base.commands);
5079       watchpoint_del_at_next_stop (b);
5080
5081       return WP_DELETED;
5082     }
5083 }
5084
5085 /* Return true if it looks like target has stopped due to hitting
5086    breakpoint location BL.  This function does not check if we should
5087    stop, only if BL explains the stop.  */
5088
5089 static int
5090 bpstat_check_location (const struct bp_location *bl,
5091                        struct address_space *aspace, CORE_ADDR bp_addr,
5092                        const struct target_waitstatus *ws)
5093 {
5094   struct breakpoint *b = bl->owner;
5095
5096   /* BL is from an existing breakpoint.  */
5097   gdb_assert (b != NULL);
5098
5099   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5100 }
5101
5102 /* Determine if the watched values have actually changed, and we
5103    should stop.  If not, set BS->stop to 0.  */
5104
5105 static void
5106 bpstat_check_watchpoint (bpstat bs)
5107 {
5108   const struct bp_location *bl;
5109   struct watchpoint *b;
5110
5111   /* BS is built for existing struct breakpoint.  */
5112   bl = bs->bp_location_at;
5113   gdb_assert (bl != NULL);
5114   b = (struct watchpoint *) bs->breakpoint_at;
5115   gdb_assert (b != NULL);
5116
5117     {
5118       int must_check_value = 0;
5119       
5120       if (b->base.type == bp_watchpoint)
5121         /* For a software watchpoint, we must always check the
5122            watched value.  */
5123         must_check_value = 1;
5124       else if (b->watchpoint_triggered == watch_triggered_yes)
5125         /* We have a hardware watchpoint (read, write, or access)
5126            and the target earlier reported an address watched by
5127            this watchpoint.  */
5128         must_check_value = 1;
5129       else if (b->watchpoint_triggered == watch_triggered_unknown
5130                && b->base.type == bp_hardware_watchpoint)
5131         /* We were stopped by a hardware watchpoint, but the target could
5132            not report the data address.  We must check the watchpoint's
5133            value.  Access and read watchpoints are out of luck; without
5134            a data address, we can't figure it out.  */
5135         must_check_value = 1;
5136
5137       if (must_check_value)
5138         {
5139           char *message
5140             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5141                           b->base.number);
5142           struct cleanup *cleanups = make_cleanup (xfree, message);
5143           int e = catch_errors (watchpoint_check, bs, message,
5144                                 RETURN_MASK_ALL);
5145           do_cleanups (cleanups);
5146           switch (e)
5147             {
5148             case WP_DELETED:
5149               /* We've already printed what needs to be printed.  */
5150               bs->print_it = print_it_done;
5151               /* Stop.  */
5152               break;
5153             case WP_IGNORE:
5154               bs->print_it = print_it_noop;
5155               bs->stop = 0;
5156               break;
5157             case WP_VALUE_CHANGED:
5158               if (b->base.type == bp_read_watchpoint)
5159                 {
5160                   /* There are two cases to consider here:
5161
5162                      1. We're watching the triggered memory for reads.
5163                      In that case, trust the target, and always report
5164                      the watchpoint hit to the user.  Even though
5165                      reads don't cause value changes, the value may
5166                      have changed since the last time it was read, and
5167                      since we're not trapping writes, we will not see
5168                      those, and as such we should ignore our notion of
5169                      old value.
5170
5171                      2. We're watching the triggered memory for both
5172                      reads and writes.  There are two ways this may
5173                      happen:
5174
5175                      2.1. This is a target that can't break on data
5176                      reads only, but can break on accesses (reads or
5177                      writes), such as e.g., x86.  We detect this case
5178                      at the time we try to insert read watchpoints.
5179
5180                      2.2. Otherwise, the target supports read
5181                      watchpoints, but, the user set an access or write
5182                      watchpoint watching the same memory as this read
5183                      watchpoint.
5184
5185                      If we're watching memory writes as well as reads,
5186                      ignore watchpoint hits when we find that the
5187                      value hasn't changed, as reads don't cause
5188                      changes.  This still gives false positives when
5189                      the program writes the same value to memory as
5190                      what there was already in memory (we will confuse
5191                      it for a read), but it's much better than
5192                      nothing.  */
5193
5194                   int other_write_watchpoint = 0;
5195
5196                   if (bl->watchpoint_type == hw_read)
5197                     {
5198                       struct breakpoint *other_b;
5199
5200                       ALL_BREAKPOINTS (other_b)
5201                         if (other_b->type == bp_hardware_watchpoint
5202                             || other_b->type == bp_access_watchpoint)
5203                           {
5204                             struct watchpoint *other_w =
5205                               (struct watchpoint *) other_b;
5206
5207                             if (other_w->watchpoint_triggered
5208                                 == watch_triggered_yes)
5209                               {
5210                                 other_write_watchpoint = 1;
5211                                 break;
5212                               }
5213                           }
5214                     }
5215
5216                   if (other_write_watchpoint
5217                       || bl->watchpoint_type == hw_access)
5218                     {
5219                       /* We're watching the same memory for writes,
5220                          and the value changed since the last time we
5221                          updated it, so this trap must be for a write.
5222                          Ignore it.  */
5223                       bs->print_it = print_it_noop;
5224                       bs->stop = 0;
5225                     }
5226                 }
5227               break;
5228             case WP_VALUE_NOT_CHANGED:
5229               if (b->base.type == bp_hardware_watchpoint
5230                   || b->base.type == bp_watchpoint)
5231                 {
5232                   /* Don't stop: write watchpoints shouldn't fire if
5233                      the value hasn't changed.  */
5234                   bs->print_it = print_it_noop;
5235                   bs->stop = 0;
5236                 }
5237               /* Stop.  */
5238               break;
5239             default:
5240               /* Can't happen.  */
5241             case 0:
5242               /* Error from catch_errors.  */
5243               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5244               watchpoint_del_at_next_stop (b);
5245               /* We've already printed what needs to be printed.  */
5246               bs->print_it = print_it_done;
5247               break;
5248             }
5249         }
5250       else      /* must_check_value == 0 */
5251         {
5252           /* This is a case where some watchpoint(s) triggered, but
5253              not at the address of this watchpoint, or else no
5254              watchpoint triggered after all.  So don't print
5255              anything for this watchpoint.  */
5256           bs->print_it = print_it_noop;
5257           bs->stop = 0;
5258         }
5259     }
5260 }
5261
5262 /* For breakpoints that are currently marked as telling gdb to stop,
5263    check conditions (condition proper, frame, thread and ignore count)
5264    of breakpoint referred to by BS.  If we should not stop for this
5265    breakpoint, set BS->stop to 0.  */
5266
5267 static void
5268 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5269 {
5270   const struct bp_location *bl;
5271   struct breakpoint *b;
5272   int value_is_zero = 0;
5273   struct expression *cond;
5274
5275   gdb_assert (bs->stop);
5276
5277   /* BS is built for existing struct breakpoint.  */
5278   bl = bs->bp_location_at;
5279   gdb_assert (bl != NULL);
5280   b = bs->breakpoint_at;
5281   gdb_assert (b != NULL);
5282
5283   /* Even if the target evaluated the condition on its end and notified GDB, we
5284      need to do so again since GDB does not know if we stopped due to a
5285      breakpoint or a single step breakpoint.  */
5286
5287   if (frame_id_p (b->frame_id)
5288       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5289     {
5290       bs->stop = 0;
5291       return;
5292     }
5293
5294   /* If this is a thread/task-specific breakpoint, don't waste cpu
5295      evaluating the condition if this isn't the specified
5296      thread/task.  */
5297   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5298       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5299
5300     {
5301       bs->stop = 0;
5302       return;
5303     }
5304
5305   /* Evaluate extension language breakpoints that have a "stop" method
5306      implemented.  */
5307   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5308
5309   if (is_watchpoint (b))
5310     {
5311       struct watchpoint *w = (struct watchpoint *) b;
5312
5313       cond = w->cond_exp;
5314     }
5315   else
5316     cond = bl->cond;
5317
5318   if (cond && b->disposition != disp_del_at_next_stop)
5319     {
5320       int within_current_scope = 1;
5321       struct watchpoint * w;
5322
5323       /* We use value_mark and value_free_to_mark because it could
5324          be a long time before we return to the command level and
5325          call free_all_values.  We can't call free_all_values
5326          because we might be in the middle of evaluating a
5327          function call.  */
5328       struct value *mark = value_mark ();
5329
5330       if (is_watchpoint (b))
5331         w = (struct watchpoint *) b;
5332       else
5333         w = NULL;
5334
5335       /* Need to select the frame, with all that implies so that
5336          the conditions will have the right context.  Because we
5337          use the frame, we will not see an inlined function's
5338          variables when we arrive at a breakpoint at the start
5339          of the inlined function; the current frame will be the
5340          call site.  */
5341       if (w == NULL || w->cond_exp_valid_block == NULL)
5342         select_frame (get_current_frame ());
5343       else
5344         {
5345           struct frame_info *frame;
5346
5347           /* For local watchpoint expressions, which particular
5348              instance of a local is being watched matters, so we
5349              keep track of the frame to evaluate the expression
5350              in.  To evaluate the condition however, it doesn't
5351              really matter which instantiation of the function
5352              where the condition makes sense triggers the
5353              watchpoint.  This allows an expression like "watch
5354              global if q > 10" set in `func', catch writes to
5355              global on all threads that call `func', or catch
5356              writes on all recursive calls of `func' by a single
5357              thread.  We simply always evaluate the condition in
5358              the innermost frame that's executing where it makes
5359              sense to evaluate the condition.  It seems
5360              intuitive.  */
5361           frame = block_innermost_frame (w->cond_exp_valid_block);
5362           if (frame != NULL)
5363             select_frame (frame);
5364           else
5365             within_current_scope = 0;
5366         }
5367       if (within_current_scope)
5368         value_is_zero
5369           = catch_errors (breakpoint_cond_eval, cond,
5370                           "Error in testing breakpoint condition:\n",
5371                           RETURN_MASK_ALL);
5372       else
5373         {
5374           warning (_("Watchpoint condition cannot be tested "
5375                      "in the current scope"));
5376           /* If we failed to set the right context for this
5377              watchpoint, unconditionally report it.  */
5378           value_is_zero = 0;
5379         }
5380       /* FIXME-someday, should give breakpoint #.  */
5381       value_free_to_mark (mark);
5382     }
5383
5384   if (cond && value_is_zero)
5385     {
5386       bs->stop = 0;
5387     }
5388   else if (b->ignore_count > 0)
5389     {
5390       b->ignore_count--;
5391       bs->stop = 0;
5392       /* Increase the hit count even though we don't stop.  */
5393       ++(b->hit_count);
5394       observer_notify_breakpoint_modified (b);
5395     }   
5396 }
5397
5398
5399 /* Get a bpstat associated with having just stopped at address
5400    BP_ADDR in thread PTID.
5401
5402    Determine whether we stopped at a breakpoint, etc, or whether we
5403    don't understand this stop.  Result is a chain of bpstat's such
5404    that:
5405
5406    if we don't understand the stop, the result is a null pointer.
5407
5408    if we understand why we stopped, the result is not null.
5409
5410    Each element of the chain refers to a particular breakpoint or
5411    watchpoint at which we have stopped.  (We may have stopped for
5412    several reasons concurrently.)
5413
5414    Each element of the chain has valid next, breakpoint_at,
5415    commands, FIXME??? fields.  */
5416
5417 bpstat
5418 bpstat_stop_status (struct address_space *aspace,
5419                     CORE_ADDR bp_addr, ptid_t ptid,
5420                     const struct target_waitstatus *ws)
5421 {
5422   struct breakpoint *b = NULL;
5423   struct bp_location *bl;
5424   struct bp_location *loc;
5425   /* First item of allocated bpstat's.  */
5426   bpstat bs_head = NULL, *bs_link = &bs_head;
5427   /* Pointer to the last thing in the chain currently.  */
5428   bpstat bs;
5429   int ix;
5430   int need_remove_insert;
5431   int removed_any;
5432
5433   /* First, build the bpstat chain with locations that explain a
5434      target stop, while being careful to not set the target running,
5435      as that may invalidate locations (in particular watchpoint
5436      locations are recreated).  Resuming will happen here with
5437      breakpoint conditions or watchpoint expressions that include
5438      inferior function calls.  */
5439
5440   ALL_BREAKPOINTS (b)
5441     {
5442       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5443         continue;
5444
5445       for (bl = b->loc; bl != NULL; bl = bl->next)
5446         {
5447           /* For hardware watchpoints, we look only at the first
5448              location.  The watchpoint_check function will work on the
5449              entire expression, not the individual locations.  For
5450              read watchpoints, the watchpoints_triggered function has
5451              checked all locations already.  */
5452           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5453             break;
5454
5455           if (!bl->enabled || bl->shlib_disabled)
5456             continue;
5457
5458           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5459             continue;
5460
5461           /* Come here if it's a watchpoint, or if the break address
5462              matches.  */
5463
5464           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5465                                                    explain stop.  */
5466
5467           /* Assume we stop.  Should we find a watchpoint that is not
5468              actually triggered, or if the condition of the breakpoint
5469              evaluates as false, we'll reset 'stop' to 0.  */
5470           bs->stop = 1;
5471           bs->print = 1;
5472
5473           /* If this is a scope breakpoint, mark the associated
5474              watchpoint as triggered so that we will handle the
5475              out-of-scope event.  We'll get to the watchpoint next
5476              iteration.  */
5477           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5478             {
5479               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5480
5481               w->watchpoint_triggered = watch_triggered_yes;
5482             }
5483         }
5484     }
5485
5486   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5487     {
5488       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5489         {
5490           bs = bpstat_alloc (loc, &bs_link);
5491           /* For hits of moribund locations, we should just proceed.  */
5492           bs->stop = 0;
5493           bs->print = 0;
5494           bs->print_it = print_it_noop;
5495         }
5496     }
5497
5498   /* A bit of special processing for shlib breakpoints.  We need to
5499      process solib loading here, so that the lists of loaded and
5500      unloaded libraries are correct before we handle "catch load" and
5501      "catch unload".  */
5502   for (bs = bs_head; bs != NULL; bs = bs->next)
5503     {
5504       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5505         {
5506           handle_solib_event ();
5507           break;
5508         }
5509     }
5510
5511   /* Now go through the locations that caused the target to stop, and
5512      check whether we're interested in reporting this stop to higher
5513      layers, or whether we should resume the target transparently.  */
5514
5515   removed_any = 0;
5516
5517   for (bs = bs_head; bs != NULL; bs = bs->next)
5518     {
5519       if (!bs->stop)
5520         continue;
5521
5522       b = bs->breakpoint_at;
5523       b->ops->check_status (bs);
5524       if (bs->stop)
5525         {
5526           bpstat_check_breakpoint_conditions (bs, ptid);
5527
5528           if (bs->stop)
5529             {
5530               ++(b->hit_count);
5531               observer_notify_breakpoint_modified (b);
5532
5533               /* We will stop here.  */
5534               if (b->disposition == disp_disable)
5535                 {
5536                   --(b->enable_count);
5537                   if (b->enable_count <= 0
5538                       && b->enable_state != bp_permanent)
5539                     b->enable_state = bp_disabled;
5540                   removed_any = 1;
5541                 }
5542               if (b->silent)
5543                 bs->print = 0;
5544               bs->commands = b->commands;
5545               incref_counted_command_line (bs->commands);
5546               if (command_line_is_silent (bs->commands
5547                                           ? bs->commands->commands : NULL))
5548                 bs->print = 0;
5549
5550               b->ops->after_condition_true (bs);
5551             }
5552
5553         }
5554
5555       /* Print nothing for this entry if we don't stop or don't
5556          print.  */
5557       if (!bs->stop || !bs->print)
5558         bs->print_it = print_it_noop;
5559     }
5560
5561   /* If we aren't stopping, the value of some hardware watchpoint may
5562      not have changed, but the intermediate memory locations we are
5563      watching may have.  Don't bother if we're stopping; this will get
5564      done later.  */
5565   need_remove_insert = 0;
5566   if (! bpstat_causes_stop (bs_head))
5567     for (bs = bs_head; bs != NULL; bs = bs->next)
5568       if (!bs->stop
5569           && bs->breakpoint_at
5570           && is_hardware_watchpoint (bs->breakpoint_at))
5571         {
5572           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5573
5574           update_watchpoint (w, 0 /* don't reparse.  */);
5575           need_remove_insert = 1;
5576         }
5577
5578   if (need_remove_insert)
5579     update_global_location_list (1);
5580   else if (removed_any)
5581     update_global_location_list (0);
5582
5583   return bs_head;
5584 }
5585
5586 static void
5587 handle_jit_event (void)
5588 {
5589   struct frame_info *frame;
5590   struct gdbarch *gdbarch;
5591
5592   /* Switch terminal for any messages produced by
5593      breakpoint_re_set.  */
5594   target_terminal_ours_for_output ();
5595
5596   frame = get_current_frame ();
5597   gdbarch = get_frame_arch (frame);
5598
5599   jit_event_handler (gdbarch);
5600
5601   target_terminal_inferior ();
5602 }
5603
5604 /* Prepare WHAT final decision for infrun.  */
5605
5606 /* Decide what infrun needs to do with this bpstat.  */
5607
5608 struct bpstat_what
5609 bpstat_what (bpstat bs_head)
5610 {
5611   struct bpstat_what retval;
5612   int jit_event = 0;
5613   bpstat bs;
5614
5615   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5616   retval.call_dummy = STOP_NONE;
5617   retval.is_longjmp = 0;
5618
5619   for (bs = bs_head; bs != NULL; bs = bs->next)
5620     {
5621       /* Extract this BS's action.  After processing each BS, we check
5622          if its action overrides all we've seem so far.  */
5623       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5624       enum bptype bptype;
5625
5626       if (bs->breakpoint_at == NULL)
5627         {
5628           /* I suspect this can happen if it was a momentary
5629              breakpoint which has since been deleted.  */
5630           bptype = bp_none;
5631         }
5632       else
5633         bptype = bs->breakpoint_at->type;
5634
5635       switch (bptype)
5636         {
5637         case bp_none:
5638           break;
5639         case bp_breakpoint:
5640         case bp_hardware_breakpoint:
5641         case bp_until:
5642         case bp_finish:
5643         case bp_shlib_event:
5644           if (bs->stop)
5645             {
5646               if (bs->print)
5647                 this_action = BPSTAT_WHAT_STOP_NOISY;
5648               else
5649                 this_action = BPSTAT_WHAT_STOP_SILENT;
5650             }
5651           else
5652             this_action = BPSTAT_WHAT_SINGLE;
5653           break;
5654         case bp_watchpoint:
5655         case bp_hardware_watchpoint:
5656         case bp_read_watchpoint:
5657         case bp_access_watchpoint:
5658           if (bs->stop)
5659             {
5660               if (bs->print)
5661                 this_action = BPSTAT_WHAT_STOP_NOISY;
5662               else
5663                 this_action = BPSTAT_WHAT_STOP_SILENT;
5664             }
5665           else
5666             {
5667               /* There was a watchpoint, but we're not stopping.
5668                  This requires no further action.  */
5669             }
5670           break;
5671         case bp_longjmp:
5672         case bp_longjmp_call_dummy:
5673         case bp_exception:
5674           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5675           retval.is_longjmp = bptype != bp_exception;
5676           break;
5677         case bp_longjmp_resume:
5678         case bp_exception_resume:
5679           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5680           retval.is_longjmp = bptype == bp_longjmp_resume;
5681           break;
5682         case bp_step_resume:
5683           if (bs->stop)
5684             this_action = BPSTAT_WHAT_STEP_RESUME;
5685           else
5686             {
5687               /* It is for the wrong frame.  */
5688               this_action = BPSTAT_WHAT_SINGLE;
5689             }
5690           break;
5691         case bp_hp_step_resume:
5692           if (bs->stop)
5693             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5694           else
5695             {
5696               /* It is for the wrong frame.  */
5697               this_action = BPSTAT_WHAT_SINGLE;
5698             }
5699           break;
5700         case bp_watchpoint_scope:
5701         case bp_thread_event:
5702         case bp_overlay_event:
5703         case bp_longjmp_master:
5704         case bp_std_terminate_master:
5705         case bp_exception_master:
5706           this_action = BPSTAT_WHAT_SINGLE;
5707           break;
5708         case bp_catchpoint:
5709           if (bs->stop)
5710             {
5711               if (bs->print)
5712                 this_action = BPSTAT_WHAT_STOP_NOISY;
5713               else
5714                 this_action = BPSTAT_WHAT_STOP_SILENT;
5715             }
5716           else
5717             {
5718               /* There was a catchpoint, but we're not stopping.
5719                  This requires no further action.  */
5720             }
5721           break;
5722         case bp_jit_event:
5723           jit_event = 1;
5724           this_action = BPSTAT_WHAT_SINGLE;
5725           break;
5726         case bp_call_dummy:
5727           /* Make sure the action is stop (silent or noisy),
5728              so infrun.c pops the dummy frame.  */
5729           retval.call_dummy = STOP_STACK_DUMMY;
5730           this_action = BPSTAT_WHAT_STOP_SILENT;
5731           break;
5732         case bp_std_terminate:
5733           /* Make sure the action is stop (silent or noisy),
5734              so infrun.c pops the dummy frame.  */
5735           retval.call_dummy = STOP_STD_TERMINATE;
5736           this_action = BPSTAT_WHAT_STOP_SILENT;
5737           break;
5738         case bp_tracepoint:
5739         case bp_fast_tracepoint:
5740         case bp_static_tracepoint:
5741           /* Tracepoint hits should not be reported back to GDB, and
5742              if one got through somehow, it should have been filtered
5743              out already.  */
5744           internal_error (__FILE__, __LINE__,
5745                           _("bpstat_what: tracepoint encountered"));
5746           break;
5747         case bp_gnu_ifunc_resolver:
5748           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5749           this_action = BPSTAT_WHAT_SINGLE;
5750           break;
5751         case bp_gnu_ifunc_resolver_return:
5752           /* The breakpoint will be removed, execution will restart from the
5753              PC of the former breakpoint.  */
5754           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5755           break;
5756
5757         case bp_dprintf:
5758           if (bs->stop)
5759             this_action = BPSTAT_WHAT_STOP_SILENT;
5760           else
5761             this_action = BPSTAT_WHAT_SINGLE;
5762           break;
5763
5764         default:
5765           internal_error (__FILE__, __LINE__,
5766                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5767         }
5768
5769       retval.main_action = max (retval.main_action, this_action);
5770     }
5771
5772   /* These operations may affect the bs->breakpoint_at state so they are
5773      delayed after MAIN_ACTION is decided above.  */
5774
5775   if (jit_event)
5776     {
5777       if (debug_infrun)
5778         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5779
5780       handle_jit_event ();
5781     }
5782
5783   for (bs = bs_head; bs != NULL; bs = bs->next)
5784     {
5785       struct breakpoint *b = bs->breakpoint_at;
5786
5787       if (b == NULL)
5788         continue;
5789       switch (b->type)
5790         {
5791         case bp_gnu_ifunc_resolver:
5792           gnu_ifunc_resolver_stop (b);
5793           break;
5794         case bp_gnu_ifunc_resolver_return:
5795           gnu_ifunc_resolver_return_stop (b);
5796           break;
5797         }
5798     }
5799
5800   return retval;
5801 }
5802
5803 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5804    without hardware support).  This isn't related to a specific bpstat,
5805    just to things like whether watchpoints are set.  */
5806
5807 int
5808 bpstat_should_step (void)
5809 {
5810   struct breakpoint *b;
5811
5812   ALL_BREAKPOINTS (b)
5813     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5814       return 1;
5815   return 0;
5816 }
5817
5818 int
5819 bpstat_causes_stop (bpstat bs)
5820 {
5821   for (; bs != NULL; bs = bs->next)
5822     if (bs->stop)
5823       return 1;
5824
5825   return 0;
5826 }
5827
5828 \f
5829
5830 /* Compute a string of spaces suitable to indent the next line
5831    so it starts at the position corresponding to the table column
5832    named COL_NAME in the currently active table of UIOUT.  */
5833
5834 static char *
5835 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5836 {
5837   static char wrap_indent[80];
5838   int i, total_width, width, align;
5839   char *text;
5840
5841   total_width = 0;
5842   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5843     {
5844       if (strcmp (text, col_name) == 0)
5845         {
5846           gdb_assert (total_width < sizeof wrap_indent);
5847           memset (wrap_indent, ' ', total_width);
5848           wrap_indent[total_width] = 0;
5849
5850           return wrap_indent;
5851         }
5852
5853       total_width += width + 1;
5854     }
5855
5856   return NULL;
5857 }
5858
5859 /* Determine if the locations of this breakpoint will have their conditions
5860    evaluated by the target, host or a mix of both.  Returns the following:
5861
5862     "host": Host evals condition.
5863     "host or target": Host or Target evals condition.
5864     "target": Target evals condition.
5865 */
5866
5867 static const char *
5868 bp_condition_evaluator (struct breakpoint *b)
5869 {
5870   struct bp_location *bl;
5871   char host_evals = 0;
5872   char target_evals = 0;
5873
5874   if (!b)
5875     return NULL;
5876
5877   if (!is_breakpoint (b))
5878     return NULL;
5879
5880   if (gdb_evaluates_breakpoint_condition_p ()
5881       || !target_supports_evaluation_of_breakpoint_conditions ())
5882     return condition_evaluation_host;
5883
5884   for (bl = b->loc; bl; bl = bl->next)
5885     {
5886       if (bl->cond_bytecode)
5887         target_evals++;
5888       else
5889         host_evals++;
5890     }
5891
5892   if (host_evals && target_evals)
5893     return condition_evaluation_both;
5894   else if (target_evals)
5895     return condition_evaluation_target;
5896   else
5897     return condition_evaluation_host;
5898 }
5899
5900 /* Determine the breakpoint location's condition evaluator.  This is
5901    similar to bp_condition_evaluator, but for locations.  */
5902
5903 static const char *
5904 bp_location_condition_evaluator (struct bp_location *bl)
5905 {
5906   if (bl && !is_breakpoint (bl->owner))
5907     return NULL;
5908
5909   if (gdb_evaluates_breakpoint_condition_p ()
5910       || !target_supports_evaluation_of_breakpoint_conditions ())
5911     return condition_evaluation_host;
5912
5913   if (bl && bl->cond_bytecode)
5914     return condition_evaluation_target;
5915   else
5916     return condition_evaluation_host;
5917 }
5918
5919 /* Print the LOC location out of the list of B->LOC locations.  */
5920
5921 static void
5922 print_breakpoint_location (struct breakpoint *b,
5923                            struct bp_location *loc)
5924 {
5925   struct ui_out *uiout = current_uiout;
5926   struct cleanup *old_chain = save_current_program_space ();
5927
5928   if (loc != NULL && loc->shlib_disabled)
5929     loc = NULL;
5930
5931   if (loc != NULL)
5932     set_current_program_space (loc->pspace);
5933
5934   if (b->display_canonical)
5935     ui_out_field_string (uiout, "what", b->addr_string);
5936   else if (loc && loc->symtab)
5937     {
5938       struct symbol *sym 
5939         = find_pc_sect_function (loc->address, loc->section);
5940       if (sym)
5941         {
5942           ui_out_text (uiout, "in ");
5943           ui_out_field_string (uiout, "func",
5944                                SYMBOL_PRINT_NAME (sym));
5945           ui_out_text (uiout, " ");
5946           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5947           ui_out_text (uiout, "at ");
5948         }
5949       ui_out_field_string (uiout, "file",
5950                            symtab_to_filename_for_display (loc->symtab));
5951       ui_out_text (uiout, ":");
5952
5953       if (ui_out_is_mi_like_p (uiout))
5954         ui_out_field_string (uiout, "fullname",
5955                              symtab_to_fullname (loc->symtab));
5956       
5957       ui_out_field_int (uiout, "line", loc->line_number);
5958     }
5959   else if (loc)
5960     {
5961       struct ui_file *stb = mem_fileopen ();
5962       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5963
5964       print_address_symbolic (loc->gdbarch, loc->address, stb,
5965                               demangle, "");
5966       ui_out_field_stream (uiout, "at", stb);
5967
5968       do_cleanups (stb_chain);
5969     }
5970   else
5971     ui_out_field_string (uiout, "pending", b->addr_string);
5972
5973   if (loc && is_breakpoint (b)
5974       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5975       && bp_condition_evaluator (b) == condition_evaluation_both)
5976     {
5977       ui_out_text (uiout, " (");
5978       ui_out_field_string (uiout, "evaluated-by",
5979                            bp_location_condition_evaluator (loc));
5980       ui_out_text (uiout, ")");
5981     }
5982
5983   do_cleanups (old_chain);
5984 }
5985
5986 static const char *
5987 bptype_string (enum bptype type)
5988 {
5989   struct ep_type_description
5990     {
5991       enum bptype type;
5992       char *description;
5993     };
5994   static struct ep_type_description bptypes[] =
5995   {
5996     {bp_none, "?deleted?"},
5997     {bp_breakpoint, "breakpoint"},
5998     {bp_hardware_breakpoint, "hw breakpoint"},
5999     {bp_until, "until"},
6000     {bp_finish, "finish"},
6001     {bp_watchpoint, "watchpoint"},
6002     {bp_hardware_watchpoint, "hw watchpoint"},
6003     {bp_read_watchpoint, "read watchpoint"},
6004     {bp_access_watchpoint, "acc watchpoint"},
6005     {bp_longjmp, "longjmp"},
6006     {bp_longjmp_resume, "longjmp resume"},
6007     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6008     {bp_exception, "exception"},
6009     {bp_exception_resume, "exception resume"},
6010     {bp_step_resume, "step resume"},
6011     {bp_hp_step_resume, "high-priority step resume"},
6012     {bp_watchpoint_scope, "watchpoint scope"},
6013     {bp_call_dummy, "call dummy"},
6014     {bp_std_terminate, "std::terminate"},
6015     {bp_shlib_event, "shlib events"},
6016     {bp_thread_event, "thread events"},
6017     {bp_overlay_event, "overlay events"},
6018     {bp_longjmp_master, "longjmp master"},
6019     {bp_std_terminate_master, "std::terminate master"},
6020     {bp_exception_master, "exception master"},
6021     {bp_catchpoint, "catchpoint"},
6022     {bp_tracepoint, "tracepoint"},
6023     {bp_fast_tracepoint, "fast tracepoint"},
6024     {bp_static_tracepoint, "static tracepoint"},
6025     {bp_dprintf, "dprintf"},
6026     {bp_jit_event, "jit events"},
6027     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6028     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6029   };
6030
6031   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6032       || ((int) type != bptypes[(int) type].type))
6033     internal_error (__FILE__, __LINE__,
6034                     _("bptypes table does not describe type #%d."),
6035                     (int) type);
6036
6037   return bptypes[(int) type].description;
6038 }
6039
6040 /* For MI, output a field named 'thread-groups' with a list as the value.
6041    For CLI, prefix the list with the string 'inf'. */
6042
6043 static void
6044 output_thread_groups (struct ui_out *uiout,
6045                       const char *field_name,
6046                       VEC(int) *inf_num,
6047                       int mi_only)
6048 {
6049   struct cleanup *back_to;
6050   int is_mi = ui_out_is_mi_like_p (uiout);
6051   int inf;
6052   int i;
6053
6054   /* For backward compatibility, don't display inferiors in CLI unless
6055      there are several.  Always display them for MI. */
6056   if (!is_mi && mi_only)
6057     return;
6058
6059   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6060
6061   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6062     {
6063       if (is_mi)
6064         {
6065           char mi_group[10];
6066
6067           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6068           ui_out_field_string (uiout, NULL, mi_group);
6069         }
6070       else
6071         {
6072           if (i == 0)
6073             ui_out_text (uiout, " inf ");
6074           else
6075             ui_out_text (uiout, ", ");
6076         
6077           ui_out_text (uiout, plongest (inf));
6078         }
6079     }
6080
6081   do_cleanups (back_to);
6082 }
6083
6084 /* Print B to gdb_stdout.  */
6085
6086 static void
6087 print_one_breakpoint_location (struct breakpoint *b,
6088                                struct bp_location *loc,
6089                                int loc_number,
6090                                struct bp_location **last_loc,
6091                                int allflag)
6092 {
6093   struct command_line *l;
6094   static char bpenables[] = "nynny";
6095
6096   struct ui_out *uiout = current_uiout;
6097   int header_of_multiple = 0;
6098   int part_of_multiple = (loc != NULL);
6099   struct value_print_options opts;
6100
6101   get_user_print_options (&opts);
6102
6103   gdb_assert (!loc || loc_number != 0);
6104   /* See comment in print_one_breakpoint concerning treatment of
6105      breakpoints with single disabled location.  */
6106   if (loc == NULL 
6107       && (b->loc != NULL 
6108           && (b->loc->next != NULL || !b->loc->enabled)))
6109     header_of_multiple = 1;
6110   if (loc == NULL)
6111     loc = b->loc;
6112
6113   annotate_record ();
6114
6115   /* 1 */
6116   annotate_field (0);
6117   if (part_of_multiple)
6118     {
6119       char *formatted;
6120       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6121       ui_out_field_string (uiout, "number", formatted);
6122       xfree (formatted);
6123     }
6124   else
6125     {
6126       ui_out_field_int (uiout, "number", b->number);
6127     }
6128
6129   /* 2 */
6130   annotate_field (1);
6131   if (part_of_multiple)
6132     ui_out_field_skip (uiout, "type");
6133   else
6134     ui_out_field_string (uiout, "type", bptype_string (b->type));
6135
6136   /* 3 */
6137   annotate_field (2);
6138   if (part_of_multiple)
6139     ui_out_field_skip (uiout, "disp");
6140   else
6141     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6142
6143
6144   /* 4 */
6145   annotate_field (3);
6146   if (part_of_multiple)
6147     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6148   else
6149     ui_out_field_fmt (uiout, "enabled", "%c", 
6150                       bpenables[(int) b->enable_state]);
6151   ui_out_spaces (uiout, 2);
6152
6153   
6154   /* 5 and 6 */
6155   if (b->ops != NULL && b->ops->print_one != NULL)
6156     {
6157       /* Although the print_one can possibly print all locations,
6158          calling it here is not likely to get any nice result.  So,
6159          make sure there's just one location.  */
6160       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6161       b->ops->print_one (b, last_loc);
6162     }
6163   else
6164     switch (b->type)
6165       {
6166       case bp_none:
6167         internal_error (__FILE__, __LINE__,
6168                         _("print_one_breakpoint: bp_none encountered\n"));
6169         break;
6170
6171       case bp_watchpoint:
6172       case bp_hardware_watchpoint:
6173       case bp_read_watchpoint:
6174       case bp_access_watchpoint:
6175         {
6176           struct watchpoint *w = (struct watchpoint *) b;
6177
6178           /* Field 4, the address, is omitted (which makes the columns
6179              not line up too nicely with the headers, but the effect
6180              is relatively readable).  */
6181           if (opts.addressprint)
6182             ui_out_field_skip (uiout, "addr");
6183           annotate_field (5);
6184           ui_out_field_string (uiout, "what", w->exp_string);
6185         }
6186         break;
6187
6188       case bp_breakpoint:
6189       case bp_hardware_breakpoint:
6190       case bp_until:
6191       case bp_finish:
6192       case bp_longjmp:
6193       case bp_longjmp_resume:
6194       case bp_longjmp_call_dummy:
6195       case bp_exception:
6196       case bp_exception_resume:
6197       case bp_step_resume:
6198       case bp_hp_step_resume:
6199       case bp_watchpoint_scope:
6200       case bp_call_dummy:
6201       case bp_std_terminate:
6202       case bp_shlib_event:
6203       case bp_thread_event:
6204       case bp_overlay_event:
6205       case bp_longjmp_master:
6206       case bp_std_terminate_master:
6207       case bp_exception_master:
6208       case bp_tracepoint:
6209       case bp_fast_tracepoint:
6210       case bp_static_tracepoint:
6211       case bp_dprintf:
6212       case bp_jit_event:
6213       case bp_gnu_ifunc_resolver:
6214       case bp_gnu_ifunc_resolver_return:
6215         if (opts.addressprint)
6216           {
6217             annotate_field (4);
6218             if (header_of_multiple)
6219               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6220             else if (b->loc == NULL || loc->shlib_disabled)
6221               ui_out_field_string (uiout, "addr", "<PENDING>");
6222             else
6223               ui_out_field_core_addr (uiout, "addr",
6224                                       loc->gdbarch, loc->address);
6225           }
6226         annotate_field (5);
6227         if (!header_of_multiple)
6228           print_breakpoint_location (b, loc);
6229         if (b->loc)
6230           *last_loc = b->loc;
6231         break;
6232       }
6233
6234
6235   if (loc != NULL && !header_of_multiple)
6236     {
6237       struct inferior *inf;
6238       VEC(int) *inf_num = NULL;
6239       int mi_only = 1;
6240
6241       ALL_INFERIORS (inf)
6242         {
6243           if (inf->pspace == loc->pspace)
6244             VEC_safe_push (int, inf_num, inf->num);
6245         }
6246
6247         /* For backward compatibility, don't display inferiors in CLI unless
6248            there are several.  Always display for MI. */
6249         if (allflag
6250             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6251                 && (number_of_program_spaces () > 1
6252                     || number_of_inferiors () > 1)
6253                 /* LOC is for existing B, it cannot be in
6254                    moribund_locations and thus having NULL OWNER.  */
6255                 && loc->owner->type != bp_catchpoint))
6256         mi_only = 0;
6257       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6258       VEC_free (int, inf_num);
6259     }
6260
6261   if (!part_of_multiple)
6262     {
6263       if (b->thread != -1)
6264         {
6265           /* FIXME: This seems to be redundant and lost here; see the
6266              "stop only in" line a little further down.  */
6267           ui_out_text (uiout, " thread ");
6268           ui_out_field_int (uiout, "thread", b->thread);
6269         }
6270       else if (b->task != 0)
6271         {
6272           ui_out_text (uiout, " task ");
6273           ui_out_field_int (uiout, "task", b->task);
6274         }
6275     }
6276
6277   ui_out_text (uiout, "\n");
6278
6279   if (!part_of_multiple)
6280     b->ops->print_one_detail (b, uiout);
6281
6282   if (part_of_multiple && frame_id_p (b->frame_id))
6283     {
6284       annotate_field (6);
6285       ui_out_text (uiout, "\tstop only in stack frame at ");
6286       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6287          the frame ID.  */
6288       ui_out_field_core_addr (uiout, "frame",
6289                               b->gdbarch, b->frame_id.stack_addr);
6290       ui_out_text (uiout, "\n");
6291     }
6292   
6293   if (!part_of_multiple && b->cond_string)
6294     {
6295       annotate_field (7);
6296       if (is_tracepoint (b))
6297         ui_out_text (uiout, "\ttrace only if ");
6298       else
6299         ui_out_text (uiout, "\tstop only if ");
6300       ui_out_field_string (uiout, "cond", b->cond_string);
6301
6302       /* Print whether the target is doing the breakpoint's condition
6303          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6304       if (is_breakpoint (b)
6305           && breakpoint_condition_evaluation_mode ()
6306           == condition_evaluation_target)
6307         {
6308           ui_out_text (uiout, " (");
6309           ui_out_field_string (uiout, "evaluated-by",
6310                                bp_condition_evaluator (b));
6311           ui_out_text (uiout, " evals)");
6312         }
6313       ui_out_text (uiout, "\n");
6314     }
6315
6316   if (!part_of_multiple && b->thread != -1)
6317     {
6318       /* FIXME should make an annotation for this.  */
6319       ui_out_text (uiout, "\tstop only in thread ");
6320       ui_out_field_int (uiout, "thread", b->thread);
6321       ui_out_text (uiout, "\n");
6322     }
6323   
6324   if (!part_of_multiple)
6325     {
6326       if (b->hit_count)
6327         {
6328           /* FIXME should make an annotation for this.  */
6329           if (is_catchpoint (b))
6330             ui_out_text (uiout, "\tcatchpoint");
6331           else if (is_tracepoint (b))
6332             ui_out_text (uiout, "\ttracepoint");
6333           else
6334             ui_out_text (uiout, "\tbreakpoint");
6335           ui_out_text (uiout, " already hit ");
6336           ui_out_field_int (uiout, "times", b->hit_count);
6337           if (b->hit_count == 1)
6338             ui_out_text (uiout, " time\n");
6339           else
6340             ui_out_text (uiout, " times\n");
6341         }
6342       else
6343         {
6344           /* Output the count also if it is zero, but only if this is mi.  */
6345           if (ui_out_is_mi_like_p (uiout))
6346             ui_out_field_int (uiout, "times", b->hit_count);
6347         }
6348     }
6349
6350   if (!part_of_multiple && b->ignore_count)
6351     {
6352       annotate_field (8);
6353       ui_out_text (uiout, "\tignore next ");
6354       ui_out_field_int (uiout, "ignore", b->ignore_count);
6355       ui_out_text (uiout, " hits\n");
6356     }
6357
6358   /* Note that an enable count of 1 corresponds to "enable once"
6359      behavior, which is reported by the combination of enablement and
6360      disposition, so we don't need to mention it here.  */
6361   if (!part_of_multiple && b->enable_count > 1)
6362     {
6363       annotate_field (8);
6364       ui_out_text (uiout, "\tdisable after ");
6365       /* Tweak the wording to clarify that ignore and enable counts
6366          are distinct, and have additive effect.  */
6367       if (b->ignore_count)
6368         ui_out_text (uiout, "additional ");
6369       else
6370         ui_out_text (uiout, "next ");
6371       ui_out_field_int (uiout, "enable", b->enable_count);
6372       ui_out_text (uiout, " hits\n");
6373     }
6374
6375   if (!part_of_multiple && is_tracepoint (b))
6376     {
6377       struct tracepoint *tp = (struct tracepoint *) b;
6378
6379       if (tp->traceframe_usage)
6380         {
6381           ui_out_text (uiout, "\ttrace buffer usage ");
6382           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6383           ui_out_text (uiout, " bytes\n");
6384         }
6385     }
6386
6387   l = b->commands ? b->commands->commands : NULL;
6388   if (!part_of_multiple && l)
6389     {
6390       struct cleanup *script_chain;
6391
6392       annotate_field (9);
6393       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6394       print_command_lines (uiout, l, 4);
6395       do_cleanups (script_chain);
6396     }
6397
6398   if (is_tracepoint (b))
6399     {
6400       struct tracepoint *t = (struct tracepoint *) b;
6401
6402       if (!part_of_multiple && t->pass_count)
6403         {
6404           annotate_field (10);
6405           ui_out_text (uiout, "\tpass count ");
6406           ui_out_field_int (uiout, "pass", t->pass_count);
6407           ui_out_text (uiout, " \n");
6408         }
6409
6410       /* Don't display it when tracepoint or tracepoint location is
6411          pending.   */
6412       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6413         {
6414           annotate_field (11);
6415
6416           if (ui_out_is_mi_like_p (uiout))
6417             ui_out_field_string (uiout, "installed",
6418                                  loc->inserted ? "y" : "n");
6419           else
6420             {
6421               if (loc->inserted)
6422                 ui_out_text (uiout, "\t");
6423               else
6424                 ui_out_text (uiout, "\tnot ");
6425               ui_out_text (uiout, "installed on target\n");
6426             }
6427         }
6428     }
6429
6430   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6431     {
6432       if (is_watchpoint (b))
6433         {
6434           struct watchpoint *w = (struct watchpoint *) b;
6435
6436           ui_out_field_string (uiout, "original-location", w->exp_string);
6437         }
6438       else if (b->addr_string)
6439         ui_out_field_string (uiout, "original-location", b->addr_string);
6440     }
6441 }
6442
6443 static void
6444 print_one_breakpoint (struct breakpoint *b,
6445                       struct bp_location **last_loc, 
6446                       int allflag)
6447 {
6448   struct cleanup *bkpt_chain;
6449   struct ui_out *uiout = current_uiout;
6450
6451   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6452
6453   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6454   do_cleanups (bkpt_chain);
6455
6456   /* If this breakpoint has custom print function,
6457      it's already printed.  Otherwise, print individual
6458      locations, if any.  */
6459   if (b->ops == NULL || b->ops->print_one == NULL)
6460     {
6461       /* If breakpoint has a single location that is disabled, we
6462          print it as if it had several locations, since otherwise it's
6463          hard to represent "breakpoint enabled, location disabled"
6464          situation.
6465
6466          Note that while hardware watchpoints have several locations
6467          internally, that's not a property exposed to user.  */
6468       if (b->loc 
6469           && !is_hardware_watchpoint (b)
6470           && (b->loc->next || !b->loc->enabled))
6471         {
6472           struct bp_location *loc;
6473           int n = 1;
6474
6475           for (loc = b->loc; loc; loc = loc->next, ++n)
6476             {
6477               struct cleanup *inner2 =
6478                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6479               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6480               do_cleanups (inner2);
6481             }
6482         }
6483     }
6484 }
6485
6486 static int
6487 breakpoint_address_bits (struct breakpoint *b)
6488 {
6489   int print_address_bits = 0;
6490   struct bp_location *loc;
6491
6492   for (loc = b->loc; loc; loc = loc->next)
6493     {
6494       int addr_bit;
6495
6496       /* Software watchpoints that aren't watching memory don't have
6497          an address to print.  */
6498       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6499         continue;
6500
6501       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6502       if (addr_bit > print_address_bits)
6503         print_address_bits = addr_bit;
6504     }
6505
6506   return print_address_bits;
6507 }
6508
6509 struct captured_breakpoint_query_args
6510   {
6511     int bnum;
6512   };
6513
6514 static int
6515 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6516 {
6517   struct captured_breakpoint_query_args *args = data;
6518   struct breakpoint *b;
6519   struct bp_location *dummy_loc = NULL;
6520
6521   ALL_BREAKPOINTS (b)
6522     {
6523       if (args->bnum == b->number)
6524         {
6525           print_one_breakpoint (b, &dummy_loc, 0);
6526           return GDB_RC_OK;
6527         }
6528     }
6529   return GDB_RC_NONE;
6530 }
6531
6532 enum gdb_rc
6533 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6534                       char **error_message)
6535 {
6536   struct captured_breakpoint_query_args args;
6537
6538   args.bnum = bnum;
6539   /* For the moment we don't trust print_one_breakpoint() to not throw
6540      an error.  */
6541   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6542                                  error_message, RETURN_MASK_ALL) < 0)
6543     return GDB_RC_FAIL;
6544   else
6545     return GDB_RC_OK;
6546 }
6547
6548 /* Return true if this breakpoint was set by the user, false if it is
6549    internal or momentary.  */
6550
6551 int
6552 user_breakpoint_p (struct breakpoint *b)
6553 {
6554   return b->number > 0;
6555 }
6556
6557 /* Print information on user settable breakpoint (watchpoint, etc)
6558    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6559    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6560    FILTER is non-NULL, call it on each breakpoint and only include the
6561    ones for which it returns non-zero.  Return the total number of
6562    breakpoints listed.  */
6563
6564 static int
6565 breakpoint_1 (char *args, int allflag, 
6566               int (*filter) (const struct breakpoint *))
6567 {
6568   struct breakpoint *b;
6569   struct bp_location *last_loc = NULL;
6570   int nr_printable_breakpoints;
6571   struct cleanup *bkpttbl_chain;
6572   struct value_print_options opts;
6573   int print_address_bits = 0;
6574   int print_type_col_width = 14;
6575   struct ui_out *uiout = current_uiout;
6576
6577   get_user_print_options (&opts);
6578
6579   /* Compute the number of rows in the table, as well as the size
6580      required for address fields.  */
6581   nr_printable_breakpoints = 0;
6582   ALL_BREAKPOINTS (b)
6583     {
6584       /* If we have a filter, only list the breakpoints it accepts.  */
6585       if (filter && !filter (b))
6586         continue;
6587
6588       /* If we have an "args" string, it is a list of breakpoints to 
6589          accept.  Skip the others.  */
6590       if (args != NULL && *args != '\0')
6591         {
6592           if (allflag && parse_and_eval_long (args) != b->number)
6593             continue;
6594           if (!allflag && !number_is_in_list (args, b->number))
6595             continue;
6596         }
6597
6598       if (allflag || user_breakpoint_p (b))
6599         {
6600           int addr_bit, type_len;
6601
6602           addr_bit = breakpoint_address_bits (b);
6603           if (addr_bit > print_address_bits)
6604             print_address_bits = addr_bit;
6605
6606           type_len = strlen (bptype_string (b->type));
6607           if (type_len > print_type_col_width)
6608             print_type_col_width = type_len;
6609
6610           nr_printable_breakpoints++;
6611         }
6612     }
6613
6614   if (opts.addressprint)
6615     bkpttbl_chain 
6616       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6617                                              nr_printable_breakpoints,
6618                                              "BreakpointTable");
6619   else
6620     bkpttbl_chain 
6621       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6622                                              nr_printable_breakpoints,
6623                                              "BreakpointTable");
6624
6625   if (nr_printable_breakpoints > 0)
6626     annotate_breakpoints_headers ();
6627   if (nr_printable_breakpoints > 0)
6628     annotate_field (0);
6629   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6630   if (nr_printable_breakpoints > 0)
6631     annotate_field (1);
6632   ui_out_table_header (uiout, print_type_col_width, ui_left,
6633                        "type", "Type");                         /* 2 */
6634   if (nr_printable_breakpoints > 0)
6635     annotate_field (2);
6636   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6637   if (nr_printable_breakpoints > 0)
6638     annotate_field (3);
6639   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6640   if (opts.addressprint)
6641     {
6642       if (nr_printable_breakpoints > 0)
6643         annotate_field (4);
6644       if (print_address_bits <= 32)
6645         ui_out_table_header (uiout, 10, ui_left, 
6646                              "addr", "Address");                /* 5 */
6647       else
6648         ui_out_table_header (uiout, 18, ui_left, 
6649                              "addr", "Address");                /* 5 */
6650     }
6651   if (nr_printable_breakpoints > 0)
6652     annotate_field (5);
6653   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6654   ui_out_table_body (uiout);
6655   if (nr_printable_breakpoints > 0)
6656     annotate_breakpoints_table ();
6657
6658   ALL_BREAKPOINTS (b)
6659     {
6660       QUIT;
6661       /* If we have a filter, only list the breakpoints it accepts.  */
6662       if (filter && !filter (b))
6663         continue;
6664
6665       /* If we have an "args" string, it is a list of breakpoints to 
6666          accept.  Skip the others.  */
6667
6668       if (args != NULL && *args != '\0')
6669         {
6670           if (allflag)  /* maintenance info breakpoint */
6671             {
6672               if (parse_and_eval_long (args) != b->number)
6673                 continue;
6674             }
6675           else          /* all others */
6676             {
6677               if (!number_is_in_list (args, b->number))
6678                 continue;
6679             }
6680         }
6681       /* We only print out user settable breakpoints unless the
6682          allflag is set.  */
6683       if (allflag || user_breakpoint_p (b))
6684         print_one_breakpoint (b, &last_loc, allflag);
6685     }
6686
6687   do_cleanups (bkpttbl_chain);
6688
6689   if (nr_printable_breakpoints == 0)
6690     {
6691       /* If there's a filter, let the caller decide how to report
6692          empty list.  */
6693       if (!filter)
6694         {
6695           if (args == NULL || *args == '\0')
6696             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6697           else
6698             ui_out_message (uiout, 0, 
6699                             "No breakpoint or watchpoint matching '%s'.\n",
6700                             args);
6701         }
6702     }
6703   else
6704     {
6705       if (last_loc && !server_command)
6706         set_next_address (last_loc->gdbarch, last_loc->address);
6707     }
6708
6709   /* FIXME?  Should this be moved up so that it is only called when
6710      there have been breakpoints? */
6711   annotate_breakpoints_table_end ();
6712
6713   return nr_printable_breakpoints;
6714 }
6715
6716 /* Display the value of default-collect in a way that is generally
6717    compatible with the breakpoint list.  */
6718
6719 static void
6720 default_collect_info (void)
6721 {
6722   struct ui_out *uiout = current_uiout;
6723
6724   /* If it has no value (which is frequently the case), say nothing; a
6725      message like "No default-collect." gets in user's face when it's
6726      not wanted.  */
6727   if (!*default_collect)
6728     return;
6729
6730   /* The following phrase lines up nicely with per-tracepoint collect
6731      actions.  */
6732   ui_out_text (uiout, "default collect ");
6733   ui_out_field_string (uiout, "default-collect", default_collect);
6734   ui_out_text (uiout, " \n");
6735 }
6736   
6737 static void
6738 breakpoints_info (char *args, int from_tty)
6739 {
6740   breakpoint_1 (args, 0, NULL);
6741
6742   default_collect_info ();
6743 }
6744
6745 static void
6746 watchpoints_info (char *args, int from_tty)
6747 {
6748   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6749   struct ui_out *uiout = current_uiout;
6750
6751   if (num_printed == 0)
6752     {
6753       if (args == NULL || *args == '\0')
6754         ui_out_message (uiout, 0, "No watchpoints.\n");
6755       else
6756         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6757     }
6758 }
6759
6760 static void
6761 maintenance_info_breakpoints (char *args, int from_tty)
6762 {
6763   breakpoint_1 (args, 1, NULL);
6764
6765   default_collect_info ();
6766 }
6767
6768 static int
6769 breakpoint_has_pc (struct breakpoint *b,
6770                    struct program_space *pspace,
6771                    CORE_ADDR pc, struct obj_section *section)
6772 {
6773   struct bp_location *bl = b->loc;
6774
6775   for (; bl; bl = bl->next)
6776     {
6777       if (bl->pspace == pspace
6778           && bl->address == pc
6779           && (!overlay_debugging || bl->section == section))
6780         return 1;         
6781     }
6782   return 0;
6783 }
6784
6785 /* Print a message describing any user-breakpoints set at PC.  This
6786    concerns with logical breakpoints, so we match program spaces, not
6787    address spaces.  */
6788
6789 static void
6790 describe_other_breakpoints (struct gdbarch *gdbarch,
6791                             struct program_space *pspace, CORE_ADDR pc,
6792                             struct obj_section *section, int thread)
6793 {
6794   int others = 0;
6795   struct breakpoint *b;
6796
6797   ALL_BREAKPOINTS (b)
6798     others += (user_breakpoint_p (b)
6799                && breakpoint_has_pc (b, pspace, pc, section));
6800   if (others > 0)
6801     {
6802       if (others == 1)
6803         printf_filtered (_("Note: breakpoint "));
6804       else /* if (others == ???) */
6805         printf_filtered (_("Note: breakpoints "));
6806       ALL_BREAKPOINTS (b)
6807         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6808           {
6809             others--;
6810             printf_filtered ("%d", b->number);
6811             if (b->thread == -1 && thread != -1)
6812               printf_filtered (" (all threads)");
6813             else if (b->thread != -1)
6814               printf_filtered (" (thread %d)", b->thread);
6815             printf_filtered ("%s%s ",
6816                              ((b->enable_state == bp_disabled
6817                                || b->enable_state == bp_call_disabled)
6818                               ? " (disabled)"
6819                               : b->enable_state == bp_permanent 
6820                               ? " (permanent)"
6821                               : ""),
6822                              (others > 1) ? "," 
6823                              : ((others == 1) ? " and" : ""));
6824           }
6825       printf_filtered (_("also set at pc "));
6826       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6827       printf_filtered (".\n");
6828     }
6829 }
6830 \f
6831
6832 /* Return true iff it is meaningful to use the address member of
6833    BPT.  For some breakpoint types, the address member is irrelevant
6834    and it makes no sense to attempt to compare it to other addresses
6835    (or use it for any other purpose either).
6836
6837    More specifically, each of the following breakpoint types will
6838    always have a zero valued address and we don't want to mark
6839    breakpoints of any of these types to be a duplicate of an actual
6840    breakpoint at address zero:
6841
6842       bp_watchpoint
6843       bp_catchpoint
6844
6845 */
6846
6847 static int
6848 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6849 {
6850   enum bptype type = bpt->type;
6851
6852   return (type != bp_watchpoint && type != bp_catchpoint);
6853 }
6854
6855 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6856    true if LOC1 and LOC2 represent the same watchpoint location.  */
6857
6858 static int
6859 watchpoint_locations_match (struct bp_location *loc1, 
6860                             struct bp_location *loc2)
6861 {
6862   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6863   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6864
6865   /* Both of them must exist.  */
6866   gdb_assert (w1 != NULL);
6867   gdb_assert (w2 != NULL);
6868
6869   /* If the target can evaluate the condition expression in hardware,
6870      then we we need to insert both watchpoints even if they are at
6871      the same place.  Otherwise the watchpoint will only trigger when
6872      the condition of whichever watchpoint was inserted evaluates to
6873      true, not giving a chance for GDB to check the condition of the
6874      other watchpoint.  */
6875   if ((w1->cond_exp
6876        && target_can_accel_watchpoint_condition (loc1->address, 
6877                                                  loc1->length,
6878                                                  loc1->watchpoint_type,
6879                                                  w1->cond_exp))
6880       || (w2->cond_exp
6881           && target_can_accel_watchpoint_condition (loc2->address, 
6882                                                     loc2->length,
6883                                                     loc2->watchpoint_type,
6884                                                     w2->cond_exp)))
6885     return 0;
6886
6887   /* Note that this checks the owner's type, not the location's.  In
6888      case the target does not support read watchpoints, but does
6889      support access watchpoints, we'll have bp_read_watchpoint
6890      watchpoints with hw_access locations.  Those should be considered
6891      duplicates of hw_read locations.  The hw_read locations will
6892      become hw_access locations later.  */
6893   return (loc1->owner->type == loc2->owner->type
6894           && loc1->pspace->aspace == loc2->pspace->aspace
6895           && loc1->address == loc2->address
6896           && loc1->length == loc2->length);
6897 }
6898
6899 /* See breakpoint.h.  */
6900
6901 int
6902 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6903                           struct address_space *aspace2, CORE_ADDR addr2)
6904 {
6905   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6906            || aspace1 == aspace2)
6907           && addr1 == addr2);
6908 }
6909
6910 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6911    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6912    matches ASPACE2.  On targets that have global breakpoints, the address
6913    space doesn't really matter.  */
6914
6915 static int
6916 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6917                                 int len1, struct address_space *aspace2,
6918                                 CORE_ADDR addr2)
6919 {
6920   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6921            || aspace1 == aspace2)
6922           && addr2 >= addr1 && addr2 < addr1 + len1);
6923 }
6924
6925 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6926    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6927    matches the breakpoint's address space.  On targets that have global
6928    breakpoints, the address space doesn't really matter.  */
6929
6930 static int
6931 breakpoint_location_address_match (struct bp_location *bl,
6932                                    struct address_space *aspace,
6933                                    CORE_ADDR addr)
6934 {
6935   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6936                                     aspace, addr)
6937           || (bl->length
6938               && breakpoint_address_match_range (bl->pspace->aspace,
6939                                                  bl->address, bl->length,
6940                                                  aspace, addr)));
6941 }
6942
6943 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6944    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6945    true, otherwise returns false.  */
6946
6947 static int
6948 tracepoint_locations_match (struct bp_location *loc1,
6949                             struct bp_location *loc2)
6950 {
6951   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6952     /* Since tracepoint locations are never duplicated with others', tracepoint
6953        locations at the same address of different tracepoints are regarded as
6954        different locations.  */
6955     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6956   else
6957     return 0;
6958 }
6959
6960 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6961    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6962    represent the same location.  */
6963
6964 static int
6965 breakpoint_locations_match (struct bp_location *loc1, 
6966                             struct bp_location *loc2)
6967 {
6968   int hw_point1, hw_point2;
6969
6970   /* Both of them must not be in moribund_locations.  */
6971   gdb_assert (loc1->owner != NULL);
6972   gdb_assert (loc2->owner != NULL);
6973
6974   hw_point1 = is_hardware_watchpoint (loc1->owner);
6975   hw_point2 = is_hardware_watchpoint (loc2->owner);
6976
6977   if (hw_point1 != hw_point2)
6978     return 0;
6979   else if (hw_point1)
6980     return watchpoint_locations_match (loc1, loc2);
6981   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6982     return tracepoint_locations_match (loc1, loc2);
6983   else
6984     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6985     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6986                                      loc2->pspace->aspace, loc2->address)
6987             && loc1->length == loc2->length);
6988 }
6989
6990 static void
6991 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6992                                int bnum, int have_bnum)
6993 {
6994   /* The longest string possibly returned by hex_string_custom
6995      is 50 chars.  These must be at least that big for safety.  */
6996   char astr1[64];
6997   char astr2[64];
6998
6999   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7000   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7001   if (have_bnum)
7002     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7003              bnum, astr1, astr2);
7004   else
7005     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7006 }
7007
7008 /* Adjust a breakpoint's address to account for architectural
7009    constraints on breakpoint placement.  Return the adjusted address.
7010    Note: Very few targets require this kind of adjustment.  For most
7011    targets, this function is simply the identity function.  */
7012
7013 static CORE_ADDR
7014 adjust_breakpoint_address (struct gdbarch *gdbarch,
7015                            CORE_ADDR bpaddr, enum bptype bptype)
7016 {
7017   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7018     {
7019       /* Very few targets need any kind of breakpoint adjustment.  */
7020       return bpaddr;
7021     }
7022   else if (bptype == bp_watchpoint
7023            || bptype == bp_hardware_watchpoint
7024            || bptype == bp_read_watchpoint
7025            || bptype == bp_access_watchpoint
7026            || bptype == bp_catchpoint)
7027     {
7028       /* Watchpoints and the various bp_catch_* eventpoints should not
7029          have their addresses modified.  */
7030       return bpaddr;
7031     }
7032   else
7033     {
7034       CORE_ADDR adjusted_bpaddr;
7035
7036       /* Some targets have architectural constraints on the placement
7037          of breakpoint instructions.  Obtain the adjusted address.  */
7038       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7039
7040       /* An adjusted breakpoint address can significantly alter
7041          a user's expectations.  Print a warning if an adjustment
7042          is required.  */
7043       if (adjusted_bpaddr != bpaddr)
7044         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7045
7046       return adjusted_bpaddr;
7047     }
7048 }
7049
7050 void
7051 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7052                   struct breakpoint *owner)
7053 {
7054   memset (loc, 0, sizeof (*loc));
7055
7056   gdb_assert (ops != NULL);
7057
7058   loc->ops = ops;
7059   loc->owner = owner;
7060   loc->cond = NULL;
7061   loc->cond_bytecode = NULL;
7062   loc->shlib_disabled = 0;
7063   loc->enabled = 1;
7064
7065   switch (owner->type)
7066     {
7067     case bp_breakpoint:
7068     case bp_until:
7069     case bp_finish:
7070     case bp_longjmp:
7071     case bp_longjmp_resume:
7072     case bp_longjmp_call_dummy:
7073     case bp_exception:
7074     case bp_exception_resume:
7075     case bp_step_resume:
7076     case bp_hp_step_resume:
7077     case bp_watchpoint_scope:
7078     case bp_call_dummy:
7079     case bp_std_terminate:
7080     case bp_shlib_event:
7081     case bp_thread_event:
7082     case bp_overlay_event:
7083     case bp_jit_event:
7084     case bp_longjmp_master:
7085     case bp_std_terminate_master:
7086     case bp_exception_master:
7087     case bp_gnu_ifunc_resolver:
7088     case bp_gnu_ifunc_resolver_return:
7089     case bp_dprintf:
7090       loc->loc_type = bp_loc_software_breakpoint;
7091       mark_breakpoint_location_modified (loc);
7092       break;
7093     case bp_hardware_breakpoint:
7094       loc->loc_type = bp_loc_hardware_breakpoint;
7095       mark_breakpoint_location_modified (loc);
7096       break;
7097     case bp_hardware_watchpoint:
7098     case bp_read_watchpoint:
7099     case bp_access_watchpoint:
7100       loc->loc_type = bp_loc_hardware_watchpoint;
7101       break;
7102     case bp_watchpoint:
7103     case bp_catchpoint:
7104     case bp_tracepoint:
7105     case bp_fast_tracepoint:
7106     case bp_static_tracepoint:
7107       loc->loc_type = bp_loc_other;
7108       break;
7109     default:
7110       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7111     }
7112
7113   loc->refc = 1;
7114 }
7115
7116 /* Allocate a struct bp_location.  */
7117
7118 static struct bp_location *
7119 allocate_bp_location (struct breakpoint *bpt)
7120 {
7121   return bpt->ops->allocate_location (bpt);
7122 }
7123
7124 static void
7125 free_bp_location (struct bp_location *loc)
7126 {
7127   loc->ops->dtor (loc);
7128   xfree (loc);
7129 }
7130
7131 /* Increment reference count.  */
7132
7133 static void
7134 incref_bp_location (struct bp_location *bl)
7135 {
7136   ++bl->refc;
7137 }
7138
7139 /* Decrement reference count.  If the reference count reaches 0,
7140    destroy the bp_location.  Sets *BLP to NULL.  */
7141
7142 static void
7143 decref_bp_location (struct bp_location **blp)
7144 {
7145   gdb_assert ((*blp)->refc > 0);
7146
7147   if (--(*blp)->refc == 0)
7148     free_bp_location (*blp);
7149   *blp = NULL;
7150 }
7151
7152 /* Add breakpoint B at the end of the global breakpoint chain.  */
7153
7154 static void
7155 add_to_breakpoint_chain (struct breakpoint *b)
7156 {
7157   struct breakpoint *b1;
7158
7159   /* Add this breakpoint to the end of the chain so that a list of
7160      breakpoints will come out in order of increasing numbers.  */
7161
7162   b1 = breakpoint_chain;
7163   if (b1 == 0)
7164     breakpoint_chain = b;
7165   else
7166     {
7167       while (b1->next)
7168         b1 = b1->next;
7169       b1->next = b;
7170     }
7171 }
7172
7173 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7174
7175 static void
7176 init_raw_breakpoint_without_location (struct breakpoint *b,
7177                                       struct gdbarch *gdbarch,
7178                                       enum bptype bptype,
7179                                       const struct breakpoint_ops *ops)
7180 {
7181   memset (b, 0, sizeof (*b));
7182
7183   gdb_assert (ops != NULL);
7184
7185   b->ops = ops;
7186   b->type = bptype;
7187   b->gdbarch = gdbarch;
7188   b->language = current_language->la_language;
7189   b->input_radix = input_radix;
7190   b->thread = -1;
7191   b->enable_state = bp_enabled;
7192   b->next = 0;
7193   b->silent = 0;
7194   b->ignore_count = 0;
7195   b->commands = NULL;
7196   b->frame_id = null_frame_id;
7197   b->condition_not_parsed = 0;
7198   b->py_bp_object = NULL;
7199   b->related_breakpoint = b;
7200 }
7201
7202 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7203    that has type BPTYPE and has no locations as yet.  */
7204
7205 static struct breakpoint *
7206 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7207                                      enum bptype bptype,
7208                                      const struct breakpoint_ops *ops)
7209 {
7210   struct breakpoint *b = XNEW (struct breakpoint);
7211
7212   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7213   add_to_breakpoint_chain (b);
7214   return b;
7215 }
7216
7217 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7218    resolutions should be made as the user specified the location explicitly
7219    enough.  */
7220
7221 static void
7222 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7223 {
7224   gdb_assert (loc->owner != NULL);
7225
7226   if (loc->owner->type == bp_breakpoint
7227       || loc->owner->type == bp_hardware_breakpoint
7228       || is_tracepoint (loc->owner))
7229     {
7230       int is_gnu_ifunc;
7231       const char *function_name;
7232       CORE_ADDR func_addr;
7233
7234       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7235                                           &func_addr, NULL, &is_gnu_ifunc);
7236
7237       if (is_gnu_ifunc && !explicit_loc)
7238         {
7239           struct breakpoint *b = loc->owner;
7240
7241           gdb_assert (loc->pspace == current_program_space);
7242           if (gnu_ifunc_resolve_name (function_name,
7243                                       &loc->requested_address))
7244             {
7245               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7246               loc->address = adjust_breakpoint_address (loc->gdbarch,
7247                                                         loc->requested_address,
7248                                                         b->type);
7249             }
7250           else if (b->type == bp_breakpoint && b->loc == loc
7251                    && loc->next == NULL && b->related_breakpoint == b)
7252             {
7253               /* Create only the whole new breakpoint of this type but do not
7254                  mess more complicated breakpoints with multiple locations.  */
7255               b->type = bp_gnu_ifunc_resolver;
7256               /* Remember the resolver's address for use by the return
7257                  breakpoint.  */
7258               loc->related_address = func_addr;
7259             }
7260         }
7261
7262       if (function_name)
7263         loc->function_name = xstrdup (function_name);
7264     }
7265 }
7266
7267 /* Attempt to determine architecture of location identified by SAL.  */
7268 struct gdbarch *
7269 get_sal_arch (struct symtab_and_line sal)
7270 {
7271   if (sal.section)
7272     return get_objfile_arch (sal.section->objfile);
7273   if (sal.symtab)
7274     return get_objfile_arch (sal.symtab->objfile);
7275
7276   return NULL;
7277 }
7278
7279 /* Low level routine for partially initializing a breakpoint of type
7280    BPTYPE.  The newly created breakpoint's address, section, source
7281    file name, and line number are provided by SAL.
7282
7283    It is expected that the caller will complete the initialization of
7284    the newly created breakpoint struct as well as output any status
7285    information regarding the creation of a new breakpoint.  */
7286
7287 static void
7288 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7289                      struct symtab_and_line sal, enum bptype bptype,
7290                      const struct breakpoint_ops *ops)
7291 {
7292   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7293
7294   add_location_to_breakpoint (b, &sal);
7295
7296   if (bptype != bp_catchpoint)
7297     gdb_assert (sal.pspace != NULL);
7298
7299   /* Store the program space that was used to set the breakpoint,
7300      except for ordinary breakpoints, which are independent of the
7301      program space.  */
7302   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7303     b->pspace = sal.pspace;
7304 }
7305
7306 /* set_raw_breakpoint is a low level routine for allocating and
7307    partially initializing a breakpoint of type BPTYPE.  The newly
7308    created breakpoint's address, section, source file name, and line
7309    number are provided by SAL.  The newly created and partially
7310    initialized breakpoint is added to the breakpoint chain and
7311    is also returned as the value of this function.
7312
7313    It is expected that the caller will complete the initialization of
7314    the newly created breakpoint struct as well as output any status
7315    information regarding the creation of a new breakpoint.  In
7316    particular, set_raw_breakpoint does NOT set the breakpoint
7317    number!  Care should be taken to not allow an error to occur
7318    prior to completing the initialization of the breakpoint.  If this
7319    should happen, a bogus breakpoint will be left on the chain.  */
7320
7321 struct breakpoint *
7322 set_raw_breakpoint (struct gdbarch *gdbarch,
7323                     struct symtab_and_line sal, enum bptype bptype,
7324                     const struct breakpoint_ops *ops)
7325 {
7326   struct breakpoint *b = XNEW (struct breakpoint);
7327
7328   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7329   add_to_breakpoint_chain (b);
7330   return b;
7331 }
7332
7333
7334 /* Note that the breakpoint object B describes a permanent breakpoint
7335    instruction, hard-wired into the inferior's code.  */
7336 void
7337 make_breakpoint_permanent (struct breakpoint *b)
7338 {
7339   struct bp_location *bl;
7340
7341   b->enable_state = bp_permanent;
7342
7343   /* By definition, permanent breakpoints are already present in the
7344      code.  Mark all locations as inserted.  For now,
7345      make_breakpoint_permanent is called in just one place, so it's
7346      hard to say if it's reasonable to have permanent breakpoint with
7347      multiple locations or not, but it's easy to implement.  */
7348   for (bl = b->loc; bl; bl = bl->next)
7349     bl->inserted = 1;
7350 }
7351
7352 /* Call this routine when stepping and nexting to enable a breakpoint
7353    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7354    initiated the operation.  */
7355
7356 void
7357 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7358 {
7359   struct breakpoint *b, *b_tmp;
7360   int thread = tp->num;
7361
7362   /* To avoid having to rescan all objfile symbols at every step,
7363      we maintain a list of continually-inserted but always disabled
7364      longjmp "master" breakpoints.  Here, we simply create momentary
7365      clones of those and enable them for the requested thread.  */
7366   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7367     if (b->pspace == current_program_space
7368         && (b->type == bp_longjmp_master
7369             || b->type == bp_exception_master))
7370       {
7371         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7372         struct breakpoint *clone;
7373
7374         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7375            after their removal.  */
7376         clone = momentary_breakpoint_from_master (b, type,
7377                                                   &longjmp_breakpoint_ops);
7378         clone->thread = thread;
7379       }
7380
7381   tp->initiating_frame = frame;
7382 }
7383
7384 /* Delete all longjmp breakpoints from THREAD.  */
7385 void
7386 delete_longjmp_breakpoint (int thread)
7387 {
7388   struct breakpoint *b, *b_tmp;
7389
7390   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7391     if (b->type == bp_longjmp || b->type == bp_exception)
7392       {
7393         if (b->thread == thread)
7394           delete_breakpoint (b);
7395       }
7396 }
7397
7398 void
7399 delete_longjmp_breakpoint_at_next_stop (int thread)
7400 {
7401   struct breakpoint *b, *b_tmp;
7402
7403   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7404     if (b->type == bp_longjmp || b->type == bp_exception)
7405       {
7406         if (b->thread == thread)
7407           b->disposition = disp_del_at_next_stop;
7408       }
7409 }
7410
7411 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7412    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7413    pointer to any of them.  Return NULL if this system cannot place longjmp
7414    breakpoints.  */
7415
7416 struct breakpoint *
7417 set_longjmp_breakpoint_for_call_dummy (void)
7418 {
7419   struct breakpoint *b, *retval = NULL;
7420
7421   ALL_BREAKPOINTS (b)
7422     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7423       {
7424         struct breakpoint *new_b;
7425
7426         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7427                                                   &momentary_breakpoint_ops);
7428         new_b->thread = pid_to_thread_id (inferior_ptid);
7429
7430         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7431
7432         gdb_assert (new_b->related_breakpoint == new_b);
7433         if (retval == NULL)
7434           retval = new_b;
7435         new_b->related_breakpoint = retval;
7436         while (retval->related_breakpoint != new_b->related_breakpoint)
7437           retval = retval->related_breakpoint;
7438         retval->related_breakpoint = new_b;
7439       }
7440
7441   return retval;
7442 }
7443
7444 /* Verify all existing dummy frames and their associated breakpoints for
7445    THREAD.  Remove those which can no longer be found in the current frame
7446    stack.
7447
7448    You should call this function only at places where it is safe to currently
7449    unwind the whole stack.  Failed stack unwind would discard live dummy
7450    frames.  */
7451
7452 void
7453 check_longjmp_breakpoint_for_call_dummy (int thread)
7454 {
7455   struct breakpoint *b, *b_tmp;
7456
7457   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7458     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7459       {
7460         struct breakpoint *dummy_b = b->related_breakpoint;
7461
7462         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7463           dummy_b = dummy_b->related_breakpoint;
7464         if (dummy_b->type != bp_call_dummy
7465             || frame_find_by_id (dummy_b->frame_id) != NULL)
7466           continue;
7467         
7468         dummy_frame_discard (dummy_b->frame_id);
7469
7470         while (b->related_breakpoint != b)
7471           {
7472             if (b_tmp == b->related_breakpoint)
7473               b_tmp = b->related_breakpoint->next;
7474             delete_breakpoint (b->related_breakpoint);
7475           }
7476         delete_breakpoint (b);
7477       }
7478 }
7479
7480 void
7481 enable_overlay_breakpoints (void)
7482 {
7483   struct breakpoint *b;
7484
7485   ALL_BREAKPOINTS (b)
7486     if (b->type == bp_overlay_event)
7487     {
7488       b->enable_state = bp_enabled;
7489       update_global_location_list (1);
7490       overlay_events_enabled = 1;
7491     }
7492 }
7493
7494 void
7495 disable_overlay_breakpoints (void)
7496 {
7497   struct breakpoint *b;
7498
7499   ALL_BREAKPOINTS (b)
7500     if (b->type == bp_overlay_event)
7501     {
7502       b->enable_state = bp_disabled;
7503       update_global_location_list (0);
7504       overlay_events_enabled = 0;
7505     }
7506 }
7507
7508 /* Set an active std::terminate breakpoint for each std::terminate
7509    master breakpoint.  */
7510 void
7511 set_std_terminate_breakpoint (void)
7512 {
7513   struct breakpoint *b, *b_tmp;
7514
7515   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7516     if (b->pspace == current_program_space
7517         && b->type == bp_std_terminate_master)
7518       {
7519         momentary_breakpoint_from_master (b, bp_std_terminate,
7520                                           &momentary_breakpoint_ops);
7521       }
7522 }
7523
7524 /* Delete all the std::terminate breakpoints.  */
7525 void
7526 delete_std_terminate_breakpoint (void)
7527 {
7528   struct breakpoint *b, *b_tmp;
7529
7530   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7531     if (b->type == bp_std_terminate)
7532       delete_breakpoint (b);
7533 }
7534
7535 struct breakpoint *
7536 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7537 {
7538   struct breakpoint *b;
7539
7540   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7541                                   &internal_breakpoint_ops);
7542
7543   b->enable_state = bp_enabled;
7544   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7545   b->addr_string
7546     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7547
7548   update_global_location_list_nothrow (1);
7549
7550   return b;
7551 }
7552
7553 void
7554 remove_thread_event_breakpoints (void)
7555 {
7556   struct breakpoint *b, *b_tmp;
7557
7558   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7559     if (b->type == bp_thread_event
7560         && b->loc->pspace == current_program_space)
7561       delete_breakpoint (b);
7562 }
7563
7564 struct lang_and_radix
7565   {
7566     enum language lang;
7567     int radix;
7568   };
7569
7570 /* Create a breakpoint for JIT code registration and unregistration.  */
7571
7572 struct breakpoint *
7573 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7574 {
7575   struct breakpoint *b;
7576
7577   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7578                                   &internal_breakpoint_ops);
7579   update_global_location_list_nothrow (1);
7580   return b;
7581 }
7582
7583 /* Remove JIT code registration and unregistration breakpoint(s).  */
7584
7585 void
7586 remove_jit_event_breakpoints (void)
7587 {
7588   struct breakpoint *b, *b_tmp;
7589
7590   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7591     if (b->type == bp_jit_event
7592         && b->loc->pspace == current_program_space)
7593       delete_breakpoint (b);
7594 }
7595
7596 void
7597 remove_solib_event_breakpoints (void)
7598 {
7599   struct breakpoint *b, *b_tmp;
7600
7601   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7602     if (b->type == bp_shlib_event
7603         && b->loc->pspace == current_program_space)
7604       delete_breakpoint (b);
7605 }
7606
7607 struct breakpoint *
7608 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7609 {
7610   struct breakpoint *b;
7611
7612   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7613                                   &internal_breakpoint_ops);
7614   update_global_location_list_nothrow (1);
7615   return b;
7616 }
7617
7618 /* Disable any breakpoints that are on code in shared libraries.  Only
7619    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7620
7621 void
7622 disable_breakpoints_in_shlibs (void)
7623 {
7624   struct bp_location *loc, **locp_tmp;
7625
7626   ALL_BP_LOCATIONS (loc, locp_tmp)
7627   {
7628     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7629     struct breakpoint *b = loc->owner;
7630
7631     /* We apply the check to all breakpoints, including disabled for
7632        those with loc->duplicate set.  This is so that when breakpoint
7633        becomes enabled, or the duplicate is removed, gdb will try to
7634        insert all breakpoints.  If we don't set shlib_disabled here,
7635        we'll try to insert those breakpoints and fail.  */
7636     if (((b->type == bp_breakpoint)
7637          || (b->type == bp_jit_event)
7638          || (b->type == bp_hardware_breakpoint)
7639          || (is_tracepoint (b)))
7640         && loc->pspace == current_program_space
7641         && !loc->shlib_disabled
7642         && solib_name_from_address (loc->pspace, loc->address)
7643         )
7644       {
7645         loc->shlib_disabled = 1;
7646       }
7647   }
7648 }
7649
7650 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7651    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7652    disabled ones can just stay disabled.  */
7653
7654 static void
7655 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7656 {
7657   struct bp_location *loc, **locp_tmp;
7658   int disabled_shlib_breaks = 0;
7659
7660   /* SunOS a.out shared libraries are always mapped, so do not
7661      disable breakpoints; they will only be reported as unloaded
7662      through clear_solib when GDB discards its shared library
7663      list.  See clear_solib for more information.  */
7664   if (exec_bfd != NULL
7665       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7666     return;
7667
7668   ALL_BP_LOCATIONS (loc, locp_tmp)
7669   {
7670     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7671     struct breakpoint *b = loc->owner;
7672
7673     if (solib->pspace == loc->pspace
7674         && !loc->shlib_disabled
7675         && (((b->type == bp_breakpoint
7676               || b->type == bp_jit_event
7677               || b->type == bp_hardware_breakpoint)
7678              && (loc->loc_type == bp_loc_hardware_breakpoint
7679                  || loc->loc_type == bp_loc_software_breakpoint))
7680             || is_tracepoint (b))
7681         && solib_contains_address_p (solib, loc->address))
7682       {
7683         loc->shlib_disabled = 1;
7684         /* At this point, we cannot rely on remove_breakpoint
7685            succeeding so we must mark the breakpoint as not inserted
7686            to prevent future errors occurring in remove_breakpoints.  */
7687         loc->inserted = 0;
7688
7689         /* This may cause duplicate notifications for the same breakpoint.  */
7690         observer_notify_breakpoint_modified (b);
7691
7692         if (!disabled_shlib_breaks)
7693           {
7694             target_terminal_ours_for_output ();
7695             warning (_("Temporarily disabling breakpoints "
7696                        "for unloaded shared library \"%s\""),
7697                      solib->so_name);
7698           }
7699         disabled_shlib_breaks = 1;
7700       }
7701   }
7702 }
7703
7704 /* Disable any breakpoints and tracepoints in OBJFILE upon
7705    notification of free_objfile.  Only apply to enabled breakpoints,
7706    disabled ones can just stay disabled.  */
7707
7708 static void
7709 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7710 {
7711   struct breakpoint *b;
7712
7713   if (objfile == NULL)
7714     return;
7715
7716   /* OBJF_USERLOADED are dynamic modules manually managed by the user
7717      with add-symbol-file/remove-symbol-file.  Similarly to how
7718      breakpoints in shared libraries are handled in response to
7719      "nosharedlibrary", mark breakpoints in OBJF_USERLOADED modules
7720      shlib_disabled so they end up uninserted on the next global
7721      location list update.  Shared libraries not loaded by the user
7722      aren't handled here -- they're already handled in
7723      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7724      solib_unloaded observer.  We skip objfiles that are not
7725      OBJF_USERLOADED (nor OBJF_SHARED) as those aren't considered
7726      dynamic objects (e.g. the main objfile).  */
7727   if ((objfile->flags & OBJF_USERLOADED) == 0)
7728     return;
7729
7730   ALL_BREAKPOINTS (b)
7731     {
7732       struct bp_location *loc;
7733       int bp_modified = 0;
7734
7735       if (!is_breakpoint (b) && !is_tracepoint (b))
7736         continue;
7737
7738       for (loc = b->loc; loc != NULL; loc = loc->next)
7739         {
7740           CORE_ADDR loc_addr = loc->address;
7741
7742           if (loc->loc_type != bp_loc_hardware_breakpoint
7743               && loc->loc_type != bp_loc_software_breakpoint)
7744             continue;
7745
7746           if (loc->shlib_disabled != 0)
7747             continue;
7748
7749           if (objfile->pspace != loc->pspace)
7750             continue;
7751
7752           if (loc->loc_type != bp_loc_hardware_breakpoint
7753               && loc->loc_type != bp_loc_software_breakpoint)
7754             continue;
7755
7756           if (is_addr_in_objfile (loc_addr, objfile))
7757             {
7758               loc->shlib_disabled = 1;
7759               /* At this point, we don't know whether the object was
7760                  unmapped from the inferior or not, so leave the
7761                  inserted flag alone.  We'll handle failure to
7762                  uninsert quietly, in case the object was indeed
7763                  unmapped.  */
7764
7765               mark_breakpoint_location_modified (loc);
7766
7767               bp_modified = 1;
7768             }
7769         }
7770
7771       if (bp_modified)
7772         observer_notify_breakpoint_modified (b);
7773     }
7774 }
7775
7776 /* FORK & VFORK catchpoints.  */
7777
7778 /* An instance of this type is used to represent a fork or vfork
7779    catchpoint.  It includes a "struct breakpoint" as a kind of base
7780    class; users downcast to "struct breakpoint *" when needed.  A
7781    breakpoint is really of this type iff its ops pointer points to
7782    CATCH_FORK_BREAKPOINT_OPS.  */
7783
7784 struct fork_catchpoint
7785 {
7786   /* The base class.  */
7787   struct breakpoint base;
7788
7789   /* Process id of a child process whose forking triggered this
7790      catchpoint.  This field is only valid immediately after this
7791      catchpoint has triggered.  */
7792   ptid_t forked_inferior_pid;
7793 };
7794
7795 /* Implement the "insert" breakpoint_ops method for fork
7796    catchpoints.  */
7797
7798 static int
7799 insert_catch_fork (struct bp_location *bl)
7800 {
7801   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7802 }
7803
7804 /* Implement the "remove" breakpoint_ops method for fork
7805    catchpoints.  */
7806
7807 static int
7808 remove_catch_fork (struct bp_location *bl)
7809 {
7810   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7811 }
7812
7813 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7814    catchpoints.  */
7815
7816 static int
7817 breakpoint_hit_catch_fork (const struct bp_location *bl,
7818                            struct address_space *aspace, CORE_ADDR bp_addr,
7819                            const struct target_waitstatus *ws)
7820 {
7821   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7822
7823   if (ws->kind != TARGET_WAITKIND_FORKED)
7824     return 0;
7825
7826   c->forked_inferior_pid = ws->value.related_pid;
7827   return 1;
7828 }
7829
7830 /* Implement the "print_it" breakpoint_ops method for fork
7831    catchpoints.  */
7832
7833 static enum print_stop_action
7834 print_it_catch_fork (bpstat bs)
7835 {
7836   struct ui_out *uiout = current_uiout;
7837   struct breakpoint *b = bs->breakpoint_at;
7838   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7839
7840   annotate_catchpoint (b->number);
7841   if (b->disposition == disp_del)
7842     ui_out_text (uiout, "\nTemporary catchpoint ");
7843   else
7844     ui_out_text (uiout, "\nCatchpoint ");
7845   if (ui_out_is_mi_like_p (uiout))
7846     {
7847       ui_out_field_string (uiout, "reason",
7848                            async_reason_lookup (EXEC_ASYNC_FORK));
7849       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7850     }
7851   ui_out_field_int (uiout, "bkptno", b->number);
7852   ui_out_text (uiout, " (forked process ");
7853   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7854   ui_out_text (uiout, "), ");
7855   return PRINT_SRC_AND_LOC;
7856 }
7857
7858 /* Implement the "print_one" breakpoint_ops method for fork
7859    catchpoints.  */
7860
7861 static void
7862 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7863 {
7864   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7865   struct value_print_options opts;
7866   struct ui_out *uiout = current_uiout;
7867
7868   get_user_print_options (&opts);
7869
7870   /* Field 4, the address, is omitted (which makes the columns not
7871      line up too nicely with the headers, but the effect is relatively
7872      readable).  */
7873   if (opts.addressprint)
7874     ui_out_field_skip (uiout, "addr");
7875   annotate_field (5);
7876   ui_out_text (uiout, "fork");
7877   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7878     {
7879       ui_out_text (uiout, ", process ");
7880       ui_out_field_int (uiout, "what",
7881                         ptid_get_pid (c->forked_inferior_pid));
7882       ui_out_spaces (uiout, 1);
7883     }
7884
7885   if (ui_out_is_mi_like_p (uiout))
7886     ui_out_field_string (uiout, "catch-type", "fork");
7887 }
7888
7889 /* Implement the "print_mention" breakpoint_ops method for fork
7890    catchpoints.  */
7891
7892 static void
7893 print_mention_catch_fork (struct breakpoint *b)
7894 {
7895   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7896 }
7897
7898 /* Implement the "print_recreate" breakpoint_ops method for fork
7899    catchpoints.  */
7900
7901 static void
7902 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7903 {
7904   fprintf_unfiltered (fp, "catch fork");
7905   print_recreate_thread (b, fp);
7906 }
7907
7908 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7909
7910 static struct breakpoint_ops catch_fork_breakpoint_ops;
7911
7912 /* Implement the "insert" breakpoint_ops method for vfork
7913    catchpoints.  */
7914
7915 static int
7916 insert_catch_vfork (struct bp_location *bl)
7917 {
7918   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7919 }
7920
7921 /* Implement the "remove" breakpoint_ops method for vfork
7922    catchpoints.  */
7923
7924 static int
7925 remove_catch_vfork (struct bp_location *bl)
7926 {
7927   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7928 }
7929
7930 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7931    catchpoints.  */
7932
7933 static int
7934 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7935                             struct address_space *aspace, CORE_ADDR bp_addr,
7936                             const struct target_waitstatus *ws)
7937 {
7938   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7939
7940   if (ws->kind != TARGET_WAITKIND_VFORKED)
7941     return 0;
7942
7943   c->forked_inferior_pid = ws->value.related_pid;
7944   return 1;
7945 }
7946
7947 /* Implement the "print_it" breakpoint_ops method for vfork
7948    catchpoints.  */
7949
7950 static enum print_stop_action
7951 print_it_catch_vfork (bpstat bs)
7952 {
7953   struct ui_out *uiout = current_uiout;
7954   struct breakpoint *b = bs->breakpoint_at;
7955   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7956
7957   annotate_catchpoint (b->number);
7958   if (b->disposition == disp_del)
7959     ui_out_text (uiout, "\nTemporary catchpoint ");
7960   else
7961     ui_out_text (uiout, "\nCatchpoint ");
7962   if (ui_out_is_mi_like_p (uiout))
7963     {
7964       ui_out_field_string (uiout, "reason",
7965                            async_reason_lookup (EXEC_ASYNC_VFORK));
7966       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7967     }
7968   ui_out_field_int (uiout, "bkptno", b->number);
7969   ui_out_text (uiout, " (vforked process ");
7970   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7971   ui_out_text (uiout, "), ");
7972   return PRINT_SRC_AND_LOC;
7973 }
7974
7975 /* Implement the "print_one" breakpoint_ops method for vfork
7976    catchpoints.  */
7977
7978 static void
7979 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7980 {
7981   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7982   struct value_print_options opts;
7983   struct ui_out *uiout = current_uiout;
7984
7985   get_user_print_options (&opts);
7986   /* Field 4, the address, is omitted (which makes the columns not
7987      line up too nicely with the headers, but the effect is relatively
7988      readable).  */
7989   if (opts.addressprint)
7990     ui_out_field_skip (uiout, "addr");
7991   annotate_field (5);
7992   ui_out_text (uiout, "vfork");
7993   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7994     {
7995       ui_out_text (uiout, ", process ");
7996       ui_out_field_int (uiout, "what",
7997                         ptid_get_pid (c->forked_inferior_pid));
7998       ui_out_spaces (uiout, 1);
7999     }
8000
8001   if (ui_out_is_mi_like_p (uiout))
8002     ui_out_field_string (uiout, "catch-type", "vfork");
8003 }
8004
8005 /* Implement the "print_mention" breakpoint_ops method for vfork
8006    catchpoints.  */
8007
8008 static void
8009 print_mention_catch_vfork (struct breakpoint *b)
8010 {
8011   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8012 }
8013
8014 /* Implement the "print_recreate" breakpoint_ops method for vfork
8015    catchpoints.  */
8016
8017 static void
8018 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8019 {
8020   fprintf_unfiltered (fp, "catch vfork");
8021   print_recreate_thread (b, fp);
8022 }
8023
8024 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8025
8026 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8027
8028 /* An instance of this type is used to represent an solib catchpoint.
8029    It includes a "struct breakpoint" as a kind of base class; users
8030    downcast to "struct breakpoint *" when needed.  A breakpoint is
8031    really of this type iff its ops pointer points to
8032    CATCH_SOLIB_BREAKPOINT_OPS.  */
8033
8034 struct solib_catchpoint
8035 {
8036   /* The base class.  */
8037   struct breakpoint base;
8038
8039   /* True for "catch load", false for "catch unload".  */
8040   unsigned char is_load;
8041
8042   /* Regular expression to match, if any.  COMPILED is only valid when
8043      REGEX is non-NULL.  */
8044   char *regex;
8045   regex_t compiled;
8046 };
8047
8048 static void
8049 dtor_catch_solib (struct breakpoint *b)
8050 {
8051   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8052
8053   if (self->regex)
8054     regfree (&self->compiled);
8055   xfree (self->regex);
8056
8057   base_breakpoint_ops.dtor (b);
8058 }
8059
8060 static int
8061 insert_catch_solib (struct bp_location *ignore)
8062 {
8063   return 0;
8064 }
8065
8066 static int
8067 remove_catch_solib (struct bp_location *ignore)
8068 {
8069   return 0;
8070 }
8071
8072 static int
8073 breakpoint_hit_catch_solib (const struct bp_location *bl,
8074                             struct address_space *aspace,
8075                             CORE_ADDR bp_addr,
8076                             const struct target_waitstatus *ws)
8077 {
8078   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8079   struct breakpoint *other;
8080
8081   if (ws->kind == TARGET_WAITKIND_LOADED)
8082     return 1;
8083
8084   ALL_BREAKPOINTS (other)
8085   {
8086     struct bp_location *other_bl;
8087
8088     if (other == bl->owner)
8089       continue;
8090
8091     if (other->type != bp_shlib_event)
8092       continue;
8093
8094     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8095       continue;
8096
8097     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8098       {
8099         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8100           return 1;
8101       }
8102   }
8103
8104   return 0;
8105 }
8106
8107 static void
8108 check_status_catch_solib (struct bpstats *bs)
8109 {
8110   struct solib_catchpoint *self
8111     = (struct solib_catchpoint *) bs->breakpoint_at;
8112   int ix;
8113
8114   if (self->is_load)
8115     {
8116       struct so_list *iter;
8117
8118       for (ix = 0;
8119            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8120                         ix, iter);
8121            ++ix)
8122         {
8123           if (!self->regex
8124               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8125             return;
8126         }
8127     }
8128   else
8129     {
8130       char *iter;
8131
8132       for (ix = 0;
8133            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8134                         ix, iter);
8135            ++ix)
8136         {
8137           if (!self->regex
8138               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8139             return;
8140         }
8141     }
8142
8143   bs->stop = 0;
8144   bs->print_it = print_it_noop;
8145 }
8146
8147 static enum print_stop_action
8148 print_it_catch_solib (bpstat bs)
8149 {
8150   struct breakpoint *b = bs->breakpoint_at;
8151   struct ui_out *uiout = current_uiout;
8152
8153   annotate_catchpoint (b->number);
8154   if (b->disposition == disp_del)
8155     ui_out_text (uiout, "\nTemporary catchpoint ");
8156   else
8157     ui_out_text (uiout, "\nCatchpoint ");
8158   ui_out_field_int (uiout, "bkptno", b->number);
8159   ui_out_text (uiout, "\n");
8160   if (ui_out_is_mi_like_p (uiout))
8161     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8162   print_solib_event (1);
8163   return PRINT_SRC_AND_LOC;
8164 }
8165
8166 static void
8167 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8168 {
8169   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8170   struct value_print_options opts;
8171   struct ui_out *uiout = current_uiout;
8172   char *msg;
8173
8174   get_user_print_options (&opts);
8175   /* Field 4, the address, is omitted (which makes the columns not
8176      line up too nicely with the headers, but the effect is relatively
8177      readable).  */
8178   if (opts.addressprint)
8179     {
8180       annotate_field (4);
8181       ui_out_field_skip (uiout, "addr");
8182     }
8183
8184   annotate_field (5);
8185   if (self->is_load)
8186     {
8187       if (self->regex)
8188         msg = xstrprintf (_("load of library matching %s"), self->regex);
8189       else
8190         msg = xstrdup (_("load of library"));
8191     }
8192   else
8193     {
8194       if (self->regex)
8195         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8196       else
8197         msg = xstrdup (_("unload of library"));
8198     }
8199   ui_out_field_string (uiout, "what", msg);
8200   xfree (msg);
8201
8202   if (ui_out_is_mi_like_p (uiout))
8203     ui_out_field_string (uiout, "catch-type",
8204                          self->is_load ? "load" : "unload");
8205 }
8206
8207 static void
8208 print_mention_catch_solib (struct breakpoint *b)
8209 {
8210   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8211
8212   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8213                    self->is_load ? "load" : "unload");
8214 }
8215
8216 static void
8217 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8218 {
8219   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8220
8221   fprintf_unfiltered (fp, "%s %s",
8222                       b->disposition == disp_del ? "tcatch" : "catch",
8223                       self->is_load ? "load" : "unload");
8224   if (self->regex)
8225     fprintf_unfiltered (fp, " %s", self->regex);
8226   fprintf_unfiltered (fp, "\n");
8227 }
8228
8229 static struct breakpoint_ops catch_solib_breakpoint_ops;
8230
8231 /* Shared helper function (MI and CLI) for creating and installing
8232    a shared object event catchpoint.  If IS_LOAD is non-zero then
8233    the events to be caught are load events, otherwise they are
8234    unload events.  If IS_TEMP is non-zero the catchpoint is a
8235    temporary one.  If ENABLED is non-zero the catchpoint is
8236    created in an enabled state.  */
8237
8238 void
8239 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8240 {
8241   struct solib_catchpoint *c;
8242   struct gdbarch *gdbarch = get_current_arch ();
8243   struct cleanup *cleanup;
8244
8245   if (!arg)
8246     arg = "";
8247   arg = skip_spaces (arg);
8248
8249   c = XCNEW (struct solib_catchpoint);
8250   cleanup = make_cleanup (xfree, c);
8251
8252   if (*arg != '\0')
8253     {
8254       int errcode;
8255
8256       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8257       if (errcode != 0)
8258         {
8259           char *err = get_regcomp_error (errcode, &c->compiled);
8260
8261           make_cleanup (xfree, err);
8262           error (_("Invalid regexp (%s): %s"), err, arg);
8263         }
8264       c->regex = xstrdup (arg);
8265     }
8266
8267   c->is_load = is_load;
8268   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8269                    &catch_solib_breakpoint_ops);
8270
8271   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8272
8273   discard_cleanups (cleanup);
8274   install_breakpoint (0, &c->base, 1);
8275 }
8276
8277 /* A helper function that does all the work for "catch load" and
8278    "catch unload".  */
8279
8280 static void
8281 catch_load_or_unload (char *arg, int from_tty, int is_load,
8282                       struct cmd_list_element *command)
8283 {
8284   int tempflag;
8285   const int enabled = 1;
8286
8287   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8288
8289   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8290 }
8291
8292 static void
8293 catch_load_command_1 (char *arg, int from_tty,
8294                       struct cmd_list_element *command)
8295 {
8296   catch_load_or_unload (arg, from_tty, 1, command);
8297 }
8298
8299 static void
8300 catch_unload_command_1 (char *arg, int from_tty,
8301                         struct cmd_list_element *command)
8302 {
8303   catch_load_or_unload (arg, from_tty, 0, command);
8304 }
8305
8306 /* An instance of this type is used to represent a syscall catchpoint.
8307    It includes a "struct breakpoint" as a kind of base class; users
8308    downcast to "struct breakpoint *" when needed.  A breakpoint is
8309    really of this type iff its ops pointer points to
8310    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8311
8312 struct syscall_catchpoint
8313 {
8314   /* The base class.  */
8315   struct breakpoint base;
8316
8317   /* Syscall numbers used for the 'catch syscall' feature.  If no
8318      syscall has been specified for filtering, its value is NULL.
8319      Otherwise, it holds a list of all syscalls to be caught.  The
8320      list elements are allocated with xmalloc.  */
8321   VEC(int) *syscalls_to_be_caught;
8322 };
8323
8324 /* Implement the "dtor" breakpoint_ops method for syscall
8325    catchpoints.  */
8326
8327 static void
8328 dtor_catch_syscall (struct breakpoint *b)
8329 {
8330   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8331
8332   VEC_free (int, c->syscalls_to_be_caught);
8333
8334   base_breakpoint_ops.dtor (b);
8335 }
8336
8337 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8338
8339 struct catch_syscall_inferior_data
8340 {
8341   /* We keep a count of the number of times the user has requested a
8342      particular syscall to be tracked, and pass this information to the
8343      target.  This lets capable targets implement filtering directly.  */
8344
8345   /* Number of times that "any" syscall is requested.  */
8346   int any_syscall_count;
8347
8348   /* Count of each system call.  */
8349   VEC(int) *syscalls_counts;
8350
8351   /* This counts all syscall catch requests, so we can readily determine
8352      if any catching is necessary.  */
8353   int total_syscalls_count;
8354 };
8355
8356 static struct catch_syscall_inferior_data*
8357 get_catch_syscall_inferior_data (struct inferior *inf)
8358 {
8359   struct catch_syscall_inferior_data *inf_data;
8360
8361   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8362   if (inf_data == NULL)
8363     {
8364       inf_data = XCNEW (struct catch_syscall_inferior_data);
8365       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8366     }
8367
8368   return inf_data;
8369 }
8370
8371 static void
8372 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8373 {
8374   xfree (arg);
8375 }
8376
8377
8378 /* Implement the "insert" breakpoint_ops method for syscall
8379    catchpoints.  */
8380
8381 static int
8382 insert_catch_syscall (struct bp_location *bl)
8383 {
8384   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8385   struct inferior *inf = current_inferior ();
8386   struct catch_syscall_inferior_data *inf_data
8387     = get_catch_syscall_inferior_data (inf);
8388
8389   ++inf_data->total_syscalls_count;
8390   if (!c->syscalls_to_be_caught)
8391     ++inf_data->any_syscall_count;
8392   else
8393     {
8394       int i, iter;
8395
8396       for (i = 0;
8397            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8398            i++)
8399         {
8400           int elem;
8401
8402           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8403             {
8404               int old_size = VEC_length (int, inf_data->syscalls_counts);
8405               uintptr_t vec_addr_offset
8406                 = old_size * ((uintptr_t) sizeof (int));
8407               uintptr_t vec_addr;
8408               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8409               vec_addr = ((uintptr_t) VEC_address (int,
8410                                                   inf_data->syscalls_counts)
8411                           + vec_addr_offset);
8412               memset ((void *) vec_addr, 0,
8413                       (iter + 1 - old_size) * sizeof (int));
8414             }
8415           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8416           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8417         }
8418     }
8419
8420   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8421                                         inf_data->total_syscalls_count != 0,
8422                                         inf_data->any_syscall_count,
8423                                         VEC_length (int,
8424                                                     inf_data->syscalls_counts),
8425                                         VEC_address (int,
8426                                                      inf_data->syscalls_counts));
8427 }
8428
8429 /* Implement the "remove" breakpoint_ops method for syscall
8430    catchpoints.  */
8431
8432 static int
8433 remove_catch_syscall (struct bp_location *bl)
8434 {
8435   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8436   struct inferior *inf = current_inferior ();
8437   struct catch_syscall_inferior_data *inf_data
8438     = get_catch_syscall_inferior_data (inf);
8439
8440   --inf_data->total_syscalls_count;
8441   if (!c->syscalls_to_be_caught)
8442     --inf_data->any_syscall_count;
8443   else
8444     {
8445       int i, iter;
8446
8447       for (i = 0;
8448            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8449            i++)
8450         {
8451           int elem;
8452           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8453             /* Shouldn't happen.  */
8454             continue;
8455           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8456           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8457         }
8458     }
8459
8460   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8461                                         inf_data->total_syscalls_count != 0,
8462                                         inf_data->any_syscall_count,
8463                                         VEC_length (int,
8464                                                     inf_data->syscalls_counts),
8465                                         VEC_address (int,
8466                                                      inf_data->syscalls_counts));
8467 }
8468
8469 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8470    catchpoints.  */
8471
8472 static int
8473 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8474                               struct address_space *aspace, CORE_ADDR bp_addr,
8475                               const struct target_waitstatus *ws)
8476 {
8477   /* We must check if we are catching specific syscalls in this
8478      breakpoint.  If we are, then we must guarantee that the called
8479      syscall is the same syscall we are catching.  */
8480   int syscall_number = 0;
8481   const struct syscall_catchpoint *c
8482     = (const struct syscall_catchpoint *) bl->owner;
8483
8484   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8485       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8486     return 0;
8487
8488   syscall_number = ws->value.syscall_number;
8489
8490   /* Now, checking if the syscall is the same.  */
8491   if (c->syscalls_to_be_caught)
8492     {
8493       int i, iter;
8494
8495       for (i = 0;
8496            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8497            i++)
8498         if (syscall_number == iter)
8499           return 1;
8500
8501       return 0;
8502     }
8503
8504   return 1;
8505 }
8506
8507 /* Implement the "print_it" breakpoint_ops method for syscall
8508    catchpoints.  */
8509
8510 static enum print_stop_action
8511 print_it_catch_syscall (bpstat bs)
8512 {
8513   struct ui_out *uiout = current_uiout;
8514   struct breakpoint *b = bs->breakpoint_at;
8515   /* These are needed because we want to know in which state a
8516      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8517      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8518      must print "called syscall" or "returned from syscall".  */
8519   ptid_t ptid;
8520   struct target_waitstatus last;
8521   struct syscall s;
8522
8523   get_last_target_status (&ptid, &last);
8524
8525   get_syscall_by_number (last.value.syscall_number, &s);
8526
8527   annotate_catchpoint (b->number);
8528
8529   if (b->disposition == disp_del)
8530     ui_out_text (uiout, "\nTemporary catchpoint ");
8531   else
8532     ui_out_text (uiout, "\nCatchpoint ");
8533   if (ui_out_is_mi_like_p (uiout))
8534     {
8535       ui_out_field_string (uiout, "reason",
8536                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8537                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8538                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8539       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8540     }
8541   ui_out_field_int (uiout, "bkptno", b->number);
8542
8543   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8544     ui_out_text (uiout, " (call to syscall ");
8545   else
8546     ui_out_text (uiout, " (returned from syscall ");
8547
8548   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8549     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8550   if (s.name != NULL)
8551     ui_out_field_string (uiout, "syscall-name", s.name);
8552
8553   ui_out_text (uiout, "), ");
8554
8555   return PRINT_SRC_AND_LOC;
8556 }
8557
8558 /* Implement the "print_one" breakpoint_ops method for syscall
8559    catchpoints.  */
8560
8561 static void
8562 print_one_catch_syscall (struct breakpoint *b,
8563                          struct bp_location **last_loc)
8564 {
8565   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8566   struct value_print_options opts;
8567   struct ui_out *uiout = current_uiout;
8568
8569   get_user_print_options (&opts);
8570   /* Field 4, the address, is omitted (which makes the columns not
8571      line up too nicely with the headers, but the effect is relatively
8572      readable).  */
8573   if (opts.addressprint)
8574     ui_out_field_skip (uiout, "addr");
8575   annotate_field (5);
8576
8577   if (c->syscalls_to_be_caught
8578       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8579     ui_out_text (uiout, "syscalls \"");
8580   else
8581     ui_out_text (uiout, "syscall \"");
8582
8583   if (c->syscalls_to_be_caught)
8584     {
8585       int i, iter;
8586       char *text = xstrprintf ("%s", "");
8587
8588       for (i = 0;
8589            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8590            i++)
8591         {
8592           char *x = text;
8593           struct syscall s;
8594           get_syscall_by_number (iter, &s);
8595
8596           if (s.name != NULL)
8597             text = xstrprintf ("%s%s, ", text, s.name);
8598           else
8599             text = xstrprintf ("%s%d, ", text, iter);
8600
8601           /* We have to xfree the last 'text' (now stored at 'x')
8602              because xstrprintf dynamically allocates new space for it
8603              on every call.  */
8604           xfree (x);
8605         }
8606       /* Remove the last comma.  */
8607       text[strlen (text) - 2] = '\0';
8608       ui_out_field_string (uiout, "what", text);
8609     }
8610   else
8611     ui_out_field_string (uiout, "what", "<any syscall>");
8612   ui_out_text (uiout, "\" ");
8613
8614   if (ui_out_is_mi_like_p (uiout))
8615     ui_out_field_string (uiout, "catch-type", "syscall");
8616 }
8617
8618 /* Implement the "print_mention" breakpoint_ops method for syscall
8619    catchpoints.  */
8620
8621 static void
8622 print_mention_catch_syscall (struct breakpoint *b)
8623 {
8624   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8625
8626   if (c->syscalls_to_be_caught)
8627     {
8628       int i, iter;
8629
8630       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8631         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8632       else
8633         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8634
8635       for (i = 0;
8636            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8637            i++)
8638         {
8639           struct syscall s;
8640           get_syscall_by_number (iter, &s);
8641
8642           if (s.name)
8643             printf_filtered (" '%s' [%d]", s.name, s.number);
8644           else
8645             printf_filtered (" %d", s.number);
8646         }
8647       printf_filtered (")");
8648     }
8649   else
8650     printf_filtered (_("Catchpoint %d (any syscall)"),
8651                      b->number);
8652 }
8653
8654 /* Implement the "print_recreate" breakpoint_ops method for syscall
8655    catchpoints.  */
8656
8657 static void
8658 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8659 {
8660   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8661
8662   fprintf_unfiltered (fp, "catch syscall");
8663
8664   if (c->syscalls_to_be_caught)
8665     {
8666       int i, iter;
8667
8668       for (i = 0;
8669            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8670            i++)
8671         {
8672           struct syscall s;
8673
8674           get_syscall_by_number (iter, &s);
8675           if (s.name)
8676             fprintf_unfiltered (fp, " %s", s.name);
8677           else
8678             fprintf_unfiltered (fp, " %d", s.number);
8679         }
8680     }
8681   print_recreate_thread (b, fp);
8682 }
8683
8684 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8685
8686 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8687
8688 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8689
8690 static int
8691 syscall_catchpoint_p (struct breakpoint *b)
8692 {
8693   return (b->ops == &catch_syscall_breakpoint_ops);
8694 }
8695
8696 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8697    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8698    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8699    the breakpoint_ops structure associated to the catchpoint.  */
8700
8701 void
8702 init_catchpoint (struct breakpoint *b,
8703                  struct gdbarch *gdbarch, int tempflag,
8704                  char *cond_string,
8705                  const struct breakpoint_ops *ops)
8706 {
8707   struct symtab_and_line sal;
8708
8709   init_sal (&sal);
8710   sal.pspace = current_program_space;
8711
8712   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8713
8714   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8715   b->disposition = tempflag ? disp_del : disp_donttouch;
8716 }
8717
8718 void
8719 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8720 {
8721   add_to_breakpoint_chain (b);
8722   set_breakpoint_number (internal, b);
8723   if (is_tracepoint (b))
8724     set_tracepoint_count (breakpoint_count);
8725   if (!internal)
8726     mention (b);
8727   observer_notify_breakpoint_created (b);
8728
8729   if (update_gll)
8730     update_global_location_list (1);
8731 }
8732
8733 static void
8734 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8735                                     int tempflag, char *cond_string,
8736                                     const struct breakpoint_ops *ops)
8737 {
8738   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8739
8740   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8741
8742   c->forked_inferior_pid = null_ptid;
8743
8744   install_breakpoint (0, &c->base, 1);
8745 }
8746
8747 /* Exec catchpoints.  */
8748
8749 /* An instance of this type is used to represent an exec catchpoint.
8750    It includes a "struct breakpoint" as a kind of base class; users
8751    downcast to "struct breakpoint *" when needed.  A breakpoint is
8752    really of this type iff its ops pointer points to
8753    CATCH_EXEC_BREAKPOINT_OPS.  */
8754
8755 struct exec_catchpoint
8756 {
8757   /* The base class.  */
8758   struct breakpoint base;
8759
8760   /* Filename of a program whose exec triggered this catchpoint.
8761      This field is only valid immediately after this catchpoint has
8762      triggered.  */
8763   char *exec_pathname;
8764 };
8765
8766 /* Implement the "dtor" breakpoint_ops method for exec
8767    catchpoints.  */
8768
8769 static void
8770 dtor_catch_exec (struct breakpoint *b)
8771 {
8772   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8773
8774   xfree (c->exec_pathname);
8775
8776   base_breakpoint_ops.dtor (b);
8777 }
8778
8779 static int
8780 insert_catch_exec (struct bp_location *bl)
8781 {
8782   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8783 }
8784
8785 static int
8786 remove_catch_exec (struct bp_location *bl)
8787 {
8788   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8789 }
8790
8791 static int
8792 breakpoint_hit_catch_exec (const struct bp_location *bl,
8793                            struct address_space *aspace, CORE_ADDR bp_addr,
8794                            const struct target_waitstatus *ws)
8795 {
8796   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8797
8798   if (ws->kind != TARGET_WAITKIND_EXECD)
8799     return 0;
8800
8801   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8802   return 1;
8803 }
8804
8805 static enum print_stop_action
8806 print_it_catch_exec (bpstat bs)
8807 {
8808   struct ui_out *uiout = current_uiout;
8809   struct breakpoint *b = bs->breakpoint_at;
8810   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8811
8812   annotate_catchpoint (b->number);
8813   if (b->disposition == disp_del)
8814     ui_out_text (uiout, "\nTemporary catchpoint ");
8815   else
8816     ui_out_text (uiout, "\nCatchpoint ");
8817   if (ui_out_is_mi_like_p (uiout))
8818     {
8819       ui_out_field_string (uiout, "reason",
8820                            async_reason_lookup (EXEC_ASYNC_EXEC));
8821       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8822     }
8823   ui_out_field_int (uiout, "bkptno", b->number);
8824   ui_out_text (uiout, " (exec'd ");
8825   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8826   ui_out_text (uiout, "), ");
8827
8828   return PRINT_SRC_AND_LOC;
8829 }
8830
8831 static void
8832 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8833 {
8834   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8835   struct value_print_options opts;
8836   struct ui_out *uiout = current_uiout;
8837
8838   get_user_print_options (&opts);
8839
8840   /* Field 4, the address, is omitted (which makes the columns
8841      not line up too nicely with the headers, but the effect
8842      is relatively readable).  */
8843   if (opts.addressprint)
8844     ui_out_field_skip (uiout, "addr");
8845   annotate_field (5);
8846   ui_out_text (uiout, "exec");
8847   if (c->exec_pathname != NULL)
8848     {
8849       ui_out_text (uiout, ", program \"");
8850       ui_out_field_string (uiout, "what", c->exec_pathname);
8851       ui_out_text (uiout, "\" ");
8852     }
8853
8854   if (ui_out_is_mi_like_p (uiout))
8855     ui_out_field_string (uiout, "catch-type", "exec");
8856 }
8857
8858 static void
8859 print_mention_catch_exec (struct breakpoint *b)
8860 {
8861   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8862 }
8863
8864 /* Implement the "print_recreate" breakpoint_ops method for exec
8865    catchpoints.  */
8866
8867 static void
8868 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8869 {
8870   fprintf_unfiltered (fp, "catch exec");
8871   print_recreate_thread (b, fp);
8872 }
8873
8874 static struct breakpoint_ops catch_exec_breakpoint_ops;
8875
8876 static void
8877 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8878                                  const struct breakpoint_ops *ops)
8879 {
8880   struct syscall_catchpoint *c;
8881   struct gdbarch *gdbarch = get_current_arch ();
8882
8883   c = XNEW (struct syscall_catchpoint);
8884   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8885   c->syscalls_to_be_caught = filter;
8886
8887   install_breakpoint (0, &c->base, 1);
8888 }
8889
8890 static int
8891 hw_breakpoint_used_count (void)
8892 {
8893   int i = 0;
8894   struct breakpoint *b;
8895   struct bp_location *bl;
8896
8897   ALL_BREAKPOINTS (b)
8898   {
8899     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8900       for (bl = b->loc; bl; bl = bl->next)
8901         {
8902           /* Special types of hardware breakpoints may use more than
8903              one register.  */
8904           i += b->ops->resources_needed (bl);
8905         }
8906   }
8907
8908   return i;
8909 }
8910
8911 /* Returns the resources B would use if it were a hardware
8912    watchpoint.  */
8913
8914 static int
8915 hw_watchpoint_use_count (struct breakpoint *b)
8916 {
8917   int i = 0;
8918   struct bp_location *bl;
8919
8920   if (!breakpoint_enabled (b))
8921     return 0;
8922
8923   for (bl = b->loc; bl; bl = bl->next)
8924     {
8925       /* Special types of hardware watchpoints may use more than
8926          one register.  */
8927       i += b->ops->resources_needed (bl);
8928     }
8929
8930   return i;
8931 }
8932
8933 /* Returns the sum the used resources of all hardware watchpoints of
8934    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8935    the sum of the used resources of all hardware watchpoints of other
8936    types _not_ TYPE.  */
8937
8938 static int
8939 hw_watchpoint_used_count_others (struct breakpoint *except,
8940                                  enum bptype type, int *other_type_used)
8941 {
8942   int i = 0;
8943   struct breakpoint *b;
8944
8945   *other_type_used = 0;
8946   ALL_BREAKPOINTS (b)
8947     {
8948       if (b == except)
8949         continue;
8950       if (!breakpoint_enabled (b))
8951         continue;
8952
8953       if (b->type == type)
8954         i += hw_watchpoint_use_count (b);
8955       else if (is_hardware_watchpoint (b))
8956         *other_type_used = 1;
8957     }
8958
8959   return i;
8960 }
8961
8962 void
8963 disable_watchpoints_before_interactive_call_start (void)
8964 {
8965   struct breakpoint *b;
8966
8967   ALL_BREAKPOINTS (b)
8968   {
8969     if (is_watchpoint (b) && breakpoint_enabled (b))
8970       {
8971         b->enable_state = bp_call_disabled;
8972         update_global_location_list (0);
8973       }
8974   }
8975 }
8976
8977 void
8978 enable_watchpoints_after_interactive_call_stop (void)
8979 {
8980   struct breakpoint *b;
8981
8982   ALL_BREAKPOINTS (b)
8983   {
8984     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8985       {
8986         b->enable_state = bp_enabled;
8987         update_global_location_list (1);
8988       }
8989   }
8990 }
8991
8992 void
8993 disable_breakpoints_before_startup (void)
8994 {
8995   current_program_space->executing_startup = 1;
8996   update_global_location_list (0);
8997 }
8998
8999 void
9000 enable_breakpoints_after_startup (void)
9001 {
9002   current_program_space->executing_startup = 0;
9003   breakpoint_re_set ();
9004 }
9005
9006
9007 /* Set a breakpoint that will evaporate an end of command
9008    at address specified by SAL.
9009    Restrict it to frame FRAME if FRAME is nonzero.  */
9010
9011 struct breakpoint *
9012 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9013                           struct frame_id frame_id, enum bptype type)
9014 {
9015   struct breakpoint *b;
9016
9017   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9018      tail-called one.  */
9019   gdb_assert (!frame_id_artificial_p (frame_id));
9020
9021   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9022   b->enable_state = bp_enabled;
9023   b->disposition = disp_donttouch;
9024   b->frame_id = frame_id;
9025
9026   /* If we're debugging a multi-threaded program, then we want
9027      momentary breakpoints to be active in only a single thread of
9028      control.  */
9029   if (in_thread_list (inferior_ptid))
9030     b->thread = pid_to_thread_id (inferior_ptid);
9031
9032   update_global_location_list_nothrow (1);
9033
9034   return b;
9035 }
9036
9037 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9038    The new breakpoint will have type TYPE, and use OPS as it
9039    breakpoint_ops.  */
9040
9041 static struct breakpoint *
9042 momentary_breakpoint_from_master (struct breakpoint *orig,
9043                                   enum bptype type,
9044                                   const struct breakpoint_ops *ops)
9045 {
9046   struct breakpoint *copy;
9047
9048   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9049   copy->loc = allocate_bp_location (copy);
9050   set_breakpoint_location_function (copy->loc, 1);
9051
9052   copy->loc->gdbarch = orig->loc->gdbarch;
9053   copy->loc->requested_address = orig->loc->requested_address;
9054   copy->loc->address = orig->loc->address;
9055   copy->loc->section = orig->loc->section;
9056   copy->loc->pspace = orig->loc->pspace;
9057   copy->loc->probe = orig->loc->probe;
9058   copy->loc->line_number = orig->loc->line_number;
9059   copy->loc->symtab = orig->loc->symtab;
9060   copy->frame_id = orig->frame_id;
9061   copy->thread = orig->thread;
9062   copy->pspace = orig->pspace;
9063
9064   copy->enable_state = bp_enabled;
9065   copy->disposition = disp_donttouch;
9066   copy->number = internal_breakpoint_number--;
9067
9068   update_global_location_list_nothrow (0);
9069   return copy;
9070 }
9071
9072 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9073    ORIG is NULL.  */
9074
9075 struct breakpoint *
9076 clone_momentary_breakpoint (struct breakpoint *orig)
9077 {
9078   /* If there's nothing to clone, then return nothing.  */
9079   if (orig == NULL)
9080     return NULL;
9081
9082   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
9083 }
9084
9085 struct breakpoint *
9086 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9087                                 enum bptype type)
9088 {
9089   struct symtab_and_line sal;
9090
9091   sal = find_pc_line (pc, 0);
9092   sal.pc = pc;
9093   sal.section = find_pc_overlay (pc);
9094   sal.explicit_pc = 1;
9095
9096   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9097 }
9098 \f
9099
9100 /* Tell the user we have just set a breakpoint B.  */
9101
9102 static void
9103 mention (struct breakpoint *b)
9104 {
9105   b->ops->print_mention (b);
9106   if (ui_out_is_mi_like_p (current_uiout))
9107     return;
9108   printf_filtered ("\n");
9109 }
9110 \f
9111
9112 static struct bp_location *
9113 add_location_to_breakpoint (struct breakpoint *b,
9114                             const struct symtab_and_line *sal)
9115 {
9116   struct bp_location *loc, **tmp;
9117   CORE_ADDR adjusted_address;
9118   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9119
9120   if (loc_gdbarch == NULL)
9121     loc_gdbarch = b->gdbarch;
9122
9123   /* Adjust the breakpoint's address prior to allocating a location.
9124      Once we call allocate_bp_location(), that mostly uninitialized
9125      location will be placed on the location chain.  Adjustment of the
9126      breakpoint may cause target_read_memory() to be called and we do
9127      not want its scan of the location chain to find a breakpoint and
9128      location that's only been partially initialized.  */
9129   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9130                                                 sal->pc, b->type);
9131
9132   /* Sort the locations by their ADDRESS.  */
9133   loc = allocate_bp_location (b);
9134   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9135        tmp = &((*tmp)->next))
9136     ;
9137   loc->next = *tmp;
9138   *tmp = loc;
9139
9140   loc->requested_address = sal->pc;
9141   loc->address = adjusted_address;
9142   loc->pspace = sal->pspace;
9143   loc->probe.probe = sal->probe;
9144   loc->probe.objfile = sal->objfile;
9145   gdb_assert (loc->pspace != NULL);
9146   loc->section = sal->section;
9147   loc->gdbarch = loc_gdbarch;
9148   loc->line_number = sal->line;
9149   loc->symtab = sal->symtab;
9150
9151   set_breakpoint_location_function (loc,
9152                                     sal->explicit_pc || sal->explicit_line);
9153   return loc;
9154 }
9155 \f
9156
9157 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9158    return 0 otherwise.  */
9159
9160 static int
9161 bp_loc_is_permanent (struct bp_location *loc)
9162 {
9163   int len;
9164   CORE_ADDR addr;
9165   const gdb_byte *bpoint;
9166   gdb_byte *target_mem;
9167   struct cleanup *cleanup;
9168   int retval = 0;
9169
9170   gdb_assert (loc != NULL);
9171
9172   addr = loc->address;
9173   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9174
9175   /* Software breakpoints unsupported?  */
9176   if (bpoint == NULL)
9177     return 0;
9178
9179   target_mem = alloca (len);
9180
9181   /* Enable the automatic memory restoration from breakpoints while
9182      we read the memory.  Otherwise we could say about our temporary
9183      breakpoints they are permanent.  */
9184   cleanup = save_current_space_and_thread ();
9185
9186   switch_to_program_space_and_thread (loc->pspace);
9187   make_show_memory_breakpoints_cleanup (0);
9188
9189   if (target_read_memory (loc->address, target_mem, len) == 0
9190       && memcmp (target_mem, bpoint, len) == 0)
9191     retval = 1;
9192
9193   do_cleanups (cleanup);
9194
9195   return retval;
9196 }
9197
9198 /* Build a command list for the dprintf corresponding to the current
9199    settings of the dprintf style options.  */
9200
9201 static void
9202 update_dprintf_command_list (struct breakpoint *b)
9203 {
9204   char *dprintf_args = b->extra_string;
9205   char *printf_line = NULL;
9206
9207   if (!dprintf_args)
9208     return;
9209
9210   dprintf_args = skip_spaces (dprintf_args);
9211
9212   /* Allow a comma, as it may have terminated a location, but don't
9213      insist on it.  */
9214   if (*dprintf_args == ',')
9215     ++dprintf_args;
9216   dprintf_args = skip_spaces (dprintf_args);
9217
9218   if (*dprintf_args != '"')
9219     error (_("Bad format string, missing '\"'."));
9220
9221   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9222     printf_line = xstrprintf ("printf %s", dprintf_args);
9223   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9224     {
9225       if (!dprintf_function)
9226         error (_("No function supplied for dprintf call"));
9227
9228       if (dprintf_channel && strlen (dprintf_channel) > 0)
9229         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9230                                   dprintf_function,
9231                                   dprintf_channel,
9232                                   dprintf_args);
9233       else
9234         printf_line = xstrprintf ("call (void) %s (%s)",
9235                                   dprintf_function,
9236                                   dprintf_args);
9237     }
9238   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9239     {
9240       if (target_can_run_breakpoint_commands ())
9241         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9242       else
9243         {
9244           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9245           printf_line = xstrprintf ("printf %s", dprintf_args);
9246         }
9247     }
9248   else
9249     internal_error (__FILE__, __LINE__,
9250                     _("Invalid dprintf style."));
9251
9252   gdb_assert (printf_line != NULL);
9253   /* Manufacture a printf sequence.  */
9254   {
9255     struct command_line *printf_cmd_line
9256       = xmalloc (sizeof (struct command_line));
9257
9258     printf_cmd_line = xmalloc (sizeof (struct command_line));
9259     printf_cmd_line->control_type = simple_control;
9260     printf_cmd_line->body_count = 0;
9261     printf_cmd_line->body_list = NULL;
9262     printf_cmd_line->next = NULL;
9263     printf_cmd_line->line = printf_line;
9264
9265     breakpoint_set_commands (b, printf_cmd_line);
9266   }
9267 }
9268
9269 /* Update all dprintf commands, making their command lists reflect
9270    current style settings.  */
9271
9272 static void
9273 update_dprintf_commands (char *args, int from_tty,
9274                          struct cmd_list_element *c)
9275 {
9276   struct breakpoint *b;
9277
9278   ALL_BREAKPOINTS (b)
9279     {
9280       if (b->type == bp_dprintf)
9281         update_dprintf_command_list (b);
9282     }
9283 }
9284
9285 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9286    as textual description of the location, and COND_STRING
9287    as condition expression.  */
9288
9289 static void
9290 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9291                      struct symtabs_and_lines sals, char *addr_string,
9292                      char *filter, char *cond_string,
9293                      char *extra_string,
9294                      enum bptype type, enum bpdisp disposition,
9295                      int thread, int task, int ignore_count,
9296                      const struct breakpoint_ops *ops, int from_tty,
9297                      int enabled, int internal, unsigned flags,
9298                      int display_canonical)
9299 {
9300   int i;
9301
9302   if (type == bp_hardware_breakpoint)
9303     {
9304       int target_resources_ok;
9305
9306       i = hw_breakpoint_used_count ();
9307       target_resources_ok =
9308         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9309                                             i + 1, 0);
9310       if (target_resources_ok == 0)
9311         error (_("No hardware breakpoint support in the target."));
9312       else if (target_resources_ok < 0)
9313         error (_("Hardware breakpoints used exceeds limit."));
9314     }
9315
9316   gdb_assert (sals.nelts > 0);
9317
9318   for (i = 0; i < sals.nelts; ++i)
9319     {
9320       struct symtab_and_line sal = sals.sals[i];
9321       struct bp_location *loc;
9322
9323       if (from_tty)
9324         {
9325           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9326           if (!loc_gdbarch)
9327             loc_gdbarch = gdbarch;
9328
9329           describe_other_breakpoints (loc_gdbarch,
9330                                       sal.pspace, sal.pc, sal.section, thread);
9331         }
9332
9333       if (i == 0)
9334         {
9335           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9336           b->thread = thread;
9337           b->task = task;
9338
9339           b->cond_string = cond_string;
9340           b->extra_string = extra_string;
9341           b->ignore_count = ignore_count;
9342           b->enable_state = enabled ? bp_enabled : bp_disabled;
9343           b->disposition = disposition;
9344
9345           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9346             b->loc->inserted = 1;
9347
9348           if (type == bp_static_tracepoint)
9349             {
9350               struct tracepoint *t = (struct tracepoint *) b;
9351               struct static_tracepoint_marker marker;
9352
9353               if (strace_marker_p (b))
9354                 {
9355                   /* We already know the marker exists, otherwise, we
9356                      wouldn't see a sal for it.  */
9357                   char *p = &addr_string[3];
9358                   char *endp;
9359                   char *marker_str;
9360
9361                   p = skip_spaces (p);
9362
9363                   endp = skip_to_space (p);
9364
9365                   marker_str = savestring (p, endp - p);
9366                   t->static_trace_marker_id = marker_str;
9367
9368                   printf_filtered (_("Probed static tracepoint "
9369                                      "marker \"%s\"\n"),
9370                                    t->static_trace_marker_id);
9371                 }
9372               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9373                 {
9374                   t->static_trace_marker_id = xstrdup (marker.str_id);
9375                   release_static_tracepoint_marker (&marker);
9376
9377                   printf_filtered (_("Probed static tracepoint "
9378                                      "marker \"%s\"\n"),
9379                                    t->static_trace_marker_id);
9380                 }
9381               else
9382                 warning (_("Couldn't determine the static "
9383                            "tracepoint marker to probe"));
9384             }
9385
9386           loc = b->loc;
9387         }
9388       else
9389         {
9390           loc = add_location_to_breakpoint (b, &sal);
9391           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9392             loc->inserted = 1;
9393         }
9394
9395       if (bp_loc_is_permanent (loc))
9396         make_breakpoint_permanent (b);
9397
9398       if (b->cond_string)
9399         {
9400           const char *arg = b->cond_string;
9401
9402           loc->cond = parse_exp_1 (&arg, loc->address,
9403                                    block_for_pc (loc->address), 0);
9404           if (*arg)
9405               error (_("Garbage '%s' follows condition"), arg);
9406         }
9407
9408       /* Dynamic printf requires and uses additional arguments on the
9409          command line, otherwise it's an error.  */
9410       if (type == bp_dprintf)
9411         {
9412           if (b->extra_string)
9413             update_dprintf_command_list (b);
9414           else
9415             error (_("Format string required"));
9416         }
9417       else if (b->extra_string)
9418         error (_("Garbage '%s' at end of command"), b->extra_string);
9419     }
9420
9421   b->display_canonical = display_canonical;
9422   if (addr_string)
9423     b->addr_string = addr_string;
9424   else
9425     /* addr_string has to be used or breakpoint_re_set will delete
9426        me.  */
9427     b->addr_string
9428       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9429   b->filter = filter;
9430 }
9431
9432 static void
9433 create_breakpoint_sal (struct gdbarch *gdbarch,
9434                        struct symtabs_and_lines sals, char *addr_string,
9435                        char *filter, char *cond_string,
9436                        char *extra_string,
9437                        enum bptype type, enum bpdisp disposition,
9438                        int thread, int task, int ignore_count,
9439                        const struct breakpoint_ops *ops, int from_tty,
9440                        int enabled, int internal, unsigned flags,
9441                        int display_canonical)
9442 {
9443   struct breakpoint *b;
9444   struct cleanup *old_chain;
9445
9446   if (is_tracepoint_type (type))
9447     {
9448       struct tracepoint *t;
9449
9450       t = XCNEW (struct tracepoint);
9451       b = &t->base;
9452     }
9453   else
9454     b = XNEW (struct breakpoint);
9455
9456   old_chain = make_cleanup (xfree, b);
9457
9458   init_breakpoint_sal (b, gdbarch,
9459                        sals, addr_string,
9460                        filter, cond_string, extra_string,
9461                        type, disposition,
9462                        thread, task, ignore_count,
9463                        ops, from_tty,
9464                        enabled, internal, flags,
9465                        display_canonical);
9466   discard_cleanups (old_chain);
9467
9468   install_breakpoint (internal, b, 0);
9469 }
9470
9471 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9472    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9473    value.  COND_STRING, if not NULL, specified the condition to be
9474    used for all breakpoints.  Essentially the only case where
9475    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9476    function.  In that case, it's still not possible to specify
9477    separate conditions for different overloaded functions, so
9478    we take just a single condition string.
9479    
9480    NOTE: If the function succeeds, the caller is expected to cleanup
9481    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9482    array contents).  If the function fails (error() is called), the
9483    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9484    COND and SALS arrays and each of those arrays contents.  */
9485
9486 static void
9487 create_breakpoints_sal (struct gdbarch *gdbarch,
9488                         struct linespec_result *canonical,
9489                         char *cond_string, char *extra_string,
9490                         enum bptype type, enum bpdisp disposition,
9491                         int thread, int task, int ignore_count,
9492                         const struct breakpoint_ops *ops, int from_tty,
9493                         int enabled, int internal, unsigned flags)
9494 {
9495   int i;
9496   struct linespec_sals *lsal;
9497
9498   if (canonical->pre_expanded)
9499     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9500
9501   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9502     {
9503       /* Note that 'addr_string' can be NULL in the case of a plain
9504          'break', without arguments.  */
9505       char *addr_string = (canonical->addr_string
9506                            ? xstrdup (canonical->addr_string)
9507                            : NULL);
9508       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9509       struct cleanup *inner = make_cleanup (xfree, addr_string);
9510
9511       make_cleanup (xfree, filter_string);
9512       create_breakpoint_sal (gdbarch, lsal->sals,
9513                              addr_string,
9514                              filter_string,
9515                              cond_string, extra_string,
9516                              type, disposition,
9517                              thread, task, ignore_count, ops,
9518                              from_tty, enabled, internal, flags,
9519                              canonical->special_display);
9520       discard_cleanups (inner);
9521     }
9522 }
9523
9524 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9525    followed by conditionals.  On return, SALS contains an array of SAL
9526    addresses found.  ADDR_STRING contains a vector of (canonical)
9527    address strings.  ADDRESS points to the end of the SAL.
9528
9529    The array and the line spec strings are allocated on the heap, it is
9530    the caller's responsibility to free them.  */
9531
9532 static void
9533 parse_breakpoint_sals (char **address,
9534                        struct linespec_result *canonical)
9535 {
9536   /* If no arg given, or if first arg is 'if ', use the default
9537      breakpoint.  */
9538   if ((*address) == NULL
9539       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9540     {
9541       /* The last displayed codepoint, if it's valid, is our default breakpoint
9542          address.  */
9543       if (last_displayed_sal_is_valid ())
9544         {
9545           struct linespec_sals lsal;
9546           struct symtab_and_line sal;
9547           CORE_ADDR pc;
9548
9549           init_sal (&sal);              /* Initialize to zeroes.  */
9550           lsal.sals.sals = (struct symtab_and_line *)
9551             xmalloc (sizeof (struct symtab_and_line));
9552
9553           /* Set sal's pspace, pc, symtab, and line to the values
9554              corresponding to the last call to print_frame_info.
9555              Be sure to reinitialize LINE with NOTCURRENT == 0
9556              as the breakpoint line number is inappropriate otherwise.
9557              find_pc_line would adjust PC, re-set it back.  */
9558           get_last_displayed_sal (&sal);
9559           pc = sal.pc;
9560           sal = find_pc_line (pc, 0);
9561
9562           /* "break" without arguments is equivalent to "break *PC"
9563              where PC is the last displayed codepoint's address.  So
9564              make sure to set sal.explicit_pc to prevent GDB from
9565              trying to expand the list of sals to include all other
9566              instances with the same symtab and line.  */
9567           sal.pc = pc;
9568           sal.explicit_pc = 1;
9569
9570           lsal.sals.sals[0] = sal;
9571           lsal.sals.nelts = 1;
9572           lsal.canonical = NULL;
9573
9574           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9575         }
9576       else
9577         error (_("No default breakpoint address now."));
9578     }
9579   else
9580     {
9581       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9582
9583       /* Force almost all breakpoints to be in terms of the
9584          current_source_symtab (which is decode_line_1's default).
9585          This should produce the results we want almost all of the
9586          time while leaving default_breakpoint_* alone.
9587
9588          ObjC: However, don't match an Objective-C method name which
9589          may have a '+' or '-' succeeded by a '['.  */
9590       if (last_displayed_sal_is_valid ()
9591           && (!cursal.symtab
9592               || ((strchr ("+-", (*address)[0]) != NULL)
9593                   && ((*address)[1] != '['))))
9594         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9595                           get_last_displayed_symtab (),
9596                           get_last_displayed_line (),
9597                           canonical, NULL, NULL);
9598       else
9599         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9600                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9601     }
9602 }
9603
9604
9605 /* Convert each SAL into a real PC.  Verify that the PC can be
9606    inserted as a breakpoint.  If it can't throw an error.  */
9607
9608 static void
9609 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9610 {    
9611   int i;
9612
9613   for (i = 0; i < sals->nelts; i++)
9614     resolve_sal_pc (&sals->sals[i]);
9615 }
9616
9617 /* Fast tracepoints may have restrictions on valid locations.  For
9618    instance, a fast tracepoint using a jump instead of a trap will
9619    likely have to overwrite more bytes than a trap would, and so can
9620    only be placed where the instruction is longer than the jump, or a
9621    multi-instruction sequence does not have a jump into the middle of
9622    it, etc.  */
9623
9624 static void
9625 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9626                             struct symtabs_and_lines *sals)
9627 {
9628   int i, rslt;
9629   struct symtab_and_line *sal;
9630   char *msg;
9631   struct cleanup *old_chain;
9632
9633   for (i = 0; i < sals->nelts; i++)
9634     {
9635       struct gdbarch *sarch;
9636
9637       sal = &sals->sals[i];
9638
9639       sarch = get_sal_arch (*sal);
9640       /* We fall back to GDBARCH if there is no architecture
9641          associated with SAL.  */
9642       if (sarch == NULL)
9643         sarch = gdbarch;
9644       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9645                                                NULL, &msg);
9646       old_chain = make_cleanup (xfree, msg);
9647
9648       if (!rslt)
9649         error (_("May not have a fast tracepoint at 0x%s%s"),
9650                paddress (sarch, sal->pc), (msg ? msg : ""));
9651
9652       do_cleanups (old_chain);
9653     }
9654 }
9655
9656 /* Issue an invalid thread ID error.  */
9657
9658 static void ATTRIBUTE_NORETURN
9659 invalid_thread_id_error (int id)
9660 {
9661   error (_("Unknown thread %d."), id);
9662 }
9663
9664 /* Given TOK, a string specification of condition and thread, as
9665    accepted by the 'break' command, extract the condition
9666    string and thread number and set *COND_STRING and *THREAD.
9667    PC identifies the context at which the condition should be parsed.
9668    If no condition is found, *COND_STRING is set to NULL.
9669    If no thread is found, *THREAD is set to -1.  */
9670
9671 static void
9672 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9673                            char **cond_string, int *thread, int *task,
9674                            char **rest)
9675 {
9676   *cond_string = NULL;
9677   *thread = -1;
9678   *task = 0;
9679   *rest = NULL;
9680
9681   while (tok && *tok)
9682     {
9683       const char *end_tok;
9684       int toklen;
9685       const char *cond_start = NULL;
9686       const char *cond_end = NULL;
9687
9688       tok = skip_spaces_const (tok);
9689
9690       if ((*tok == '"' || *tok == ',') && rest)
9691         {
9692           *rest = savestring (tok, strlen (tok));
9693           return;
9694         }
9695
9696       end_tok = skip_to_space_const (tok);
9697
9698       toklen = end_tok - tok;
9699
9700       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9701         {
9702           struct expression *expr;
9703
9704           tok = cond_start = end_tok + 1;
9705           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9706           xfree (expr);
9707           cond_end = tok;
9708           *cond_string = savestring (cond_start, cond_end - cond_start);
9709         }
9710       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9711         {
9712           char *tmptok;
9713
9714           tok = end_tok + 1;
9715           *thread = strtol (tok, &tmptok, 0);
9716           if (tok == tmptok)
9717             error (_("Junk after thread keyword."));
9718           if (!valid_thread_id (*thread))
9719             invalid_thread_id_error (*thread);
9720           tok = tmptok;
9721         }
9722       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9723         {
9724           char *tmptok;
9725
9726           tok = end_tok + 1;
9727           *task = strtol (tok, &tmptok, 0);
9728           if (tok == tmptok)
9729             error (_("Junk after task keyword."));
9730           if (!valid_task_id (*task))
9731             error (_("Unknown task %d."), *task);
9732           tok = tmptok;
9733         }
9734       else if (rest)
9735         {
9736           *rest = savestring (tok, strlen (tok));
9737           return;
9738         }
9739       else
9740         error (_("Junk at end of arguments."));
9741     }
9742 }
9743
9744 /* Decode a static tracepoint marker spec.  */
9745
9746 static struct symtabs_and_lines
9747 decode_static_tracepoint_spec (char **arg_p)
9748 {
9749   VEC(static_tracepoint_marker_p) *markers = NULL;
9750   struct symtabs_and_lines sals;
9751   struct cleanup *old_chain;
9752   char *p = &(*arg_p)[3];
9753   char *endp;
9754   char *marker_str;
9755   int i;
9756
9757   p = skip_spaces (p);
9758
9759   endp = skip_to_space (p);
9760
9761   marker_str = savestring (p, endp - p);
9762   old_chain = make_cleanup (xfree, marker_str);
9763
9764   markers = target_static_tracepoint_markers_by_strid (marker_str);
9765   if (VEC_empty(static_tracepoint_marker_p, markers))
9766     error (_("No known static tracepoint marker named %s"), marker_str);
9767
9768   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9769   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9770
9771   for (i = 0; i < sals.nelts; i++)
9772     {
9773       struct static_tracepoint_marker *marker;
9774
9775       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9776
9777       init_sal (&sals.sals[i]);
9778
9779       sals.sals[i] = find_pc_line (marker->address, 0);
9780       sals.sals[i].pc = marker->address;
9781
9782       release_static_tracepoint_marker (marker);
9783     }
9784
9785   do_cleanups (old_chain);
9786
9787   *arg_p = endp;
9788   return sals;
9789 }
9790
9791 /* Set a breakpoint.  This function is shared between CLI and MI
9792    functions for setting a breakpoint.  This function has two major
9793    modes of operations, selected by the PARSE_ARG parameter.  If
9794    non-zero, the function will parse ARG, extracting location,
9795    condition, thread and extra string.  Otherwise, ARG is just the
9796    breakpoint's location, with condition, thread, and extra string
9797    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9798    If INTERNAL is non-zero, the breakpoint number will be allocated
9799    from the internal breakpoint count.  Returns true if any breakpoint
9800    was created; false otherwise.  */
9801
9802 int
9803 create_breakpoint (struct gdbarch *gdbarch,
9804                    char *arg, char *cond_string,
9805                    int thread, char *extra_string,
9806                    int parse_arg,
9807                    int tempflag, enum bptype type_wanted,
9808                    int ignore_count,
9809                    enum auto_boolean pending_break_support,
9810                    const struct breakpoint_ops *ops,
9811                    int from_tty, int enabled, int internal,
9812                    unsigned flags)
9813 {
9814   volatile struct gdb_exception e;
9815   char *copy_arg = NULL;
9816   char *addr_start = arg;
9817   struct linespec_result canonical;
9818   struct cleanup *old_chain;
9819   struct cleanup *bkpt_chain = NULL;
9820   int pending = 0;
9821   int task = 0;
9822   int prev_bkpt_count = breakpoint_count;
9823
9824   gdb_assert (ops != NULL);
9825
9826   init_linespec_result (&canonical);
9827
9828   TRY_CATCH (e, RETURN_MASK_ALL)
9829     {
9830       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9831                                      addr_start, &copy_arg);
9832     }
9833
9834   /* If caller is interested in rc value from parse, set value.  */
9835   switch (e.reason)
9836     {
9837     case GDB_NO_ERROR:
9838       if (VEC_empty (linespec_sals, canonical.sals))
9839         return 0;
9840       break;
9841     case RETURN_ERROR:
9842       switch (e.error)
9843         {
9844         case NOT_FOUND_ERROR:
9845
9846           /* If pending breakpoint support is turned off, throw
9847              error.  */
9848
9849           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9850             throw_exception (e);
9851
9852           exception_print (gdb_stderr, e);
9853
9854           /* If pending breakpoint support is auto query and the user
9855              selects no, then simply return the error code.  */
9856           if (pending_break_support == AUTO_BOOLEAN_AUTO
9857               && !nquery (_("Make %s pending on future shared library load? "),
9858                           bptype_string (type_wanted)))
9859             return 0;
9860
9861           /* At this point, either the user was queried about setting
9862              a pending breakpoint and selected yes, or pending
9863              breakpoint behavior is on and thus a pending breakpoint
9864              is defaulted on behalf of the user.  */
9865           {
9866             struct linespec_sals lsal;
9867
9868             copy_arg = xstrdup (addr_start);
9869             lsal.canonical = xstrdup (copy_arg);
9870             lsal.sals.nelts = 1;
9871             lsal.sals.sals = XNEW (struct symtab_and_line);
9872             init_sal (&lsal.sals.sals[0]);
9873             pending = 1;
9874             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9875           }
9876           break;
9877         default:
9878           throw_exception (e);
9879         }
9880       break;
9881     default:
9882       throw_exception (e);
9883     }
9884
9885   /* Create a chain of things that always need to be cleaned up.  */
9886   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9887
9888   /* ----------------------------- SNIP -----------------------------
9889      Anything added to the cleanup chain beyond this point is assumed
9890      to be part of a breakpoint.  If the breakpoint create succeeds
9891      then the memory is not reclaimed.  */
9892   bkpt_chain = make_cleanup (null_cleanup, 0);
9893
9894   /* Resolve all line numbers to PC's and verify that the addresses
9895      are ok for the target.  */
9896   if (!pending)
9897     {
9898       int ix;
9899       struct linespec_sals *iter;
9900
9901       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9902         breakpoint_sals_to_pc (&iter->sals);
9903     }
9904
9905   /* Fast tracepoints may have additional restrictions on location.  */
9906   if (!pending && type_wanted == bp_fast_tracepoint)
9907     {
9908       int ix;
9909       struct linespec_sals *iter;
9910
9911       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9912         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9913     }
9914
9915   /* Verify that condition can be parsed, before setting any
9916      breakpoints.  Allocate a separate condition expression for each
9917      breakpoint.  */
9918   if (!pending)
9919     {
9920       if (parse_arg)
9921         {
9922           char *rest;
9923           struct linespec_sals *lsal;
9924
9925           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9926
9927           /* Here we only parse 'arg' to separate condition
9928              from thread number, so parsing in context of first
9929              sal is OK.  When setting the breakpoint we'll
9930              re-parse it in context of each sal.  */
9931
9932           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9933                                      &thread, &task, &rest);
9934           if (cond_string)
9935             make_cleanup (xfree, cond_string);
9936           if (rest)
9937             make_cleanup (xfree, rest);
9938           if (rest)
9939             extra_string = rest;
9940         }
9941       else
9942         {
9943           if (*arg != '\0')
9944             error (_("Garbage '%s' at end of location"), arg);
9945
9946           /* Create a private copy of condition string.  */
9947           if (cond_string)
9948             {
9949               cond_string = xstrdup (cond_string);
9950               make_cleanup (xfree, cond_string);
9951             }
9952           /* Create a private copy of any extra string.  */
9953           if (extra_string)
9954             {
9955               extra_string = xstrdup (extra_string);
9956               make_cleanup (xfree, extra_string);
9957             }
9958         }
9959
9960       ops->create_breakpoints_sal (gdbarch, &canonical,
9961                                    cond_string, extra_string, type_wanted,
9962                                    tempflag ? disp_del : disp_donttouch,
9963                                    thread, task, ignore_count, ops,
9964                                    from_tty, enabled, internal, flags);
9965     }
9966   else
9967     {
9968       struct breakpoint *b;
9969
9970       make_cleanup (xfree, copy_arg);
9971
9972       if (is_tracepoint_type (type_wanted))
9973         {
9974           struct tracepoint *t;
9975
9976           t = XCNEW (struct tracepoint);
9977           b = &t->base;
9978         }
9979       else
9980         b = XNEW (struct breakpoint);
9981
9982       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9983
9984       b->addr_string = copy_arg;
9985       if (parse_arg)
9986         b->cond_string = NULL;
9987       else
9988         {
9989           /* Create a private copy of condition string.  */
9990           if (cond_string)
9991             {
9992               cond_string = xstrdup (cond_string);
9993               make_cleanup (xfree, cond_string);
9994             }
9995           b->cond_string = cond_string;
9996         }
9997       b->extra_string = NULL;
9998       b->ignore_count = ignore_count;
9999       b->disposition = tempflag ? disp_del : disp_donttouch;
10000       b->condition_not_parsed = 1;
10001       b->enable_state = enabled ? bp_enabled : bp_disabled;
10002       if ((type_wanted != bp_breakpoint
10003            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10004         b->pspace = current_program_space;
10005
10006       install_breakpoint (internal, b, 0);
10007     }
10008   
10009   if (VEC_length (linespec_sals, canonical.sals) > 1)
10010     {
10011       warning (_("Multiple breakpoints were set.\nUse the "
10012                  "\"delete\" command to delete unwanted breakpoints."));
10013       prev_breakpoint_count = prev_bkpt_count;
10014     }
10015
10016   /* That's it.  Discard the cleanups for data inserted into the
10017      breakpoint.  */
10018   discard_cleanups (bkpt_chain);
10019   /* But cleanup everything else.  */
10020   do_cleanups (old_chain);
10021
10022   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10023   update_global_location_list (1);
10024
10025   return 1;
10026 }
10027
10028 /* Set a breakpoint.
10029    ARG is a string describing breakpoint address,
10030    condition, and thread.
10031    FLAG specifies if a breakpoint is hardware on,
10032    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10033    and BP_TEMPFLAG.  */
10034
10035 static void
10036 break_command_1 (char *arg, int flag, int from_tty)
10037 {
10038   int tempflag = flag & BP_TEMPFLAG;
10039   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10040                              ? bp_hardware_breakpoint
10041                              : bp_breakpoint);
10042   struct breakpoint_ops *ops;
10043   const char *arg_cp = arg;
10044
10045   /* Matching breakpoints on probes.  */
10046   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10047     ops = &bkpt_probe_breakpoint_ops;
10048   else
10049     ops = &bkpt_breakpoint_ops;
10050
10051   create_breakpoint (get_current_arch (),
10052                      arg,
10053                      NULL, 0, NULL, 1 /* parse arg */,
10054                      tempflag, type_wanted,
10055                      0 /* Ignore count */,
10056                      pending_break_support,
10057                      ops,
10058                      from_tty,
10059                      1 /* enabled */,
10060                      0 /* internal */,
10061                      0);
10062 }
10063
10064 /* Helper function for break_command_1 and disassemble_command.  */
10065
10066 void
10067 resolve_sal_pc (struct symtab_and_line *sal)
10068 {
10069   CORE_ADDR pc;
10070
10071   if (sal->pc == 0 && sal->symtab != NULL)
10072     {
10073       if (!find_line_pc (sal->symtab, sal->line, &pc))
10074         error (_("No line %d in file \"%s\"."),
10075                sal->line, symtab_to_filename_for_display (sal->symtab));
10076       sal->pc = pc;
10077
10078       /* If this SAL corresponds to a breakpoint inserted using a line
10079          number, then skip the function prologue if necessary.  */
10080       if (sal->explicit_line)
10081         skip_prologue_sal (sal);
10082     }
10083
10084   if (sal->section == 0 && sal->symtab != NULL)
10085     {
10086       struct blockvector *bv;
10087       struct block *b;
10088       struct symbol *sym;
10089
10090       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10091       if (bv != NULL)
10092         {
10093           sym = block_linkage_function (b);
10094           if (sym != NULL)
10095             {
10096               fixup_symbol_section (sym, sal->symtab->objfile);
10097               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10098             }
10099           else
10100             {
10101               /* It really is worthwhile to have the section, so we'll
10102                  just have to look harder. This case can be executed
10103                  if we have line numbers but no functions (as can
10104                  happen in assembly source).  */
10105
10106               struct bound_minimal_symbol msym;
10107               struct cleanup *old_chain = save_current_space_and_thread ();
10108
10109               switch_to_program_space_and_thread (sal->pspace);
10110
10111               msym = lookup_minimal_symbol_by_pc (sal->pc);
10112               if (msym.minsym)
10113                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10114
10115               do_cleanups (old_chain);
10116             }
10117         }
10118     }
10119 }
10120
10121 void
10122 break_command (char *arg, int from_tty)
10123 {
10124   break_command_1 (arg, 0, from_tty);
10125 }
10126
10127 void
10128 tbreak_command (char *arg, int from_tty)
10129 {
10130   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10131 }
10132
10133 static void
10134 hbreak_command (char *arg, int from_tty)
10135 {
10136   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10137 }
10138
10139 static void
10140 thbreak_command (char *arg, int from_tty)
10141 {
10142   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10143 }
10144
10145 static void
10146 stop_command (char *arg, int from_tty)
10147 {
10148   printf_filtered (_("Specify the type of breakpoint to set.\n\
10149 Usage: stop in <function | address>\n\
10150        stop at <line>\n"));
10151 }
10152
10153 static void
10154 stopin_command (char *arg, int from_tty)
10155 {
10156   int badInput = 0;
10157
10158   if (arg == (char *) NULL)
10159     badInput = 1;
10160   else if (*arg != '*')
10161     {
10162       char *argptr = arg;
10163       int hasColon = 0;
10164
10165       /* Look for a ':'.  If this is a line number specification, then
10166          say it is bad, otherwise, it should be an address or
10167          function/method name.  */
10168       while (*argptr && !hasColon)
10169         {
10170           hasColon = (*argptr == ':');
10171           argptr++;
10172         }
10173
10174       if (hasColon)
10175         badInput = (*argptr != ':');    /* Not a class::method */
10176       else
10177         badInput = isdigit (*arg);      /* a simple line number */
10178     }
10179
10180   if (badInput)
10181     printf_filtered (_("Usage: stop in <function | address>\n"));
10182   else
10183     break_command_1 (arg, 0, from_tty);
10184 }
10185
10186 static void
10187 stopat_command (char *arg, int from_tty)
10188 {
10189   int badInput = 0;
10190
10191   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10192     badInput = 1;
10193   else
10194     {
10195       char *argptr = arg;
10196       int hasColon = 0;
10197
10198       /* Look for a ':'.  If there is a '::' then get out, otherwise
10199          it is probably a line number.  */
10200       while (*argptr && !hasColon)
10201         {
10202           hasColon = (*argptr == ':');
10203           argptr++;
10204         }
10205
10206       if (hasColon)
10207         badInput = (*argptr == ':');    /* we have class::method */
10208       else
10209         badInput = !isdigit (*arg);     /* not a line number */
10210     }
10211
10212   if (badInput)
10213     printf_filtered (_("Usage: stop at <line>\n"));
10214   else
10215     break_command_1 (arg, 0, from_tty);
10216 }
10217
10218 /* The dynamic printf command is mostly like a regular breakpoint, but
10219    with a prewired command list consisting of a single output command,
10220    built from extra arguments supplied on the dprintf command
10221    line.  */
10222
10223 static void
10224 dprintf_command (char *arg, int from_tty)
10225 {
10226   create_breakpoint (get_current_arch (),
10227                      arg,
10228                      NULL, 0, NULL, 1 /* parse arg */,
10229                      0, bp_dprintf,
10230                      0 /* Ignore count */,
10231                      pending_break_support,
10232                      &dprintf_breakpoint_ops,
10233                      from_tty,
10234                      1 /* enabled */,
10235                      0 /* internal */,
10236                      0);
10237 }
10238
10239 static void
10240 agent_printf_command (char *arg, int from_tty)
10241 {
10242   error (_("May only run agent-printf on the target"));
10243 }
10244
10245 /* Implement the "breakpoint_hit" breakpoint_ops method for
10246    ranged breakpoints.  */
10247
10248 static int
10249 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10250                                   struct address_space *aspace,
10251                                   CORE_ADDR bp_addr,
10252                                   const struct target_waitstatus *ws)
10253 {
10254   if (ws->kind != TARGET_WAITKIND_STOPPED
10255       || ws->value.sig != GDB_SIGNAL_TRAP)
10256     return 0;
10257
10258   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10259                                          bl->length, aspace, bp_addr);
10260 }
10261
10262 /* Implement the "resources_needed" breakpoint_ops method for
10263    ranged breakpoints.  */
10264
10265 static int
10266 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10267 {
10268   return target_ranged_break_num_registers ();
10269 }
10270
10271 /* Implement the "print_it" breakpoint_ops method for
10272    ranged breakpoints.  */
10273
10274 static enum print_stop_action
10275 print_it_ranged_breakpoint (bpstat bs)
10276 {
10277   struct breakpoint *b = bs->breakpoint_at;
10278   struct bp_location *bl = b->loc;
10279   struct ui_out *uiout = current_uiout;
10280
10281   gdb_assert (b->type == bp_hardware_breakpoint);
10282
10283   /* Ranged breakpoints have only one location.  */
10284   gdb_assert (bl && bl->next == NULL);
10285
10286   annotate_breakpoint (b->number);
10287   if (b->disposition == disp_del)
10288     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10289   else
10290     ui_out_text (uiout, "\nRanged breakpoint ");
10291   if (ui_out_is_mi_like_p (uiout))
10292     {
10293       ui_out_field_string (uiout, "reason",
10294                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10295       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10296     }
10297   ui_out_field_int (uiout, "bkptno", b->number);
10298   ui_out_text (uiout, ", ");
10299
10300   return PRINT_SRC_AND_LOC;
10301 }
10302
10303 /* Implement the "print_one" breakpoint_ops method for
10304    ranged breakpoints.  */
10305
10306 static void
10307 print_one_ranged_breakpoint (struct breakpoint *b,
10308                              struct bp_location **last_loc)
10309 {
10310   struct bp_location *bl = b->loc;
10311   struct value_print_options opts;
10312   struct ui_out *uiout = current_uiout;
10313
10314   /* Ranged breakpoints have only one location.  */
10315   gdb_assert (bl && bl->next == NULL);
10316
10317   get_user_print_options (&opts);
10318
10319   if (opts.addressprint)
10320     /* We don't print the address range here, it will be printed later
10321        by print_one_detail_ranged_breakpoint.  */
10322     ui_out_field_skip (uiout, "addr");
10323   annotate_field (5);
10324   print_breakpoint_location (b, bl);
10325   *last_loc = bl;
10326 }
10327
10328 /* Implement the "print_one_detail" breakpoint_ops method for
10329    ranged breakpoints.  */
10330
10331 static void
10332 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10333                                     struct ui_out *uiout)
10334 {
10335   CORE_ADDR address_start, address_end;
10336   struct bp_location *bl = b->loc;
10337   struct ui_file *stb = mem_fileopen ();
10338   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10339
10340   gdb_assert (bl);
10341
10342   address_start = bl->address;
10343   address_end = address_start + bl->length - 1;
10344
10345   ui_out_text (uiout, "\taddress range: ");
10346   fprintf_unfiltered (stb, "[%s, %s]",
10347                       print_core_address (bl->gdbarch, address_start),
10348                       print_core_address (bl->gdbarch, address_end));
10349   ui_out_field_stream (uiout, "addr", stb);
10350   ui_out_text (uiout, "\n");
10351
10352   do_cleanups (cleanup);
10353 }
10354
10355 /* Implement the "print_mention" breakpoint_ops method for
10356    ranged breakpoints.  */
10357
10358 static void
10359 print_mention_ranged_breakpoint (struct breakpoint *b)
10360 {
10361   struct bp_location *bl = b->loc;
10362   struct ui_out *uiout = current_uiout;
10363
10364   gdb_assert (bl);
10365   gdb_assert (b->type == bp_hardware_breakpoint);
10366
10367   if (ui_out_is_mi_like_p (uiout))
10368     return;
10369
10370   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10371                    b->number, paddress (bl->gdbarch, bl->address),
10372                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10373 }
10374
10375 /* Implement the "print_recreate" breakpoint_ops method for
10376    ranged breakpoints.  */
10377
10378 static void
10379 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10380 {
10381   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10382                       b->addr_string_range_end);
10383   print_recreate_thread (b, fp);
10384 }
10385
10386 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10387
10388 static struct breakpoint_ops ranged_breakpoint_ops;
10389
10390 /* Find the address where the end of the breakpoint range should be
10391    placed, given the SAL of the end of the range.  This is so that if
10392    the user provides a line number, the end of the range is set to the
10393    last instruction of the given line.  */
10394
10395 static CORE_ADDR
10396 find_breakpoint_range_end (struct symtab_and_line sal)
10397 {
10398   CORE_ADDR end;
10399
10400   /* If the user provided a PC value, use it.  Otherwise,
10401      find the address of the end of the given location.  */
10402   if (sal.explicit_pc)
10403     end = sal.pc;
10404   else
10405     {
10406       int ret;
10407       CORE_ADDR start;
10408
10409       ret = find_line_pc_range (sal, &start, &end);
10410       if (!ret)
10411         error (_("Could not find location of the end of the range."));
10412
10413       /* find_line_pc_range returns the start of the next line.  */
10414       end--;
10415     }
10416
10417   return end;
10418 }
10419
10420 /* Implement the "break-range" CLI command.  */
10421
10422 static void
10423 break_range_command (char *arg, int from_tty)
10424 {
10425   char *arg_start, *addr_string_start, *addr_string_end;
10426   struct linespec_result canonical_start, canonical_end;
10427   int bp_count, can_use_bp, length;
10428   CORE_ADDR end;
10429   struct breakpoint *b;
10430   struct symtab_and_line sal_start, sal_end;
10431   struct cleanup *cleanup_bkpt;
10432   struct linespec_sals *lsal_start, *lsal_end;
10433
10434   /* We don't support software ranged breakpoints.  */
10435   if (target_ranged_break_num_registers () < 0)
10436     error (_("This target does not support hardware ranged breakpoints."));
10437
10438   bp_count = hw_breakpoint_used_count ();
10439   bp_count += target_ranged_break_num_registers ();
10440   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10441                                                    bp_count, 0);
10442   if (can_use_bp < 0)
10443     error (_("Hardware breakpoints used exceeds limit."));
10444
10445   arg = skip_spaces (arg);
10446   if (arg == NULL || arg[0] == '\0')
10447     error(_("No address range specified."));
10448
10449   init_linespec_result (&canonical_start);
10450
10451   arg_start = arg;
10452   parse_breakpoint_sals (&arg, &canonical_start);
10453
10454   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10455
10456   if (arg[0] != ',')
10457     error (_("Too few arguments."));
10458   else if (VEC_empty (linespec_sals, canonical_start.sals))
10459     error (_("Could not find location of the beginning of the range."));
10460
10461   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10462
10463   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10464       || lsal_start->sals.nelts != 1)
10465     error (_("Cannot create a ranged breakpoint with multiple locations."));
10466
10467   sal_start = lsal_start->sals.sals[0];
10468   addr_string_start = savestring (arg_start, arg - arg_start);
10469   make_cleanup (xfree, addr_string_start);
10470
10471   arg++;        /* Skip the comma.  */
10472   arg = skip_spaces (arg);
10473
10474   /* Parse the end location.  */
10475
10476   init_linespec_result (&canonical_end);
10477   arg_start = arg;
10478
10479   /* We call decode_line_full directly here instead of using
10480      parse_breakpoint_sals because we need to specify the start location's
10481      symtab and line as the default symtab and line for the end of the
10482      range.  This makes it possible to have ranges like "foo.c:27, +14",
10483      where +14 means 14 lines from the start location.  */
10484   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10485                     sal_start.symtab, sal_start.line,
10486                     &canonical_end, NULL, NULL);
10487
10488   make_cleanup_destroy_linespec_result (&canonical_end);
10489
10490   if (VEC_empty (linespec_sals, canonical_end.sals))
10491     error (_("Could not find location of the end of the range."));
10492
10493   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10494   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10495       || lsal_end->sals.nelts != 1)
10496     error (_("Cannot create a ranged breakpoint with multiple locations."));
10497
10498   sal_end = lsal_end->sals.sals[0];
10499   addr_string_end = savestring (arg_start, arg - arg_start);
10500   make_cleanup (xfree, addr_string_end);
10501
10502   end = find_breakpoint_range_end (sal_end);
10503   if (sal_start.pc > end)
10504     error (_("Invalid address range, end precedes start."));
10505
10506   length = end - sal_start.pc + 1;
10507   if (length < 0)
10508     /* Length overflowed.  */
10509     error (_("Address range too large."));
10510   else if (length == 1)
10511     {
10512       /* This range is simple enough to be handled by
10513          the `hbreak' command.  */
10514       hbreak_command (addr_string_start, 1);
10515
10516       do_cleanups (cleanup_bkpt);
10517
10518       return;
10519     }
10520
10521   /* Now set up the breakpoint.  */
10522   b = set_raw_breakpoint (get_current_arch (), sal_start,
10523                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10524   set_breakpoint_count (breakpoint_count + 1);
10525   b->number = breakpoint_count;
10526   b->disposition = disp_donttouch;
10527   b->addr_string = xstrdup (addr_string_start);
10528   b->addr_string_range_end = xstrdup (addr_string_end);
10529   b->loc->length = length;
10530
10531   do_cleanups (cleanup_bkpt);
10532
10533   mention (b);
10534   observer_notify_breakpoint_created (b);
10535   update_global_location_list (1);
10536 }
10537
10538 /*  Return non-zero if EXP is verified as constant.  Returned zero
10539     means EXP is variable.  Also the constant detection may fail for
10540     some constant expressions and in such case still falsely return
10541     zero.  */
10542
10543 static int
10544 watchpoint_exp_is_const (const struct expression *exp)
10545 {
10546   int i = exp->nelts;
10547
10548   while (i > 0)
10549     {
10550       int oplenp, argsp;
10551
10552       /* We are only interested in the descriptor of each element.  */
10553       operator_length (exp, i, &oplenp, &argsp);
10554       i -= oplenp;
10555
10556       switch (exp->elts[i].opcode)
10557         {
10558         case BINOP_ADD:
10559         case BINOP_SUB:
10560         case BINOP_MUL:
10561         case BINOP_DIV:
10562         case BINOP_REM:
10563         case BINOP_MOD:
10564         case BINOP_LSH:
10565         case BINOP_RSH:
10566         case BINOP_LOGICAL_AND:
10567         case BINOP_LOGICAL_OR:
10568         case BINOP_BITWISE_AND:
10569         case BINOP_BITWISE_IOR:
10570         case BINOP_BITWISE_XOR:
10571         case BINOP_EQUAL:
10572         case BINOP_NOTEQUAL:
10573         case BINOP_LESS:
10574         case BINOP_GTR:
10575         case BINOP_LEQ:
10576         case BINOP_GEQ:
10577         case BINOP_REPEAT:
10578         case BINOP_COMMA:
10579         case BINOP_EXP:
10580         case BINOP_MIN:
10581         case BINOP_MAX:
10582         case BINOP_INTDIV:
10583         case BINOP_CONCAT:
10584         case BINOP_IN:
10585         case BINOP_RANGE:
10586         case TERNOP_COND:
10587         case TERNOP_SLICE:
10588
10589         case OP_LONG:
10590         case OP_DOUBLE:
10591         case OP_DECFLOAT:
10592         case OP_LAST:
10593         case OP_COMPLEX:
10594         case OP_STRING:
10595         case OP_ARRAY:
10596         case OP_TYPE:
10597         case OP_TYPEOF:
10598         case OP_DECLTYPE:
10599         case OP_TYPEID:
10600         case OP_NAME:
10601         case OP_OBJC_NSSTRING:
10602
10603         case UNOP_NEG:
10604         case UNOP_LOGICAL_NOT:
10605         case UNOP_COMPLEMENT:
10606         case UNOP_ADDR:
10607         case UNOP_HIGH:
10608         case UNOP_CAST:
10609
10610         case UNOP_CAST_TYPE:
10611         case UNOP_REINTERPRET_CAST:
10612         case UNOP_DYNAMIC_CAST:
10613           /* Unary, binary and ternary operators: We have to check
10614              their operands.  If they are constant, then so is the
10615              result of that operation.  For instance, if A and B are
10616              determined to be constants, then so is "A + B".
10617
10618              UNOP_IND is one exception to the rule above, because the
10619              value of *ADDR is not necessarily a constant, even when
10620              ADDR is.  */
10621           break;
10622
10623         case OP_VAR_VALUE:
10624           /* Check whether the associated symbol is a constant.
10625
10626              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10627              possible that a buggy compiler could mark a variable as
10628              constant even when it is not, and TYPE_CONST would return
10629              true in this case, while SYMBOL_CLASS wouldn't.
10630
10631              We also have to check for function symbols because they
10632              are always constant.  */
10633           {
10634             struct symbol *s = exp->elts[i + 2].symbol;
10635
10636             if (SYMBOL_CLASS (s) != LOC_BLOCK
10637                 && SYMBOL_CLASS (s) != LOC_CONST
10638                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10639               return 0;
10640             break;
10641           }
10642
10643         /* The default action is to return 0 because we are using
10644            the optimistic approach here: If we don't know something,
10645            then it is not a constant.  */
10646         default:
10647           return 0;
10648         }
10649     }
10650
10651   return 1;
10652 }
10653
10654 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10655
10656 static void
10657 dtor_watchpoint (struct breakpoint *self)
10658 {
10659   struct watchpoint *w = (struct watchpoint *) self;
10660
10661   xfree (w->cond_exp);
10662   xfree (w->exp);
10663   xfree (w->exp_string);
10664   xfree (w->exp_string_reparse);
10665   value_free (w->val);
10666
10667   base_breakpoint_ops.dtor (self);
10668 }
10669
10670 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10671
10672 static void
10673 re_set_watchpoint (struct breakpoint *b)
10674 {
10675   struct watchpoint *w = (struct watchpoint *) b;
10676
10677   /* Watchpoint can be either on expression using entirely global
10678      variables, or it can be on local variables.
10679
10680      Watchpoints of the first kind are never auto-deleted, and even
10681      persist across program restarts.  Since they can use variables
10682      from shared libraries, we need to reparse expression as libraries
10683      are loaded and unloaded.
10684
10685      Watchpoints on local variables can also change meaning as result
10686      of solib event.  For example, if a watchpoint uses both a local
10687      and a global variables in expression, it's a local watchpoint,
10688      but unloading of a shared library will make the expression
10689      invalid.  This is not a very common use case, but we still
10690      re-evaluate expression, to avoid surprises to the user.
10691
10692      Note that for local watchpoints, we re-evaluate it only if
10693      watchpoints frame id is still valid.  If it's not, it means the
10694      watchpoint is out of scope and will be deleted soon.  In fact,
10695      I'm not sure we'll ever be called in this case.
10696
10697      If a local watchpoint's frame id is still valid, then
10698      w->exp_valid_block is likewise valid, and we can safely use it.
10699
10700      Don't do anything about disabled watchpoints, since they will be
10701      reevaluated again when enabled.  */
10702   update_watchpoint (w, 1 /* reparse */);
10703 }
10704
10705 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10706
10707 static int
10708 insert_watchpoint (struct bp_location *bl)
10709 {
10710   struct watchpoint *w = (struct watchpoint *) bl->owner;
10711   int length = w->exact ? 1 : bl->length;
10712
10713   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10714                                    w->cond_exp);
10715 }
10716
10717 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10718
10719 static int
10720 remove_watchpoint (struct bp_location *bl)
10721 {
10722   struct watchpoint *w = (struct watchpoint *) bl->owner;
10723   int length = w->exact ? 1 : bl->length;
10724
10725   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10726                                    w->cond_exp);
10727 }
10728
10729 static int
10730 breakpoint_hit_watchpoint (const struct bp_location *bl,
10731                            struct address_space *aspace, CORE_ADDR bp_addr,
10732                            const struct target_waitstatus *ws)
10733 {
10734   struct breakpoint *b = bl->owner;
10735   struct watchpoint *w = (struct watchpoint *) b;
10736
10737   /* Continuable hardware watchpoints are treated as non-existent if the
10738      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10739      some data address).  Otherwise gdb won't stop on a break instruction
10740      in the code (not from a breakpoint) when a hardware watchpoint has
10741      been defined.  Also skip watchpoints which we know did not trigger
10742      (did not match the data address).  */
10743   if (is_hardware_watchpoint (b)
10744       && w->watchpoint_triggered == watch_triggered_no)
10745     return 0;
10746
10747   return 1;
10748 }
10749
10750 static void
10751 check_status_watchpoint (bpstat bs)
10752 {
10753   gdb_assert (is_watchpoint (bs->breakpoint_at));
10754
10755   bpstat_check_watchpoint (bs);
10756 }
10757
10758 /* Implement the "resources_needed" breakpoint_ops method for
10759    hardware watchpoints.  */
10760
10761 static int
10762 resources_needed_watchpoint (const struct bp_location *bl)
10763 {
10764   struct watchpoint *w = (struct watchpoint *) bl->owner;
10765   int length = w->exact? 1 : bl->length;
10766
10767   return target_region_ok_for_hw_watchpoint (bl->address, length);
10768 }
10769
10770 /* Implement the "works_in_software_mode" breakpoint_ops method for
10771    hardware watchpoints.  */
10772
10773 static int
10774 works_in_software_mode_watchpoint (const struct breakpoint *b)
10775 {
10776   /* Read and access watchpoints only work with hardware support.  */
10777   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10778 }
10779
10780 static enum print_stop_action
10781 print_it_watchpoint (bpstat bs)
10782 {
10783   struct cleanup *old_chain;
10784   struct breakpoint *b;
10785   struct ui_file *stb;
10786   enum print_stop_action result;
10787   struct watchpoint *w;
10788   struct ui_out *uiout = current_uiout;
10789
10790   gdb_assert (bs->bp_location_at != NULL);
10791
10792   b = bs->breakpoint_at;
10793   w = (struct watchpoint *) b;
10794
10795   stb = mem_fileopen ();
10796   old_chain = make_cleanup_ui_file_delete (stb);
10797
10798   switch (b->type)
10799     {
10800     case bp_watchpoint:
10801     case bp_hardware_watchpoint:
10802       annotate_watchpoint (b->number);
10803       if (ui_out_is_mi_like_p (uiout))
10804         ui_out_field_string
10805           (uiout, "reason",
10806            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10807       mention (b);
10808       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10809       ui_out_text (uiout, "\nOld value = ");
10810       watchpoint_value_print (bs->old_val, stb);
10811       ui_out_field_stream (uiout, "old", stb);
10812       ui_out_text (uiout, "\nNew value = ");
10813       watchpoint_value_print (w->val, stb);
10814       ui_out_field_stream (uiout, "new", stb);
10815       ui_out_text (uiout, "\n");
10816       /* More than one watchpoint may have been triggered.  */
10817       result = PRINT_UNKNOWN;
10818       break;
10819
10820     case bp_read_watchpoint:
10821       if (ui_out_is_mi_like_p (uiout))
10822         ui_out_field_string
10823           (uiout, "reason",
10824            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10825       mention (b);
10826       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10827       ui_out_text (uiout, "\nValue = ");
10828       watchpoint_value_print (w->val, stb);
10829       ui_out_field_stream (uiout, "value", stb);
10830       ui_out_text (uiout, "\n");
10831       result = PRINT_UNKNOWN;
10832       break;
10833
10834     case bp_access_watchpoint:
10835       if (bs->old_val != NULL)
10836         {
10837           annotate_watchpoint (b->number);
10838           if (ui_out_is_mi_like_p (uiout))
10839             ui_out_field_string
10840               (uiout, "reason",
10841                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10842           mention (b);
10843           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10844           ui_out_text (uiout, "\nOld value = ");
10845           watchpoint_value_print (bs->old_val, stb);
10846           ui_out_field_stream (uiout, "old", stb);
10847           ui_out_text (uiout, "\nNew value = ");
10848         }
10849       else
10850         {
10851           mention (b);
10852           if (ui_out_is_mi_like_p (uiout))
10853             ui_out_field_string
10854               (uiout, "reason",
10855                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10856           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10857           ui_out_text (uiout, "\nValue = ");
10858         }
10859       watchpoint_value_print (w->val, stb);
10860       ui_out_field_stream (uiout, "new", stb);
10861       ui_out_text (uiout, "\n");
10862       result = PRINT_UNKNOWN;
10863       break;
10864     default:
10865       result = PRINT_UNKNOWN;
10866     }
10867
10868   do_cleanups (old_chain);
10869   return result;
10870 }
10871
10872 /* Implement the "print_mention" breakpoint_ops method for hardware
10873    watchpoints.  */
10874
10875 static void
10876 print_mention_watchpoint (struct breakpoint *b)
10877 {
10878   struct cleanup *ui_out_chain;
10879   struct watchpoint *w = (struct watchpoint *) b;
10880   struct ui_out *uiout = current_uiout;
10881
10882   switch (b->type)
10883     {
10884     case bp_watchpoint:
10885       ui_out_text (uiout, "Watchpoint ");
10886       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10887       break;
10888     case bp_hardware_watchpoint:
10889       ui_out_text (uiout, "Hardware watchpoint ");
10890       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10891       break;
10892     case bp_read_watchpoint:
10893       ui_out_text (uiout, "Hardware read watchpoint ");
10894       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10895       break;
10896     case bp_access_watchpoint:
10897       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10898       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10899       break;
10900     default:
10901       internal_error (__FILE__, __LINE__,
10902                       _("Invalid hardware watchpoint type."));
10903     }
10904
10905   ui_out_field_int (uiout, "number", b->number);
10906   ui_out_text (uiout, ": ");
10907   ui_out_field_string (uiout, "exp", w->exp_string);
10908   do_cleanups (ui_out_chain);
10909 }
10910
10911 /* Implement the "print_recreate" breakpoint_ops method for
10912    watchpoints.  */
10913
10914 static void
10915 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10916 {
10917   struct watchpoint *w = (struct watchpoint *) b;
10918
10919   switch (b->type)
10920     {
10921     case bp_watchpoint:
10922     case bp_hardware_watchpoint:
10923       fprintf_unfiltered (fp, "watch");
10924       break;
10925     case bp_read_watchpoint:
10926       fprintf_unfiltered (fp, "rwatch");
10927       break;
10928     case bp_access_watchpoint:
10929       fprintf_unfiltered (fp, "awatch");
10930       break;
10931     default:
10932       internal_error (__FILE__, __LINE__,
10933                       _("Invalid watchpoint type."));
10934     }
10935
10936   fprintf_unfiltered (fp, " %s", w->exp_string);
10937   print_recreate_thread (b, fp);
10938 }
10939
10940 /* Implement the "explains_signal" breakpoint_ops method for
10941    watchpoints.  */
10942
10943 static int
10944 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10945 {
10946   /* A software watchpoint cannot cause a signal other than
10947      GDB_SIGNAL_TRAP.  */
10948   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10949     return 0;
10950
10951   return 1;
10952 }
10953
10954 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10955
10956 static struct breakpoint_ops watchpoint_breakpoint_ops;
10957
10958 /* Implement the "insert" breakpoint_ops method for
10959    masked hardware watchpoints.  */
10960
10961 static int
10962 insert_masked_watchpoint (struct bp_location *bl)
10963 {
10964   struct watchpoint *w = (struct watchpoint *) bl->owner;
10965
10966   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10967                                         bl->watchpoint_type);
10968 }
10969
10970 /* Implement the "remove" breakpoint_ops method for
10971    masked hardware watchpoints.  */
10972
10973 static int
10974 remove_masked_watchpoint (struct bp_location *bl)
10975 {
10976   struct watchpoint *w = (struct watchpoint *) bl->owner;
10977
10978   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10979                                         bl->watchpoint_type);
10980 }
10981
10982 /* Implement the "resources_needed" breakpoint_ops method for
10983    masked hardware watchpoints.  */
10984
10985 static int
10986 resources_needed_masked_watchpoint (const struct bp_location *bl)
10987 {
10988   struct watchpoint *w = (struct watchpoint *) bl->owner;
10989
10990   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10991 }
10992
10993 /* Implement the "works_in_software_mode" breakpoint_ops method for
10994    masked hardware watchpoints.  */
10995
10996 static int
10997 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10998 {
10999   return 0;
11000 }
11001
11002 /* Implement the "print_it" breakpoint_ops method for
11003    masked hardware watchpoints.  */
11004
11005 static enum print_stop_action
11006 print_it_masked_watchpoint (bpstat bs)
11007 {
11008   struct breakpoint *b = bs->breakpoint_at;
11009   struct ui_out *uiout = current_uiout;
11010
11011   /* Masked watchpoints have only one location.  */
11012   gdb_assert (b->loc && b->loc->next == NULL);
11013
11014   switch (b->type)
11015     {
11016     case bp_hardware_watchpoint:
11017       annotate_watchpoint (b->number);
11018       if (ui_out_is_mi_like_p (uiout))
11019         ui_out_field_string
11020           (uiout, "reason",
11021            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11022       break;
11023
11024     case bp_read_watchpoint:
11025       if (ui_out_is_mi_like_p (uiout))
11026         ui_out_field_string
11027           (uiout, "reason",
11028            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11029       break;
11030
11031     case bp_access_watchpoint:
11032       if (ui_out_is_mi_like_p (uiout))
11033         ui_out_field_string
11034           (uiout, "reason",
11035            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11036       break;
11037     default:
11038       internal_error (__FILE__, __LINE__,
11039                       _("Invalid hardware watchpoint type."));
11040     }
11041
11042   mention (b);
11043   ui_out_text (uiout, _("\n\
11044 Check the underlying instruction at PC for the memory\n\
11045 address and value which triggered this watchpoint.\n"));
11046   ui_out_text (uiout, "\n");
11047
11048   /* More than one watchpoint may have been triggered.  */
11049   return PRINT_UNKNOWN;
11050 }
11051
11052 /* Implement the "print_one_detail" breakpoint_ops method for
11053    masked hardware watchpoints.  */
11054
11055 static void
11056 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11057                                     struct ui_out *uiout)
11058 {
11059   struct watchpoint *w = (struct watchpoint *) b;
11060
11061   /* Masked watchpoints have only one location.  */
11062   gdb_assert (b->loc && b->loc->next == NULL);
11063
11064   ui_out_text (uiout, "\tmask ");
11065   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11066   ui_out_text (uiout, "\n");
11067 }
11068
11069 /* Implement the "print_mention" breakpoint_ops method for
11070    masked hardware watchpoints.  */
11071
11072 static void
11073 print_mention_masked_watchpoint (struct breakpoint *b)
11074 {
11075   struct watchpoint *w = (struct watchpoint *) b;
11076   struct ui_out *uiout = current_uiout;
11077   struct cleanup *ui_out_chain;
11078
11079   switch (b->type)
11080     {
11081     case bp_hardware_watchpoint:
11082       ui_out_text (uiout, "Masked hardware watchpoint ");
11083       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11084       break;
11085     case bp_read_watchpoint:
11086       ui_out_text (uiout, "Masked hardware read watchpoint ");
11087       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11088       break;
11089     case bp_access_watchpoint:
11090       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11091       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11092       break;
11093     default:
11094       internal_error (__FILE__, __LINE__,
11095                       _("Invalid hardware watchpoint type."));
11096     }
11097
11098   ui_out_field_int (uiout, "number", b->number);
11099   ui_out_text (uiout, ": ");
11100   ui_out_field_string (uiout, "exp", w->exp_string);
11101   do_cleanups (ui_out_chain);
11102 }
11103
11104 /* Implement the "print_recreate" breakpoint_ops method for
11105    masked hardware watchpoints.  */
11106
11107 static void
11108 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11109 {
11110   struct watchpoint *w = (struct watchpoint *) b;
11111   char tmp[40];
11112
11113   switch (b->type)
11114     {
11115     case bp_hardware_watchpoint:
11116       fprintf_unfiltered (fp, "watch");
11117       break;
11118     case bp_read_watchpoint:
11119       fprintf_unfiltered (fp, "rwatch");
11120       break;
11121     case bp_access_watchpoint:
11122       fprintf_unfiltered (fp, "awatch");
11123       break;
11124     default:
11125       internal_error (__FILE__, __LINE__,
11126                       _("Invalid hardware watchpoint type."));
11127     }
11128
11129   sprintf_vma (tmp, w->hw_wp_mask);
11130   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11131   print_recreate_thread (b, fp);
11132 }
11133
11134 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11135
11136 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11137
11138 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11139
11140 static int
11141 is_masked_watchpoint (const struct breakpoint *b)
11142 {
11143   return b->ops == &masked_watchpoint_breakpoint_ops;
11144 }
11145
11146 /* accessflag:  hw_write:  watch write, 
11147                 hw_read:   watch read, 
11148                 hw_access: watch access (read or write) */
11149 static void
11150 watch_command_1 (const char *arg, int accessflag, int from_tty,
11151                  int just_location, int internal)
11152 {
11153   volatile struct gdb_exception e;
11154   struct breakpoint *b, *scope_breakpoint = NULL;
11155   struct expression *exp;
11156   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11157   struct value *val, *mark, *result;
11158   struct frame_info *frame;
11159   const char *exp_start = NULL;
11160   const char *exp_end = NULL;
11161   const char *tok, *end_tok;
11162   int toklen = -1;
11163   const char *cond_start = NULL;
11164   const char *cond_end = NULL;
11165   enum bptype bp_type;
11166   int thread = -1;
11167   int pc = 0;
11168   /* Flag to indicate whether we are going to use masks for
11169      the hardware watchpoint.  */
11170   int use_mask = 0;
11171   CORE_ADDR mask = 0;
11172   struct watchpoint *w;
11173   char *expression;
11174   struct cleanup *back_to;
11175
11176   /* Make sure that we actually have parameters to parse.  */
11177   if (arg != NULL && arg[0] != '\0')
11178     {
11179       const char *value_start;
11180
11181       exp_end = arg + strlen (arg);
11182
11183       /* Look for "parameter value" pairs at the end
11184          of the arguments string.  */
11185       for (tok = exp_end - 1; tok > arg; tok--)
11186         {
11187           /* Skip whitespace at the end of the argument list.  */
11188           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11189             tok--;
11190
11191           /* Find the beginning of the last token.
11192              This is the value of the parameter.  */
11193           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11194             tok--;
11195           value_start = tok + 1;
11196
11197           /* Skip whitespace.  */
11198           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11199             tok--;
11200
11201           end_tok = tok;
11202
11203           /* Find the beginning of the second to last token.
11204              This is the parameter itself.  */
11205           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11206             tok--;
11207           tok++;
11208           toklen = end_tok - tok + 1;
11209
11210           if (toklen == 6 && !strncmp (tok, "thread", 6))
11211             {
11212               /* At this point we've found a "thread" token, which means
11213                  the user is trying to set a watchpoint that triggers
11214                  only in a specific thread.  */
11215               char *endp;
11216
11217               if (thread != -1)
11218                 error(_("You can specify only one thread."));
11219
11220               /* Extract the thread ID from the next token.  */
11221               thread = strtol (value_start, &endp, 0);
11222
11223               /* Check if the user provided a valid numeric value for the
11224                  thread ID.  */
11225               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11226                 error (_("Invalid thread ID specification %s."), value_start);
11227
11228               /* Check if the thread actually exists.  */
11229               if (!valid_thread_id (thread))
11230                 invalid_thread_id_error (thread);
11231             }
11232           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11233             {
11234               /* We've found a "mask" token, which means the user wants to
11235                  create a hardware watchpoint that is going to have the mask
11236                  facility.  */
11237               struct value *mask_value, *mark;
11238
11239               if (use_mask)
11240                 error(_("You can specify only one mask."));
11241
11242               use_mask = just_location = 1;
11243
11244               mark = value_mark ();
11245               mask_value = parse_to_comma_and_eval (&value_start);
11246               mask = value_as_address (mask_value);
11247               value_free_to_mark (mark);
11248             }
11249           else
11250             /* We didn't recognize what we found.  We should stop here.  */
11251             break;
11252
11253           /* Truncate the string and get rid of the "parameter value" pair before
11254              the arguments string is parsed by the parse_exp_1 function.  */
11255           exp_end = tok;
11256         }
11257     }
11258   else
11259     exp_end = arg;
11260
11261   /* Parse the rest of the arguments.  From here on out, everything
11262      is in terms of a newly allocated string instead of the original
11263      ARG.  */
11264   innermost_block = NULL;
11265   expression = savestring (arg, exp_end - arg);
11266   back_to = make_cleanup (xfree, expression);
11267   exp_start = arg = expression;
11268   exp = parse_exp_1 (&arg, 0, 0, 0);
11269   exp_end = arg;
11270   /* Remove trailing whitespace from the expression before saving it.
11271      This makes the eventual display of the expression string a bit
11272      prettier.  */
11273   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11274     --exp_end;
11275
11276   /* Checking if the expression is not constant.  */
11277   if (watchpoint_exp_is_const (exp))
11278     {
11279       int len;
11280
11281       len = exp_end - exp_start;
11282       while (len > 0 && isspace (exp_start[len - 1]))
11283         len--;
11284       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11285     }
11286
11287   exp_valid_block = innermost_block;
11288   mark = value_mark ();
11289   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11290
11291   if (just_location)
11292     {
11293       int ret;
11294
11295       exp_valid_block = NULL;
11296       val = value_addr (result);
11297       release_value (val);
11298       value_free_to_mark (mark);
11299
11300       if (use_mask)
11301         {
11302           ret = target_masked_watch_num_registers (value_as_address (val),
11303                                                    mask);
11304           if (ret == -1)
11305             error (_("This target does not support masked watchpoints."));
11306           else if (ret == -2)
11307             error (_("Invalid mask or memory region."));
11308         }
11309     }
11310   else if (val != NULL)
11311     release_value (val);
11312
11313   tok = skip_spaces_const (arg);
11314   end_tok = skip_to_space_const (tok);
11315
11316   toklen = end_tok - tok;
11317   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11318     {
11319       struct expression *cond;
11320
11321       innermost_block = NULL;
11322       tok = cond_start = end_tok + 1;
11323       cond = parse_exp_1 (&tok, 0, 0, 0);
11324
11325       /* The watchpoint expression may not be local, but the condition
11326          may still be.  E.g.: `watch global if local > 0'.  */
11327       cond_exp_valid_block = innermost_block;
11328
11329       xfree (cond);
11330       cond_end = tok;
11331     }
11332   if (*tok)
11333     error (_("Junk at end of command."));
11334
11335   frame = block_innermost_frame (exp_valid_block);
11336
11337   /* If the expression is "local", then set up a "watchpoint scope"
11338      breakpoint at the point where we've left the scope of the watchpoint
11339      expression.  Create the scope breakpoint before the watchpoint, so
11340      that we will encounter it first in bpstat_stop_status.  */
11341   if (exp_valid_block && frame)
11342     {
11343       if (frame_id_p (frame_unwind_caller_id (frame)))
11344         {
11345           scope_breakpoint
11346             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11347                                           frame_unwind_caller_pc (frame),
11348                                           bp_watchpoint_scope,
11349                                           &momentary_breakpoint_ops);
11350
11351           scope_breakpoint->enable_state = bp_enabled;
11352
11353           /* Automatically delete the breakpoint when it hits.  */
11354           scope_breakpoint->disposition = disp_del;
11355
11356           /* Only break in the proper frame (help with recursion).  */
11357           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11358
11359           /* Set the address at which we will stop.  */
11360           scope_breakpoint->loc->gdbarch
11361             = frame_unwind_caller_arch (frame);
11362           scope_breakpoint->loc->requested_address
11363             = frame_unwind_caller_pc (frame);
11364           scope_breakpoint->loc->address
11365             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11366                                          scope_breakpoint->loc->requested_address,
11367                                          scope_breakpoint->type);
11368         }
11369     }
11370
11371   /* Now set up the breakpoint.  We create all watchpoints as hardware
11372      watchpoints here even if hardware watchpoints are turned off, a call
11373      to update_watchpoint later in this function will cause the type to
11374      drop back to bp_watchpoint (software watchpoint) if required.  */
11375
11376   if (accessflag == hw_read)
11377     bp_type = bp_read_watchpoint;
11378   else if (accessflag == hw_access)
11379     bp_type = bp_access_watchpoint;
11380   else
11381     bp_type = bp_hardware_watchpoint;
11382
11383   w = XCNEW (struct watchpoint);
11384   b = &w->base;
11385   if (use_mask)
11386     init_raw_breakpoint_without_location (b, NULL, bp_type,
11387                                           &masked_watchpoint_breakpoint_ops);
11388   else
11389     init_raw_breakpoint_without_location (b, NULL, bp_type,
11390                                           &watchpoint_breakpoint_ops);
11391   b->thread = thread;
11392   b->disposition = disp_donttouch;
11393   b->pspace = current_program_space;
11394   w->exp = exp;
11395   w->exp_valid_block = exp_valid_block;
11396   w->cond_exp_valid_block = cond_exp_valid_block;
11397   if (just_location)
11398     {
11399       struct type *t = value_type (val);
11400       CORE_ADDR addr = value_as_address (val);
11401       char *name;
11402
11403       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11404       name = type_to_string (t);
11405
11406       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11407                                           core_addr_to_string (addr));
11408       xfree (name);
11409
11410       w->exp_string = xstrprintf ("-location %.*s",
11411                                   (int) (exp_end - exp_start), exp_start);
11412
11413       /* The above expression is in C.  */
11414       b->language = language_c;
11415     }
11416   else
11417     w->exp_string = savestring (exp_start, exp_end - exp_start);
11418
11419   if (use_mask)
11420     {
11421       w->hw_wp_mask = mask;
11422     }
11423   else
11424     {
11425       w->val = val;
11426       w->val_valid = 1;
11427     }
11428
11429   if (cond_start)
11430     b->cond_string = savestring (cond_start, cond_end - cond_start);
11431   else
11432     b->cond_string = 0;
11433
11434   if (frame)
11435     {
11436       w->watchpoint_frame = get_frame_id (frame);
11437       w->watchpoint_thread = inferior_ptid;
11438     }
11439   else
11440     {
11441       w->watchpoint_frame = null_frame_id;
11442       w->watchpoint_thread = null_ptid;
11443     }
11444
11445   if (scope_breakpoint != NULL)
11446     {
11447       /* The scope breakpoint is related to the watchpoint.  We will
11448          need to act on them together.  */
11449       b->related_breakpoint = scope_breakpoint;
11450       scope_breakpoint->related_breakpoint = b;
11451     }
11452
11453   if (!just_location)
11454     value_free_to_mark (mark);
11455
11456   TRY_CATCH (e, RETURN_MASK_ALL)
11457     {
11458       /* Finally update the new watchpoint.  This creates the locations
11459          that should be inserted.  */
11460       update_watchpoint (w, 1);
11461     }
11462   if (e.reason < 0)
11463     {
11464       delete_breakpoint (b);
11465       throw_exception (e);
11466     }
11467
11468   install_breakpoint (internal, b, 1);
11469   do_cleanups (back_to);
11470 }
11471
11472 /* Return count of debug registers needed to watch the given expression.
11473    If the watchpoint cannot be handled in hardware return zero.  */
11474
11475 static int
11476 can_use_hardware_watchpoint (struct value *v)
11477 {
11478   int found_memory_cnt = 0;
11479   struct value *head = v;
11480
11481   /* Did the user specifically forbid us to use hardware watchpoints? */
11482   if (!can_use_hw_watchpoints)
11483     return 0;
11484
11485   /* Make sure that the value of the expression depends only upon
11486      memory contents, and values computed from them within GDB.  If we
11487      find any register references or function calls, we can't use a
11488      hardware watchpoint.
11489
11490      The idea here is that evaluating an expression generates a series
11491      of values, one holding the value of every subexpression.  (The
11492      expression a*b+c has five subexpressions: a, b, a*b, c, and
11493      a*b+c.)  GDB's values hold almost enough information to establish
11494      the criteria given above --- they identify memory lvalues,
11495      register lvalues, computed values, etcetera.  So we can evaluate
11496      the expression, and then scan the chain of values that leaves
11497      behind to decide whether we can detect any possible change to the
11498      expression's final value using only hardware watchpoints.
11499
11500      However, I don't think that the values returned by inferior
11501      function calls are special in any way.  So this function may not
11502      notice that an expression involving an inferior function call
11503      can't be watched with hardware watchpoints.  FIXME.  */
11504   for (; v; v = value_next (v))
11505     {
11506       if (VALUE_LVAL (v) == lval_memory)
11507         {
11508           if (v != head && value_lazy (v))
11509             /* A lazy memory lvalue in the chain is one that GDB never
11510                needed to fetch; we either just used its address (e.g.,
11511                `a' in `a.b') or we never needed it at all (e.g., `a'
11512                in `a,b').  This doesn't apply to HEAD; if that is
11513                lazy then it was not readable, but watch it anyway.  */
11514             ;
11515           else
11516             {
11517               /* Ahh, memory we actually used!  Check if we can cover
11518                  it with hardware watchpoints.  */
11519               struct type *vtype = check_typedef (value_type (v));
11520
11521               /* We only watch structs and arrays if user asked for it
11522                  explicitly, never if they just happen to appear in a
11523                  middle of some value chain.  */
11524               if (v == head
11525                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11526                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11527                 {
11528                   CORE_ADDR vaddr = value_address (v);
11529                   int len;
11530                   int num_regs;
11531
11532                   len = (target_exact_watchpoints
11533                          && is_scalar_type_recursive (vtype))?
11534                     1 : TYPE_LENGTH (value_type (v));
11535
11536                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11537                   if (!num_regs)
11538                     return 0;
11539                   else
11540                     found_memory_cnt += num_regs;
11541                 }
11542             }
11543         }
11544       else if (VALUE_LVAL (v) != not_lval
11545                && deprecated_value_modifiable (v) == 0)
11546         return 0;       /* These are values from the history (e.g., $1).  */
11547       else if (VALUE_LVAL (v) == lval_register)
11548         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11549     }
11550
11551   /* The expression itself looks suitable for using a hardware
11552      watchpoint, but give the target machine a chance to reject it.  */
11553   return found_memory_cnt;
11554 }
11555
11556 void
11557 watch_command_wrapper (char *arg, int from_tty, int internal)
11558 {
11559   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11560 }
11561
11562 /* A helper function that looks for the "-location" argument and then
11563    calls watch_command_1.  */
11564
11565 static void
11566 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11567 {
11568   int just_location = 0;
11569
11570   if (arg
11571       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11572           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11573     {
11574       arg = skip_spaces (arg);
11575       just_location = 1;
11576     }
11577
11578   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11579 }
11580
11581 static void
11582 watch_command (char *arg, int from_tty)
11583 {
11584   watch_maybe_just_location (arg, hw_write, from_tty);
11585 }
11586
11587 void
11588 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11589 {
11590   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11591 }
11592
11593 static void
11594 rwatch_command (char *arg, int from_tty)
11595 {
11596   watch_maybe_just_location (arg, hw_read, from_tty);
11597 }
11598
11599 void
11600 awatch_command_wrapper (char *arg, int from_tty, int internal)
11601 {
11602   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11603 }
11604
11605 static void
11606 awatch_command (char *arg, int from_tty)
11607 {
11608   watch_maybe_just_location (arg, hw_access, from_tty);
11609 }
11610 \f
11611
11612 /* Helper routines for the until_command routine in infcmd.c.  Here
11613    because it uses the mechanisms of breakpoints.  */
11614
11615 struct until_break_command_continuation_args
11616 {
11617   struct breakpoint *breakpoint;
11618   struct breakpoint *breakpoint2;
11619   int thread_num;
11620 };
11621
11622 /* This function is called by fetch_inferior_event via the
11623    cmd_continuation pointer, to complete the until command.  It takes
11624    care of cleaning up the temporary breakpoints set up by the until
11625    command.  */
11626 static void
11627 until_break_command_continuation (void *arg, int err)
11628 {
11629   struct until_break_command_continuation_args *a = arg;
11630
11631   delete_breakpoint (a->breakpoint);
11632   if (a->breakpoint2)
11633     delete_breakpoint (a->breakpoint2);
11634   delete_longjmp_breakpoint (a->thread_num);
11635 }
11636
11637 void
11638 until_break_command (char *arg, int from_tty, int anywhere)
11639 {
11640   struct symtabs_and_lines sals;
11641   struct symtab_and_line sal;
11642   struct frame_info *frame;
11643   struct gdbarch *frame_gdbarch;
11644   struct frame_id stack_frame_id;
11645   struct frame_id caller_frame_id;
11646   struct breakpoint *breakpoint;
11647   struct breakpoint *breakpoint2 = NULL;
11648   struct cleanup *old_chain;
11649   int thread;
11650   struct thread_info *tp;
11651
11652   clear_proceed_status ();
11653
11654   /* Set a breakpoint where the user wants it and at return from
11655      this function.  */
11656
11657   if (last_displayed_sal_is_valid ())
11658     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11659                           get_last_displayed_symtab (),
11660                           get_last_displayed_line ());
11661   else
11662     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11663                           (struct symtab *) NULL, 0);
11664
11665   if (sals.nelts != 1)
11666     error (_("Couldn't get information on specified line."));
11667
11668   sal = sals.sals[0];
11669   xfree (sals.sals);    /* malloc'd, so freed.  */
11670
11671   if (*arg)
11672     error (_("Junk at end of arguments."));
11673
11674   resolve_sal_pc (&sal);
11675
11676   tp = inferior_thread ();
11677   thread = tp->num;
11678
11679   old_chain = make_cleanup (null_cleanup, NULL);
11680
11681   /* Note linespec handling above invalidates the frame chain.
11682      Installing a breakpoint also invalidates the frame chain (as it
11683      may need to switch threads), so do any frame handling before
11684      that.  */
11685
11686   frame = get_selected_frame (NULL);
11687   frame_gdbarch = get_frame_arch (frame);
11688   stack_frame_id = get_stack_frame_id (frame);
11689   caller_frame_id = frame_unwind_caller_id (frame);
11690
11691   /* Keep within the current frame, or in frames called by the current
11692      one.  */
11693
11694   if (frame_id_p (caller_frame_id))
11695     {
11696       struct symtab_and_line sal2;
11697
11698       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11699       sal2.pc = frame_unwind_caller_pc (frame);
11700       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11701                                               sal2,
11702                                               caller_frame_id,
11703                                               bp_until);
11704       make_cleanup_delete_breakpoint (breakpoint2);
11705
11706       set_longjmp_breakpoint (tp, caller_frame_id);
11707       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11708     }
11709
11710   /* set_momentary_breakpoint could invalidate FRAME.  */
11711   frame = NULL;
11712
11713   if (anywhere)
11714     /* If the user told us to continue until a specified location,
11715        we don't specify a frame at which we need to stop.  */
11716     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11717                                            null_frame_id, bp_until);
11718   else
11719     /* Otherwise, specify the selected frame, because we want to stop
11720        only at the very same frame.  */
11721     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11722                                            stack_frame_id, bp_until);
11723   make_cleanup_delete_breakpoint (breakpoint);
11724
11725   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11726
11727   /* If we are running asynchronously, and proceed call above has
11728      actually managed to start the target, arrange for breakpoints to
11729      be deleted when the target stops.  Otherwise, we're already
11730      stopped and delete breakpoints via cleanup chain.  */
11731
11732   if (target_can_async_p () && is_running (inferior_ptid))
11733     {
11734       struct until_break_command_continuation_args *args;
11735       args = xmalloc (sizeof (*args));
11736
11737       args->breakpoint = breakpoint;
11738       args->breakpoint2 = breakpoint2;
11739       args->thread_num = thread;
11740
11741       discard_cleanups (old_chain);
11742       add_continuation (inferior_thread (),
11743                         until_break_command_continuation, args,
11744                         xfree);
11745     }
11746   else
11747     do_cleanups (old_chain);
11748 }
11749
11750 /* This function attempts to parse an optional "if <cond>" clause
11751    from the arg string.  If one is not found, it returns NULL.
11752
11753    Else, it returns a pointer to the condition string.  (It does not
11754    attempt to evaluate the string against a particular block.)  And,
11755    it updates arg to point to the first character following the parsed
11756    if clause in the arg string.  */
11757
11758 char *
11759 ep_parse_optional_if_clause (char **arg)
11760 {
11761   char *cond_string;
11762
11763   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11764     return NULL;
11765
11766   /* Skip the "if" keyword.  */
11767   (*arg) += 2;
11768
11769   /* Skip any extra leading whitespace, and record the start of the
11770      condition string.  */
11771   *arg = skip_spaces (*arg);
11772   cond_string = *arg;
11773
11774   /* Assume that the condition occupies the remainder of the arg
11775      string.  */
11776   (*arg) += strlen (cond_string);
11777
11778   return cond_string;
11779 }
11780
11781 /* Commands to deal with catching events, such as signals, exceptions,
11782    process start/exit, etc.  */
11783
11784 typedef enum
11785 {
11786   catch_fork_temporary, catch_vfork_temporary,
11787   catch_fork_permanent, catch_vfork_permanent
11788 }
11789 catch_fork_kind;
11790
11791 static void
11792 catch_fork_command_1 (char *arg, int from_tty, 
11793                       struct cmd_list_element *command)
11794 {
11795   struct gdbarch *gdbarch = get_current_arch ();
11796   char *cond_string = NULL;
11797   catch_fork_kind fork_kind;
11798   int tempflag;
11799
11800   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11801   tempflag = (fork_kind == catch_fork_temporary
11802               || fork_kind == catch_vfork_temporary);
11803
11804   if (!arg)
11805     arg = "";
11806   arg = skip_spaces (arg);
11807
11808   /* The allowed syntax is:
11809      catch [v]fork
11810      catch [v]fork if <cond>
11811
11812      First, check if there's an if clause.  */
11813   cond_string = ep_parse_optional_if_clause (&arg);
11814
11815   if ((*arg != '\0') && !isspace (*arg))
11816     error (_("Junk at end of arguments."));
11817
11818   /* If this target supports it, create a fork or vfork catchpoint
11819      and enable reporting of such events.  */
11820   switch (fork_kind)
11821     {
11822     case catch_fork_temporary:
11823     case catch_fork_permanent:
11824       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11825                                           &catch_fork_breakpoint_ops);
11826       break;
11827     case catch_vfork_temporary:
11828     case catch_vfork_permanent:
11829       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11830                                           &catch_vfork_breakpoint_ops);
11831       break;
11832     default:
11833       error (_("unsupported or unknown fork kind; cannot catch it"));
11834       break;
11835     }
11836 }
11837
11838 static void
11839 catch_exec_command_1 (char *arg, int from_tty, 
11840                       struct cmd_list_element *command)
11841 {
11842   struct exec_catchpoint *c;
11843   struct gdbarch *gdbarch = get_current_arch ();
11844   int tempflag;
11845   char *cond_string = NULL;
11846
11847   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11848
11849   if (!arg)
11850     arg = "";
11851   arg = skip_spaces (arg);
11852
11853   /* The allowed syntax is:
11854      catch exec
11855      catch exec if <cond>
11856
11857      First, check if there's an if clause.  */
11858   cond_string = ep_parse_optional_if_clause (&arg);
11859
11860   if ((*arg != '\0') && !isspace (*arg))
11861     error (_("Junk at end of arguments."));
11862
11863   c = XNEW (struct exec_catchpoint);
11864   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11865                    &catch_exec_breakpoint_ops);
11866   c->exec_pathname = NULL;
11867
11868   install_breakpoint (0, &c->base, 1);
11869 }
11870
11871 void
11872 init_ada_exception_breakpoint (struct breakpoint *b,
11873                                struct gdbarch *gdbarch,
11874                                struct symtab_and_line sal,
11875                                char *addr_string,
11876                                const struct breakpoint_ops *ops,
11877                                int tempflag,
11878                                int enabled,
11879                                int from_tty)
11880 {
11881   if (from_tty)
11882     {
11883       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11884       if (!loc_gdbarch)
11885         loc_gdbarch = gdbarch;
11886
11887       describe_other_breakpoints (loc_gdbarch,
11888                                   sal.pspace, sal.pc, sal.section, -1);
11889       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11890          version for exception catchpoints, because two catchpoints
11891          used for different exception names will use the same address.
11892          In this case, a "breakpoint ... also set at..." warning is
11893          unproductive.  Besides, the warning phrasing is also a bit
11894          inappropriate, we should use the word catchpoint, and tell
11895          the user what type of catchpoint it is.  The above is good
11896          enough for now, though.  */
11897     }
11898
11899   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11900
11901   b->enable_state = enabled ? bp_enabled : bp_disabled;
11902   b->disposition = tempflag ? disp_del : disp_donttouch;
11903   b->addr_string = addr_string;
11904   b->language = language_ada;
11905 }
11906
11907 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11908    filter list, or NULL if no filtering is required.  */
11909 static VEC(int) *
11910 catch_syscall_split_args (char *arg)
11911 {
11912   VEC(int) *result = NULL;
11913   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11914
11915   while (*arg != '\0')
11916     {
11917       int i, syscall_number;
11918       char *endptr;
11919       char cur_name[128];
11920       struct syscall s;
11921
11922       /* Skip whitespace.  */
11923       arg = skip_spaces (arg);
11924
11925       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11926         cur_name[i] = arg[i];
11927       cur_name[i] = '\0';
11928       arg += i;
11929
11930       /* Check if the user provided a syscall name or a number.  */
11931       syscall_number = (int) strtol (cur_name, &endptr, 0);
11932       if (*endptr == '\0')
11933         get_syscall_by_number (syscall_number, &s);
11934       else
11935         {
11936           /* We have a name.  Let's check if it's valid and convert it
11937              to a number.  */
11938           get_syscall_by_name (cur_name, &s);
11939
11940           if (s.number == UNKNOWN_SYSCALL)
11941             /* Here we have to issue an error instead of a warning,
11942                because GDB cannot do anything useful if there's no
11943                syscall number to be caught.  */
11944             error (_("Unknown syscall name '%s'."), cur_name);
11945         }
11946
11947       /* Ok, it's valid.  */
11948       VEC_safe_push (int, result, s.number);
11949     }
11950
11951   discard_cleanups (cleanup);
11952   return result;
11953 }
11954
11955 /* Implement the "catch syscall" command.  */
11956
11957 static void
11958 catch_syscall_command_1 (char *arg, int from_tty, 
11959                          struct cmd_list_element *command)
11960 {
11961   int tempflag;
11962   VEC(int) *filter;
11963   struct syscall s;
11964   struct gdbarch *gdbarch = get_current_arch ();
11965
11966   /* Checking if the feature if supported.  */
11967   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11968     error (_("The feature 'catch syscall' is not supported on \
11969 this architecture yet."));
11970
11971   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11972
11973   arg = skip_spaces (arg);
11974
11975   /* We need to do this first "dummy" translation in order
11976      to get the syscall XML file loaded or, most important,
11977      to display a warning to the user if there's no XML file
11978      for his/her architecture.  */
11979   get_syscall_by_number (0, &s);
11980
11981   /* The allowed syntax is:
11982      catch syscall
11983      catch syscall <name | number> [<name | number> ... <name | number>]
11984
11985      Let's check if there's a syscall name.  */
11986
11987   if (arg != NULL)
11988     filter = catch_syscall_split_args (arg);
11989   else
11990     filter = NULL;
11991
11992   create_syscall_event_catchpoint (tempflag, filter,
11993                                    &catch_syscall_breakpoint_ops);
11994 }
11995
11996 static void
11997 catch_command (char *arg, int from_tty)
11998 {
11999   error (_("Catch requires an event name."));
12000 }
12001 \f
12002
12003 static void
12004 tcatch_command (char *arg, int from_tty)
12005 {
12006   error (_("Catch requires an event name."));
12007 }
12008
12009 /* A qsort comparison function that sorts breakpoints in order.  */
12010
12011 static int
12012 compare_breakpoints (const void *a, const void *b)
12013 {
12014   const breakpoint_p *ba = a;
12015   uintptr_t ua = (uintptr_t) *ba;
12016   const breakpoint_p *bb = b;
12017   uintptr_t ub = (uintptr_t) *bb;
12018
12019   if ((*ba)->number < (*bb)->number)
12020     return -1;
12021   else if ((*ba)->number > (*bb)->number)
12022     return 1;
12023
12024   /* Now sort by address, in case we see, e..g, two breakpoints with
12025      the number 0.  */
12026   if (ua < ub)
12027     return -1;
12028   return ua > ub ? 1 : 0;
12029 }
12030
12031 /* Delete breakpoints by address or line.  */
12032
12033 static void
12034 clear_command (char *arg, int from_tty)
12035 {
12036   struct breakpoint *b, *prev;
12037   VEC(breakpoint_p) *found = 0;
12038   int ix;
12039   int default_match;
12040   struct symtabs_and_lines sals;
12041   struct symtab_and_line sal;
12042   int i;
12043   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12044
12045   if (arg)
12046     {
12047       sals = decode_line_with_current_source (arg,
12048                                               (DECODE_LINE_FUNFIRSTLINE
12049                                                | DECODE_LINE_LIST_MODE));
12050       make_cleanup (xfree, sals.sals);
12051       default_match = 0;
12052     }
12053   else
12054     {
12055       sals.sals = (struct symtab_and_line *)
12056         xmalloc (sizeof (struct symtab_and_line));
12057       make_cleanup (xfree, sals.sals);
12058       init_sal (&sal);          /* Initialize to zeroes.  */
12059
12060       /* Set sal's line, symtab, pc, and pspace to the values
12061          corresponding to the last call to print_frame_info.  If the
12062          codepoint is not valid, this will set all the fields to 0.  */
12063       get_last_displayed_sal (&sal);
12064       if (sal.symtab == 0)
12065         error (_("No source file specified."));
12066
12067       sals.sals[0] = sal;
12068       sals.nelts = 1;
12069
12070       default_match = 1;
12071     }
12072
12073   /* We don't call resolve_sal_pc here.  That's not as bad as it
12074      seems, because all existing breakpoints typically have both
12075      file/line and pc set.  So, if clear is given file/line, we can
12076      match this to existing breakpoint without obtaining pc at all.
12077
12078      We only support clearing given the address explicitly 
12079      present in breakpoint table.  Say, we've set breakpoint 
12080      at file:line.  There were several PC values for that file:line,
12081      due to optimization, all in one block.
12082
12083      We've picked one PC value.  If "clear" is issued with another
12084      PC corresponding to the same file:line, the breakpoint won't
12085      be cleared.  We probably can still clear the breakpoint, but 
12086      since the other PC value is never presented to user, user
12087      can only find it by guessing, and it does not seem important
12088      to support that.  */
12089
12090   /* For each line spec given, delete bps which correspond to it.  Do
12091      it in two passes, solely to preserve the current behavior that
12092      from_tty is forced true if we delete more than one
12093      breakpoint.  */
12094
12095   found = NULL;
12096   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12097   for (i = 0; i < sals.nelts; i++)
12098     {
12099       const char *sal_fullname;
12100
12101       /* If exact pc given, clear bpts at that pc.
12102          If line given (pc == 0), clear all bpts on specified line.
12103          If defaulting, clear all bpts on default line
12104          or at default pc.
12105
12106          defaulting    sal.pc != 0    tests to do
12107
12108          0              1             pc
12109          1              1             pc _and_ line
12110          0              0             line
12111          1              0             <can't happen> */
12112
12113       sal = sals.sals[i];
12114       sal_fullname = (sal.symtab == NULL
12115                       ? NULL : symtab_to_fullname (sal.symtab));
12116
12117       /* Find all matching breakpoints and add them to 'found'.  */
12118       ALL_BREAKPOINTS (b)
12119         {
12120           int match = 0;
12121           /* Are we going to delete b?  */
12122           if (b->type != bp_none && !is_watchpoint (b))
12123             {
12124               struct bp_location *loc = b->loc;
12125               for (; loc; loc = loc->next)
12126                 {
12127                   /* If the user specified file:line, don't allow a PC
12128                      match.  This matches historical gdb behavior.  */
12129                   int pc_match = (!sal.explicit_line
12130                                   && sal.pc
12131                                   && (loc->pspace == sal.pspace)
12132                                   && (loc->address == sal.pc)
12133                                   && (!section_is_overlay (loc->section)
12134                                       || loc->section == sal.section));
12135                   int line_match = 0;
12136
12137                   if ((default_match || sal.explicit_line)
12138                       && loc->symtab != NULL
12139                       && sal_fullname != NULL
12140                       && sal.pspace == loc->pspace
12141                       && loc->line_number == sal.line
12142                       && filename_cmp (symtab_to_fullname (loc->symtab),
12143                                        sal_fullname) == 0)
12144                     line_match = 1;
12145
12146                   if (pc_match || line_match)
12147                     {
12148                       match = 1;
12149                       break;
12150                     }
12151                 }
12152             }
12153
12154           if (match)
12155             VEC_safe_push(breakpoint_p, found, b);
12156         }
12157     }
12158
12159   /* Now go thru the 'found' chain and delete them.  */
12160   if (VEC_empty(breakpoint_p, found))
12161     {
12162       if (arg)
12163         error (_("No breakpoint at %s."), arg);
12164       else
12165         error (_("No breakpoint at this line."));
12166     }
12167
12168   /* Remove duplicates from the vec.  */
12169   qsort (VEC_address (breakpoint_p, found),
12170          VEC_length (breakpoint_p, found),
12171          sizeof (breakpoint_p),
12172          compare_breakpoints);
12173   prev = VEC_index (breakpoint_p, found, 0);
12174   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12175     {
12176       if (b == prev)
12177         {
12178           VEC_ordered_remove (breakpoint_p, found, ix);
12179           --ix;
12180         }
12181     }
12182
12183   if (VEC_length(breakpoint_p, found) > 1)
12184     from_tty = 1;       /* Always report if deleted more than one.  */
12185   if (from_tty)
12186     {
12187       if (VEC_length(breakpoint_p, found) == 1)
12188         printf_unfiltered (_("Deleted breakpoint "));
12189       else
12190         printf_unfiltered (_("Deleted breakpoints "));
12191     }
12192
12193   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12194     {
12195       if (from_tty)
12196         printf_unfiltered ("%d ", b->number);
12197       delete_breakpoint (b);
12198     }
12199   if (from_tty)
12200     putchar_unfiltered ('\n');
12201
12202   do_cleanups (cleanups);
12203 }
12204 \f
12205 /* Delete breakpoint in BS if they are `delete' breakpoints and
12206    all breakpoints that are marked for deletion, whether hit or not.
12207    This is called after any breakpoint is hit, or after errors.  */
12208
12209 void
12210 breakpoint_auto_delete (bpstat bs)
12211 {
12212   struct breakpoint *b, *b_tmp;
12213
12214   for (; bs; bs = bs->next)
12215     if (bs->breakpoint_at
12216         && bs->breakpoint_at->disposition == disp_del
12217         && bs->stop)
12218       delete_breakpoint (bs->breakpoint_at);
12219
12220   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12221   {
12222     if (b->disposition == disp_del_at_next_stop)
12223       delete_breakpoint (b);
12224   }
12225 }
12226
12227 /* A comparison function for bp_location AP and BP being interfaced to
12228    qsort.  Sort elements primarily by their ADDRESS (no matter what
12229    does breakpoint_address_is_meaningful say for its OWNER),
12230    secondarily by ordering first bp_permanent OWNERed elements and
12231    terciarily just ensuring the array is sorted stable way despite
12232    qsort being an unstable algorithm.  */
12233
12234 static int
12235 bp_location_compare (const void *ap, const void *bp)
12236 {
12237   struct bp_location *a = *(void **) ap;
12238   struct bp_location *b = *(void **) bp;
12239   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12240   int a_perm = a->owner->enable_state == bp_permanent;
12241   int b_perm = b->owner->enable_state == bp_permanent;
12242
12243   if (a->address != b->address)
12244     return (a->address > b->address) - (a->address < b->address);
12245
12246   /* Sort locations at the same address by their pspace number, keeping
12247      locations of the same inferior (in a multi-inferior environment)
12248      grouped.  */
12249
12250   if (a->pspace->num != b->pspace->num)
12251     return ((a->pspace->num > b->pspace->num)
12252             - (a->pspace->num < b->pspace->num));
12253
12254   /* Sort permanent breakpoints first.  */
12255   if (a_perm != b_perm)
12256     return (a_perm < b_perm) - (a_perm > b_perm);
12257
12258   /* Make the internal GDB representation stable across GDB runs
12259      where A and B memory inside GDB can differ.  Breakpoint locations of
12260      the same type at the same address can be sorted in arbitrary order.  */
12261
12262   if (a->owner->number != b->owner->number)
12263     return ((a->owner->number > b->owner->number)
12264             - (a->owner->number < b->owner->number));
12265
12266   return (a > b) - (a < b);
12267 }
12268
12269 /* Set bp_location_placed_address_before_address_max and
12270    bp_location_shadow_len_after_address_max according to the current
12271    content of the bp_location array.  */
12272
12273 static void
12274 bp_location_target_extensions_update (void)
12275 {
12276   struct bp_location *bl, **blp_tmp;
12277
12278   bp_location_placed_address_before_address_max = 0;
12279   bp_location_shadow_len_after_address_max = 0;
12280
12281   ALL_BP_LOCATIONS (bl, blp_tmp)
12282     {
12283       CORE_ADDR start, end, addr;
12284
12285       if (!bp_location_has_shadow (bl))
12286         continue;
12287
12288       start = bl->target_info.placed_address;
12289       end = start + bl->target_info.shadow_len;
12290
12291       gdb_assert (bl->address >= start);
12292       addr = bl->address - start;
12293       if (addr > bp_location_placed_address_before_address_max)
12294         bp_location_placed_address_before_address_max = addr;
12295
12296       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12297
12298       gdb_assert (bl->address < end);
12299       addr = end - bl->address;
12300       if (addr > bp_location_shadow_len_after_address_max)
12301         bp_location_shadow_len_after_address_max = addr;
12302     }
12303 }
12304
12305 /* Download tracepoint locations if they haven't been.  */
12306
12307 static void
12308 download_tracepoint_locations (void)
12309 {
12310   struct breakpoint *b;
12311   struct cleanup *old_chain;
12312
12313   if (!target_can_download_tracepoint ())
12314     return;
12315
12316   old_chain = save_current_space_and_thread ();
12317
12318   ALL_TRACEPOINTS (b)
12319     {
12320       struct bp_location *bl;
12321       struct tracepoint *t;
12322       int bp_location_downloaded = 0;
12323
12324       if ((b->type == bp_fast_tracepoint
12325            ? !may_insert_fast_tracepoints
12326            : !may_insert_tracepoints))
12327         continue;
12328
12329       for (bl = b->loc; bl; bl = bl->next)
12330         {
12331           /* In tracepoint, locations are _never_ duplicated, so
12332              should_be_inserted is equivalent to
12333              unduplicated_should_be_inserted.  */
12334           if (!should_be_inserted (bl) || bl->inserted)
12335             continue;
12336
12337           switch_to_program_space_and_thread (bl->pspace);
12338
12339           target_download_tracepoint (bl);
12340
12341           bl->inserted = 1;
12342           bp_location_downloaded = 1;
12343         }
12344       t = (struct tracepoint *) b;
12345       t->number_on_target = b->number;
12346       if (bp_location_downloaded)
12347         observer_notify_breakpoint_modified (b);
12348     }
12349
12350   do_cleanups (old_chain);
12351 }
12352
12353 /* Swap the insertion/duplication state between two locations.  */
12354
12355 static void
12356 swap_insertion (struct bp_location *left, struct bp_location *right)
12357 {
12358   const int left_inserted = left->inserted;
12359   const int left_duplicate = left->duplicate;
12360   const int left_needs_update = left->needs_update;
12361   const struct bp_target_info left_target_info = left->target_info;
12362
12363   /* Locations of tracepoints can never be duplicated.  */
12364   if (is_tracepoint (left->owner))
12365     gdb_assert (!left->duplicate);
12366   if (is_tracepoint (right->owner))
12367     gdb_assert (!right->duplicate);
12368
12369   left->inserted = right->inserted;
12370   left->duplicate = right->duplicate;
12371   left->needs_update = right->needs_update;
12372   left->target_info = right->target_info;
12373   right->inserted = left_inserted;
12374   right->duplicate = left_duplicate;
12375   right->needs_update = left_needs_update;
12376   right->target_info = left_target_info;
12377 }
12378
12379 /* Force the re-insertion of the locations at ADDRESS.  This is called
12380    once a new/deleted/modified duplicate location is found and we are evaluating
12381    conditions on the target's side.  Such conditions need to be updated on
12382    the target.  */
12383
12384 static void
12385 force_breakpoint_reinsertion (struct bp_location *bl)
12386 {
12387   struct bp_location **locp = NULL, **loc2p;
12388   struct bp_location *loc;
12389   CORE_ADDR address = 0;
12390   int pspace_num;
12391
12392   address = bl->address;
12393   pspace_num = bl->pspace->num;
12394
12395   /* This is only meaningful if the target is
12396      evaluating conditions and if the user has
12397      opted for condition evaluation on the target's
12398      side.  */
12399   if (gdb_evaluates_breakpoint_condition_p ()
12400       || !target_supports_evaluation_of_breakpoint_conditions ())
12401     return;
12402
12403   /* Flag all breakpoint locations with this address and
12404      the same program space as the location
12405      as "its condition has changed".  We need to
12406      update the conditions on the target's side.  */
12407   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12408     {
12409       loc = *loc2p;
12410
12411       if (!is_breakpoint (loc->owner)
12412           || pspace_num != loc->pspace->num)
12413         continue;
12414
12415       /* Flag the location appropriately.  We use a different state to
12416          let everyone know that we already updated the set of locations
12417          with addr bl->address and program space bl->pspace.  This is so
12418          we don't have to keep calling these functions just to mark locations
12419          that have already been marked.  */
12420       loc->condition_changed = condition_updated;
12421
12422       /* Free the agent expression bytecode as well.  We will compute
12423          it later on.  */
12424       if (loc->cond_bytecode)
12425         {
12426           free_agent_expr (loc->cond_bytecode);
12427           loc->cond_bytecode = NULL;
12428         }
12429     }
12430 }
12431
12432 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12433    into the inferior, only remove already-inserted locations that no
12434    longer should be inserted.  Functions that delete a breakpoint or
12435    breakpoints should pass false, so that deleting a breakpoint
12436    doesn't have the side effect of inserting the locations of other
12437    breakpoints that are marked not-inserted, but should_be_inserted
12438    returns true on them.
12439
12440    This behaviour is useful is situations close to tear-down -- e.g.,
12441    after an exec, while the target still has execution, but breakpoint
12442    shadows of the previous executable image should *NOT* be restored
12443    to the new image; or before detaching, where the target still has
12444    execution and wants to delete breakpoints from GDB's lists, and all
12445    breakpoints had already been removed from the inferior.  */
12446
12447 static void
12448 update_global_location_list (int should_insert)
12449 {
12450   struct breakpoint *b;
12451   struct bp_location **locp, *loc;
12452   struct cleanup *cleanups;
12453   /* Last breakpoint location address that was marked for update.  */
12454   CORE_ADDR last_addr = 0;
12455   /* Last breakpoint location program space that was marked for update.  */
12456   int last_pspace_num = -1;
12457
12458   /* Used in the duplicates detection below.  When iterating over all
12459      bp_locations, points to the first bp_location of a given address.
12460      Breakpoints and watchpoints of different types are never
12461      duplicates of each other.  Keep one pointer for each type of
12462      breakpoint/watchpoint, so we only need to loop over all locations
12463      once.  */
12464   struct bp_location *bp_loc_first;  /* breakpoint */
12465   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12466   struct bp_location *awp_loc_first; /* access watchpoint */
12467   struct bp_location *rwp_loc_first; /* read watchpoint */
12468
12469   /* Saved former bp_location array which we compare against the newly
12470      built bp_location from the current state of ALL_BREAKPOINTS.  */
12471   struct bp_location **old_location, **old_locp;
12472   unsigned old_location_count;
12473
12474   old_location = bp_location;
12475   old_location_count = bp_location_count;
12476   bp_location = NULL;
12477   bp_location_count = 0;
12478   cleanups = make_cleanup (xfree, old_location);
12479
12480   ALL_BREAKPOINTS (b)
12481     for (loc = b->loc; loc; loc = loc->next)
12482       bp_location_count++;
12483
12484   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12485   locp = bp_location;
12486   ALL_BREAKPOINTS (b)
12487     for (loc = b->loc; loc; loc = loc->next)
12488       *locp++ = loc;
12489   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12490          bp_location_compare);
12491
12492   bp_location_target_extensions_update ();
12493
12494   /* Identify bp_location instances that are no longer present in the
12495      new list, and therefore should be freed.  Note that it's not
12496      necessary that those locations should be removed from inferior --
12497      if there's another location at the same address (previously
12498      marked as duplicate), we don't need to remove/insert the
12499      location.
12500      
12501      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12502      and former bp_location array state respectively.  */
12503
12504   locp = bp_location;
12505   for (old_locp = old_location; old_locp < old_location + old_location_count;
12506        old_locp++)
12507     {
12508       struct bp_location *old_loc = *old_locp;
12509       struct bp_location **loc2p;
12510
12511       /* Tells if 'old_loc' is found among the new locations.  If
12512          not, we have to free it.  */
12513       int found_object = 0;
12514       /* Tells if the location should remain inserted in the target.  */
12515       int keep_in_target = 0;
12516       int removed = 0;
12517
12518       /* Skip LOCP entries which will definitely never be needed.
12519          Stop either at or being the one matching OLD_LOC.  */
12520       while (locp < bp_location + bp_location_count
12521              && (*locp)->address < old_loc->address)
12522         locp++;
12523
12524       for (loc2p = locp;
12525            (loc2p < bp_location + bp_location_count
12526             && (*loc2p)->address == old_loc->address);
12527            loc2p++)
12528         {
12529           /* Check if this is a new/duplicated location or a duplicated
12530              location that had its condition modified.  If so, we want to send
12531              its condition to the target if evaluation of conditions is taking
12532              place there.  */
12533           if ((*loc2p)->condition_changed == condition_modified
12534               && (last_addr != old_loc->address
12535                   || last_pspace_num != old_loc->pspace->num))
12536             {
12537               force_breakpoint_reinsertion (*loc2p);
12538               last_pspace_num = old_loc->pspace->num;
12539             }
12540
12541           if (*loc2p == old_loc)
12542             found_object = 1;
12543         }
12544
12545       /* We have already handled this address, update it so that we don't
12546          have to go through updates again.  */
12547       last_addr = old_loc->address;
12548
12549       /* Target-side condition evaluation: Handle deleted locations.  */
12550       if (!found_object)
12551         force_breakpoint_reinsertion (old_loc);
12552
12553       /* If this location is no longer present, and inserted, look if
12554          there's maybe a new location at the same address.  If so,
12555          mark that one inserted, and don't remove this one.  This is
12556          needed so that we don't have a time window where a breakpoint
12557          at certain location is not inserted.  */
12558
12559       if (old_loc->inserted)
12560         {
12561           /* If the location is inserted now, we might have to remove
12562              it.  */
12563
12564           if (found_object && should_be_inserted (old_loc))
12565             {
12566               /* The location is still present in the location list,
12567                  and still should be inserted.  Don't do anything.  */
12568               keep_in_target = 1;
12569             }
12570           else
12571             {
12572               /* This location still exists, but it won't be kept in the
12573                  target since it may have been disabled.  We proceed to
12574                  remove its target-side condition.  */
12575
12576               /* The location is either no longer present, or got
12577                  disabled.  See if there's another location at the
12578                  same address, in which case we don't need to remove
12579                  this one from the target.  */
12580
12581               /* OLD_LOC comes from existing struct breakpoint.  */
12582               if (breakpoint_address_is_meaningful (old_loc->owner))
12583                 {
12584                   for (loc2p = locp;
12585                        (loc2p < bp_location + bp_location_count
12586                         && (*loc2p)->address == old_loc->address);
12587                        loc2p++)
12588                     {
12589                       struct bp_location *loc2 = *loc2p;
12590
12591                       if (breakpoint_locations_match (loc2, old_loc))
12592                         {
12593                           /* Read watchpoint locations are switched to
12594                              access watchpoints, if the former are not
12595                              supported, but the latter are.  */
12596                           if (is_hardware_watchpoint (old_loc->owner))
12597                             {
12598                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12599                               loc2->watchpoint_type = old_loc->watchpoint_type;
12600                             }
12601
12602                           /* loc2 is a duplicated location. We need to check
12603                              if it should be inserted in case it will be
12604                              unduplicated.  */
12605                           if (loc2 != old_loc
12606                               && unduplicated_should_be_inserted (loc2))
12607                             {
12608                               swap_insertion (old_loc, loc2);
12609                               keep_in_target = 1;
12610                               break;
12611                             }
12612                         }
12613                     }
12614                 }
12615             }
12616
12617           if (!keep_in_target)
12618             {
12619               if (remove_breakpoint (old_loc, mark_uninserted))
12620                 {
12621                   /* This is just about all we can do.  We could keep
12622                      this location on the global list, and try to
12623                      remove it next time, but there's no particular
12624                      reason why we will succeed next time.
12625                      
12626                      Note that at this point, old_loc->owner is still
12627                      valid, as delete_breakpoint frees the breakpoint
12628                      only after calling us.  */
12629                   printf_filtered (_("warning: Error removing "
12630                                      "breakpoint %d\n"), 
12631                                    old_loc->owner->number);
12632                 }
12633               removed = 1;
12634             }
12635         }
12636
12637       if (!found_object)
12638         {
12639           if (removed && non_stop
12640               && breakpoint_address_is_meaningful (old_loc->owner)
12641               && !is_hardware_watchpoint (old_loc->owner))
12642             {
12643               /* This location was removed from the target.  In
12644                  non-stop mode, a race condition is possible where
12645                  we've removed a breakpoint, but stop events for that
12646                  breakpoint are already queued and will arrive later.
12647                  We apply an heuristic to be able to distinguish such
12648                  SIGTRAPs from other random SIGTRAPs: we keep this
12649                  breakpoint location for a bit, and will retire it
12650                  after we see some number of events.  The theory here
12651                  is that reporting of events should, "on the average",
12652                  be fair, so after a while we'll see events from all
12653                  threads that have anything of interest, and no longer
12654                  need to keep this breakpoint location around.  We
12655                  don't hold locations forever so to reduce chances of
12656                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12657                  SIGTRAP.
12658
12659                  The heuristic failing can be disastrous on
12660                  decr_pc_after_break targets.
12661
12662                  On decr_pc_after_break targets, like e.g., x86-linux,
12663                  if we fail to recognize a late breakpoint SIGTRAP,
12664                  because events_till_retirement has reached 0 too
12665                  soon, we'll fail to do the PC adjustment, and report
12666                  a random SIGTRAP to the user.  When the user resumes
12667                  the inferior, it will most likely immediately crash
12668                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12669                  corrupted, because of being resumed e.g., in the
12670                  middle of a multi-byte instruction, or skipped a
12671                  one-byte instruction.  This was actually seen happen
12672                  on native x86-linux, and should be less rare on
12673                  targets that do not support new thread events, like
12674                  remote, due to the heuristic depending on
12675                  thread_count.
12676
12677                  Mistaking a random SIGTRAP for a breakpoint trap
12678                  causes similar symptoms (PC adjustment applied when
12679                  it shouldn't), but then again, playing with SIGTRAPs
12680                  behind the debugger's back is asking for trouble.
12681
12682                  Since hardware watchpoint traps are always
12683                  distinguishable from other traps, so we don't need to
12684                  apply keep hardware watchpoint moribund locations
12685                  around.  We simply always ignore hardware watchpoint
12686                  traps we can no longer explain.  */
12687
12688               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12689               old_loc->owner = NULL;
12690
12691               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12692             }
12693           else
12694             {
12695               old_loc->owner = NULL;
12696               decref_bp_location (&old_loc);
12697             }
12698         }
12699     }
12700
12701   /* Rescan breakpoints at the same address and section, marking the
12702      first one as "first" and any others as "duplicates".  This is so
12703      that the bpt instruction is only inserted once.  If we have a
12704      permanent breakpoint at the same place as BPT, make that one the
12705      official one, and the rest as duplicates.  Permanent breakpoints
12706      are sorted first for the same address.
12707
12708      Do the same for hardware watchpoints, but also considering the
12709      watchpoint's type (regular/access/read) and length.  */
12710
12711   bp_loc_first = NULL;
12712   wp_loc_first = NULL;
12713   awp_loc_first = NULL;
12714   rwp_loc_first = NULL;
12715   ALL_BP_LOCATIONS (loc, locp)
12716     {
12717       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12718          non-NULL.  */
12719       struct bp_location **loc_first_p;
12720       b = loc->owner;
12721
12722       if (!unduplicated_should_be_inserted (loc)
12723           || !breakpoint_address_is_meaningful (b)
12724           /* Don't detect duplicate for tracepoint locations because they are
12725            never duplicated.  See the comments in field `duplicate' of
12726            `struct bp_location'.  */
12727           || is_tracepoint (b))
12728         {
12729           /* Clear the condition modification flag.  */
12730           loc->condition_changed = condition_unchanged;
12731           continue;
12732         }
12733
12734       /* Permanent breakpoint should always be inserted.  */
12735       if (b->enable_state == bp_permanent && ! loc->inserted)
12736         internal_error (__FILE__, __LINE__,
12737                         _("allegedly permanent breakpoint is not "
12738                         "actually inserted"));
12739
12740       if (b->type == bp_hardware_watchpoint)
12741         loc_first_p = &wp_loc_first;
12742       else if (b->type == bp_read_watchpoint)
12743         loc_first_p = &rwp_loc_first;
12744       else if (b->type == bp_access_watchpoint)
12745         loc_first_p = &awp_loc_first;
12746       else
12747         loc_first_p = &bp_loc_first;
12748
12749       if (*loc_first_p == NULL
12750           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12751           || !breakpoint_locations_match (loc, *loc_first_p))
12752         {
12753           *loc_first_p = loc;
12754           loc->duplicate = 0;
12755
12756           if (is_breakpoint (loc->owner) && loc->condition_changed)
12757             {
12758               loc->needs_update = 1;
12759               /* Clear the condition modification flag.  */
12760               loc->condition_changed = condition_unchanged;
12761             }
12762           continue;
12763         }
12764
12765
12766       /* This and the above ensure the invariant that the first location
12767          is not duplicated, and is the inserted one.
12768          All following are marked as duplicated, and are not inserted.  */
12769       if (loc->inserted)
12770         swap_insertion (loc, *loc_first_p);
12771       loc->duplicate = 1;
12772
12773       /* Clear the condition modification flag.  */
12774       loc->condition_changed = condition_unchanged;
12775
12776       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12777           && b->enable_state != bp_permanent)
12778         internal_error (__FILE__, __LINE__,
12779                         _("another breakpoint was inserted on top of "
12780                         "a permanent breakpoint"));
12781     }
12782
12783   if (breakpoints_always_inserted_mode ()
12784       && (have_live_inferiors ()
12785           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12786     {
12787       if (should_insert)
12788         insert_breakpoint_locations ();
12789       else
12790         {
12791           /* Though should_insert is false, we may need to update conditions
12792              on the target's side if it is evaluating such conditions.  We
12793              only update conditions for locations that are marked
12794              "needs_update".  */
12795           update_inserted_breakpoint_locations ();
12796         }
12797     }
12798
12799   if (should_insert)
12800     download_tracepoint_locations ();
12801
12802   do_cleanups (cleanups);
12803 }
12804
12805 void
12806 breakpoint_retire_moribund (void)
12807 {
12808   struct bp_location *loc;
12809   int ix;
12810
12811   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12812     if (--(loc->events_till_retirement) == 0)
12813       {
12814         decref_bp_location (&loc);
12815         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12816         --ix;
12817       }
12818 }
12819
12820 static void
12821 update_global_location_list_nothrow (int inserting)
12822 {
12823   volatile struct gdb_exception e;
12824
12825   TRY_CATCH (e, RETURN_MASK_ERROR)
12826     update_global_location_list (inserting);
12827 }
12828
12829 /* Clear BKP from a BPS.  */
12830
12831 static void
12832 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12833 {
12834   bpstat bs;
12835
12836   for (bs = bps; bs; bs = bs->next)
12837     if (bs->breakpoint_at == bpt)
12838       {
12839         bs->breakpoint_at = NULL;
12840         bs->old_val = NULL;
12841         /* bs->commands will be freed later.  */
12842       }
12843 }
12844
12845 /* Callback for iterate_over_threads.  */
12846 static int
12847 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12848 {
12849   struct breakpoint *bpt = data;
12850
12851   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12852   return 0;
12853 }
12854
12855 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12856    callbacks.  */
12857
12858 static void
12859 say_where (struct breakpoint *b)
12860 {
12861   struct value_print_options opts;
12862
12863   get_user_print_options (&opts);
12864
12865   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12866      single string.  */
12867   if (b->loc == NULL)
12868     {
12869       printf_filtered (_(" (%s) pending."), b->addr_string);
12870     }
12871   else
12872     {
12873       if (opts.addressprint || b->loc->symtab == NULL)
12874         {
12875           printf_filtered (" at ");
12876           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12877                           gdb_stdout);
12878         }
12879       if (b->loc->symtab != NULL)
12880         {
12881           /* If there is a single location, we can print the location
12882              more nicely.  */
12883           if (b->loc->next == NULL)
12884             printf_filtered (": file %s, line %d.",
12885                              symtab_to_filename_for_display (b->loc->symtab),
12886                              b->loc->line_number);
12887           else
12888             /* This is not ideal, but each location may have a
12889                different file name, and this at least reflects the
12890                real situation somewhat.  */
12891             printf_filtered (": %s.", b->addr_string);
12892         }
12893
12894       if (b->loc->next)
12895         {
12896           struct bp_location *loc = b->loc;
12897           int n = 0;
12898           for (; loc; loc = loc->next)
12899             ++n;
12900           printf_filtered (" (%d locations)", n);
12901         }
12902     }
12903 }
12904
12905 /* Default bp_location_ops methods.  */
12906
12907 static void
12908 bp_location_dtor (struct bp_location *self)
12909 {
12910   xfree (self->cond);
12911   if (self->cond_bytecode)
12912     free_agent_expr (self->cond_bytecode);
12913   xfree (self->function_name);
12914
12915   VEC_free (agent_expr_p, self->target_info.conditions);
12916   VEC_free (agent_expr_p, self->target_info.tcommands);
12917 }
12918
12919 static const struct bp_location_ops bp_location_ops =
12920 {
12921   bp_location_dtor
12922 };
12923
12924 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12925    inherit from.  */
12926
12927 static void
12928 base_breakpoint_dtor (struct breakpoint *self)
12929 {
12930   decref_counted_command_line (&self->commands);
12931   xfree (self->cond_string);
12932   xfree (self->extra_string);
12933   xfree (self->addr_string);
12934   xfree (self->filter);
12935   xfree (self->addr_string_range_end);
12936 }
12937
12938 static struct bp_location *
12939 base_breakpoint_allocate_location (struct breakpoint *self)
12940 {
12941   struct bp_location *loc;
12942
12943   loc = XNEW (struct bp_location);
12944   init_bp_location (loc, &bp_location_ops, self);
12945   return loc;
12946 }
12947
12948 static void
12949 base_breakpoint_re_set (struct breakpoint *b)
12950 {
12951   /* Nothing to re-set. */
12952 }
12953
12954 #define internal_error_pure_virtual_called() \
12955   gdb_assert_not_reached ("pure virtual function called")
12956
12957 static int
12958 base_breakpoint_insert_location (struct bp_location *bl)
12959 {
12960   internal_error_pure_virtual_called ();
12961 }
12962
12963 static int
12964 base_breakpoint_remove_location (struct bp_location *bl)
12965 {
12966   internal_error_pure_virtual_called ();
12967 }
12968
12969 static int
12970 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12971                                 struct address_space *aspace,
12972                                 CORE_ADDR bp_addr,
12973                                 const struct target_waitstatus *ws)
12974 {
12975   internal_error_pure_virtual_called ();
12976 }
12977
12978 static void
12979 base_breakpoint_check_status (bpstat bs)
12980 {
12981   /* Always stop.   */
12982 }
12983
12984 /* A "works_in_software_mode" breakpoint_ops method that just internal
12985    errors.  */
12986
12987 static int
12988 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12989 {
12990   internal_error_pure_virtual_called ();
12991 }
12992
12993 /* A "resources_needed" breakpoint_ops method that just internal
12994    errors.  */
12995
12996 static int
12997 base_breakpoint_resources_needed (const struct bp_location *bl)
12998 {
12999   internal_error_pure_virtual_called ();
13000 }
13001
13002 static enum print_stop_action
13003 base_breakpoint_print_it (bpstat bs)
13004 {
13005   internal_error_pure_virtual_called ();
13006 }
13007
13008 static void
13009 base_breakpoint_print_one_detail (const struct breakpoint *self,
13010                                   struct ui_out *uiout)
13011 {
13012   /* nothing */
13013 }
13014
13015 static void
13016 base_breakpoint_print_mention (struct breakpoint *b)
13017 {
13018   internal_error_pure_virtual_called ();
13019 }
13020
13021 static void
13022 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13023 {
13024   internal_error_pure_virtual_called ();
13025 }
13026
13027 static void
13028 base_breakpoint_create_sals_from_address (char **arg,
13029                                           struct linespec_result *canonical,
13030                                           enum bptype type_wanted,
13031                                           char *addr_start,
13032                                           char **copy_arg)
13033 {
13034   internal_error_pure_virtual_called ();
13035 }
13036
13037 static void
13038 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13039                                         struct linespec_result *c,
13040                                         char *cond_string,
13041                                         char *extra_string,
13042                                         enum bptype type_wanted,
13043                                         enum bpdisp disposition,
13044                                         int thread,
13045                                         int task, int ignore_count,
13046                                         const struct breakpoint_ops *o,
13047                                         int from_tty, int enabled,
13048                                         int internal, unsigned flags)
13049 {
13050   internal_error_pure_virtual_called ();
13051 }
13052
13053 static void
13054 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13055                                  struct symtabs_and_lines *sals)
13056 {
13057   internal_error_pure_virtual_called ();
13058 }
13059
13060 /* The default 'explains_signal' method.  */
13061
13062 static int
13063 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13064 {
13065   return 1;
13066 }
13067
13068 /* The default "after_condition_true" method.  */
13069
13070 static void
13071 base_breakpoint_after_condition_true (struct bpstats *bs)
13072 {
13073   /* Nothing to do.   */
13074 }
13075
13076 struct breakpoint_ops base_breakpoint_ops =
13077 {
13078   base_breakpoint_dtor,
13079   base_breakpoint_allocate_location,
13080   base_breakpoint_re_set,
13081   base_breakpoint_insert_location,
13082   base_breakpoint_remove_location,
13083   base_breakpoint_breakpoint_hit,
13084   base_breakpoint_check_status,
13085   base_breakpoint_resources_needed,
13086   base_breakpoint_works_in_software_mode,
13087   base_breakpoint_print_it,
13088   NULL,
13089   base_breakpoint_print_one_detail,
13090   base_breakpoint_print_mention,
13091   base_breakpoint_print_recreate,
13092   base_breakpoint_create_sals_from_address,
13093   base_breakpoint_create_breakpoints_sal,
13094   base_breakpoint_decode_linespec,
13095   base_breakpoint_explains_signal,
13096   base_breakpoint_after_condition_true,
13097 };
13098
13099 /* Default breakpoint_ops methods.  */
13100
13101 static void
13102 bkpt_re_set (struct breakpoint *b)
13103 {
13104   /* FIXME: is this still reachable?  */
13105   if (b->addr_string == NULL)
13106     {
13107       /* Anything without a string can't be re-set.  */
13108       delete_breakpoint (b);
13109       return;
13110     }
13111
13112   breakpoint_re_set_default (b);
13113 }
13114
13115 static int
13116 bkpt_insert_location (struct bp_location *bl)
13117 {
13118   if (bl->loc_type == bp_loc_hardware_breakpoint)
13119     return target_insert_hw_breakpoint (bl->gdbarch,
13120                                         &bl->target_info);
13121   else
13122     return target_insert_breakpoint (bl->gdbarch,
13123                                      &bl->target_info);
13124 }
13125
13126 static int
13127 bkpt_remove_location (struct bp_location *bl)
13128 {
13129   if (bl->loc_type == bp_loc_hardware_breakpoint)
13130     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13131   else
13132     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13133 }
13134
13135 static int
13136 bkpt_breakpoint_hit (const struct bp_location *bl,
13137                      struct address_space *aspace, CORE_ADDR bp_addr,
13138                      const struct target_waitstatus *ws)
13139 {
13140   if (ws->kind != TARGET_WAITKIND_STOPPED
13141       || ws->value.sig != GDB_SIGNAL_TRAP)
13142     return 0;
13143
13144   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13145                                  aspace, bp_addr))
13146     return 0;
13147
13148   if (overlay_debugging         /* unmapped overlay section */
13149       && section_is_overlay (bl->section)
13150       && !section_is_mapped (bl->section))
13151     return 0;
13152
13153   return 1;
13154 }
13155
13156 static int
13157 dprintf_breakpoint_hit (const struct bp_location *bl,
13158                         struct address_space *aspace, CORE_ADDR bp_addr,
13159                         const struct target_waitstatus *ws)
13160 {
13161   if (dprintf_style == dprintf_style_agent
13162       && target_can_run_breakpoint_commands ())
13163     {
13164       /* An agent-style dprintf never causes a stop.  If we see a trap
13165          for this address it must be for a breakpoint that happens to
13166          be set at the same address.  */
13167       return 0;
13168     }
13169
13170   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13171 }
13172
13173 static int
13174 bkpt_resources_needed (const struct bp_location *bl)
13175 {
13176   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13177
13178   return 1;
13179 }
13180
13181 static enum print_stop_action
13182 bkpt_print_it (bpstat bs)
13183 {
13184   struct breakpoint *b;
13185   const struct bp_location *bl;
13186   int bp_temp;
13187   struct ui_out *uiout = current_uiout;
13188
13189   gdb_assert (bs->bp_location_at != NULL);
13190
13191   bl = bs->bp_location_at;
13192   b = bs->breakpoint_at;
13193
13194   bp_temp = b->disposition == disp_del;
13195   if (bl->address != bl->requested_address)
13196     breakpoint_adjustment_warning (bl->requested_address,
13197                                    bl->address,
13198                                    b->number, 1);
13199   annotate_breakpoint (b->number);
13200   if (bp_temp)
13201     ui_out_text (uiout, "\nTemporary breakpoint ");
13202   else
13203     ui_out_text (uiout, "\nBreakpoint ");
13204   if (ui_out_is_mi_like_p (uiout))
13205     {
13206       ui_out_field_string (uiout, "reason",
13207                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13208       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13209     }
13210   ui_out_field_int (uiout, "bkptno", b->number);
13211   ui_out_text (uiout, ", ");
13212
13213   return PRINT_SRC_AND_LOC;
13214 }
13215
13216 static void
13217 bkpt_print_mention (struct breakpoint *b)
13218 {
13219   if (ui_out_is_mi_like_p (current_uiout))
13220     return;
13221
13222   switch (b->type)
13223     {
13224     case bp_breakpoint:
13225     case bp_gnu_ifunc_resolver:
13226       if (b->disposition == disp_del)
13227         printf_filtered (_("Temporary breakpoint"));
13228       else
13229         printf_filtered (_("Breakpoint"));
13230       printf_filtered (_(" %d"), b->number);
13231       if (b->type == bp_gnu_ifunc_resolver)
13232         printf_filtered (_(" at gnu-indirect-function resolver"));
13233       break;
13234     case bp_hardware_breakpoint:
13235       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13236       break;
13237     case bp_dprintf:
13238       printf_filtered (_("Dprintf %d"), b->number);
13239       break;
13240     }
13241
13242   say_where (b);
13243 }
13244
13245 static void
13246 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13247 {
13248   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13249     fprintf_unfiltered (fp, "tbreak");
13250   else if (tp->type == bp_breakpoint)
13251     fprintf_unfiltered (fp, "break");
13252   else if (tp->type == bp_hardware_breakpoint
13253            && tp->disposition == disp_del)
13254     fprintf_unfiltered (fp, "thbreak");
13255   else if (tp->type == bp_hardware_breakpoint)
13256     fprintf_unfiltered (fp, "hbreak");
13257   else
13258     internal_error (__FILE__, __LINE__,
13259                     _("unhandled breakpoint type %d"), (int) tp->type);
13260
13261   fprintf_unfiltered (fp, " %s", tp->addr_string);
13262   print_recreate_thread (tp, fp);
13263 }
13264
13265 static void
13266 bkpt_create_sals_from_address (char **arg,
13267                                struct linespec_result *canonical,
13268                                enum bptype type_wanted,
13269                                char *addr_start, char **copy_arg)
13270 {
13271   create_sals_from_address_default (arg, canonical, type_wanted,
13272                                     addr_start, copy_arg);
13273 }
13274
13275 static void
13276 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13277                              struct linespec_result *canonical,
13278                              char *cond_string,
13279                              char *extra_string,
13280                              enum bptype type_wanted,
13281                              enum bpdisp disposition,
13282                              int thread,
13283                              int task, int ignore_count,
13284                              const struct breakpoint_ops *ops,
13285                              int from_tty, int enabled,
13286                              int internal, unsigned flags)
13287 {
13288   create_breakpoints_sal_default (gdbarch, canonical,
13289                                   cond_string, extra_string,
13290                                   type_wanted,
13291                                   disposition, thread, task,
13292                                   ignore_count, ops, from_tty,
13293                                   enabled, internal, flags);
13294 }
13295
13296 static void
13297 bkpt_decode_linespec (struct breakpoint *b, char **s,
13298                       struct symtabs_and_lines *sals)
13299 {
13300   decode_linespec_default (b, s, sals);
13301 }
13302
13303 /* Virtual table for internal breakpoints.  */
13304
13305 static void
13306 internal_bkpt_re_set (struct breakpoint *b)
13307 {
13308   switch (b->type)
13309     {
13310       /* Delete overlay event and longjmp master breakpoints; they
13311          will be reset later by breakpoint_re_set.  */
13312     case bp_overlay_event:
13313     case bp_longjmp_master:
13314     case bp_std_terminate_master:
13315     case bp_exception_master:
13316       delete_breakpoint (b);
13317       break;
13318
13319       /* This breakpoint is special, it's set up when the inferior
13320          starts and we really don't want to touch it.  */
13321     case bp_shlib_event:
13322
13323       /* Like bp_shlib_event, this breakpoint type is special.  Once
13324          it is set up, we do not want to touch it.  */
13325     case bp_thread_event:
13326       break;
13327     }
13328 }
13329
13330 static void
13331 internal_bkpt_check_status (bpstat bs)
13332 {
13333   if (bs->breakpoint_at->type == bp_shlib_event)
13334     {
13335       /* If requested, stop when the dynamic linker notifies GDB of
13336          events.  This allows the user to get control and place
13337          breakpoints in initializer routines for dynamically loaded
13338          objects (among other things).  */
13339       bs->stop = stop_on_solib_events;
13340       bs->print = stop_on_solib_events;
13341     }
13342   else
13343     bs->stop = 0;
13344 }
13345
13346 static enum print_stop_action
13347 internal_bkpt_print_it (bpstat bs)
13348 {
13349   struct breakpoint *b;
13350
13351   b = bs->breakpoint_at;
13352
13353   switch (b->type)
13354     {
13355     case bp_shlib_event:
13356       /* Did we stop because the user set the stop_on_solib_events
13357          variable?  (If so, we report this as a generic, "Stopped due
13358          to shlib event" message.) */
13359       print_solib_event (0);
13360       break;
13361
13362     case bp_thread_event:
13363       /* Not sure how we will get here.
13364          GDB should not stop for these breakpoints.  */
13365       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13366       break;
13367
13368     case bp_overlay_event:
13369       /* By analogy with the thread event, GDB should not stop for these.  */
13370       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13371       break;
13372
13373     case bp_longjmp_master:
13374       /* These should never be enabled.  */
13375       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13376       break;
13377
13378     case bp_std_terminate_master:
13379       /* These should never be enabled.  */
13380       printf_filtered (_("std::terminate Master Breakpoint: "
13381                          "gdb should not stop!\n"));
13382       break;
13383
13384     case bp_exception_master:
13385       /* These should never be enabled.  */
13386       printf_filtered (_("Exception Master Breakpoint: "
13387                          "gdb should not stop!\n"));
13388       break;
13389     }
13390
13391   return PRINT_NOTHING;
13392 }
13393
13394 static void
13395 internal_bkpt_print_mention (struct breakpoint *b)
13396 {
13397   /* Nothing to mention.  These breakpoints are internal.  */
13398 }
13399
13400 /* Virtual table for momentary breakpoints  */
13401
13402 static void
13403 momentary_bkpt_re_set (struct breakpoint *b)
13404 {
13405   /* Keep temporary breakpoints, which can be encountered when we step
13406      over a dlopen call and solib_add is resetting the breakpoints.
13407      Otherwise these should have been blown away via the cleanup chain
13408      or by breakpoint_init_inferior when we rerun the executable.  */
13409 }
13410
13411 static void
13412 momentary_bkpt_check_status (bpstat bs)
13413 {
13414   /* Nothing.  The point of these breakpoints is causing a stop.  */
13415 }
13416
13417 static enum print_stop_action
13418 momentary_bkpt_print_it (bpstat bs)
13419 {
13420   struct ui_out *uiout = current_uiout;
13421
13422   if (ui_out_is_mi_like_p (uiout))
13423     {
13424       struct breakpoint *b = bs->breakpoint_at;
13425
13426       switch (b->type)
13427         {
13428         case bp_finish:
13429           ui_out_field_string
13430             (uiout, "reason",
13431              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13432           break;
13433
13434         case bp_until:
13435           ui_out_field_string
13436             (uiout, "reason",
13437              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13438           break;
13439         }
13440     }
13441
13442   return PRINT_UNKNOWN;
13443 }
13444
13445 static void
13446 momentary_bkpt_print_mention (struct breakpoint *b)
13447 {
13448   /* Nothing to mention.  These breakpoints are internal.  */
13449 }
13450
13451 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13452
13453    It gets cleared already on the removal of the first one of such placed
13454    breakpoints.  This is OK as they get all removed altogether.  */
13455
13456 static void
13457 longjmp_bkpt_dtor (struct breakpoint *self)
13458 {
13459   struct thread_info *tp = find_thread_id (self->thread);
13460
13461   if (tp)
13462     tp->initiating_frame = null_frame_id;
13463
13464   momentary_breakpoint_ops.dtor (self);
13465 }
13466
13467 /* Specific methods for probe breakpoints.  */
13468
13469 static int
13470 bkpt_probe_insert_location (struct bp_location *bl)
13471 {
13472   int v = bkpt_insert_location (bl);
13473
13474   if (v == 0)
13475     {
13476       /* The insertion was successful, now let's set the probe's semaphore
13477          if needed.  */
13478       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13479                                             bl->probe.objfile,
13480                                             bl->gdbarch);
13481     }
13482
13483   return v;
13484 }
13485
13486 static int
13487 bkpt_probe_remove_location (struct bp_location *bl)
13488 {
13489   /* Let's clear the semaphore before removing the location.  */
13490   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13491                                           bl->probe.objfile,
13492                                           bl->gdbarch);
13493
13494   return bkpt_remove_location (bl);
13495 }
13496
13497 static void
13498 bkpt_probe_create_sals_from_address (char **arg,
13499                                      struct linespec_result *canonical,
13500                                      enum bptype type_wanted,
13501                                      char *addr_start, char **copy_arg)
13502 {
13503   struct linespec_sals lsal;
13504
13505   lsal.sals = parse_probes (arg, canonical);
13506
13507   *copy_arg = xstrdup (canonical->addr_string);
13508   lsal.canonical = xstrdup (*copy_arg);
13509
13510   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13511 }
13512
13513 static void
13514 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13515                             struct symtabs_and_lines *sals)
13516 {
13517   *sals = parse_probes (s, NULL);
13518   if (!sals->sals)
13519     error (_("probe not found"));
13520 }
13521
13522 /* The breakpoint_ops structure to be used in tracepoints.  */
13523
13524 static void
13525 tracepoint_re_set (struct breakpoint *b)
13526 {
13527   breakpoint_re_set_default (b);
13528 }
13529
13530 static int
13531 tracepoint_breakpoint_hit (const struct bp_location *bl,
13532                            struct address_space *aspace, CORE_ADDR bp_addr,
13533                            const struct target_waitstatus *ws)
13534 {
13535   /* By definition, the inferior does not report stops at
13536      tracepoints.  */
13537   return 0;
13538 }
13539
13540 static void
13541 tracepoint_print_one_detail (const struct breakpoint *self,
13542                              struct ui_out *uiout)
13543 {
13544   struct tracepoint *tp = (struct tracepoint *) self;
13545   if (tp->static_trace_marker_id)
13546     {
13547       gdb_assert (self->type == bp_static_tracepoint);
13548
13549       ui_out_text (uiout, "\tmarker id is ");
13550       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13551                            tp->static_trace_marker_id);
13552       ui_out_text (uiout, "\n");
13553     }
13554 }
13555
13556 static void
13557 tracepoint_print_mention (struct breakpoint *b)
13558 {
13559   if (ui_out_is_mi_like_p (current_uiout))
13560     return;
13561
13562   switch (b->type)
13563     {
13564     case bp_tracepoint:
13565       printf_filtered (_("Tracepoint"));
13566       printf_filtered (_(" %d"), b->number);
13567       break;
13568     case bp_fast_tracepoint:
13569       printf_filtered (_("Fast tracepoint"));
13570       printf_filtered (_(" %d"), b->number);
13571       break;
13572     case bp_static_tracepoint:
13573       printf_filtered (_("Static tracepoint"));
13574       printf_filtered (_(" %d"), b->number);
13575       break;
13576     default:
13577       internal_error (__FILE__, __LINE__,
13578                       _("unhandled tracepoint type %d"), (int) b->type);
13579     }
13580
13581   say_where (b);
13582 }
13583
13584 static void
13585 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13586 {
13587   struct tracepoint *tp = (struct tracepoint *) self;
13588
13589   if (self->type == bp_fast_tracepoint)
13590     fprintf_unfiltered (fp, "ftrace");
13591   if (self->type == bp_static_tracepoint)
13592     fprintf_unfiltered (fp, "strace");
13593   else if (self->type == bp_tracepoint)
13594     fprintf_unfiltered (fp, "trace");
13595   else
13596     internal_error (__FILE__, __LINE__,
13597                     _("unhandled tracepoint type %d"), (int) self->type);
13598
13599   fprintf_unfiltered (fp, " %s", self->addr_string);
13600   print_recreate_thread (self, fp);
13601
13602   if (tp->pass_count)
13603     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13604 }
13605
13606 static void
13607 tracepoint_create_sals_from_address (char **arg,
13608                                      struct linespec_result *canonical,
13609                                      enum bptype type_wanted,
13610                                      char *addr_start, char **copy_arg)
13611 {
13612   create_sals_from_address_default (arg, canonical, type_wanted,
13613                                     addr_start, copy_arg);
13614 }
13615
13616 static void
13617 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13618                                    struct linespec_result *canonical,
13619                                    char *cond_string,
13620                                    char *extra_string,
13621                                    enum bptype type_wanted,
13622                                    enum bpdisp disposition,
13623                                    int thread,
13624                                    int task, int ignore_count,
13625                                    const struct breakpoint_ops *ops,
13626                                    int from_tty, int enabled,
13627                                    int internal, unsigned flags)
13628 {
13629   create_breakpoints_sal_default (gdbarch, canonical,
13630                                   cond_string, extra_string,
13631                                   type_wanted,
13632                                   disposition, thread, task,
13633                                   ignore_count, ops, from_tty,
13634                                   enabled, internal, flags);
13635 }
13636
13637 static void
13638 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13639                             struct symtabs_and_lines *sals)
13640 {
13641   decode_linespec_default (b, s, sals);
13642 }
13643
13644 struct breakpoint_ops tracepoint_breakpoint_ops;
13645
13646 /* The breakpoint_ops structure to be use on tracepoints placed in a
13647    static probe.  */
13648
13649 static void
13650 tracepoint_probe_create_sals_from_address (char **arg,
13651                                            struct linespec_result *canonical,
13652                                            enum bptype type_wanted,
13653                                            char *addr_start, char **copy_arg)
13654 {
13655   /* We use the same method for breakpoint on probes.  */
13656   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13657                                        addr_start, copy_arg);
13658 }
13659
13660 static void
13661 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13662                                   struct symtabs_and_lines *sals)
13663 {
13664   /* We use the same method for breakpoint on probes.  */
13665   bkpt_probe_decode_linespec (b, s, sals);
13666 }
13667
13668 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13669
13670 /* Dprintf breakpoint_ops methods.  */
13671
13672 static void
13673 dprintf_re_set (struct breakpoint *b)
13674 {
13675   breakpoint_re_set_default (b);
13676
13677   /* This breakpoint could have been pending, and be resolved now, and
13678      if so, we should now have the extra string.  If we don't, the
13679      dprintf was malformed when created, but we couldn't tell because
13680      we can't extract the extra string until the location is
13681      resolved.  */
13682   if (b->loc != NULL && b->extra_string == NULL)
13683     error (_("Format string required"));
13684
13685   /* 1 - connect to target 1, that can run breakpoint commands.
13686      2 - create a dprintf, which resolves fine.
13687      3 - disconnect from target 1
13688      4 - connect to target 2, that can NOT run breakpoint commands.
13689
13690      After steps #3/#4, you'll want the dprintf command list to
13691      be updated, because target 1 and 2 may well return different
13692      answers for target_can_run_breakpoint_commands().
13693      Given absence of finer grained resetting, we get to do
13694      it all the time.  */
13695   if (b->extra_string != NULL)
13696     update_dprintf_command_list (b);
13697 }
13698
13699 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13700
13701 static void
13702 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13703 {
13704   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13705                       tp->extra_string);
13706   print_recreate_thread (tp, fp);
13707 }
13708
13709 /* Implement the "after_condition_true" breakpoint_ops method for
13710    dprintf.
13711
13712    dprintf's are implemented with regular commands in their command
13713    list, but we run the commands here instead of before presenting the
13714    stop to the user, as dprintf's don't actually cause a stop.  This
13715    also makes it so that the commands of multiple dprintfs at the same
13716    address are all handled.  */
13717
13718 static void
13719 dprintf_after_condition_true (struct bpstats *bs)
13720 {
13721   struct cleanup *old_chain;
13722   struct bpstats tmp_bs = { NULL };
13723   struct bpstats *tmp_bs_p = &tmp_bs;
13724
13725   /* dprintf's never cause a stop.  This wasn't set in the
13726      check_status hook instead because that would make the dprintf's
13727      condition not be evaluated.  */
13728   bs->stop = 0;
13729
13730   /* Run the command list here.  Take ownership of it instead of
13731      copying.  We never want these commands to run later in
13732      bpstat_do_actions, if a breakpoint that causes a stop happens to
13733      be set at same address as this dprintf, or even if running the
13734      commands here throws.  */
13735   tmp_bs.commands = bs->commands;
13736   bs->commands = NULL;
13737   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13738
13739   bpstat_do_actions_1 (&tmp_bs_p);
13740
13741   /* 'tmp_bs.commands' will usually be NULL by now, but
13742      bpstat_do_actions_1 may return early without processing the whole
13743      list.  */
13744   do_cleanups (old_chain);
13745 }
13746
13747 /* The breakpoint_ops structure to be used on static tracepoints with
13748    markers (`-m').  */
13749
13750 static void
13751 strace_marker_create_sals_from_address (char **arg,
13752                                         struct linespec_result *canonical,
13753                                         enum bptype type_wanted,
13754                                         char *addr_start, char **copy_arg)
13755 {
13756   struct linespec_sals lsal;
13757
13758   lsal.sals = decode_static_tracepoint_spec (arg);
13759
13760   *copy_arg = savestring (addr_start, *arg - addr_start);
13761
13762   canonical->addr_string = xstrdup (*copy_arg);
13763   lsal.canonical = xstrdup (*copy_arg);
13764   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13765 }
13766
13767 static void
13768 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13769                                       struct linespec_result *canonical,
13770                                       char *cond_string,
13771                                       char *extra_string,
13772                                       enum bptype type_wanted,
13773                                       enum bpdisp disposition,
13774                                       int thread,
13775                                       int task, int ignore_count,
13776                                       const struct breakpoint_ops *ops,
13777                                       int from_tty, int enabled,
13778                                       int internal, unsigned flags)
13779 {
13780   int i;
13781   struct linespec_sals *lsal = VEC_index (linespec_sals,
13782                                           canonical->sals, 0);
13783
13784   /* If the user is creating a static tracepoint by marker id
13785      (strace -m MARKER_ID), then store the sals index, so that
13786      breakpoint_re_set can try to match up which of the newly
13787      found markers corresponds to this one, and, don't try to
13788      expand multiple locations for each sal, given than SALS
13789      already should contain all sals for MARKER_ID.  */
13790
13791   for (i = 0; i < lsal->sals.nelts; ++i)
13792     {
13793       struct symtabs_and_lines expanded;
13794       struct tracepoint *tp;
13795       struct cleanup *old_chain;
13796       char *addr_string;
13797
13798       expanded.nelts = 1;
13799       expanded.sals = &lsal->sals.sals[i];
13800
13801       addr_string = xstrdup (canonical->addr_string);
13802       old_chain = make_cleanup (xfree, addr_string);
13803
13804       tp = XCNEW (struct tracepoint);
13805       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13806                            addr_string, NULL,
13807                            cond_string, extra_string,
13808                            type_wanted, disposition,
13809                            thread, task, ignore_count, ops,
13810                            from_tty, enabled, internal, flags,
13811                            canonical->special_display);
13812       /* Given that its possible to have multiple markers with
13813          the same string id, if the user is creating a static
13814          tracepoint by marker id ("strace -m MARKER_ID"), then
13815          store the sals index, so that breakpoint_re_set can
13816          try to match up which of the newly found markers
13817          corresponds to this one  */
13818       tp->static_trace_marker_id_idx = i;
13819
13820       install_breakpoint (internal, &tp->base, 0);
13821
13822       discard_cleanups (old_chain);
13823     }
13824 }
13825
13826 static void
13827 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13828                                struct symtabs_and_lines *sals)
13829 {
13830   struct tracepoint *tp = (struct tracepoint *) b;
13831
13832   *sals = decode_static_tracepoint_spec (s);
13833   if (sals->nelts > tp->static_trace_marker_id_idx)
13834     {
13835       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13836       sals->nelts = 1;
13837     }
13838   else
13839     error (_("marker %s not found"), tp->static_trace_marker_id);
13840 }
13841
13842 static struct breakpoint_ops strace_marker_breakpoint_ops;
13843
13844 static int
13845 strace_marker_p (struct breakpoint *b)
13846 {
13847   return b->ops == &strace_marker_breakpoint_ops;
13848 }
13849
13850 /* Delete a breakpoint and clean up all traces of it in the data
13851    structures.  */
13852
13853 void
13854 delete_breakpoint (struct breakpoint *bpt)
13855 {
13856   struct breakpoint *b;
13857
13858   gdb_assert (bpt != NULL);
13859
13860   /* Has this bp already been deleted?  This can happen because
13861      multiple lists can hold pointers to bp's.  bpstat lists are
13862      especial culprits.
13863
13864      One example of this happening is a watchpoint's scope bp.  When
13865      the scope bp triggers, we notice that the watchpoint is out of
13866      scope, and delete it.  We also delete its scope bp.  But the
13867      scope bp is marked "auto-deleting", and is already on a bpstat.
13868      That bpstat is then checked for auto-deleting bp's, which are
13869      deleted.
13870
13871      A real solution to this problem might involve reference counts in
13872      bp's, and/or giving them pointers back to their referencing
13873      bpstat's, and teaching delete_breakpoint to only free a bp's
13874      storage when no more references were extent.  A cheaper bandaid
13875      was chosen.  */
13876   if (bpt->type == bp_none)
13877     return;
13878
13879   /* At least avoid this stale reference until the reference counting
13880      of breakpoints gets resolved.  */
13881   if (bpt->related_breakpoint != bpt)
13882     {
13883       struct breakpoint *related;
13884       struct watchpoint *w;
13885
13886       if (bpt->type == bp_watchpoint_scope)
13887         w = (struct watchpoint *) bpt->related_breakpoint;
13888       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13889         w = (struct watchpoint *) bpt;
13890       else
13891         w = NULL;
13892       if (w != NULL)
13893         watchpoint_del_at_next_stop (w);
13894
13895       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13896       for (related = bpt; related->related_breakpoint != bpt;
13897            related = related->related_breakpoint);
13898       related->related_breakpoint = bpt->related_breakpoint;
13899       bpt->related_breakpoint = bpt;
13900     }
13901
13902   /* watch_command_1 creates a watchpoint but only sets its number if
13903      update_watchpoint succeeds in creating its bp_locations.  If there's
13904      a problem in that process, we'll be asked to delete the half-created
13905      watchpoint.  In that case, don't announce the deletion.  */
13906   if (bpt->number)
13907     observer_notify_breakpoint_deleted (bpt);
13908
13909   if (breakpoint_chain == bpt)
13910     breakpoint_chain = bpt->next;
13911
13912   ALL_BREAKPOINTS (b)
13913     if (b->next == bpt)
13914     {
13915       b->next = bpt->next;
13916       break;
13917     }
13918
13919   /* Be sure no bpstat's are pointing at the breakpoint after it's
13920      been freed.  */
13921   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13922      in all threads for now.  Note that we cannot just remove bpstats
13923      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13924      commands are associated with the bpstat; if we remove it here,
13925      then the later call to bpstat_do_actions (&stop_bpstat); in
13926      event-top.c won't do anything, and temporary breakpoints with
13927      commands won't work.  */
13928
13929   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13930
13931   /* Now that breakpoint is removed from breakpoint list, update the
13932      global location list.  This will remove locations that used to
13933      belong to this breakpoint.  Do this before freeing the breakpoint
13934      itself, since remove_breakpoint looks at location's owner.  It
13935      might be better design to have location completely
13936      self-contained, but it's not the case now.  */
13937   update_global_location_list (0);
13938
13939   bpt->ops->dtor (bpt);
13940   /* On the chance that someone will soon try again to delete this
13941      same bp, we mark it as deleted before freeing its storage.  */
13942   bpt->type = bp_none;
13943   xfree (bpt);
13944 }
13945
13946 static void
13947 do_delete_breakpoint_cleanup (void *b)
13948 {
13949   delete_breakpoint (b);
13950 }
13951
13952 struct cleanup *
13953 make_cleanup_delete_breakpoint (struct breakpoint *b)
13954 {
13955   return make_cleanup (do_delete_breakpoint_cleanup, b);
13956 }
13957
13958 /* Iterator function to call a user-provided callback function once
13959    for each of B and its related breakpoints.  */
13960
13961 static void
13962 iterate_over_related_breakpoints (struct breakpoint *b,
13963                                   void (*function) (struct breakpoint *,
13964                                                     void *),
13965                                   void *data)
13966 {
13967   struct breakpoint *related;
13968
13969   related = b;
13970   do
13971     {
13972       struct breakpoint *next;
13973
13974       /* FUNCTION may delete RELATED.  */
13975       next = related->related_breakpoint;
13976
13977       if (next == related)
13978         {
13979           /* RELATED is the last ring entry.  */
13980           function (related, data);
13981
13982           /* FUNCTION may have deleted it, so we'd never reach back to
13983              B.  There's nothing left to do anyway, so just break
13984              out.  */
13985           break;
13986         }
13987       else
13988         function (related, data);
13989
13990       related = next;
13991     }
13992   while (related != b);
13993 }
13994
13995 static void
13996 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13997 {
13998   delete_breakpoint (b);
13999 }
14000
14001 /* A callback for map_breakpoint_numbers that calls
14002    delete_breakpoint.  */
14003
14004 static void
14005 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14006 {
14007   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14008 }
14009
14010 void
14011 delete_command (char *arg, int from_tty)
14012 {
14013   struct breakpoint *b, *b_tmp;
14014
14015   dont_repeat ();
14016
14017   if (arg == 0)
14018     {
14019       int breaks_to_delete = 0;
14020
14021       /* Delete all breakpoints if no argument.  Do not delete
14022          internal breakpoints, these have to be deleted with an
14023          explicit breakpoint number argument.  */
14024       ALL_BREAKPOINTS (b)
14025         if (user_breakpoint_p (b))
14026           {
14027             breaks_to_delete = 1;
14028             break;
14029           }
14030
14031       /* Ask user only if there are some breakpoints to delete.  */
14032       if (!from_tty
14033           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14034         {
14035           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14036             if (user_breakpoint_p (b))
14037               delete_breakpoint (b);
14038         }
14039     }
14040   else
14041     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14042 }
14043
14044 static int
14045 all_locations_are_pending (struct bp_location *loc)
14046 {
14047   for (; loc; loc = loc->next)
14048     if (!loc->shlib_disabled
14049         && !loc->pspace->executing_startup)
14050       return 0;
14051   return 1;
14052 }
14053
14054 /* Subroutine of update_breakpoint_locations to simplify it.
14055    Return non-zero if multiple fns in list LOC have the same name.
14056    Null names are ignored.  */
14057
14058 static int
14059 ambiguous_names_p (struct bp_location *loc)
14060 {
14061   struct bp_location *l;
14062   htab_t htab = htab_create_alloc (13, htab_hash_string,
14063                                    (int (*) (const void *, 
14064                                              const void *)) streq,
14065                                    NULL, xcalloc, xfree);
14066
14067   for (l = loc; l != NULL; l = l->next)
14068     {
14069       const char **slot;
14070       const char *name = l->function_name;
14071
14072       /* Allow for some names to be NULL, ignore them.  */
14073       if (name == NULL)
14074         continue;
14075
14076       slot = (const char **) htab_find_slot (htab, (const void *) name,
14077                                              INSERT);
14078       /* NOTE: We can assume slot != NULL here because xcalloc never
14079          returns NULL.  */
14080       if (*slot != NULL)
14081         {
14082           htab_delete (htab);
14083           return 1;
14084         }
14085       *slot = name;
14086     }
14087
14088   htab_delete (htab);
14089   return 0;
14090 }
14091
14092 /* When symbols change, it probably means the sources changed as well,
14093    and it might mean the static tracepoint markers are no longer at
14094    the same address or line numbers they used to be at last we
14095    checked.  Losing your static tracepoints whenever you rebuild is
14096    undesirable.  This function tries to resync/rematch gdb static
14097    tracepoints with the markers on the target, for static tracepoints
14098    that have not been set by marker id.  Static tracepoint that have
14099    been set by marker id are reset by marker id in breakpoint_re_set.
14100    The heuristic is:
14101
14102    1) For a tracepoint set at a specific address, look for a marker at
14103    the old PC.  If one is found there, assume to be the same marker.
14104    If the name / string id of the marker found is different from the
14105    previous known name, assume that means the user renamed the marker
14106    in the sources, and output a warning.
14107
14108    2) For a tracepoint set at a given line number, look for a marker
14109    at the new address of the old line number.  If one is found there,
14110    assume to be the same marker.  If the name / string id of the
14111    marker found is different from the previous known name, assume that
14112    means the user renamed the marker in the sources, and output a
14113    warning.
14114
14115    3) If a marker is no longer found at the same address or line, it
14116    may mean the marker no longer exists.  But it may also just mean
14117    the code changed a bit.  Maybe the user added a few lines of code
14118    that made the marker move up or down (in line number terms).  Ask
14119    the target for info about the marker with the string id as we knew
14120    it.  If found, update line number and address in the matching
14121    static tracepoint.  This will get confused if there's more than one
14122    marker with the same ID (possible in UST, although unadvised
14123    precisely because it confuses tools).  */
14124
14125 static struct symtab_and_line
14126 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14127 {
14128   struct tracepoint *tp = (struct tracepoint *) b;
14129   struct static_tracepoint_marker marker;
14130   CORE_ADDR pc;
14131
14132   pc = sal.pc;
14133   if (sal.line)
14134     find_line_pc (sal.symtab, sal.line, &pc);
14135
14136   if (target_static_tracepoint_marker_at (pc, &marker))
14137     {
14138       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14139         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14140                  b->number,
14141                  tp->static_trace_marker_id, marker.str_id);
14142
14143       xfree (tp->static_trace_marker_id);
14144       tp->static_trace_marker_id = xstrdup (marker.str_id);
14145       release_static_tracepoint_marker (&marker);
14146
14147       return sal;
14148     }
14149
14150   /* Old marker wasn't found on target at lineno.  Try looking it up
14151      by string ID.  */
14152   if (!sal.explicit_pc
14153       && sal.line != 0
14154       && sal.symtab != NULL
14155       && tp->static_trace_marker_id != NULL)
14156     {
14157       VEC(static_tracepoint_marker_p) *markers;
14158
14159       markers
14160         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14161
14162       if (!VEC_empty(static_tracepoint_marker_p, markers))
14163         {
14164           struct symtab_and_line sal2;
14165           struct symbol *sym;
14166           struct static_tracepoint_marker *tpmarker;
14167           struct ui_out *uiout = current_uiout;
14168
14169           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14170
14171           xfree (tp->static_trace_marker_id);
14172           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14173
14174           warning (_("marker for static tracepoint %d (%s) not "
14175                      "found at previous line number"),
14176                    b->number, tp->static_trace_marker_id);
14177
14178           init_sal (&sal2);
14179
14180           sal2.pc = tpmarker->address;
14181
14182           sal2 = find_pc_line (tpmarker->address, 0);
14183           sym = find_pc_sect_function (tpmarker->address, NULL);
14184           ui_out_text (uiout, "Now in ");
14185           if (sym)
14186             {
14187               ui_out_field_string (uiout, "func",
14188                                    SYMBOL_PRINT_NAME (sym));
14189               ui_out_text (uiout, " at ");
14190             }
14191           ui_out_field_string (uiout, "file",
14192                                symtab_to_filename_for_display (sal2.symtab));
14193           ui_out_text (uiout, ":");
14194
14195           if (ui_out_is_mi_like_p (uiout))
14196             {
14197               const char *fullname = symtab_to_fullname (sal2.symtab);
14198
14199               ui_out_field_string (uiout, "fullname", fullname);
14200             }
14201
14202           ui_out_field_int (uiout, "line", sal2.line);
14203           ui_out_text (uiout, "\n");
14204
14205           b->loc->line_number = sal2.line;
14206           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14207
14208           xfree (b->addr_string);
14209           b->addr_string = xstrprintf ("%s:%d",
14210                                    symtab_to_filename_for_display (sal2.symtab),
14211                                        b->loc->line_number);
14212
14213           /* Might be nice to check if function changed, and warn if
14214              so.  */
14215
14216           release_static_tracepoint_marker (tpmarker);
14217         }
14218     }
14219   return sal;
14220 }
14221
14222 /* Returns 1 iff locations A and B are sufficiently same that
14223    we don't need to report breakpoint as changed.  */
14224
14225 static int
14226 locations_are_equal (struct bp_location *a, struct bp_location *b)
14227 {
14228   while (a && b)
14229     {
14230       if (a->address != b->address)
14231         return 0;
14232
14233       if (a->shlib_disabled != b->shlib_disabled)
14234         return 0;
14235
14236       if (a->enabled != b->enabled)
14237         return 0;
14238
14239       a = a->next;
14240       b = b->next;
14241     }
14242
14243   if ((a == NULL) != (b == NULL))
14244     return 0;
14245
14246   return 1;
14247 }
14248
14249 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14250    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14251    a ranged breakpoint.  */
14252
14253 void
14254 update_breakpoint_locations (struct breakpoint *b,
14255                              struct symtabs_and_lines sals,
14256                              struct symtabs_and_lines sals_end)
14257 {
14258   int i;
14259   struct bp_location *existing_locations = b->loc;
14260
14261   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14262     {
14263       /* Ranged breakpoints have only one start location and one end
14264          location.  */
14265       b->enable_state = bp_disabled;
14266       update_global_location_list (1);
14267       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14268                            "multiple locations found\n"),
14269                          b->number);
14270       return;
14271     }
14272
14273   /* If there's no new locations, and all existing locations are
14274      pending, don't do anything.  This optimizes the common case where
14275      all locations are in the same shared library, that was unloaded.
14276      We'd like to retain the location, so that when the library is
14277      loaded again, we don't loose the enabled/disabled status of the
14278      individual locations.  */
14279   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14280     return;
14281
14282   b->loc = NULL;
14283
14284   for (i = 0; i < sals.nelts; ++i)
14285     {
14286       struct bp_location *new_loc;
14287
14288       switch_to_program_space_and_thread (sals.sals[i].pspace);
14289
14290       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14291
14292       /* Reparse conditions, they might contain references to the
14293          old symtab.  */
14294       if (b->cond_string != NULL)
14295         {
14296           const char *s;
14297           volatile struct gdb_exception e;
14298
14299           s = b->cond_string;
14300           TRY_CATCH (e, RETURN_MASK_ERROR)
14301             {
14302               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14303                                            block_for_pc (sals.sals[i].pc), 
14304                                            0);
14305             }
14306           if (e.reason < 0)
14307             {
14308               warning (_("failed to reevaluate condition "
14309                          "for breakpoint %d: %s"), 
14310                        b->number, e.message);
14311               new_loc->enabled = 0;
14312             }
14313         }
14314
14315       if (sals_end.nelts)
14316         {
14317           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14318
14319           new_loc->length = end - sals.sals[0].pc + 1;
14320         }
14321     }
14322
14323   /* Update locations of permanent breakpoints.  */
14324   if (b->enable_state == bp_permanent)
14325     make_breakpoint_permanent (b);
14326
14327   /* If possible, carry over 'disable' status from existing
14328      breakpoints.  */
14329   {
14330     struct bp_location *e = existing_locations;
14331     /* If there are multiple breakpoints with the same function name,
14332        e.g. for inline functions, comparing function names won't work.
14333        Instead compare pc addresses; this is just a heuristic as things
14334        may have moved, but in practice it gives the correct answer
14335        often enough until a better solution is found.  */
14336     int have_ambiguous_names = ambiguous_names_p (b->loc);
14337
14338     for (; e; e = e->next)
14339       {
14340         if (!e->enabled && e->function_name)
14341           {
14342             struct bp_location *l = b->loc;
14343             if (have_ambiguous_names)
14344               {
14345                 for (; l; l = l->next)
14346                   if (breakpoint_locations_match (e, l))
14347                     {
14348                       l->enabled = 0;
14349                       break;
14350                     }
14351               }
14352             else
14353               {
14354                 for (; l; l = l->next)
14355                   if (l->function_name
14356                       && strcmp (e->function_name, l->function_name) == 0)
14357                     {
14358                       l->enabled = 0;
14359                       break;
14360                     }
14361               }
14362           }
14363       }
14364   }
14365
14366   if (!locations_are_equal (existing_locations, b->loc))
14367     observer_notify_breakpoint_modified (b);
14368
14369   update_global_location_list (1);
14370 }
14371
14372 /* Find the SaL locations corresponding to the given ADDR_STRING.
14373    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14374
14375 static struct symtabs_and_lines
14376 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14377 {
14378   char *s;
14379   struct symtabs_and_lines sals = {0};
14380   volatile struct gdb_exception e;
14381
14382   gdb_assert (b->ops != NULL);
14383   s = addr_string;
14384
14385   TRY_CATCH (e, RETURN_MASK_ERROR)
14386     {
14387       b->ops->decode_linespec (b, &s, &sals);
14388     }
14389   if (e.reason < 0)
14390     {
14391       int not_found_and_ok = 0;
14392       /* For pending breakpoints, it's expected that parsing will
14393          fail until the right shared library is loaded.  User has
14394          already told to create pending breakpoints and don't need
14395          extra messages.  If breakpoint is in bp_shlib_disabled
14396          state, then user already saw the message about that
14397          breakpoint being disabled, and don't want to see more
14398          errors.  */
14399       if (e.error == NOT_FOUND_ERROR
14400           && (b->condition_not_parsed 
14401               || (b->loc && b->loc->shlib_disabled)
14402               || (b->loc && b->loc->pspace->executing_startup)
14403               || b->enable_state == bp_disabled))
14404         not_found_and_ok = 1;
14405
14406       if (!not_found_and_ok)
14407         {
14408           /* We surely don't want to warn about the same breakpoint
14409              10 times.  One solution, implemented here, is disable
14410              the breakpoint on error.  Another solution would be to
14411              have separate 'warning emitted' flag.  Since this
14412              happens only when a binary has changed, I don't know
14413              which approach is better.  */
14414           b->enable_state = bp_disabled;
14415           throw_exception (e);
14416         }
14417     }
14418
14419   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14420     {
14421       int i;
14422
14423       for (i = 0; i < sals.nelts; ++i)
14424         resolve_sal_pc (&sals.sals[i]);
14425       if (b->condition_not_parsed && s && s[0])
14426         {
14427           char *cond_string, *extra_string;
14428           int thread, task;
14429
14430           find_condition_and_thread (s, sals.sals[0].pc,
14431                                      &cond_string, &thread, &task,
14432                                      &extra_string);
14433           if (cond_string)
14434             b->cond_string = cond_string;
14435           b->thread = thread;
14436           b->task = task;
14437           if (extra_string)
14438             b->extra_string = extra_string;
14439           b->condition_not_parsed = 0;
14440         }
14441
14442       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14443         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14444
14445       *found = 1;
14446     }
14447   else
14448     *found = 0;
14449
14450   return sals;
14451 }
14452
14453 /* The default re_set method, for typical hardware or software
14454    breakpoints.  Reevaluate the breakpoint and recreate its
14455    locations.  */
14456
14457 static void
14458 breakpoint_re_set_default (struct breakpoint *b)
14459 {
14460   int found;
14461   struct symtabs_and_lines sals, sals_end;
14462   struct symtabs_and_lines expanded = {0};
14463   struct symtabs_and_lines expanded_end = {0};
14464
14465   sals = addr_string_to_sals (b, b->addr_string, &found);
14466   if (found)
14467     {
14468       make_cleanup (xfree, sals.sals);
14469       expanded = sals;
14470     }
14471
14472   if (b->addr_string_range_end)
14473     {
14474       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14475       if (found)
14476         {
14477           make_cleanup (xfree, sals_end.sals);
14478           expanded_end = sals_end;
14479         }
14480     }
14481
14482   update_breakpoint_locations (b, expanded, expanded_end);
14483 }
14484
14485 /* Default method for creating SALs from an address string.  It basically
14486    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14487
14488 static void
14489 create_sals_from_address_default (char **arg,
14490                                   struct linespec_result *canonical,
14491                                   enum bptype type_wanted,
14492                                   char *addr_start, char **copy_arg)
14493 {
14494   parse_breakpoint_sals (arg, canonical);
14495 }
14496
14497 /* Call create_breakpoints_sal for the given arguments.  This is the default
14498    function for the `create_breakpoints_sal' method of
14499    breakpoint_ops.  */
14500
14501 static void
14502 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14503                                 struct linespec_result *canonical,
14504                                 char *cond_string,
14505                                 char *extra_string,
14506                                 enum bptype type_wanted,
14507                                 enum bpdisp disposition,
14508                                 int thread,
14509                                 int task, int ignore_count,
14510                                 const struct breakpoint_ops *ops,
14511                                 int from_tty, int enabled,
14512                                 int internal, unsigned flags)
14513 {
14514   create_breakpoints_sal (gdbarch, canonical, cond_string,
14515                           extra_string,
14516                           type_wanted, disposition,
14517                           thread, task, ignore_count, ops, from_tty,
14518                           enabled, internal, flags);
14519 }
14520
14521 /* Decode the line represented by S by calling decode_line_full.  This is the
14522    default function for the `decode_linespec' method of breakpoint_ops.  */
14523
14524 static void
14525 decode_linespec_default (struct breakpoint *b, char **s,
14526                          struct symtabs_and_lines *sals)
14527 {
14528   struct linespec_result canonical;
14529
14530   init_linespec_result (&canonical);
14531   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14532                     (struct symtab *) NULL, 0,
14533                     &canonical, multiple_symbols_all,
14534                     b->filter);
14535
14536   /* We should get 0 or 1 resulting SALs.  */
14537   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14538
14539   if (VEC_length (linespec_sals, canonical.sals) > 0)
14540     {
14541       struct linespec_sals *lsal;
14542
14543       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14544       *sals = lsal->sals;
14545       /* Arrange it so the destructor does not free the
14546          contents.  */
14547       lsal->sals.sals = NULL;
14548     }
14549
14550   destroy_linespec_result (&canonical);
14551 }
14552
14553 /* Prepare the global context for a re-set of breakpoint B.  */
14554
14555 static struct cleanup *
14556 prepare_re_set_context (struct breakpoint *b)
14557 {
14558   struct cleanup *cleanups;
14559
14560   input_radix = b->input_radix;
14561   cleanups = save_current_space_and_thread ();
14562   if (b->pspace != NULL)
14563     switch_to_program_space_and_thread (b->pspace);
14564   set_language (b->language);
14565
14566   return cleanups;
14567 }
14568
14569 /* Reset a breakpoint given it's struct breakpoint * BINT.
14570    The value we return ends up being the return value from catch_errors.
14571    Unused in this case.  */
14572
14573 static int
14574 breakpoint_re_set_one (void *bint)
14575 {
14576   /* Get past catch_errs.  */
14577   struct breakpoint *b = (struct breakpoint *) bint;
14578   struct cleanup *cleanups;
14579
14580   cleanups = prepare_re_set_context (b);
14581   b->ops->re_set (b);
14582   do_cleanups (cleanups);
14583   return 0;
14584 }
14585
14586 /* Re-set all breakpoints after symbols have been re-loaded.  */
14587 void
14588 breakpoint_re_set (void)
14589 {
14590   struct breakpoint *b, *b_tmp;
14591   enum language save_language;
14592   int save_input_radix;
14593   struct cleanup *old_chain;
14594
14595   save_language = current_language->la_language;
14596   save_input_radix = input_radix;
14597   old_chain = save_current_program_space ();
14598
14599   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14600   {
14601     /* Format possible error msg.  */
14602     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14603                                 b->number);
14604     struct cleanup *cleanups = make_cleanup (xfree, message);
14605     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14606     do_cleanups (cleanups);
14607   }
14608   set_language (save_language);
14609   input_radix = save_input_radix;
14610
14611   jit_breakpoint_re_set ();
14612
14613   do_cleanups (old_chain);
14614
14615   create_overlay_event_breakpoint ();
14616   create_longjmp_master_breakpoint ();
14617   create_std_terminate_master_breakpoint ();
14618   create_exception_master_breakpoint ();
14619 }
14620 \f
14621 /* Reset the thread number of this breakpoint:
14622
14623    - If the breakpoint is for all threads, leave it as-is.
14624    - Else, reset it to the current thread for inferior_ptid.  */
14625 void
14626 breakpoint_re_set_thread (struct breakpoint *b)
14627 {
14628   if (b->thread != -1)
14629     {
14630       if (in_thread_list (inferior_ptid))
14631         b->thread = pid_to_thread_id (inferior_ptid);
14632
14633       /* We're being called after following a fork.  The new fork is
14634          selected as current, and unless this was a vfork will have a
14635          different program space from the original thread.  Reset that
14636          as well.  */
14637       b->loc->pspace = current_program_space;
14638     }
14639 }
14640
14641 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14642    If from_tty is nonzero, it prints a message to that effect,
14643    which ends with a period (no newline).  */
14644
14645 void
14646 set_ignore_count (int bptnum, int count, int from_tty)
14647 {
14648   struct breakpoint *b;
14649
14650   if (count < 0)
14651     count = 0;
14652
14653   ALL_BREAKPOINTS (b)
14654     if (b->number == bptnum)
14655     {
14656       if (is_tracepoint (b))
14657         {
14658           if (from_tty && count != 0)
14659             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14660                              bptnum);
14661           return;
14662         }
14663       
14664       b->ignore_count = count;
14665       if (from_tty)
14666         {
14667           if (count == 0)
14668             printf_filtered (_("Will stop next time "
14669                                "breakpoint %d is reached."),
14670                              bptnum);
14671           else if (count == 1)
14672             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14673                              bptnum);
14674           else
14675             printf_filtered (_("Will ignore next %d "
14676                                "crossings of breakpoint %d."),
14677                              count, bptnum);
14678         }
14679       observer_notify_breakpoint_modified (b);
14680       return;
14681     }
14682
14683   error (_("No breakpoint number %d."), bptnum);
14684 }
14685
14686 /* Command to set ignore-count of breakpoint N to COUNT.  */
14687
14688 static void
14689 ignore_command (char *args, int from_tty)
14690 {
14691   char *p = args;
14692   int num;
14693
14694   if (p == 0)
14695     error_no_arg (_("a breakpoint number"));
14696
14697   num = get_number (&p);
14698   if (num == 0)
14699     error (_("bad breakpoint number: '%s'"), args);
14700   if (*p == 0)
14701     error (_("Second argument (specified ignore-count) is missing."));
14702
14703   set_ignore_count (num,
14704                     longest_to_int (value_as_long (parse_and_eval (p))),
14705                     from_tty);
14706   if (from_tty)
14707     printf_filtered ("\n");
14708 }
14709 \f
14710 /* Call FUNCTION on each of the breakpoints
14711    whose numbers are given in ARGS.  */
14712
14713 static void
14714 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14715                                                       void *),
14716                         void *data)
14717 {
14718   int num;
14719   struct breakpoint *b, *tmp;
14720   int match;
14721   struct get_number_or_range_state state;
14722
14723   if (args == 0)
14724     error_no_arg (_("one or more breakpoint numbers"));
14725
14726   init_number_or_range (&state, args);
14727
14728   while (!state.finished)
14729     {
14730       char *p = state.string;
14731
14732       match = 0;
14733
14734       num = get_number_or_range (&state);
14735       if (num == 0)
14736         {
14737           warning (_("bad breakpoint number at or near '%s'"), p);
14738         }
14739       else
14740         {
14741           ALL_BREAKPOINTS_SAFE (b, tmp)
14742             if (b->number == num)
14743               {
14744                 match = 1;
14745                 function (b, data);
14746                 break;
14747               }
14748           if (match == 0)
14749             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14750         }
14751     }
14752 }
14753
14754 static struct bp_location *
14755 find_location_by_number (char *number)
14756 {
14757   char *dot = strchr (number, '.');
14758   char *p1;
14759   int bp_num;
14760   int loc_num;
14761   struct breakpoint *b;
14762   struct bp_location *loc;  
14763
14764   *dot = '\0';
14765
14766   p1 = number;
14767   bp_num = get_number (&p1);
14768   if (bp_num == 0)
14769     error (_("Bad breakpoint number '%s'"), number);
14770
14771   ALL_BREAKPOINTS (b)
14772     if (b->number == bp_num)
14773       {
14774         break;
14775       }
14776
14777   if (!b || b->number != bp_num)
14778     error (_("Bad breakpoint number '%s'"), number);
14779   
14780   p1 = dot+1;
14781   loc_num = get_number (&p1);
14782   if (loc_num == 0)
14783     error (_("Bad breakpoint location number '%s'"), number);
14784
14785   --loc_num;
14786   loc = b->loc;
14787   for (;loc_num && loc; --loc_num, loc = loc->next)
14788     ;
14789   if (!loc)
14790     error (_("Bad breakpoint location number '%s'"), dot+1);
14791     
14792   return loc;  
14793 }
14794
14795
14796 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14797    If from_tty is nonzero, it prints a message to that effect,
14798    which ends with a period (no newline).  */
14799
14800 void
14801 disable_breakpoint (struct breakpoint *bpt)
14802 {
14803   /* Never disable a watchpoint scope breakpoint; we want to
14804      hit them when we leave scope so we can delete both the
14805      watchpoint and its scope breakpoint at that time.  */
14806   if (bpt->type == bp_watchpoint_scope)
14807     return;
14808
14809   /* You can't disable permanent breakpoints.  */
14810   if (bpt->enable_state == bp_permanent)
14811     return;
14812
14813   bpt->enable_state = bp_disabled;
14814
14815   /* Mark breakpoint locations modified.  */
14816   mark_breakpoint_modified (bpt);
14817
14818   if (target_supports_enable_disable_tracepoint ()
14819       && current_trace_status ()->running && is_tracepoint (bpt))
14820     {
14821       struct bp_location *location;
14822      
14823       for (location = bpt->loc; location; location = location->next)
14824         target_disable_tracepoint (location);
14825     }
14826
14827   update_global_location_list (0);
14828
14829   observer_notify_breakpoint_modified (bpt);
14830 }
14831
14832 /* A callback for iterate_over_related_breakpoints.  */
14833
14834 static void
14835 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14836 {
14837   disable_breakpoint (b);
14838 }
14839
14840 /* A callback for map_breakpoint_numbers that calls
14841    disable_breakpoint.  */
14842
14843 static void
14844 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14845 {
14846   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14847 }
14848
14849 static void
14850 disable_command (char *args, int from_tty)
14851 {
14852   if (args == 0)
14853     {
14854       struct breakpoint *bpt;
14855
14856       ALL_BREAKPOINTS (bpt)
14857         if (user_breakpoint_p (bpt))
14858           disable_breakpoint (bpt);
14859     }
14860   else
14861     {
14862       char *num = extract_arg (&args);
14863
14864       while (num)
14865         {
14866           if (strchr (num, '.'))
14867             {
14868               struct bp_location *loc = find_location_by_number (num);
14869
14870               if (loc)
14871                 {
14872                   if (loc->enabled)
14873                     {
14874                       loc->enabled = 0;
14875                       mark_breakpoint_location_modified (loc);
14876                     }
14877                   if (target_supports_enable_disable_tracepoint ()
14878                       && current_trace_status ()->running && loc->owner
14879                       && is_tracepoint (loc->owner))
14880                     target_disable_tracepoint (loc);
14881                 }
14882               update_global_location_list (0);
14883             }
14884           else
14885             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14886           num = extract_arg (&args);
14887         }
14888     }
14889 }
14890
14891 static void
14892 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14893                         int count)
14894 {
14895   int target_resources_ok;
14896
14897   if (bpt->type == bp_hardware_breakpoint)
14898     {
14899       int i;
14900       i = hw_breakpoint_used_count ();
14901       target_resources_ok = 
14902         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14903                                             i + 1, 0);
14904       if (target_resources_ok == 0)
14905         error (_("No hardware breakpoint support in the target."));
14906       else if (target_resources_ok < 0)
14907         error (_("Hardware breakpoints used exceeds limit."));
14908     }
14909
14910   if (is_watchpoint (bpt))
14911     {
14912       /* Initialize it just to avoid a GCC false warning.  */
14913       enum enable_state orig_enable_state = 0;
14914       volatile struct gdb_exception e;
14915
14916       TRY_CATCH (e, RETURN_MASK_ALL)
14917         {
14918           struct watchpoint *w = (struct watchpoint *) bpt;
14919
14920           orig_enable_state = bpt->enable_state;
14921           bpt->enable_state = bp_enabled;
14922           update_watchpoint (w, 1 /* reparse */);
14923         }
14924       if (e.reason < 0)
14925         {
14926           bpt->enable_state = orig_enable_state;
14927           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14928                              bpt->number);
14929           return;
14930         }
14931     }
14932
14933   if (bpt->enable_state != bp_permanent)
14934     bpt->enable_state = bp_enabled;
14935
14936   bpt->enable_state = bp_enabled;
14937
14938   /* Mark breakpoint locations modified.  */
14939   mark_breakpoint_modified (bpt);
14940
14941   if (target_supports_enable_disable_tracepoint ()
14942       && current_trace_status ()->running && is_tracepoint (bpt))
14943     {
14944       struct bp_location *location;
14945
14946       for (location = bpt->loc; location; location = location->next)
14947         target_enable_tracepoint (location);
14948     }
14949
14950   bpt->disposition = disposition;
14951   bpt->enable_count = count;
14952   update_global_location_list (1);
14953
14954   observer_notify_breakpoint_modified (bpt);
14955 }
14956
14957
14958 void
14959 enable_breakpoint (struct breakpoint *bpt)
14960 {
14961   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14962 }
14963
14964 static void
14965 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14966 {
14967   enable_breakpoint (bpt);
14968 }
14969
14970 /* A callback for map_breakpoint_numbers that calls
14971    enable_breakpoint.  */
14972
14973 static void
14974 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14975 {
14976   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14977 }
14978
14979 /* The enable command enables the specified breakpoints (or all defined
14980    breakpoints) so they once again become (or continue to be) effective
14981    in stopping the inferior.  */
14982
14983 static void
14984 enable_command (char *args, int from_tty)
14985 {
14986   if (args == 0)
14987     {
14988       struct breakpoint *bpt;
14989
14990       ALL_BREAKPOINTS (bpt)
14991         if (user_breakpoint_p (bpt))
14992           enable_breakpoint (bpt);
14993     }
14994   else
14995     {
14996       char *num = extract_arg (&args);
14997
14998       while (num)
14999         {
15000           if (strchr (num, '.'))
15001             {
15002               struct bp_location *loc = find_location_by_number (num);
15003
15004               if (loc)
15005                 {
15006                   if (!loc->enabled)
15007                     {
15008                       loc->enabled = 1;
15009                       mark_breakpoint_location_modified (loc);
15010                     }
15011                   if (target_supports_enable_disable_tracepoint ()
15012                       && current_trace_status ()->running && loc->owner
15013                       && is_tracepoint (loc->owner))
15014                     target_enable_tracepoint (loc);
15015                 }
15016               update_global_location_list (1);
15017             }
15018           else
15019             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15020           num = extract_arg (&args);
15021         }
15022     }
15023 }
15024
15025 /* This struct packages up disposition data for application to multiple
15026    breakpoints.  */
15027
15028 struct disp_data
15029 {
15030   enum bpdisp disp;
15031   int count;
15032 };
15033
15034 static void
15035 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15036 {
15037   struct disp_data disp_data = *(struct disp_data *) arg;
15038
15039   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15040 }
15041
15042 static void
15043 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15044 {
15045   struct disp_data disp = { disp_disable, 1 };
15046
15047   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15048 }
15049
15050 static void
15051 enable_once_command (char *args, int from_tty)
15052 {
15053   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15054 }
15055
15056 static void
15057 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15058 {
15059   struct disp_data disp = { disp_disable, *(int *) countptr };
15060
15061   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15062 }
15063
15064 static void
15065 enable_count_command (char *args, int from_tty)
15066 {
15067   int count = get_number (&args);
15068
15069   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15070 }
15071
15072 static void
15073 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15074 {
15075   struct disp_data disp = { disp_del, 1 };
15076
15077   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15078 }
15079
15080 static void
15081 enable_delete_command (char *args, int from_tty)
15082 {
15083   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15084 }
15085 \f
15086 static void
15087 set_breakpoint_cmd (char *args, int from_tty)
15088 {
15089 }
15090
15091 static void
15092 show_breakpoint_cmd (char *args, int from_tty)
15093 {
15094 }
15095
15096 /* Invalidate last known value of any hardware watchpoint if
15097    the memory which that value represents has been written to by
15098    GDB itself.  */
15099
15100 static void
15101 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15102                                       CORE_ADDR addr, ssize_t len,
15103                                       const bfd_byte *data)
15104 {
15105   struct breakpoint *bp;
15106
15107   ALL_BREAKPOINTS (bp)
15108     if (bp->enable_state == bp_enabled
15109         && bp->type == bp_hardware_watchpoint)
15110       {
15111         struct watchpoint *wp = (struct watchpoint *) bp;
15112
15113         if (wp->val_valid && wp->val)
15114           {
15115             struct bp_location *loc;
15116
15117             for (loc = bp->loc; loc != NULL; loc = loc->next)
15118               if (loc->loc_type == bp_loc_hardware_watchpoint
15119                   && loc->address + loc->length > addr
15120                   && addr + len > loc->address)
15121                 {
15122                   value_free (wp->val);
15123                   wp->val = NULL;
15124                   wp->val_valid = 0;
15125                 }
15126           }
15127       }
15128 }
15129
15130 /* Create and insert a raw software breakpoint at PC.  Return an
15131    identifier, which should be used to remove the breakpoint later.
15132    In general, places which call this should be using something on the
15133    breakpoint chain instead; this function should be eliminated
15134    someday.  */
15135
15136 void *
15137 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15138                                   struct address_space *aspace, CORE_ADDR pc)
15139 {
15140   struct bp_target_info *bp_tgt;
15141
15142   bp_tgt = XCNEW (struct bp_target_info);
15143
15144   bp_tgt->placed_address_space = aspace;
15145   bp_tgt->placed_address = pc;
15146
15147   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15148     {
15149       /* Could not insert the breakpoint.  */
15150       xfree (bp_tgt);
15151       return NULL;
15152     }
15153
15154   return bp_tgt;
15155 }
15156
15157 /* Remove a breakpoint BP inserted by
15158    deprecated_insert_raw_breakpoint.  */
15159
15160 int
15161 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15162 {
15163   struct bp_target_info *bp_tgt = bp;
15164   int ret;
15165
15166   ret = target_remove_breakpoint (gdbarch, bp_tgt);
15167   xfree (bp_tgt);
15168
15169   return ret;
15170 }
15171
15172 /* Create and insert a breakpoint for software single step.  */
15173
15174 void
15175 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15176                                struct address_space *aspace, 
15177                                CORE_ADDR next_pc)
15178 {
15179   void **bpt_p;
15180
15181   if (single_step_breakpoints[0] == NULL)
15182     {
15183       bpt_p = &single_step_breakpoints[0];
15184       single_step_gdbarch[0] = gdbarch;
15185     }
15186   else
15187     {
15188       gdb_assert (single_step_breakpoints[1] == NULL);
15189       bpt_p = &single_step_breakpoints[1];
15190       single_step_gdbarch[1] = gdbarch;
15191     }
15192
15193   /* NOTE drow/2006-04-11: A future improvement to this function would
15194      be to only create the breakpoints once, and actually put them on
15195      the breakpoint chain.  That would let us use set_raw_breakpoint.
15196      We could adjust the addresses each time they were needed.  Doing
15197      this requires corresponding changes elsewhere where single step
15198      breakpoints are handled, however.  So, for now, we use this.  */
15199
15200   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15201   if (*bpt_p == NULL)
15202     error (_("Could not insert single-step breakpoint at %s"),
15203              paddress (gdbarch, next_pc));
15204 }
15205
15206 /* Check if the breakpoints used for software single stepping
15207    were inserted or not.  */
15208
15209 int
15210 single_step_breakpoints_inserted (void)
15211 {
15212   return (single_step_breakpoints[0] != NULL
15213           || single_step_breakpoints[1] != NULL);
15214 }
15215
15216 /* Remove and delete any breakpoints used for software single step.  */
15217
15218 void
15219 remove_single_step_breakpoints (void)
15220 {
15221   gdb_assert (single_step_breakpoints[0] != NULL);
15222
15223   /* See insert_single_step_breakpoint for more about this deprecated
15224      call.  */
15225   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15226                                     single_step_breakpoints[0]);
15227   single_step_gdbarch[0] = NULL;
15228   single_step_breakpoints[0] = NULL;
15229
15230   if (single_step_breakpoints[1] != NULL)
15231     {
15232       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15233                                         single_step_breakpoints[1]);
15234       single_step_gdbarch[1] = NULL;
15235       single_step_breakpoints[1] = NULL;
15236     }
15237 }
15238
15239 /* Delete software single step breakpoints without removing them from
15240    the inferior.  This is intended to be used if the inferior's address
15241    space where they were inserted is already gone, e.g. after exit or
15242    exec.  */
15243
15244 void
15245 cancel_single_step_breakpoints (void)
15246 {
15247   int i;
15248
15249   for (i = 0; i < 2; i++)
15250     if (single_step_breakpoints[i])
15251       {
15252         xfree (single_step_breakpoints[i]);
15253         single_step_breakpoints[i] = NULL;
15254         single_step_gdbarch[i] = NULL;
15255       }
15256 }
15257
15258 /* Detach software single-step breakpoints from INFERIOR_PTID without
15259    removing them.  */
15260
15261 static void
15262 detach_single_step_breakpoints (void)
15263 {
15264   int i;
15265
15266   for (i = 0; i < 2; i++)
15267     if (single_step_breakpoints[i])
15268       target_remove_breakpoint (single_step_gdbarch[i],
15269                                 single_step_breakpoints[i]);
15270 }
15271
15272 /* Check whether a software single-step breakpoint is inserted at
15273    PC.  */
15274
15275 int
15276 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15277                                         CORE_ADDR pc)
15278 {
15279   int i;
15280
15281   for (i = 0; i < 2; i++)
15282     {
15283       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15284       if (bp_tgt
15285           && breakpoint_address_match (bp_tgt->placed_address_space,
15286                                        bp_tgt->placed_address,
15287                                        aspace, pc))
15288         return 1;
15289     }
15290
15291   return 0;
15292 }
15293
15294 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15295    non-zero otherwise.  */
15296 static int
15297 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15298 {
15299   if (syscall_catchpoint_p (bp)
15300       && bp->enable_state != bp_disabled
15301       && bp->enable_state != bp_call_disabled)
15302     return 1;
15303   else
15304     return 0;
15305 }
15306
15307 int
15308 catch_syscall_enabled (void)
15309 {
15310   struct catch_syscall_inferior_data *inf_data
15311     = get_catch_syscall_inferior_data (current_inferior ());
15312
15313   return inf_data->total_syscalls_count != 0;
15314 }
15315
15316 int
15317 catching_syscall_number (int syscall_number)
15318 {
15319   struct breakpoint *bp;
15320
15321   ALL_BREAKPOINTS (bp)
15322     if (is_syscall_catchpoint_enabled (bp))
15323       {
15324         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15325
15326         if (c->syscalls_to_be_caught)
15327           {
15328             int i, iter;
15329             for (i = 0;
15330                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15331                  i++)
15332               if (syscall_number == iter)
15333                 return 1;
15334           }
15335         else
15336           return 1;
15337       }
15338
15339   return 0;
15340 }
15341
15342 /* Complete syscall names.  Used by "catch syscall".  */
15343 static VEC (char_ptr) *
15344 catch_syscall_completer (struct cmd_list_element *cmd,
15345                          const char *text, const char *word)
15346 {
15347   const char **list = get_syscall_names ();
15348   VEC (char_ptr) *retlist
15349     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15350
15351   xfree (list);
15352   return retlist;
15353 }
15354
15355 /* Tracepoint-specific operations.  */
15356
15357 /* Set tracepoint count to NUM.  */
15358 static void
15359 set_tracepoint_count (int num)
15360 {
15361   tracepoint_count = num;
15362   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15363 }
15364
15365 static void
15366 trace_command (char *arg, int from_tty)
15367 {
15368   struct breakpoint_ops *ops;
15369   const char *arg_cp = arg;
15370
15371   if (arg && probe_linespec_to_ops (&arg_cp))
15372     ops = &tracepoint_probe_breakpoint_ops;
15373   else
15374     ops = &tracepoint_breakpoint_ops;
15375
15376   create_breakpoint (get_current_arch (),
15377                      arg,
15378                      NULL, 0, NULL, 1 /* parse arg */,
15379                      0 /* tempflag */,
15380                      bp_tracepoint /* type_wanted */,
15381                      0 /* Ignore count */,
15382                      pending_break_support,
15383                      ops,
15384                      from_tty,
15385                      1 /* enabled */,
15386                      0 /* internal */, 0);
15387 }
15388
15389 static void
15390 ftrace_command (char *arg, int from_tty)
15391 {
15392   create_breakpoint (get_current_arch (),
15393                      arg,
15394                      NULL, 0, NULL, 1 /* parse arg */,
15395                      0 /* tempflag */,
15396                      bp_fast_tracepoint /* type_wanted */,
15397                      0 /* Ignore count */,
15398                      pending_break_support,
15399                      &tracepoint_breakpoint_ops,
15400                      from_tty,
15401                      1 /* enabled */,
15402                      0 /* internal */, 0);
15403 }
15404
15405 /* strace command implementation.  Creates a static tracepoint.  */
15406
15407 static void
15408 strace_command (char *arg, int from_tty)
15409 {
15410   struct breakpoint_ops *ops;
15411
15412   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15413      or with a normal static tracepoint.  */
15414   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15415     ops = &strace_marker_breakpoint_ops;
15416   else
15417     ops = &tracepoint_breakpoint_ops;
15418
15419   create_breakpoint (get_current_arch (),
15420                      arg,
15421                      NULL, 0, NULL, 1 /* parse arg */,
15422                      0 /* tempflag */,
15423                      bp_static_tracepoint /* type_wanted */,
15424                      0 /* Ignore count */,
15425                      pending_break_support,
15426                      ops,
15427                      from_tty,
15428                      1 /* enabled */,
15429                      0 /* internal */, 0);
15430 }
15431
15432 /* Set up a fake reader function that gets command lines from a linked
15433    list that was acquired during tracepoint uploading.  */
15434
15435 static struct uploaded_tp *this_utp;
15436 static int next_cmd;
15437
15438 static char *
15439 read_uploaded_action (void)
15440 {
15441   char *rslt;
15442
15443   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15444
15445   next_cmd++;
15446
15447   return rslt;
15448 }
15449
15450 /* Given information about a tracepoint as recorded on a target (which
15451    can be either a live system or a trace file), attempt to create an
15452    equivalent GDB tracepoint.  This is not a reliable process, since
15453    the target does not necessarily have all the information used when
15454    the tracepoint was originally defined.  */
15455   
15456 struct tracepoint *
15457 create_tracepoint_from_upload (struct uploaded_tp *utp)
15458 {
15459   char *addr_str, small_buf[100];
15460   struct tracepoint *tp;
15461
15462   if (utp->at_string)
15463     addr_str = utp->at_string;
15464   else
15465     {
15466       /* In the absence of a source location, fall back to raw
15467          address.  Since there is no way to confirm that the address
15468          means the same thing as when the trace was started, warn the
15469          user.  */
15470       warning (_("Uploaded tracepoint %d has no "
15471                  "source location, using raw address"),
15472                utp->number);
15473       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15474       addr_str = small_buf;
15475     }
15476
15477   /* There's not much we can do with a sequence of bytecodes.  */
15478   if (utp->cond && !utp->cond_string)
15479     warning (_("Uploaded tracepoint %d condition "
15480                "has no source form, ignoring it"),
15481              utp->number);
15482
15483   if (!create_breakpoint (get_current_arch (),
15484                           addr_str,
15485                           utp->cond_string, -1, NULL,
15486                           0 /* parse cond/thread */,
15487                           0 /* tempflag */,
15488                           utp->type /* type_wanted */,
15489                           0 /* Ignore count */,
15490                           pending_break_support,
15491                           &tracepoint_breakpoint_ops,
15492                           0 /* from_tty */,
15493                           utp->enabled /* enabled */,
15494                           0 /* internal */,
15495                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15496     return NULL;
15497
15498   /* Get the tracepoint we just created.  */
15499   tp = get_tracepoint (tracepoint_count);
15500   gdb_assert (tp != NULL);
15501
15502   if (utp->pass > 0)
15503     {
15504       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15505                  tp->base.number);
15506
15507       trace_pass_command (small_buf, 0);
15508     }
15509
15510   /* If we have uploaded versions of the original commands, set up a
15511      special-purpose "reader" function and call the usual command line
15512      reader, then pass the result to the breakpoint command-setting
15513      function.  */
15514   if (!VEC_empty (char_ptr, utp->cmd_strings))
15515     {
15516       struct command_line *cmd_list;
15517
15518       this_utp = utp;
15519       next_cmd = 0;
15520
15521       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15522
15523       breakpoint_set_commands (&tp->base, cmd_list);
15524     }
15525   else if (!VEC_empty (char_ptr, utp->actions)
15526            || !VEC_empty (char_ptr, utp->step_actions))
15527     warning (_("Uploaded tracepoint %d actions "
15528                "have no source form, ignoring them"),
15529              utp->number);
15530
15531   /* Copy any status information that might be available.  */
15532   tp->base.hit_count = utp->hit_count;
15533   tp->traceframe_usage = utp->traceframe_usage;
15534
15535   return tp;
15536 }
15537   
15538 /* Print information on tracepoint number TPNUM_EXP, or all if
15539    omitted.  */
15540
15541 static void
15542 tracepoints_info (char *args, int from_tty)
15543 {
15544   struct ui_out *uiout = current_uiout;
15545   int num_printed;
15546
15547   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15548
15549   if (num_printed == 0)
15550     {
15551       if (args == NULL || *args == '\0')
15552         ui_out_message (uiout, 0, "No tracepoints.\n");
15553       else
15554         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15555     }
15556
15557   default_collect_info ();
15558 }
15559
15560 /* The 'enable trace' command enables tracepoints.
15561    Not supported by all targets.  */
15562 static void
15563 enable_trace_command (char *args, int from_tty)
15564 {
15565   enable_command (args, from_tty);
15566 }
15567
15568 /* The 'disable trace' command disables tracepoints.
15569    Not supported by all targets.  */
15570 static void
15571 disable_trace_command (char *args, int from_tty)
15572 {
15573   disable_command (args, from_tty);
15574 }
15575
15576 /* Remove a tracepoint (or all if no argument).  */
15577 static void
15578 delete_trace_command (char *arg, int from_tty)
15579 {
15580   struct breakpoint *b, *b_tmp;
15581
15582   dont_repeat ();
15583
15584   if (arg == 0)
15585     {
15586       int breaks_to_delete = 0;
15587
15588       /* Delete all breakpoints if no argument.
15589          Do not delete internal or call-dummy breakpoints, these
15590          have to be deleted with an explicit breakpoint number 
15591          argument.  */
15592       ALL_TRACEPOINTS (b)
15593         if (is_tracepoint (b) && user_breakpoint_p (b))
15594           {
15595             breaks_to_delete = 1;
15596             break;
15597           }
15598
15599       /* Ask user only if there are some breakpoints to delete.  */
15600       if (!from_tty
15601           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15602         {
15603           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15604             if (is_tracepoint (b) && user_breakpoint_p (b))
15605               delete_breakpoint (b);
15606         }
15607     }
15608   else
15609     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15610 }
15611
15612 /* Helper function for trace_pass_command.  */
15613
15614 static void
15615 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15616 {
15617   tp->pass_count = count;
15618   observer_notify_breakpoint_modified (&tp->base);
15619   if (from_tty)
15620     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15621                      tp->base.number, count);
15622 }
15623
15624 /* Set passcount for tracepoint.
15625
15626    First command argument is passcount, second is tracepoint number.
15627    If tracepoint number omitted, apply to most recently defined.
15628    Also accepts special argument "all".  */
15629
15630 static void
15631 trace_pass_command (char *args, int from_tty)
15632 {
15633   struct tracepoint *t1;
15634   unsigned int count;
15635
15636   if (args == 0 || *args == 0)
15637     error (_("passcount command requires an "
15638              "argument (count + optional TP num)"));
15639
15640   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15641
15642   args = skip_spaces (args);
15643   if (*args && strncasecmp (args, "all", 3) == 0)
15644     {
15645       struct breakpoint *b;
15646
15647       args += 3;                        /* Skip special argument "all".  */
15648       if (*args)
15649         error (_("Junk at end of arguments."));
15650
15651       ALL_TRACEPOINTS (b)
15652       {
15653         t1 = (struct tracepoint *) b;
15654         trace_pass_set_count (t1, count, from_tty);
15655       }
15656     }
15657   else if (*args == '\0')
15658     {
15659       t1 = get_tracepoint_by_number (&args, NULL);
15660       if (t1)
15661         trace_pass_set_count (t1, count, from_tty);
15662     }
15663   else
15664     {
15665       struct get_number_or_range_state state;
15666
15667       init_number_or_range (&state, args);
15668       while (!state.finished)
15669         {
15670           t1 = get_tracepoint_by_number (&args, &state);
15671           if (t1)
15672             trace_pass_set_count (t1, count, from_tty);
15673         }
15674     }
15675 }
15676
15677 struct tracepoint *
15678 get_tracepoint (int num)
15679 {
15680   struct breakpoint *t;
15681
15682   ALL_TRACEPOINTS (t)
15683     if (t->number == num)
15684       return (struct tracepoint *) t;
15685
15686   return NULL;
15687 }
15688
15689 /* Find the tracepoint with the given target-side number (which may be
15690    different from the tracepoint number after disconnecting and
15691    reconnecting).  */
15692
15693 struct tracepoint *
15694 get_tracepoint_by_number_on_target (int num)
15695 {
15696   struct breakpoint *b;
15697
15698   ALL_TRACEPOINTS (b)
15699     {
15700       struct tracepoint *t = (struct tracepoint *) b;
15701
15702       if (t->number_on_target == num)
15703         return t;
15704     }
15705
15706   return NULL;
15707 }
15708
15709 /* Utility: parse a tracepoint number and look it up in the list.
15710    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15711    If the argument is missing, the most recent tracepoint
15712    (tracepoint_count) is returned.  */
15713
15714 struct tracepoint *
15715 get_tracepoint_by_number (char **arg,
15716                           struct get_number_or_range_state *state)
15717 {
15718   struct breakpoint *t;
15719   int tpnum;
15720   char *instring = arg == NULL ? NULL : *arg;
15721
15722   if (state)
15723     {
15724       gdb_assert (!state->finished);
15725       tpnum = get_number_or_range (state);
15726     }
15727   else if (arg == NULL || *arg == NULL || ! **arg)
15728     tpnum = tracepoint_count;
15729   else
15730     tpnum = get_number (arg);
15731
15732   if (tpnum <= 0)
15733     {
15734       if (instring && *instring)
15735         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15736                          instring);
15737       else
15738         printf_filtered (_("No previous tracepoint\n"));
15739       return NULL;
15740     }
15741
15742   ALL_TRACEPOINTS (t)
15743     if (t->number == tpnum)
15744     {
15745       return (struct tracepoint *) t;
15746     }
15747
15748   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15749   return NULL;
15750 }
15751
15752 void
15753 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15754 {
15755   if (b->thread != -1)
15756     fprintf_unfiltered (fp, " thread %d", b->thread);
15757
15758   if (b->task != 0)
15759     fprintf_unfiltered (fp, " task %d", b->task);
15760
15761   fprintf_unfiltered (fp, "\n");
15762 }
15763
15764 /* Save information on user settable breakpoints (watchpoints, etc) to
15765    a new script file named FILENAME.  If FILTER is non-NULL, call it
15766    on each breakpoint and only include the ones for which it returns
15767    non-zero.  */
15768
15769 static void
15770 save_breakpoints (char *filename, int from_tty,
15771                   int (*filter) (const struct breakpoint *))
15772 {
15773   struct breakpoint *tp;
15774   int any = 0;
15775   struct cleanup *cleanup;
15776   struct ui_file *fp;
15777   int extra_trace_bits = 0;
15778
15779   if (filename == 0 || *filename == 0)
15780     error (_("Argument required (file name in which to save)"));
15781
15782   /* See if we have anything to save.  */
15783   ALL_BREAKPOINTS (tp)
15784   {
15785     /* Skip internal and momentary breakpoints.  */
15786     if (!user_breakpoint_p (tp))
15787       continue;
15788
15789     /* If we have a filter, only save the breakpoints it accepts.  */
15790     if (filter && !filter (tp))
15791       continue;
15792
15793     any = 1;
15794
15795     if (is_tracepoint (tp))
15796       {
15797         extra_trace_bits = 1;
15798
15799         /* We can stop searching.  */
15800         break;
15801       }
15802   }
15803
15804   if (!any)
15805     {
15806       warning (_("Nothing to save."));
15807       return;
15808     }
15809
15810   filename = tilde_expand (filename);
15811   cleanup = make_cleanup (xfree, filename);
15812   fp = gdb_fopen (filename, "w");
15813   if (!fp)
15814     error (_("Unable to open file '%s' for saving (%s)"),
15815            filename, safe_strerror (errno));
15816   make_cleanup_ui_file_delete (fp);
15817
15818   if (extra_trace_bits)
15819     save_trace_state_variables (fp);
15820
15821   ALL_BREAKPOINTS (tp)
15822   {
15823     /* Skip internal and momentary breakpoints.  */
15824     if (!user_breakpoint_p (tp))
15825       continue;
15826
15827     /* If we have a filter, only save the breakpoints it accepts.  */
15828     if (filter && !filter (tp))
15829       continue;
15830
15831     tp->ops->print_recreate (tp, fp);
15832
15833     /* Note, we can't rely on tp->number for anything, as we can't
15834        assume the recreated breakpoint numbers will match.  Use $bpnum
15835        instead.  */
15836
15837     if (tp->cond_string)
15838       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15839
15840     if (tp->ignore_count)
15841       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15842
15843     if (tp->type != bp_dprintf && tp->commands)
15844       {
15845         volatile struct gdb_exception ex;       
15846
15847         fprintf_unfiltered (fp, "  commands\n");
15848         
15849         ui_out_redirect (current_uiout, fp);
15850         TRY_CATCH (ex, RETURN_MASK_ALL)
15851           {
15852             print_command_lines (current_uiout, tp->commands->commands, 2);
15853           }
15854         ui_out_redirect (current_uiout, NULL);
15855
15856         if (ex.reason < 0)
15857           throw_exception (ex);
15858
15859         fprintf_unfiltered (fp, "  end\n");
15860       }
15861
15862     if (tp->enable_state == bp_disabled)
15863       fprintf_unfiltered (fp, "disable\n");
15864
15865     /* If this is a multi-location breakpoint, check if the locations
15866        should be individually disabled.  Watchpoint locations are
15867        special, and not user visible.  */
15868     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15869       {
15870         struct bp_location *loc;
15871         int n = 1;
15872
15873         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15874           if (!loc->enabled)
15875             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15876       }
15877   }
15878
15879   if (extra_trace_bits && *default_collect)
15880     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15881
15882   if (from_tty)
15883     printf_filtered (_("Saved to file '%s'.\n"), filename);
15884   do_cleanups (cleanup);
15885 }
15886
15887 /* The `save breakpoints' command.  */
15888
15889 static void
15890 save_breakpoints_command (char *args, int from_tty)
15891 {
15892   save_breakpoints (args, from_tty, NULL);
15893 }
15894
15895 /* The `save tracepoints' command.  */
15896
15897 static void
15898 save_tracepoints_command (char *args, int from_tty)
15899 {
15900   save_breakpoints (args, from_tty, is_tracepoint);
15901 }
15902
15903 /* Create a vector of all tracepoints.  */
15904
15905 VEC(breakpoint_p) *
15906 all_tracepoints (void)
15907 {
15908   VEC(breakpoint_p) *tp_vec = 0;
15909   struct breakpoint *tp;
15910
15911   ALL_TRACEPOINTS (tp)
15912   {
15913     VEC_safe_push (breakpoint_p, tp_vec, tp);
15914   }
15915
15916   return tp_vec;
15917 }
15918
15919 \f
15920 /* This help string is used for the break, hbreak, tbreak and thbreak
15921    commands.  It is defined as a macro to prevent duplication.
15922    COMMAND should be a string constant containing the name of the
15923    command.  */
15924 #define BREAK_ARGS_HELP(command) \
15925 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15926 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15927 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15928 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15929 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15930 If a line number is specified, break at start of code for that line.\n\
15931 If a function is specified, break at start of code for that function.\n\
15932 If an address is specified, break at that exact address.\n\
15933 With no LOCATION, uses current execution address of the selected\n\
15934 stack frame.  This is useful for breaking on return to a stack frame.\n\
15935 \n\
15936 THREADNUM is the number from \"info threads\".\n\
15937 CONDITION is a boolean expression.\n\
15938 \n\
15939 Multiple breakpoints at one place are permitted, and useful if their\n\
15940 conditions are different.\n\
15941 \n\
15942 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15943
15944 /* List of subcommands for "catch".  */
15945 static struct cmd_list_element *catch_cmdlist;
15946
15947 /* List of subcommands for "tcatch".  */
15948 static struct cmd_list_element *tcatch_cmdlist;
15949
15950 void
15951 add_catch_command (char *name, char *docstring,
15952                    void (*sfunc) (char *args, int from_tty,
15953                                   struct cmd_list_element *command),
15954                    completer_ftype *completer,
15955                    void *user_data_catch,
15956                    void *user_data_tcatch)
15957 {
15958   struct cmd_list_element *command;
15959
15960   command = add_cmd (name, class_breakpoint, NULL, docstring,
15961                      &catch_cmdlist);
15962   set_cmd_sfunc (command, sfunc);
15963   set_cmd_context (command, user_data_catch);
15964   set_cmd_completer (command, completer);
15965
15966   command = add_cmd (name, class_breakpoint, NULL, docstring,
15967                      &tcatch_cmdlist);
15968   set_cmd_sfunc (command, sfunc);
15969   set_cmd_context (command, user_data_tcatch);
15970   set_cmd_completer (command, completer);
15971 }
15972
15973 static void
15974 clear_syscall_counts (struct inferior *inf)
15975 {
15976   struct catch_syscall_inferior_data *inf_data
15977     = get_catch_syscall_inferior_data (inf);
15978
15979   inf_data->total_syscalls_count = 0;
15980   inf_data->any_syscall_count = 0;
15981   VEC_free (int, inf_data->syscalls_counts);
15982 }
15983
15984 static void
15985 save_command (char *arg, int from_tty)
15986 {
15987   printf_unfiltered (_("\"save\" must be followed by "
15988                        "the name of a save subcommand.\n"));
15989   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15990 }
15991
15992 struct breakpoint *
15993 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15994                           void *data)
15995 {
15996   struct breakpoint *b, *b_tmp;
15997
15998   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15999     {
16000       if ((*callback) (b, data))
16001         return b;
16002     }
16003
16004   return NULL;
16005 }
16006
16007 /* Zero if any of the breakpoint's locations could be a location where
16008    functions have been inlined, nonzero otherwise.  */
16009
16010 static int
16011 is_non_inline_function (struct breakpoint *b)
16012 {
16013   /* The shared library event breakpoint is set on the address of a
16014      non-inline function.  */
16015   if (b->type == bp_shlib_event)
16016     return 1;
16017
16018   return 0;
16019 }
16020
16021 /* Nonzero if the specified PC cannot be a location where functions
16022    have been inlined.  */
16023
16024 int
16025 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16026                            const struct target_waitstatus *ws)
16027 {
16028   struct breakpoint *b;
16029   struct bp_location *bl;
16030
16031   ALL_BREAKPOINTS (b)
16032     {
16033       if (!is_non_inline_function (b))
16034         continue;
16035
16036       for (bl = b->loc; bl != NULL; bl = bl->next)
16037         {
16038           if (!bl->shlib_disabled
16039               && bpstat_check_location (bl, aspace, pc, ws))
16040             return 1;
16041         }
16042     }
16043
16044   return 0;
16045 }
16046
16047 /* Remove any references to OBJFILE which is going to be freed.  */
16048
16049 void
16050 breakpoint_free_objfile (struct objfile *objfile)
16051 {
16052   struct bp_location **locp, *loc;
16053
16054   ALL_BP_LOCATIONS (loc, locp)
16055     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16056       loc->symtab = NULL;
16057 }
16058
16059 void
16060 initialize_breakpoint_ops (void)
16061 {
16062   static int initialized = 0;
16063
16064   struct breakpoint_ops *ops;
16065
16066   if (initialized)
16067     return;
16068   initialized = 1;
16069
16070   /* The breakpoint_ops structure to be inherit by all kinds of
16071      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16072      internal and momentary breakpoints, etc.).  */
16073   ops = &bkpt_base_breakpoint_ops;
16074   *ops = base_breakpoint_ops;
16075   ops->re_set = bkpt_re_set;
16076   ops->insert_location = bkpt_insert_location;
16077   ops->remove_location = bkpt_remove_location;
16078   ops->breakpoint_hit = bkpt_breakpoint_hit;
16079   ops->create_sals_from_address = bkpt_create_sals_from_address;
16080   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16081   ops->decode_linespec = bkpt_decode_linespec;
16082
16083   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16084   ops = &bkpt_breakpoint_ops;
16085   *ops = bkpt_base_breakpoint_ops;
16086   ops->re_set = bkpt_re_set;
16087   ops->resources_needed = bkpt_resources_needed;
16088   ops->print_it = bkpt_print_it;
16089   ops->print_mention = bkpt_print_mention;
16090   ops->print_recreate = bkpt_print_recreate;
16091
16092   /* Ranged breakpoints.  */
16093   ops = &ranged_breakpoint_ops;
16094   *ops = bkpt_breakpoint_ops;
16095   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16096   ops->resources_needed = resources_needed_ranged_breakpoint;
16097   ops->print_it = print_it_ranged_breakpoint;
16098   ops->print_one = print_one_ranged_breakpoint;
16099   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16100   ops->print_mention = print_mention_ranged_breakpoint;
16101   ops->print_recreate = print_recreate_ranged_breakpoint;
16102
16103   /* Internal breakpoints.  */
16104   ops = &internal_breakpoint_ops;
16105   *ops = bkpt_base_breakpoint_ops;
16106   ops->re_set = internal_bkpt_re_set;
16107   ops->check_status = internal_bkpt_check_status;
16108   ops->print_it = internal_bkpt_print_it;
16109   ops->print_mention = internal_bkpt_print_mention;
16110
16111   /* Momentary breakpoints.  */
16112   ops = &momentary_breakpoint_ops;
16113   *ops = bkpt_base_breakpoint_ops;
16114   ops->re_set = momentary_bkpt_re_set;
16115   ops->check_status = momentary_bkpt_check_status;
16116   ops->print_it = momentary_bkpt_print_it;
16117   ops->print_mention = momentary_bkpt_print_mention;
16118
16119   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16120   ops = &longjmp_breakpoint_ops;
16121   *ops = momentary_breakpoint_ops;
16122   ops->dtor = longjmp_bkpt_dtor;
16123
16124   /* Probe breakpoints.  */
16125   ops = &bkpt_probe_breakpoint_ops;
16126   *ops = bkpt_breakpoint_ops;
16127   ops->insert_location = bkpt_probe_insert_location;
16128   ops->remove_location = bkpt_probe_remove_location;
16129   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16130   ops->decode_linespec = bkpt_probe_decode_linespec;
16131
16132   /* Watchpoints.  */
16133   ops = &watchpoint_breakpoint_ops;
16134   *ops = base_breakpoint_ops;
16135   ops->dtor = dtor_watchpoint;
16136   ops->re_set = re_set_watchpoint;
16137   ops->insert_location = insert_watchpoint;
16138   ops->remove_location = remove_watchpoint;
16139   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16140   ops->check_status = check_status_watchpoint;
16141   ops->resources_needed = resources_needed_watchpoint;
16142   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16143   ops->print_it = print_it_watchpoint;
16144   ops->print_mention = print_mention_watchpoint;
16145   ops->print_recreate = print_recreate_watchpoint;
16146   ops->explains_signal = explains_signal_watchpoint;
16147
16148   /* Masked watchpoints.  */
16149   ops = &masked_watchpoint_breakpoint_ops;
16150   *ops = watchpoint_breakpoint_ops;
16151   ops->insert_location = insert_masked_watchpoint;
16152   ops->remove_location = remove_masked_watchpoint;
16153   ops->resources_needed = resources_needed_masked_watchpoint;
16154   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16155   ops->print_it = print_it_masked_watchpoint;
16156   ops->print_one_detail = print_one_detail_masked_watchpoint;
16157   ops->print_mention = print_mention_masked_watchpoint;
16158   ops->print_recreate = print_recreate_masked_watchpoint;
16159
16160   /* Tracepoints.  */
16161   ops = &tracepoint_breakpoint_ops;
16162   *ops = base_breakpoint_ops;
16163   ops->re_set = tracepoint_re_set;
16164   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16165   ops->print_one_detail = tracepoint_print_one_detail;
16166   ops->print_mention = tracepoint_print_mention;
16167   ops->print_recreate = tracepoint_print_recreate;
16168   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16169   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16170   ops->decode_linespec = tracepoint_decode_linespec;
16171
16172   /* Probe tracepoints.  */
16173   ops = &tracepoint_probe_breakpoint_ops;
16174   *ops = tracepoint_breakpoint_ops;
16175   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16176   ops->decode_linespec = tracepoint_probe_decode_linespec;
16177
16178   /* Static tracepoints with marker (`-m').  */
16179   ops = &strace_marker_breakpoint_ops;
16180   *ops = tracepoint_breakpoint_ops;
16181   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16182   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16183   ops->decode_linespec = strace_marker_decode_linespec;
16184
16185   /* Fork catchpoints.  */
16186   ops = &catch_fork_breakpoint_ops;
16187   *ops = base_breakpoint_ops;
16188   ops->insert_location = insert_catch_fork;
16189   ops->remove_location = remove_catch_fork;
16190   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16191   ops->print_it = print_it_catch_fork;
16192   ops->print_one = print_one_catch_fork;
16193   ops->print_mention = print_mention_catch_fork;
16194   ops->print_recreate = print_recreate_catch_fork;
16195
16196   /* Vfork catchpoints.  */
16197   ops = &catch_vfork_breakpoint_ops;
16198   *ops = base_breakpoint_ops;
16199   ops->insert_location = insert_catch_vfork;
16200   ops->remove_location = remove_catch_vfork;
16201   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16202   ops->print_it = print_it_catch_vfork;
16203   ops->print_one = print_one_catch_vfork;
16204   ops->print_mention = print_mention_catch_vfork;
16205   ops->print_recreate = print_recreate_catch_vfork;
16206
16207   /* Exec catchpoints.  */
16208   ops = &catch_exec_breakpoint_ops;
16209   *ops = base_breakpoint_ops;
16210   ops->dtor = dtor_catch_exec;
16211   ops->insert_location = insert_catch_exec;
16212   ops->remove_location = remove_catch_exec;
16213   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16214   ops->print_it = print_it_catch_exec;
16215   ops->print_one = print_one_catch_exec;
16216   ops->print_mention = print_mention_catch_exec;
16217   ops->print_recreate = print_recreate_catch_exec;
16218
16219   /* Syscall catchpoints.  */
16220   ops = &catch_syscall_breakpoint_ops;
16221   *ops = base_breakpoint_ops;
16222   ops->dtor = dtor_catch_syscall;
16223   ops->insert_location = insert_catch_syscall;
16224   ops->remove_location = remove_catch_syscall;
16225   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16226   ops->print_it = print_it_catch_syscall;
16227   ops->print_one = print_one_catch_syscall;
16228   ops->print_mention = print_mention_catch_syscall;
16229   ops->print_recreate = print_recreate_catch_syscall;
16230
16231   /* Solib-related catchpoints.  */
16232   ops = &catch_solib_breakpoint_ops;
16233   *ops = base_breakpoint_ops;
16234   ops->dtor = dtor_catch_solib;
16235   ops->insert_location = insert_catch_solib;
16236   ops->remove_location = remove_catch_solib;
16237   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16238   ops->check_status = check_status_catch_solib;
16239   ops->print_it = print_it_catch_solib;
16240   ops->print_one = print_one_catch_solib;
16241   ops->print_mention = print_mention_catch_solib;
16242   ops->print_recreate = print_recreate_catch_solib;
16243
16244   ops = &dprintf_breakpoint_ops;
16245   *ops = bkpt_base_breakpoint_ops;
16246   ops->re_set = dprintf_re_set;
16247   ops->resources_needed = bkpt_resources_needed;
16248   ops->print_it = bkpt_print_it;
16249   ops->print_mention = bkpt_print_mention;
16250   ops->print_recreate = dprintf_print_recreate;
16251   ops->after_condition_true = dprintf_after_condition_true;
16252   ops->breakpoint_hit = dprintf_breakpoint_hit;
16253 }
16254
16255 /* Chain containing all defined "enable breakpoint" subcommands.  */
16256
16257 static struct cmd_list_element *enablebreaklist = NULL;
16258
16259 void
16260 _initialize_breakpoint (void)
16261 {
16262   struct cmd_list_element *c;
16263
16264   initialize_breakpoint_ops ();
16265
16266   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16267   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16268   observer_attach_inferior_exit (clear_syscall_counts);
16269   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16270
16271   breakpoint_objfile_key
16272     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16273
16274   catch_syscall_inferior_data
16275     = register_inferior_data_with_cleanup (NULL,
16276                                            catch_syscall_inferior_data_cleanup);
16277
16278   breakpoint_chain = 0;
16279   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16280      before a breakpoint is set.  */
16281   breakpoint_count = 0;
16282
16283   tracepoint_count = 0;
16284
16285   add_com ("ignore", class_breakpoint, ignore_command, _("\
16286 Set ignore-count of breakpoint number N to COUNT.\n\
16287 Usage is `ignore N COUNT'."));
16288   if (xdb_commands)
16289     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16290
16291   add_com ("commands", class_breakpoint, commands_command, _("\
16292 Set commands to be executed when a breakpoint is hit.\n\
16293 Give breakpoint number as argument after \"commands\".\n\
16294 With no argument, the targeted breakpoint is the last one set.\n\
16295 The commands themselves follow starting on the next line.\n\
16296 Type a line containing \"end\" to indicate the end of them.\n\
16297 Give \"silent\" as the first line to make the breakpoint silent;\n\
16298 then no output is printed when it is hit, except what the commands print."));
16299
16300   c = add_com ("condition", class_breakpoint, condition_command, _("\
16301 Specify breakpoint number N to break only if COND is true.\n\
16302 Usage is `condition N COND', where N is an integer and COND is an\n\
16303 expression to be evaluated whenever breakpoint N is reached."));
16304   set_cmd_completer (c, condition_completer);
16305
16306   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16307 Set a temporary breakpoint.\n\
16308 Like \"break\" except the breakpoint is only temporary,\n\
16309 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16310 by using \"enable delete\" on the breakpoint number.\n\
16311 \n"
16312 BREAK_ARGS_HELP ("tbreak")));
16313   set_cmd_completer (c, location_completer);
16314
16315   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16316 Set a hardware assisted breakpoint.\n\
16317 Like \"break\" except the breakpoint requires hardware support,\n\
16318 some target hardware may not have this support.\n\
16319 \n"
16320 BREAK_ARGS_HELP ("hbreak")));
16321   set_cmd_completer (c, location_completer);
16322
16323   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16324 Set a temporary hardware assisted breakpoint.\n\
16325 Like \"hbreak\" except the breakpoint is only temporary,\n\
16326 so it will be deleted when hit.\n\
16327 \n"
16328 BREAK_ARGS_HELP ("thbreak")));
16329   set_cmd_completer (c, location_completer);
16330
16331   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16332 Enable some breakpoints.\n\
16333 Give breakpoint numbers (separated by spaces) as arguments.\n\
16334 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16335 This is used to cancel the effect of the \"disable\" command.\n\
16336 With a subcommand you can enable temporarily."),
16337                   &enablelist, "enable ", 1, &cmdlist);
16338   if (xdb_commands)
16339     add_com ("ab", class_breakpoint, enable_command, _("\
16340 Enable some breakpoints.\n\
16341 Give breakpoint numbers (separated by spaces) as arguments.\n\
16342 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16343 This is used to cancel the effect of the \"disable\" command.\n\
16344 With a subcommand you can enable temporarily."));
16345
16346   add_com_alias ("en", "enable", class_breakpoint, 1);
16347
16348   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16349 Enable some breakpoints.\n\
16350 Give breakpoint numbers (separated by spaces) as arguments.\n\
16351 This is used to cancel the effect of the \"disable\" command.\n\
16352 May be abbreviated to simply \"enable\".\n"),
16353                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16354
16355   add_cmd ("once", no_class, enable_once_command, _("\
16356 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16357 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16358            &enablebreaklist);
16359
16360   add_cmd ("delete", no_class, enable_delete_command, _("\
16361 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16362 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16363            &enablebreaklist);
16364
16365   add_cmd ("count", no_class, enable_count_command, _("\
16366 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16367 If a breakpoint is hit while enabled in this fashion,\n\
16368 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16369            &enablebreaklist);
16370
16371   add_cmd ("delete", no_class, enable_delete_command, _("\
16372 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16373 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16374            &enablelist);
16375
16376   add_cmd ("once", no_class, enable_once_command, _("\
16377 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16378 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16379            &enablelist);
16380
16381   add_cmd ("count", no_class, enable_count_command, _("\
16382 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16383 If a breakpoint is hit while enabled in this fashion,\n\
16384 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16385            &enablelist);
16386
16387   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16388 Disable some breakpoints.\n\
16389 Arguments are breakpoint numbers with spaces in between.\n\
16390 To disable all breakpoints, give no argument.\n\
16391 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16392                   &disablelist, "disable ", 1, &cmdlist);
16393   add_com_alias ("dis", "disable", class_breakpoint, 1);
16394   add_com_alias ("disa", "disable", class_breakpoint, 1);
16395   if (xdb_commands)
16396     add_com ("sb", class_breakpoint, disable_command, _("\
16397 Disable some breakpoints.\n\
16398 Arguments are breakpoint numbers with spaces in between.\n\
16399 To disable all breakpoints, give no argument.\n\
16400 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16401
16402   add_cmd ("breakpoints", class_alias, disable_command, _("\
16403 Disable some breakpoints.\n\
16404 Arguments are breakpoint numbers with spaces in between.\n\
16405 To disable all breakpoints, give no argument.\n\
16406 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16407 This command may be abbreviated \"disable\"."),
16408            &disablelist);
16409
16410   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16411 Delete some breakpoints or auto-display expressions.\n\
16412 Arguments are breakpoint numbers with spaces in between.\n\
16413 To delete all breakpoints, give no argument.\n\
16414 \n\
16415 Also a prefix command for deletion of other GDB objects.\n\
16416 The \"unset\" command is also an alias for \"delete\"."),
16417                   &deletelist, "delete ", 1, &cmdlist);
16418   add_com_alias ("d", "delete", class_breakpoint, 1);
16419   add_com_alias ("del", "delete", class_breakpoint, 1);
16420   if (xdb_commands)
16421     add_com ("db", class_breakpoint, delete_command, _("\
16422 Delete some breakpoints.\n\
16423 Arguments are breakpoint numbers with spaces in between.\n\
16424 To delete all breakpoints, give no argument.\n"));
16425
16426   add_cmd ("breakpoints", class_alias, delete_command, _("\
16427 Delete some breakpoints or auto-display expressions.\n\
16428 Arguments are breakpoint numbers with spaces in between.\n\
16429 To delete all breakpoints, give no argument.\n\
16430 This command may be abbreviated \"delete\"."),
16431            &deletelist);
16432
16433   add_com ("clear", class_breakpoint, clear_command, _("\
16434 Clear breakpoint at specified line or function.\n\
16435 Argument may be line number, function name, or \"*\" and an address.\n\
16436 If line number is specified, all breakpoints in that line are cleared.\n\
16437 If function is specified, breakpoints at beginning of function are cleared.\n\
16438 If an address is specified, breakpoints at that address are cleared.\n\
16439 \n\
16440 With no argument, clears all breakpoints in the line that the selected frame\n\
16441 is executing in.\n\
16442 \n\
16443 See also the \"delete\" command which clears breakpoints by number."));
16444   add_com_alias ("cl", "clear", class_breakpoint, 1);
16445
16446   c = add_com ("break", class_breakpoint, break_command, _("\
16447 Set breakpoint at specified line or function.\n"
16448 BREAK_ARGS_HELP ("break")));
16449   set_cmd_completer (c, location_completer);
16450
16451   add_com_alias ("b", "break", class_run, 1);
16452   add_com_alias ("br", "break", class_run, 1);
16453   add_com_alias ("bre", "break", class_run, 1);
16454   add_com_alias ("brea", "break", class_run, 1);
16455
16456   if (xdb_commands)
16457    add_com_alias ("ba", "break", class_breakpoint, 1);
16458
16459   if (dbx_commands)
16460     {
16461       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16462 Break in function/address or break at a line in the current file."),
16463                              &stoplist, "stop ", 1, &cmdlist);
16464       add_cmd ("in", class_breakpoint, stopin_command,
16465                _("Break in function or address."), &stoplist);
16466       add_cmd ("at", class_breakpoint, stopat_command,
16467                _("Break at a line in the current file."), &stoplist);
16468       add_com ("status", class_info, breakpoints_info, _("\
16469 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16470 The \"Type\" column indicates one of:\n\
16471 \tbreakpoint     - normal breakpoint\n\
16472 \twatchpoint     - watchpoint\n\
16473 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16474 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16475 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16476 address and file/line number respectively.\n\
16477 \n\
16478 Convenience variable \"$_\" and default examine address for \"x\"\n\
16479 are set to the address of the last breakpoint listed unless the command\n\
16480 is prefixed with \"server \".\n\n\
16481 Convenience variable \"$bpnum\" contains the number of the last\n\
16482 breakpoint set."));
16483     }
16484
16485   add_info ("breakpoints", breakpoints_info, _("\
16486 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16487 The \"Type\" column indicates one of:\n\
16488 \tbreakpoint     - normal breakpoint\n\
16489 \twatchpoint     - watchpoint\n\
16490 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16491 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16492 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16493 address and file/line number respectively.\n\
16494 \n\
16495 Convenience variable \"$_\" and default examine address for \"x\"\n\
16496 are set to the address of the last breakpoint listed unless the command\n\
16497 is prefixed with \"server \".\n\n\
16498 Convenience variable \"$bpnum\" contains the number of the last\n\
16499 breakpoint set."));
16500
16501   add_info_alias ("b", "breakpoints", 1);
16502
16503   if (xdb_commands)
16504     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16505 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16506 The \"Type\" column indicates one of:\n\
16507 \tbreakpoint     - normal breakpoint\n\
16508 \twatchpoint     - watchpoint\n\
16509 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16510 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16511 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16512 address and file/line number respectively.\n\
16513 \n\
16514 Convenience variable \"$_\" and default examine address for \"x\"\n\
16515 are set to the address of the last breakpoint listed unless the command\n\
16516 is prefixed with \"server \".\n\n\
16517 Convenience variable \"$bpnum\" contains the number of the last\n\
16518 breakpoint set."));
16519
16520   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16521 Status of all breakpoints, or breakpoint number NUMBER.\n\
16522 The \"Type\" column indicates one of:\n\
16523 \tbreakpoint     - normal breakpoint\n\
16524 \twatchpoint     - watchpoint\n\
16525 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16526 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16527 \tuntil          - internal breakpoint used by the \"until\" command\n\
16528 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16529 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16530 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16531 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16532 address and file/line number respectively.\n\
16533 \n\
16534 Convenience variable \"$_\" and default examine address for \"x\"\n\
16535 are set to the address of the last breakpoint listed unless the command\n\
16536 is prefixed with \"server \".\n\n\
16537 Convenience variable \"$bpnum\" contains the number of the last\n\
16538 breakpoint set."),
16539            &maintenanceinfolist);
16540
16541   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16542 Set catchpoints to catch events."),
16543                   &catch_cmdlist, "catch ",
16544                   0/*allow-unknown*/, &cmdlist);
16545
16546   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16547 Set temporary catchpoints to catch events."),
16548                   &tcatch_cmdlist, "tcatch ",
16549                   0/*allow-unknown*/, &cmdlist);
16550
16551   add_catch_command ("fork", _("Catch calls to fork."),
16552                      catch_fork_command_1,
16553                      NULL,
16554                      (void *) (uintptr_t) catch_fork_permanent,
16555                      (void *) (uintptr_t) catch_fork_temporary);
16556   add_catch_command ("vfork", _("Catch calls to vfork."),
16557                      catch_fork_command_1,
16558                      NULL,
16559                      (void *) (uintptr_t) catch_vfork_permanent,
16560                      (void *) (uintptr_t) catch_vfork_temporary);
16561   add_catch_command ("exec", _("Catch calls to exec."),
16562                      catch_exec_command_1,
16563                      NULL,
16564                      CATCH_PERMANENT,
16565                      CATCH_TEMPORARY);
16566   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16567 Usage: catch load [REGEX]\n\
16568 If REGEX is given, only stop for libraries matching the regular expression."),
16569                      catch_load_command_1,
16570                      NULL,
16571                      CATCH_PERMANENT,
16572                      CATCH_TEMPORARY);
16573   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16574 Usage: catch unload [REGEX]\n\
16575 If REGEX is given, only stop for libraries matching the regular expression."),
16576                      catch_unload_command_1,
16577                      NULL,
16578                      CATCH_PERMANENT,
16579                      CATCH_TEMPORARY);
16580   add_catch_command ("syscall", _("\
16581 Catch system calls by their names and/or numbers.\n\
16582 Arguments say which system calls to catch.  If no arguments\n\
16583 are given, every system call will be caught.\n\
16584 Arguments, if given, should be one or more system call names\n\
16585 (if your system supports that), or system call numbers."),
16586                      catch_syscall_command_1,
16587                      catch_syscall_completer,
16588                      CATCH_PERMANENT,
16589                      CATCH_TEMPORARY);
16590
16591   c = add_com ("watch", class_breakpoint, watch_command, _("\
16592 Set a watchpoint for an expression.\n\
16593 Usage: watch [-l|-location] EXPRESSION\n\
16594 A watchpoint stops execution of your program whenever the value of\n\
16595 an expression changes.\n\
16596 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16597 the memory to which it refers."));
16598   set_cmd_completer (c, expression_completer);
16599
16600   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16601 Set a read watchpoint for an expression.\n\
16602 Usage: rwatch [-l|-location] EXPRESSION\n\
16603 A watchpoint stops execution of your program whenever the value of\n\
16604 an expression is read.\n\
16605 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16606 the memory to which it refers."));
16607   set_cmd_completer (c, expression_completer);
16608
16609   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16610 Set a watchpoint for an expression.\n\
16611 Usage: awatch [-l|-location] EXPRESSION\n\
16612 A watchpoint stops execution of your program whenever the value of\n\
16613 an expression is either read or written.\n\
16614 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16615 the memory to which it refers."));
16616   set_cmd_completer (c, expression_completer);
16617
16618   add_info ("watchpoints", watchpoints_info, _("\
16619 Status of specified watchpoints (all watchpoints if no argument)."));
16620
16621   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16622      respond to changes - contrary to the description.  */
16623   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16624                             &can_use_hw_watchpoints, _("\
16625 Set debugger's willingness to use watchpoint hardware."), _("\
16626 Show debugger's willingness to use watchpoint hardware."), _("\
16627 If zero, gdb will not use hardware for new watchpoints, even if\n\
16628 such is available.  (However, any hardware watchpoints that were\n\
16629 created before setting this to nonzero, will continue to use watchpoint\n\
16630 hardware.)"),
16631                             NULL,
16632                             show_can_use_hw_watchpoints,
16633                             &setlist, &showlist);
16634
16635   can_use_hw_watchpoints = 1;
16636
16637   /* Tracepoint manipulation commands.  */
16638
16639   c = add_com ("trace", class_breakpoint, trace_command, _("\
16640 Set a tracepoint at specified line or function.\n\
16641 \n"
16642 BREAK_ARGS_HELP ("trace") "\n\
16643 Do \"help tracepoints\" for info on other tracepoint commands."));
16644   set_cmd_completer (c, location_completer);
16645
16646   add_com_alias ("tp", "trace", class_alias, 0);
16647   add_com_alias ("tr", "trace", class_alias, 1);
16648   add_com_alias ("tra", "trace", class_alias, 1);
16649   add_com_alias ("trac", "trace", class_alias, 1);
16650
16651   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16652 Set a fast tracepoint at specified line or function.\n\
16653 \n"
16654 BREAK_ARGS_HELP ("ftrace") "\n\
16655 Do \"help tracepoints\" for info on other tracepoint commands."));
16656   set_cmd_completer (c, location_completer);
16657
16658   c = add_com ("strace", class_breakpoint, strace_command, _("\
16659 Set a static tracepoint at specified line, function or marker.\n\
16660 \n\
16661 strace [LOCATION] [if CONDITION]\n\
16662 LOCATION may be a line number, function name, \"*\" and an address,\n\
16663 or -m MARKER_ID.\n\
16664 If a line number is specified, probe the marker at start of code\n\
16665 for that line.  If a function is specified, probe the marker at start\n\
16666 of code for that function.  If an address is specified, probe the marker\n\
16667 at that exact address.  If a marker id is specified, probe the marker\n\
16668 with that name.  With no LOCATION, uses current execution address of\n\
16669 the selected stack frame.\n\
16670 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16671 This collects arbitrary user data passed in the probe point call to the\n\
16672 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16673 by printing the $_sdata variable like any other convenience variable.\n\
16674 \n\
16675 CONDITION is a boolean expression.\n\
16676 \n\
16677 Multiple tracepoints at one place are permitted, and useful if their\n\
16678 conditions are different.\n\
16679 \n\
16680 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16681 Do \"help tracepoints\" for info on other tracepoint commands."));
16682   set_cmd_completer (c, location_completer);
16683
16684   add_info ("tracepoints", tracepoints_info, _("\
16685 Status of specified tracepoints (all tracepoints if no argument).\n\
16686 Convenience variable \"$tpnum\" contains the number of the\n\
16687 last tracepoint set."));
16688
16689   add_info_alias ("tp", "tracepoints", 1);
16690
16691   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16692 Delete specified tracepoints.\n\
16693 Arguments are tracepoint numbers, separated by spaces.\n\
16694 No argument means delete all tracepoints."),
16695            &deletelist);
16696   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16697
16698   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16699 Disable specified tracepoints.\n\
16700 Arguments are tracepoint numbers, separated by spaces.\n\
16701 No argument means disable all tracepoints."),
16702            &disablelist);
16703   deprecate_cmd (c, "disable");
16704
16705   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16706 Enable specified tracepoints.\n\
16707 Arguments are tracepoint numbers, separated by spaces.\n\
16708 No argument means enable all tracepoints."),
16709            &enablelist);
16710   deprecate_cmd (c, "enable");
16711
16712   add_com ("passcount", class_trace, trace_pass_command, _("\
16713 Set the passcount for a tracepoint.\n\
16714 The trace will end when the tracepoint has been passed 'count' times.\n\
16715 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16716 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16717
16718   add_prefix_cmd ("save", class_breakpoint, save_command,
16719                   _("Save breakpoint definitions as a script."),
16720                   &save_cmdlist, "save ",
16721                   0/*allow-unknown*/, &cmdlist);
16722
16723   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16724 Save current breakpoint definitions as a script.\n\
16725 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16726 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16727 session to restore them."),
16728                &save_cmdlist);
16729   set_cmd_completer (c, filename_completer);
16730
16731   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16732 Save current tracepoint definitions as a script.\n\
16733 Use the 'source' command in another debug session to restore them."),
16734                &save_cmdlist);
16735   set_cmd_completer (c, filename_completer);
16736
16737   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16738   deprecate_cmd (c, "save tracepoints");
16739
16740   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16741 Breakpoint specific settings\n\
16742 Configure various breakpoint-specific variables such as\n\
16743 pending breakpoint behavior"),
16744                   &breakpoint_set_cmdlist, "set breakpoint ",
16745                   0/*allow-unknown*/, &setlist);
16746   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16747 Breakpoint specific settings\n\
16748 Configure various breakpoint-specific variables such as\n\
16749 pending breakpoint behavior"),
16750                   &breakpoint_show_cmdlist, "show breakpoint ",
16751                   0/*allow-unknown*/, &showlist);
16752
16753   add_setshow_auto_boolean_cmd ("pending", no_class,
16754                                 &pending_break_support, _("\
16755 Set debugger's behavior regarding pending breakpoints."), _("\
16756 Show debugger's behavior regarding pending breakpoints."), _("\
16757 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16758 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16759 an error.  If auto, an unrecognized breakpoint location results in a\n\
16760 user-query to see if a pending breakpoint should be created."),
16761                                 NULL,
16762                                 show_pending_break_support,
16763                                 &breakpoint_set_cmdlist,
16764                                 &breakpoint_show_cmdlist);
16765
16766   pending_break_support = AUTO_BOOLEAN_AUTO;
16767
16768   add_setshow_boolean_cmd ("auto-hw", no_class,
16769                            &automatic_hardware_breakpoints, _("\
16770 Set automatic usage of hardware breakpoints."), _("\
16771 Show automatic usage of hardware breakpoints."), _("\
16772 If set, the debugger will automatically use hardware breakpoints for\n\
16773 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16774 a warning will be emitted for such breakpoints."),
16775                            NULL,
16776                            show_automatic_hardware_breakpoints,
16777                            &breakpoint_set_cmdlist,
16778                            &breakpoint_show_cmdlist);
16779
16780   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16781                                 &always_inserted_mode, _("\
16782 Set mode for inserting breakpoints."), _("\
16783 Show mode for inserting breakpoints."), _("\
16784 When this mode is off, breakpoints are inserted in inferior when it is\n\
16785 resumed, and removed when execution stops.  When this mode is on,\n\
16786 breakpoints are inserted immediately and removed only when the user\n\
16787 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16788 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16789 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16790 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16791 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16792                                 NULL,
16793                                 &show_always_inserted_mode,
16794                                 &breakpoint_set_cmdlist,
16795                                 &breakpoint_show_cmdlist);
16796
16797   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16798                         condition_evaluation_enums,
16799                         &condition_evaluation_mode_1, _("\
16800 Set mode of breakpoint condition evaluation."), _("\
16801 Show mode of breakpoint condition evaluation."), _("\
16802 When this is set to \"host\", breakpoint conditions will be\n\
16803 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16804 breakpoint conditions will be downloaded to the target (if the target\n\
16805 supports such feature) and conditions will be evaluated on the target's side.\n\
16806 If this is set to \"auto\" (default), this will be automatically set to\n\
16807 \"target\" if it supports condition evaluation, otherwise it will\n\
16808 be set to \"gdb\""),
16809                            &set_condition_evaluation_mode,
16810                            &show_condition_evaluation_mode,
16811                            &breakpoint_set_cmdlist,
16812                            &breakpoint_show_cmdlist);
16813
16814   add_com ("break-range", class_breakpoint, break_range_command, _("\
16815 Set a breakpoint for an address range.\n\
16816 break-range START-LOCATION, END-LOCATION\n\
16817 where START-LOCATION and END-LOCATION can be one of the following:\n\
16818   LINENUM, for that line in the current file,\n\
16819   FILE:LINENUM, for that line in that file,\n\
16820   +OFFSET, for that number of lines after the current line\n\
16821            or the start of the range\n\
16822   FUNCTION, for the first line in that function,\n\
16823   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16824   *ADDRESS, for the instruction at that address.\n\
16825 \n\
16826 The breakpoint will stop execution of the inferior whenever it executes\n\
16827 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16828 range (including START-LOCATION and END-LOCATION)."));
16829
16830   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16831 Set a dynamic printf at specified line or function.\n\
16832 dprintf location,format string,arg1,arg2,...\n\
16833 location may be a line number, function name, or \"*\" and an address.\n\
16834 If a line number is specified, break at start of code for that line.\n\
16835 If a function is specified, break at start of code for that function."));
16836   set_cmd_completer (c, location_completer);
16837
16838   add_setshow_enum_cmd ("dprintf-style", class_support,
16839                         dprintf_style_enums, &dprintf_style, _("\
16840 Set the style of usage for dynamic printf."), _("\
16841 Show the style of usage for dynamic printf."), _("\
16842 This setting chooses how GDB will do a dynamic printf.\n\
16843 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16844 console, as with the \"printf\" command.\n\
16845 If the value is \"call\", the print is done by calling a function in your\n\
16846 program; by default printf(), but you can choose a different function or\n\
16847 output stream by setting dprintf-function and dprintf-channel."),
16848                         update_dprintf_commands, NULL,
16849                         &setlist, &showlist);
16850
16851   dprintf_function = xstrdup ("printf");
16852   add_setshow_string_cmd ("dprintf-function", class_support,
16853                           &dprintf_function, _("\
16854 Set the function to use for dynamic printf"), _("\
16855 Show the function to use for dynamic printf"), NULL,
16856                           update_dprintf_commands, NULL,
16857                           &setlist, &showlist);
16858
16859   dprintf_channel = xstrdup ("");
16860   add_setshow_string_cmd ("dprintf-channel", class_support,
16861                           &dprintf_channel, _("\
16862 Set the channel to use for dynamic printf"), _("\
16863 Show the channel to use for dynamic printf"), NULL,
16864                           update_dprintf_commands, NULL,
16865                           &setlist, &showlist);
16866
16867   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16868                            &disconnected_dprintf, _("\
16869 Set whether dprintf continues after GDB disconnects."), _("\
16870 Show whether dprintf continues after GDB disconnects."), _("\
16871 Use this to let dprintf commands continue to hit and produce output\n\
16872 even if GDB disconnects or detaches from the target."),
16873                            NULL,
16874                            NULL,
16875                            &setlist, &showlist);
16876
16877   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16878 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16879 (target agent only) This is useful for formatted output in user-defined commands."));
16880
16881   automatic_hardware_breakpoints = 1;
16882
16883   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16884   observer_attach_thread_exit (remove_threaded_breakpoints);
16885 }