dprintf-style agent can't explain a trap.
[platform/upstream/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "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   /* For now, limit to agent-style dprintf breakpoints.  */
2355   if (bl->owner->type != bp_dprintf
2356       || strcmp (dprintf_style, dprintf_style_agent) != 0)
2357     return;
2358
2359   if (!target_can_run_breakpoint_commands ())
2360     return;
2361
2362   /* Do a first pass to check for locations with no assigned
2363      conditions or conditions that fail to parse to a valid agent expression
2364      bytecode.  If any of these happen, then it's no use to send conditions
2365      to the target since this location will always trigger and generate a
2366      response back to GDB.  */
2367   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2368     {
2369       loc = (*loc2p);
2370       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2371         {
2372           if (modified)
2373             {
2374               struct agent_expr *aexpr;
2375
2376               /* Re-parse the commands since something changed.  In that
2377                  case we already freed the command bytecodes (see
2378                  force_breakpoint_reinsertion).  We just
2379                  need to parse the command to bytecodes again.  */
2380               aexpr = parse_cmd_to_aexpr (bl->address,
2381                                           loc->owner->extra_string);
2382               loc->cmd_bytecode = aexpr;
2383
2384               if (!aexpr)
2385                 continue;
2386             }
2387
2388           /* If we have a NULL bytecode expression, it means something
2389              went wrong or we have a null command expression.  */
2390           if (!loc->cmd_bytecode)
2391             {
2392               null_command_or_parse_error = 1;
2393               break;
2394             }
2395         }
2396     }
2397
2398   /* If anything failed, then we're not doing target-side commands,
2399      and so clean up.  */
2400   if (null_command_or_parse_error)
2401     {
2402       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2403         {
2404           loc = (*loc2p);
2405           if (is_breakpoint (loc->owner)
2406               && loc->pspace->num == bl->pspace->num)
2407             {
2408               /* Only go as far as the first NULL bytecode is
2409                  located.  */
2410               if (loc->cmd_bytecode == NULL)
2411                 return;
2412
2413               free_agent_expr (loc->cmd_bytecode);
2414               loc->cmd_bytecode = NULL;
2415             }
2416         }
2417     }
2418
2419   /* No NULL commands or failed bytecode generation.  Build a command list
2420      for this location's address.  */
2421   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2422     {
2423       loc = (*loc2p);
2424       if (loc->owner->extra_string
2425           && is_breakpoint (loc->owner)
2426           && loc->pspace->num == bl->pspace->num
2427           && loc->owner->enable_state == bp_enabled
2428           && loc->enabled)
2429         /* Add the command to the vector.  This will be used later
2430            to send the commands to the target.  */
2431         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2432                        loc->cmd_bytecode);
2433     }
2434
2435   bl->target_info.persist = 0;
2436   /* Maybe flag this location as persistent.  */
2437   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2438     bl->target_info.persist = 1;
2439 }
2440
2441 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2442    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2443    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2444    Returns 0 for success, 1 if the bp_location type is not supported or
2445    -1 for failure.
2446
2447    NOTE drow/2003-09-09: This routine could be broken down to an
2448    object-style method for each breakpoint or catchpoint type.  */
2449 static int
2450 insert_bp_location (struct bp_location *bl,
2451                     struct ui_file *tmp_error_stream,
2452                     int *disabled_breaks,
2453                     int *hw_breakpoint_error,
2454                     int *hw_bp_error_explained_already)
2455 {
2456   enum errors bp_err = GDB_NO_ERROR;
2457   const char *bp_err_message = NULL;
2458   volatile struct gdb_exception e;
2459
2460   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2461     return 0;
2462
2463   /* Note we don't initialize bl->target_info, as that wipes out
2464      the breakpoint location's shadow_contents if the breakpoint
2465      is still inserted at that location.  This in turn breaks
2466      target_read_memory which depends on these buffers when
2467      a memory read is requested at the breakpoint location:
2468      Once the target_info has been wiped, we fail to see that
2469      we have a breakpoint inserted at that address and thus
2470      read the breakpoint instead of returning the data saved in
2471      the breakpoint location's shadow contents.  */
2472   bl->target_info.placed_address = bl->address;
2473   bl->target_info.placed_address_space = bl->pspace->aspace;
2474   bl->target_info.length = bl->length;
2475
2476   /* When working with target-side conditions, we must pass all the conditions
2477      for the same breakpoint address down to the target since GDB will not
2478      insert those locations.  With a list of breakpoint conditions, the target
2479      can decide when to stop and notify GDB.  */
2480
2481   if (is_breakpoint (bl->owner))
2482     {
2483       build_target_condition_list (bl);
2484       build_target_command_list (bl);
2485       /* Reset the modification marker.  */
2486       bl->needs_update = 0;
2487     }
2488
2489   if (bl->loc_type == bp_loc_software_breakpoint
2490       || bl->loc_type == bp_loc_hardware_breakpoint)
2491     {
2492       if (bl->owner->type != bp_hardware_breakpoint)
2493         {
2494           /* If the explicitly specified breakpoint type
2495              is not hardware breakpoint, check the memory map to see
2496              if the breakpoint address is in read only memory or not.
2497
2498              Two important cases are:
2499              - location type is not hardware breakpoint, memory
2500              is readonly.  We change the type of the location to
2501              hardware breakpoint.
2502              - location type is hardware breakpoint, memory is
2503              read-write.  This means we've previously made the
2504              location hardware one, but then the memory map changed,
2505              so we undo.
2506              
2507              When breakpoints are removed, remove_breakpoints will use
2508              location types we've just set here, the only possible
2509              problem is that memory map has changed during running
2510              program, but it's not going to work anyway with current
2511              gdb.  */
2512           struct mem_region *mr 
2513             = lookup_mem_region (bl->target_info.placed_address);
2514           
2515           if (mr)
2516             {
2517               if (automatic_hardware_breakpoints)
2518                 {
2519                   enum bp_loc_type new_type;
2520                   
2521                   if (mr->attrib.mode != MEM_RW)
2522                     new_type = bp_loc_hardware_breakpoint;
2523                   else 
2524                     new_type = bp_loc_software_breakpoint;
2525                   
2526                   if (new_type != bl->loc_type)
2527                     {
2528                       static int said = 0;
2529
2530                       bl->loc_type = new_type;
2531                       if (!said)
2532                         {
2533                           fprintf_filtered (gdb_stdout,
2534                                             _("Note: automatically using "
2535                                               "hardware breakpoints for "
2536                                               "read-only addresses.\n"));
2537                           said = 1;
2538                         }
2539                     }
2540                 }
2541               else if (bl->loc_type == bp_loc_software_breakpoint
2542                        && mr->attrib.mode != MEM_RW)        
2543                 warning (_("cannot set software breakpoint "
2544                            "at readonly address %s"),
2545                          paddress (bl->gdbarch, bl->address));
2546             }
2547         }
2548         
2549       /* First check to see if we have to handle an overlay.  */
2550       if (overlay_debugging == ovly_off
2551           || bl->section == NULL
2552           || !(section_is_overlay (bl->section)))
2553         {
2554           /* No overlay handling: just set the breakpoint.  */
2555           TRY_CATCH (e, RETURN_MASK_ALL)
2556             {
2557               int val;
2558
2559               val = bl->owner->ops->insert_location (bl);
2560               if (val)
2561                 bp_err = GENERIC_ERROR;
2562             }
2563           if (e.reason < 0)
2564             {
2565               bp_err = e.error;
2566               bp_err_message = e.message;
2567             }
2568         }
2569       else
2570         {
2571           /* This breakpoint is in an overlay section.
2572              Shall we set a breakpoint at the LMA?  */
2573           if (!overlay_events_enabled)
2574             {
2575               /* Yes -- overlay event support is not active, 
2576                  so we must try to set a breakpoint at the LMA.
2577                  This will not work for a hardware breakpoint.  */
2578               if (bl->loc_type == bp_loc_hardware_breakpoint)
2579                 warning (_("hardware breakpoint %d not supported in overlay!"),
2580                          bl->owner->number);
2581               else
2582                 {
2583                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2584                                                              bl->section);
2585                   /* Set a software (trap) breakpoint at the LMA.  */
2586                   bl->overlay_target_info = bl->target_info;
2587                   bl->overlay_target_info.placed_address = addr;
2588
2589                   /* No overlay handling: just set the breakpoint.  */
2590                   TRY_CATCH (e, RETURN_MASK_ALL)
2591                     {
2592                       int val;
2593
2594                       val = target_insert_breakpoint (bl->gdbarch,
2595                                                       &bl->overlay_target_info);
2596                       if (val)
2597                         bp_err = GENERIC_ERROR;
2598                     }
2599                   if (e.reason < 0)
2600                     {
2601                       bp_err = e.error;
2602                       bp_err_message = e.message;
2603                     }
2604
2605                   if (bp_err != GDB_NO_ERROR)
2606                     fprintf_unfiltered (tmp_error_stream,
2607                                         "Overlay breakpoint %d "
2608                                         "failed: in ROM?\n",
2609                                         bl->owner->number);
2610                 }
2611             }
2612           /* Shall we set a breakpoint at the VMA? */
2613           if (section_is_mapped (bl->section))
2614             {
2615               /* Yes.  This overlay section is mapped into memory.  */
2616               TRY_CATCH (e, RETURN_MASK_ALL)
2617                 {
2618                   int val;
2619
2620                   val = bl->owner->ops->insert_location (bl);
2621                   if (val)
2622                     bp_err = GENERIC_ERROR;
2623                 }
2624               if (e.reason < 0)
2625                 {
2626                   bp_err = e.error;
2627                   bp_err_message = e.message;
2628                 }
2629             }
2630           else
2631             {
2632               /* No.  This breakpoint will not be inserted.  
2633                  No error, but do not mark the bp as 'inserted'.  */
2634               return 0;
2635             }
2636         }
2637
2638       if (bp_err != GDB_NO_ERROR)
2639         {
2640           /* Can't set the breakpoint.  */
2641
2642           /* In some cases, we might not be able to insert a
2643              breakpoint in a shared library that has already been
2644              removed, but we have not yet processed the shlib unload
2645              event.  Unfortunately, some targets that implement
2646              breakpoint insertion themselves can't tell why the
2647              breakpoint insertion failed (e.g., the remote target
2648              doesn't define error codes), so we must treat generic
2649              errors as memory errors.  */
2650           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2651               && bl->loc_type == bp_loc_software_breakpoint
2652               && (solib_name_from_address (bl->pspace, bl->address)
2653                   || userloaded_objfile_contains_address_p (bl->pspace,
2654                                                             bl->address)))
2655             {
2656               /* See also: disable_breakpoints_in_shlibs.  */
2657               bl->shlib_disabled = 1;
2658               observer_notify_breakpoint_modified (bl->owner);
2659               if (!*disabled_breaks)
2660                 {
2661                   fprintf_unfiltered (tmp_error_stream, 
2662                                       "Cannot insert breakpoint %d.\n", 
2663                                       bl->owner->number);
2664                   fprintf_unfiltered (tmp_error_stream, 
2665                                       "Temporarily disabling shared "
2666                                       "library breakpoints:\n");
2667                 }
2668               *disabled_breaks = 1;
2669               fprintf_unfiltered (tmp_error_stream,
2670                                   "breakpoint #%d\n", bl->owner->number);
2671               return 0;
2672             }
2673           else
2674             {
2675               if (bl->loc_type == bp_loc_hardware_breakpoint)
2676                 {
2677                   *hw_breakpoint_error = 1;
2678                   *hw_bp_error_explained_already = bp_err_message != NULL;
2679                   fprintf_unfiltered (tmp_error_stream,
2680                                       "Cannot insert hardware breakpoint %d%s",
2681                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2682                   if (bp_err_message != NULL)
2683                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2684                 }
2685               else
2686                 {
2687                   if (bp_err_message == NULL)
2688                     {
2689                       char *message
2690                         = memory_error_message (TARGET_XFER_E_IO,
2691                                                 bl->gdbarch, bl->address);
2692                       struct cleanup *old_chain = make_cleanup (xfree, message);
2693
2694                       fprintf_unfiltered (tmp_error_stream,
2695                                           "Cannot insert breakpoint %d.\n"
2696                                           "%s\n",
2697                                           bl->owner->number, message);
2698                       do_cleanups (old_chain);
2699                     }
2700                   else
2701                     {
2702                       fprintf_unfiltered (tmp_error_stream,
2703                                           "Cannot insert breakpoint %d: %s\n",
2704                                           bl->owner->number,
2705                                           bp_err_message);
2706                     }
2707                 }
2708               return 1;
2709
2710             }
2711         }
2712       else
2713         bl->inserted = 1;
2714
2715       return 0;
2716     }
2717
2718   else if (bl->loc_type == bp_loc_hardware_watchpoint
2719            /* NOTE drow/2003-09-08: This state only exists for removing
2720               watchpoints.  It's not clear that it's necessary...  */
2721            && bl->owner->disposition != disp_del_at_next_stop)
2722     {
2723       int val;
2724
2725       gdb_assert (bl->owner->ops != NULL
2726                   && bl->owner->ops->insert_location != NULL);
2727
2728       val = bl->owner->ops->insert_location (bl);
2729
2730       /* If trying to set a read-watchpoint, and it turns out it's not
2731          supported, try emulating one with an access watchpoint.  */
2732       if (val == 1 && bl->watchpoint_type == hw_read)
2733         {
2734           struct bp_location *loc, **loc_temp;
2735
2736           /* But don't try to insert it, if there's already another
2737              hw_access location that would be considered a duplicate
2738              of this one.  */
2739           ALL_BP_LOCATIONS (loc, loc_temp)
2740             if (loc != bl
2741                 && loc->watchpoint_type == hw_access
2742                 && watchpoint_locations_match (bl, loc))
2743               {
2744                 bl->duplicate = 1;
2745                 bl->inserted = 1;
2746                 bl->target_info = loc->target_info;
2747                 bl->watchpoint_type = hw_access;
2748                 val = 0;
2749                 break;
2750               }
2751
2752           if (val == 1)
2753             {
2754               bl->watchpoint_type = hw_access;
2755               val = bl->owner->ops->insert_location (bl);
2756
2757               if (val)
2758                 /* Back to the original value.  */
2759                 bl->watchpoint_type = hw_read;
2760             }
2761         }
2762
2763       bl->inserted = (val == 0);
2764     }
2765
2766   else if (bl->owner->type == bp_catchpoint)
2767     {
2768       int val;
2769
2770       gdb_assert (bl->owner->ops != NULL
2771                   && bl->owner->ops->insert_location != NULL);
2772
2773       val = bl->owner->ops->insert_location (bl);
2774       if (val)
2775         {
2776           bl->owner->enable_state = bp_disabled;
2777
2778           if (val == 1)
2779             warning (_("\
2780 Error inserting catchpoint %d: Your system does not support this type\n\
2781 of catchpoint."), bl->owner->number);
2782           else
2783             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2784         }
2785
2786       bl->inserted = (val == 0);
2787
2788       /* We've already printed an error message if there was a problem
2789          inserting this catchpoint, and we've disabled the catchpoint,
2790          so just return success.  */
2791       return 0;
2792     }
2793
2794   return 0;
2795 }
2796
2797 /* This function is called when program space PSPACE is about to be
2798    deleted.  It takes care of updating breakpoints to not reference
2799    PSPACE anymore.  */
2800
2801 void
2802 breakpoint_program_space_exit (struct program_space *pspace)
2803 {
2804   struct breakpoint *b, *b_temp;
2805   struct bp_location *loc, **loc_temp;
2806
2807   /* Remove any breakpoint that was set through this program space.  */
2808   ALL_BREAKPOINTS_SAFE (b, b_temp)
2809     {
2810       if (b->pspace == pspace)
2811         delete_breakpoint (b);
2812     }
2813
2814   /* Breakpoints set through other program spaces could have locations
2815      bound to PSPACE as well.  Remove those.  */
2816   ALL_BP_LOCATIONS (loc, loc_temp)
2817     {
2818       struct bp_location *tmp;
2819
2820       if (loc->pspace == pspace)
2821         {
2822           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2823           if (loc->owner->loc == loc)
2824             loc->owner->loc = loc->next;
2825           else
2826             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2827               if (tmp->next == loc)
2828                 {
2829                   tmp->next = loc->next;
2830                   break;
2831                 }
2832         }
2833     }
2834
2835   /* Now update the global location list to permanently delete the
2836      removed locations above.  */
2837   update_global_location_list (0);
2838 }
2839
2840 /* Make sure all breakpoints are inserted in inferior.
2841    Throws exception on any error.
2842    A breakpoint that is already inserted won't be inserted
2843    again, so calling this function twice is safe.  */
2844 void
2845 insert_breakpoints (void)
2846 {
2847   struct breakpoint *bpt;
2848
2849   ALL_BREAKPOINTS (bpt)
2850     if (is_hardware_watchpoint (bpt))
2851       {
2852         struct watchpoint *w = (struct watchpoint *) bpt;
2853
2854         update_watchpoint (w, 0 /* don't reparse.  */);
2855       }
2856
2857   update_global_location_list (1);
2858
2859   /* update_global_location_list does not insert breakpoints when
2860      always_inserted_mode is not enabled.  Explicitly insert them
2861      now.  */
2862   if (!breakpoints_always_inserted_mode ())
2863     insert_breakpoint_locations ();
2864 }
2865
2866 /* Invoke CALLBACK for each of bp_location.  */
2867
2868 void
2869 iterate_over_bp_locations (walk_bp_location_callback callback)
2870 {
2871   struct bp_location *loc, **loc_tmp;
2872
2873   ALL_BP_LOCATIONS (loc, loc_tmp)
2874     {
2875       callback (loc, NULL);
2876     }
2877 }
2878
2879 /* This is used when we need to synch breakpoint conditions between GDB and the
2880    target.  It is the case with deleting and disabling of breakpoints when using
2881    always-inserted mode.  */
2882
2883 static void
2884 update_inserted_breakpoint_locations (void)
2885 {
2886   struct bp_location *bl, **blp_tmp;
2887   int error_flag = 0;
2888   int val = 0;
2889   int disabled_breaks = 0;
2890   int hw_breakpoint_error = 0;
2891   int hw_bp_details_reported = 0;
2892
2893   struct ui_file *tmp_error_stream = mem_fileopen ();
2894   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2895
2896   /* Explicitly mark the warning -- this will only be printed if
2897      there was an error.  */
2898   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2899
2900   save_current_space_and_thread ();
2901
2902   ALL_BP_LOCATIONS (bl, blp_tmp)
2903     {
2904       /* We only want to update software breakpoints and hardware
2905          breakpoints.  */
2906       if (!is_breakpoint (bl->owner))
2907         continue;
2908
2909       /* We only want to update locations that are already inserted
2910          and need updating.  This is to avoid unwanted insertion during
2911          deletion of breakpoints.  */
2912       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2913         continue;
2914
2915       switch_to_program_space_and_thread (bl->pspace);
2916
2917       /* For targets that support global breakpoints, there's no need
2918          to select an inferior to insert breakpoint to.  In fact, even
2919          if we aren't attached to any process yet, we should still
2920          insert breakpoints.  */
2921       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2922           && ptid_equal (inferior_ptid, null_ptid))
2923         continue;
2924
2925       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2926                                     &hw_breakpoint_error, &hw_bp_details_reported);
2927       if (val)
2928         error_flag = val;
2929     }
2930
2931   if (error_flag)
2932     {
2933       target_terminal_ours_for_output ();
2934       error_stream (tmp_error_stream);
2935     }
2936
2937   do_cleanups (cleanups);
2938 }
2939
2940 /* Used when starting or continuing the program.  */
2941
2942 static void
2943 insert_breakpoint_locations (void)
2944 {
2945   struct breakpoint *bpt;
2946   struct bp_location *bl, **blp_tmp;
2947   int error_flag = 0;
2948   int val = 0;
2949   int disabled_breaks = 0;
2950   int hw_breakpoint_error = 0;
2951   int hw_bp_error_explained_already = 0;
2952
2953   struct ui_file *tmp_error_stream = mem_fileopen ();
2954   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2955   
2956   /* Explicitly mark the warning -- this will only be printed if
2957      there was an error.  */
2958   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2959
2960   save_current_space_and_thread ();
2961
2962   ALL_BP_LOCATIONS (bl, blp_tmp)
2963     {
2964       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2965         continue;
2966
2967       /* There is no point inserting thread-specific breakpoints if
2968          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2969          has BL->OWNER always non-NULL.  */
2970       if (bl->owner->thread != -1
2971           && !valid_thread_id (bl->owner->thread))
2972         continue;
2973
2974       switch_to_program_space_and_thread (bl->pspace);
2975
2976       /* For targets that support global breakpoints, there's no need
2977          to select an inferior to insert breakpoint to.  In fact, even
2978          if we aren't attached to any process yet, we should still
2979          insert breakpoints.  */
2980       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2981           && ptid_equal (inferior_ptid, null_ptid))
2982         continue;
2983
2984       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2985                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2986       if (val)
2987         error_flag = val;
2988     }
2989
2990   /* If we failed to insert all locations of a watchpoint, remove
2991      them, as half-inserted watchpoint is of limited use.  */
2992   ALL_BREAKPOINTS (bpt)  
2993     {
2994       int some_failed = 0;
2995       struct bp_location *loc;
2996
2997       if (!is_hardware_watchpoint (bpt))
2998         continue;
2999
3000       if (!breakpoint_enabled (bpt))
3001         continue;
3002
3003       if (bpt->disposition == disp_del_at_next_stop)
3004         continue;
3005       
3006       for (loc = bpt->loc; loc; loc = loc->next)
3007         if (!loc->inserted && should_be_inserted (loc))
3008           {
3009             some_failed = 1;
3010             break;
3011           }
3012       if (some_failed)
3013         {
3014           for (loc = bpt->loc; loc; loc = loc->next)
3015             if (loc->inserted)
3016               remove_breakpoint (loc, mark_uninserted);
3017
3018           hw_breakpoint_error = 1;
3019           fprintf_unfiltered (tmp_error_stream,
3020                               "Could not insert hardware watchpoint %d.\n", 
3021                               bpt->number);
3022           error_flag = -1;
3023         }
3024     }
3025
3026   if (error_flag)
3027     {
3028       /* If a hardware breakpoint or watchpoint was inserted, add a
3029          message about possibly exhausted resources.  */
3030       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3031         {
3032           fprintf_unfiltered (tmp_error_stream, 
3033                               "Could not insert hardware breakpoints:\n\
3034 You may have requested too many hardware breakpoints/watchpoints.\n");
3035         }
3036       target_terminal_ours_for_output ();
3037       error_stream (tmp_error_stream);
3038     }
3039
3040   do_cleanups (cleanups);
3041 }
3042
3043 /* Used when the program stops.
3044    Returns zero if successful, or non-zero if there was a problem
3045    removing a breakpoint location.  */
3046
3047 int
3048 remove_breakpoints (void)
3049 {
3050   struct bp_location *bl, **blp_tmp;
3051   int val = 0;
3052
3053   ALL_BP_LOCATIONS (bl, blp_tmp)
3054   {
3055     if (bl->inserted && !is_tracepoint (bl->owner))
3056       val |= remove_breakpoint (bl, mark_uninserted);
3057   }
3058   return val;
3059 }
3060
3061 /* When a thread exits, remove breakpoints that are related to
3062    that thread.  */
3063
3064 static void
3065 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3066 {
3067   struct breakpoint *b, *b_tmp;
3068
3069   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3070     {
3071       if (b->thread == tp->num && user_breakpoint_p (b))
3072         {
3073           b->disposition = disp_del_at_next_stop;
3074
3075           printf_filtered (_("\
3076 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3077                           b->number, tp->num);
3078
3079           /* Hide it from the user.  */
3080           b->number = 0;
3081        }
3082     }
3083 }
3084
3085 /* Remove breakpoints of process PID.  */
3086
3087 int
3088 remove_breakpoints_pid (int pid)
3089 {
3090   struct bp_location *bl, **blp_tmp;
3091   int val;
3092   struct inferior *inf = find_inferior_pid (pid);
3093
3094   ALL_BP_LOCATIONS (bl, blp_tmp)
3095   {
3096     if (bl->pspace != inf->pspace)
3097       continue;
3098
3099     if (bl->owner->type == bp_dprintf)
3100       continue;
3101
3102     if (bl->inserted)
3103       {
3104         val = remove_breakpoint (bl, mark_uninserted);
3105         if (val != 0)
3106           return val;
3107       }
3108   }
3109   return 0;
3110 }
3111
3112 int
3113 reattach_breakpoints (int pid)
3114 {
3115   struct cleanup *old_chain;
3116   struct bp_location *bl, **blp_tmp;
3117   int val;
3118   struct ui_file *tmp_error_stream;
3119   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3120   struct inferior *inf;
3121   struct thread_info *tp;
3122
3123   tp = any_live_thread_of_process (pid);
3124   if (tp == NULL)
3125     return 1;
3126
3127   inf = find_inferior_pid (pid);
3128   old_chain = save_inferior_ptid ();
3129
3130   inferior_ptid = tp->ptid;
3131
3132   tmp_error_stream = mem_fileopen ();
3133   make_cleanup_ui_file_delete (tmp_error_stream);
3134
3135   ALL_BP_LOCATIONS (bl, blp_tmp)
3136   {
3137     if (bl->pspace != inf->pspace)
3138       continue;
3139
3140     if (bl->inserted)
3141       {
3142         bl->inserted = 0;
3143         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3144         if (val != 0)
3145           {
3146             do_cleanups (old_chain);
3147             return val;
3148           }
3149       }
3150   }
3151   do_cleanups (old_chain);
3152   return 0;
3153 }
3154
3155 static int internal_breakpoint_number = -1;
3156
3157 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3158    If INTERNAL is non-zero, the breakpoint number will be populated
3159    from internal_breakpoint_number and that variable decremented.
3160    Otherwise the breakpoint number will be populated from
3161    breakpoint_count and that value incremented.  Internal breakpoints
3162    do not set the internal var bpnum.  */
3163 static void
3164 set_breakpoint_number (int internal, struct breakpoint *b)
3165 {
3166   if (internal)
3167     b->number = internal_breakpoint_number--;
3168   else
3169     {
3170       set_breakpoint_count (breakpoint_count + 1);
3171       b->number = breakpoint_count;
3172     }
3173 }
3174
3175 static struct breakpoint *
3176 create_internal_breakpoint (struct gdbarch *gdbarch,
3177                             CORE_ADDR address, enum bptype type,
3178                             const struct breakpoint_ops *ops)
3179 {
3180   struct symtab_and_line sal;
3181   struct breakpoint *b;
3182
3183   init_sal (&sal);              /* Initialize to zeroes.  */
3184
3185   sal.pc = address;
3186   sal.section = find_pc_overlay (sal.pc);
3187   sal.pspace = current_program_space;
3188
3189   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3190   b->number = internal_breakpoint_number--;
3191   b->disposition = disp_donttouch;
3192
3193   return b;
3194 }
3195
3196 static const char *const longjmp_names[] =
3197   {
3198     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3199   };
3200 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3201
3202 /* Per-objfile data private to breakpoint.c.  */
3203 struct breakpoint_objfile_data
3204 {
3205   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3206   struct bound_minimal_symbol overlay_msym;
3207
3208   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3209   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3210
3211   /* True if we have looked for longjmp probes.  */
3212   int longjmp_searched;
3213
3214   /* SystemTap probe points for longjmp (if any).  */
3215   VEC (probe_p) *longjmp_probes;
3216
3217   /* Minimal symbol for "std::terminate()" (if any).  */
3218   struct bound_minimal_symbol terminate_msym;
3219
3220   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3221   struct bound_minimal_symbol exception_msym;
3222
3223   /* True if we have looked for exception probes.  */
3224   int exception_searched;
3225
3226   /* SystemTap probe points for unwinding (if any).  */
3227   VEC (probe_p) *exception_probes;
3228 };
3229
3230 static const struct objfile_data *breakpoint_objfile_key;
3231
3232 /* Minimal symbol not found sentinel.  */
3233 static struct minimal_symbol msym_not_found;
3234
3235 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3236
3237 static int
3238 msym_not_found_p (const struct minimal_symbol *msym)
3239 {
3240   return msym == &msym_not_found;
3241 }
3242
3243 /* Return per-objfile data needed by breakpoint.c.
3244    Allocate the data if necessary.  */
3245
3246 static struct breakpoint_objfile_data *
3247 get_breakpoint_objfile_data (struct objfile *objfile)
3248 {
3249   struct breakpoint_objfile_data *bp_objfile_data;
3250
3251   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3252   if (bp_objfile_data == NULL)
3253     {
3254       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3255                                        sizeof (*bp_objfile_data));
3256
3257       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3258       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3259     }
3260   return bp_objfile_data;
3261 }
3262
3263 static void
3264 free_breakpoint_probes (struct objfile *obj, void *data)
3265 {
3266   struct breakpoint_objfile_data *bp_objfile_data = data;
3267
3268   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3269   VEC_free (probe_p, bp_objfile_data->exception_probes);
3270 }
3271
3272 static void
3273 create_overlay_event_breakpoint (void)
3274 {
3275   struct objfile *objfile;
3276   const char *const func_name = "_ovly_debug_event";
3277
3278   ALL_OBJFILES (objfile)
3279     {
3280       struct breakpoint *b;
3281       struct breakpoint_objfile_data *bp_objfile_data;
3282       CORE_ADDR addr;
3283
3284       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3285
3286       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3287         continue;
3288
3289       if (bp_objfile_data->overlay_msym.minsym == NULL)
3290         {
3291           struct bound_minimal_symbol m;
3292
3293           m = lookup_minimal_symbol_text (func_name, objfile);
3294           if (m.minsym == NULL)
3295             {
3296               /* Avoid future lookups in this objfile.  */
3297               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3298               continue;
3299             }
3300           bp_objfile_data->overlay_msym = m;
3301         }
3302
3303       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3304       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3305                                       bp_overlay_event,
3306                                       &internal_breakpoint_ops);
3307       b->addr_string = xstrdup (func_name);
3308
3309       if (overlay_debugging == ovly_auto)
3310         {
3311           b->enable_state = bp_enabled;
3312           overlay_events_enabled = 1;
3313         }
3314       else
3315        {
3316          b->enable_state = bp_disabled;
3317          overlay_events_enabled = 0;
3318        }
3319     }
3320   update_global_location_list (1);
3321 }
3322
3323 static void
3324 create_longjmp_master_breakpoint (void)
3325 {
3326   struct program_space *pspace;
3327   struct cleanup *old_chain;
3328
3329   old_chain = save_current_program_space ();
3330
3331   ALL_PSPACES (pspace)
3332   {
3333     struct objfile *objfile;
3334
3335     set_current_program_space (pspace);
3336
3337     ALL_OBJFILES (objfile)
3338     {
3339       int i;
3340       struct gdbarch *gdbarch;
3341       struct breakpoint_objfile_data *bp_objfile_data;
3342
3343       gdbarch = get_objfile_arch (objfile);
3344
3345       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3346
3347       if (!bp_objfile_data->longjmp_searched)
3348         {
3349           VEC (probe_p) *ret;
3350
3351           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3352           if (ret != NULL)
3353             {
3354               /* We are only interested in checking one element.  */
3355               struct probe *p = VEC_index (probe_p, ret, 0);
3356
3357               if (!can_evaluate_probe_arguments (p))
3358                 {
3359                   /* We cannot use the probe interface here, because it does
3360                      not know how to evaluate arguments.  */
3361                   VEC_free (probe_p, ret);
3362                   ret = NULL;
3363                 }
3364             }
3365           bp_objfile_data->longjmp_probes = ret;
3366           bp_objfile_data->longjmp_searched = 1;
3367         }
3368
3369       if (bp_objfile_data->longjmp_probes != NULL)
3370         {
3371           int i;
3372           struct probe *probe;
3373           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3374
3375           for (i = 0;
3376                VEC_iterate (probe_p,
3377                             bp_objfile_data->longjmp_probes,
3378                             i, probe);
3379                ++i)
3380             {
3381               struct breakpoint *b;
3382
3383               b = create_internal_breakpoint (gdbarch,
3384                                               get_probe_address (probe,
3385                                                                  objfile),
3386                                               bp_longjmp_master,
3387                                               &internal_breakpoint_ops);
3388               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3389               b->enable_state = bp_disabled;
3390             }
3391
3392           continue;
3393         }
3394
3395       if (!gdbarch_get_longjmp_target_p (gdbarch))
3396         continue;
3397
3398       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3399         {
3400           struct breakpoint *b;
3401           const char *func_name;
3402           CORE_ADDR addr;
3403
3404           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3405             continue;
3406
3407           func_name = longjmp_names[i];
3408           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3409             {
3410               struct bound_minimal_symbol m;
3411
3412               m = lookup_minimal_symbol_text (func_name, objfile);
3413               if (m.minsym == NULL)
3414                 {
3415                   /* Prevent future lookups in this objfile.  */
3416                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3417                   continue;
3418                 }
3419               bp_objfile_data->longjmp_msym[i] = m;
3420             }
3421
3422           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3423           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3424                                           &internal_breakpoint_ops);
3425           b->addr_string = xstrdup (func_name);
3426           b->enable_state = bp_disabled;
3427         }
3428     }
3429   }
3430   update_global_location_list (1);
3431
3432   do_cleanups (old_chain);
3433 }
3434
3435 /* Create a master std::terminate breakpoint.  */
3436 static void
3437 create_std_terminate_master_breakpoint (void)
3438 {
3439   struct program_space *pspace;
3440   struct cleanup *old_chain;
3441   const char *const func_name = "std::terminate()";
3442
3443   old_chain = save_current_program_space ();
3444
3445   ALL_PSPACES (pspace)
3446   {
3447     struct objfile *objfile;
3448     CORE_ADDR addr;
3449
3450     set_current_program_space (pspace);
3451
3452     ALL_OBJFILES (objfile)
3453     {
3454       struct breakpoint *b;
3455       struct breakpoint_objfile_data *bp_objfile_data;
3456
3457       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3458
3459       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3460         continue;
3461
3462       if (bp_objfile_data->terminate_msym.minsym == NULL)
3463         {
3464           struct bound_minimal_symbol m;
3465
3466           m = lookup_minimal_symbol (func_name, NULL, objfile);
3467           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3468                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3469             {
3470               /* Prevent future lookups in this objfile.  */
3471               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3472               continue;
3473             }
3474           bp_objfile_data->terminate_msym = m;
3475         }
3476
3477       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3478       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3479                                       bp_std_terminate_master,
3480                                       &internal_breakpoint_ops);
3481       b->addr_string = xstrdup (func_name);
3482       b->enable_state = bp_disabled;
3483     }
3484   }
3485
3486   update_global_location_list (1);
3487
3488   do_cleanups (old_chain);
3489 }
3490
3491 /* Install a master breakpoint on the unwinder's debug hook.  */
3492
3493 static void
3494 create_exception_master_breakpoint (void)
3495 {
3496   struct objfile *objfile;
3497   const char *const func_name = "_Unwind_DebugHook";
3498
3499   ALL_OBJFILES (objfile)
3500     {
3501       struct breakpoint *b;
3502       struct gdbarch *gdbarch;
3503       struct breakpoint_objfile_data *bp_objfile_data;
3504       CORE_ADDR addr;
3505
3506       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3507
3508       /* We prefer the SystemTap probe point if it exists.  */
3509       if (!bp_objfile_data->exception_searched)
3510         {
3511           VEC (probe_p) *ret;
3512
3513           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3514
3515           if (ret != NULL)
3516             {
3517               /* We are only interested in checking one element.  */
3518               struct probe *p = VEC_index (probe_p, ret, 0);
3519
3520               if (!can_evaluate_probe_arguments (p))
3521                 {
3522                   /* We cannot use the probe interface here, because it does
3523                      not know how to evaluate arguments.  */
3524                   VEC_free (probe_p, ret);
3525                   ret = NULL;
3526                 }
3527             }
3528           bp_objfile_data->exception_probes = ret;
3529           bp_objfile_data->exception_searched = 1;
3530         }
3531
3532       if (bp_objfile_data->exception_probes != NULL)
3533         {
3534           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3535           int i;
3536           struct probe *probe;
3537
3538           for (i = 0;
3539                VEC_iterate (probe_p,
3540                             bp_objfile_data->exception_probes,
3541                             i, probe);
3542                ++i)
3543             {
3544               struct breakpoint *b;
3545
3546               b = create_internal_breakpoint (gdbarch,
3547                                               get_probe_address (probe,
3548                                                                  objfile),
3549                                               bp_exception_master,
3550                                               &internal_breakpoint_ops);
3551               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3552               b->enable_state = bp_disabled;
3553             }
3554
3555           continue;
3556         }
3557
3558       /* Otherwise, try the hook function.  */
3559
3560       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3561         continue;
3562
3563       gdbarch = get_objfile_arch (objfile);
3564
3565       if (bp_objfile_data->exception_msym.minsym == NULL)
3566         {
3567           struct bound_minimal_symbol debug_hook;
3568
3569           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3570           if (debug_hook.minsym == NULL)
3571             {
3572               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3573               continue;
3574             }
3575
3576           bp_objfile_data->exception_msym = debug_hook;
3577         }
3578
3579       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3580       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3581                                                  &current_target);
3582       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3583                                       &internal_breakpoint_ops);
3584       b->addr_string = xstrdup (func_name);
3585       b->enable_state = bp_disabled;
3586     }
3587
3588   update_global_location_list (1);
3589 }
3590
3591 void
3592 update_breakpoints_after_exec (void)
3593 {
3594   struct breakpoint *b, *b_tmp;
3595   struct bp_location *bploc, **bplocp_tmp;
3596
3597   /* We're about to delete breakpoints from GDB's lists.  If the
3598      INSERTED flag is true, GDB will try to lift the breakpoints by
3599      writing the breakpoints' "shadow contents" back into memory.  The
3600      "shadow contents" are NOT valid after an exec, so GDB should not
3601      do that.  Instead, the target is responsible from marking
3602      breakpoints out as soon as it detects an exec.  We don't do that
3603      here instead, because there may be other attempts to delete
3604      breakpoints after detecting an exec and before reaching here.  */
3605   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3606     if (bploc->pspace == current_program_space)
3607       gdb_assert (!bploc->inserted);
3608
3609   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3610   {
3611     if (b->pspace != current_program_space)
3612       continue;
3613
3614     /* Solib breakpoints must be explicitly reset after an exec().  */
3615     if (b->type == bp_shlib_event)
3616       {
3617         delete_breakpoint (b);
3618         continue;
3619       }
3620
3621     /* JIT breakpoints must be explicitly reset after an exec().  */
3622     if (b->type == bp_jit_event)
3623       {
3624         delete_breakpoint (b);
3625         continue;
3626       }
3627
3628     /* Thread event breakpoints must be set anew after an exec(),
3629        as must overlay event and longjmp master breakpoints.  */
3630     if (b->type == bp_thread_event || b->type == bp_overlay_event
3631         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3632         || b->type == bp_exception_master)
3633       {
3634         delete_breakpoint (b);
3635         continue;
3636       }
3637
3638     /* Step-resume breakpoints are meaningless after an exec().  */
3639     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3640       {
3641         delete_breakpoint (b);
3642         continue;
3643       }
3644
3645     /* Longjmp and longjmp-resume breakpoints are also meaningless
3646        after an exec.  */
3647     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3648         || b->type == bp_longjmp_call_dummy
3649         || b->type == bp_exception || b->type == bp_exception_resume)
3650       {
3651         delete_breakpoint (b);
3652         continue;
3653       }
3654
3655     if (b->type == bp_catchpoint)
3656       {
3657         /* For now, none of the bp_catchpoint breakpoints need to
3658            do anything at this point.  In the future, if some of
3659            the catchpoints need to something, we will need to add
3660            a new method, and call this method from here.  */
3661         continue;
3662       }
3663
3664     /* bp_finish is a special case.  The only way we ought to be able
3665        to see one of these when an exec() has happened, is if the user
3666        caught a vfork, and then said "finish".  Ordinarily a finish just
3667        carries them to the call-site of the current callee, by setting
3668        a temporary bp there and resuming.  But in this case, the finish
3669        will carry them entirely through the vfork & exec.
3670
3671        We don't want to allow a bp_finish to remain inserted now.  But
3672        we can't safely delete it, 'cause finish_command has a handle to
3673        the bp on a bpstat, and will later want to delete it.  There's a
3674        chance (and I've seen it happen) that if we delete the bp_finish
3675        here, that its storage will get reused by the time finish_command
3676        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3677        We really must allow finish_command to delete a bp_finish.
3678
3679        In the absence of a general solution for the "how do we know
3680        it's safe to delete something others may have handles to?"
3681        problem, what we'll do here is just uninsert the bp_finish, and
3682        let finish_command delete it.
3683
3684        (We know the bp_finish is "doomed" in the sense that it's
3685        momentary, and will be deleted as soon as finish_command sees
3686        the inferior stopped.  So it doesn't matter that the bp's
3687        address is probably bogus in the new a.out, unlike e.g., the
3688        solib breakpoints.)  */
3689
3690     if (b->type == bp_finish)
3691       {
3692         continue;
3693       }
3694
3695     /* Without a symbolic address, we have little hope of the
3696        pre-exec() address meaning the same thing in the post-exec()
3697        a.out.  */
3698     if (b->addr_string == NULL)
3699       {
3700         delete_breakpoint (b);
3701         continue;
3702       }
3703   }
3704   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3705   create_overlay_event_breakpoint ();
3706   create_longjmp_master_breakpoint ();
3707   create_std_terminate_master_breakpoint ();
3708   create_exception_master_breakpoint ();
3709 }
3710
3711 int
3712 detach_breakpoints (ptid_t ptid)
3713 {
3714   struct bp_location *bl, **blp_tmp;
3715   int val = 0;
3716   struct cleanup *old_chain = save_inferior_ptid ();
3717   struct inferior *inf = current_inferior ();
3718
3719   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3720     error (_("Cannot detach breakpoints of inferior_ptid"));
3721
3722   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3723   inferior_ptid = ptid;
3724   ALL_BP_LOCATIONS (bl, blp_tmp)
3725   {
3726     if (bl->pspace != inf->pspace)
3727       continue;
3728
3729     /* This function must physically remove breakpoints locations
3730        from the specified ptid, without modifying the breakpoint
3731        package's state.  Locations of type bp_loc_other are only
3732        maintained at GDB side.  So, there is no need to remove
3733        these bp_loc_other locations.  Moreover, removing these
3734        would modify the breakpoint package's state.  */
3735     if (bl->loc_type == bp_loc_other)
3736       continue;
3737
3738     if (bl->inserted)
3739       val |= remove_breakpoint_1 (bl, mark_inserted);
3740   }
3741
3742   /* Detach single-step breakpoints as well.  */
3743   detach_single_step_breakpoints ();
3744
3745   do_cleanups (old_chain);
3746   return val;
3747 }
3748
3749 /* Remove the breakpoint location BL from the current address space.
3750    Note that this is used to detach breakpoints from a child fork.
3751    When we get here, the child isn't in the inferior list, and neither
3752    do we have objects to represent its address space --- we should
3753    *not* look at bl->pspace->aspace here.  */
3754
3755 static int
3756 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3757 {
3758   int val;
3759
3760   /* BL is never in moribund_locations by our callers.  */
3761   gdb_assert (bl->owner != NULL);
3762
3763   if (bl->owner->enable_state == bp_permanent)
3764     /* Permanent breakpoints cannot be inserted or removed.  */
3765     return 0;
3766
3767   /* The type of none suggests that owner is actually deleted.
3768      This should not ever happen.  */
3769   gdb_assert (bl->owner->type != bp_none);
3770
3771   if (bl->loc_type == bp_loc_software_breakpoint
3772       || bl->loc_type == bp_loc_hardware_breakpoint)
3773     {
3774       /* "Normal" instruction breakpoint: either the standard
3775          trap-instruction bp (bp_breakpoint), or a
3776          bp_hardware_breakpoint.  */
3777
3778       /* First check to see if we have to handle an overlay.  */
3779       if (overlay_debugging == ovly_off
3780           || bl->section == NULL
3781           || !(section_is_overlay (bl->section)))
3782         {
3783           /* No overlay handling: just remove the breakpoint.  */
3784
3785           /* If we're trying to uninsert a memory breakpoint that we
3786              know is set in a dynamic object that is marked
3787              shlib_disabled, then either the dynamic object was
3788              removed with "remove-symbol-file" or with
3789              "nosharedlibrary".  In the former case, we don't know
3790              whether another dynamic object might have loaded over the
3791              breakpoint's address -- the user might well let us know
3792              about it next with add-symbol-file (the whole point of
3793              OBJF_USERLOADED is letting the user manually maintain a
3794              list of dynamically loaded objects).  If we have the
3795              breakpoint's shadow memory, that is, this is a software
3796              breakpoint managed by GDB, check whether the breakpoint
3797              is still inserted in memory, to avoid overwriting wrong
3798              code with stale saved shadow contents.  Note that HW
3799              breakpoints don't have shadow memory, as they're
3800              implemented using a mechanism that is not dependent on
3801              being able to modify the target's memory, and as such
3802              they should always be removed.  */
3803           if (bl->shlib_disabled
3804               && bl->target_info.shadow_len != 0
3805               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3806             val = 0;
3807           else
3808             val = bl->owner->ops->remove_location (bl);
3809         }
3810       else
3811         {
3812           /* This breakpoint is in an overlay section.
3813              Did we set a breakpoint at the LMA?  */
3814           if (!overlay_events_enabled)
3815               {
3816                 /* Yes -- overlay event support is not active, so we
3817                    should have set a breakpoint at the LMA.  Remove it.  
3818                 */
3819                 /* Ignore any failures: if the LMA is in ROM, we will
3820                    have already warned when we failed to insert it.  */
3821                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3822                   target_remove_hw_breakpoint (bl->gdbarch,
3823                                                &bl->overlay_target_info);
3824                 else
3825                   target_remove_breakpoint (bl->gdbarch,
3826                                             &bl->overlay_target_info);
3827               }
3828           /* Did we set a breakpoint at the VMA? 
3829              If so, we will have marked the breakpoint 'inserted'.  */
3830           if (bl->inserted)
3831             {
3832               /* Yes -- remove it.  Previously we did not bother to
3833                  remove the breakpoint if the section had been
3834                  unmapped, but let's not rely on that being safe.  We
3835                  don't know what the overlay manager might do.  */
3836
3837               /* However, we should remove *software* breakpoints only
3838                  if the section is still mapped, or else we overwrite
3839                  wrong code with the saved shadow contents.  */
3840               if (bl->loc_type == bp_loc_hardware_breakpoint
3841                   || section_is_mapped (bl->section))
3842                 val = bl->owner->ops->remove_location (bl);
3843               else
3844                 val = 0;
3845             }
3846           else
3847             {
3848               /* No -- not inserted, so no need to remove.  No error.  */
3849               val = 0;
3850             }
3851         }
3852
3853       /* In some cases, we might not be able to remove a breakpoint in
3854          a shared library that has already been removed, but we have
3855          not yet processed the shlib unload event.  Similarly for an
3856          unloaded add-symbol-file object - the user might not yet have
3857          had the chance to remove-symbol-file it.  shlib_disabled will
3858          be set if the library/object has already been removed, but
3859          the breakpoint hasn't been uninserted yet, e.g., after
3860          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3861          always-inserted mode.  */
3862       if (val
3863           && (bl->loc_type == bp_loc_software_breakpoint
3864               && (bl->shlib_disabled
3865                   || solib_name_from_address (bl->pspace, bl->address)
3866                   || userloaded_objfile_contains_address_p (bl->pspace,
3867                                                             bl->address))))
3868         val = 0;
3869
3870       if (val)
3871         return val;
3872       bl->inserted = (is == mark_inserted);
3873     }
3874   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3875     {
3876       gdb_assert (bl->owner->ops != NULL
3877                   && bl->owner->ops->remove_location != NULL);
3878
3879       bl->inserted = (is == mark_inserted);
3880       bl->owner->ops->remove_location (bl);
3881
3882       /* Failure to remove any of the hardware watchpoints comes here.  */
3883       if ((is == mark_uninserted) && (bl->inserted))
3884         warning (_("Could not remove hardware watchpoint %d."),
3885                  bl->owner->number);
3886     }
3887   else if (bl->owner->type == bp_catchpoint
3888            && breakpoint_enabled (bl->owner)
3889            && !bl->duplicate)
3890     {
3891       gdb_assert (bl->owner->ops != NULL
3892                   && bl->owner->ops->remove_location != NULL);
3893
3894       val = bl->owner->ops->remove_location (bl);
3895       if (val)
3896         return val;
3897
3898       bl->inserted = (is == mark_inserted);
3899     }
3900
3901   return 0;
3902 }
3903
3904 static int
3905 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3906 {
3907   int ret;
3908   struct cleanup *old_chain;
3909
3910   /* BL is never in moribund_locations by our callers.  */
3911   gdb_assert (bl->owner != NULL);
3912
3913   if (bl->owner->enable_state == bp_permanent)
3914     /* Permanent breakpoints cannot be inserted or removed.  */
3915     return 0;
3916
3917   /* The type of none suggests that owner is actually deleted.
3918      This should not ever happen.  */
3919   gdb_assert (bl->owner->type != bp_none);
3920
3921   old_chain = save_current_space_and_thread ();
3922
3923   switch_to_program_space_and_thread (bl->pspace);
3924
3925   ret = remove_breakpoint_1 (bl, is);
3926
3927   do_cleanups (old_chain);
3928   return ret;
3929 }
3930
3931 /* Clear the "inserted" flag in all breakpoints.  */
3932
3933 void
3934 mark_breakpoints_out (void)
3935 {
3936   struct bp_location *bl, **blp_tmp;
3937
3938   ALL_BP_LOCATIONS (bl, blp_tmp)
3939     if (bl->pspace == current_program_space)
3940       bl->inserted = 0;
3941 }
3942
3943 /* Clear the "inserted" flag in all breakpoints and delete any
3944    breakpoints which should go away between runs of the program.
3945
3946    Plus other such housekeeping that has to be done for breakpoints
3947    between runs.
3948
3949    Note: this function gets called at the end of a run (by
3950    generic_mourn_inferior) and when a run begins (by
3951    init_wait_for_inferior).  */
3952
3953
3954
3955 void
3956 breakpoint_init_inferior (enum inf_context context)
3957 {
3958   struct breakpoint *b, *b_tmp;
3959   struct bp_location *bl, **blp_tmp;
3960   int ix;
3961   struct program_space *pspace = current_program_space;
3962
3963   /* If breakpoint locations are shared across processes, then there's
3964      nothing to do.  */
3965   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3966     return;
3967
3968   ALL_BP_LOCATIONS (bl, blp_tmp)
3969   {
3970     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3971     if (bl->pspace == pspace
3972         && bl->owner->enable_state != bp_permanent)
3973       bl->inserted = 0;
3974   }
3975
3976   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3977   {
3978     if (b->loc && b->loc->pspace != pspace)
3979       continue;
3980
3981     switch (b->type)
3982       {
3983       case bp_call_dummy:
3984       case bp_longjmp_call_dummy:
3985
3986         /* If the call dummy breakpoint is at the entry point it will
3987            cause problems when the inferior is rerun, so we better get
3988            rid of it.  */
3989
3990       case bp_watchpoint_scope:
3991
3992         /* Also get rid of scope breakpoints.  */
3993
3994       case bp_shlib_event:
3995
3996         /* Also remove solib event breakpoints.  Their addresses may
3997            have changed since the last time we ran the program.
3998            Actually we may now be debugging against different target;
3999            and so the solib backend that installed this breakpoint may
4000            not be used in by the target.  E.g.,
4001
4002            (gdb) file prog-linux
4003            (gdb) run               # native linux target
4004            ...
4005            (gdb) kill
4006            (gdb) file prog-win.exe
4007            (gdb) tar rem :9999     # remote Windows gdbserver.
4008         */
4009
4010       case bp_step_resume:
4011
4012         /* Also remove step-resume breakpoints.  */
4013
4014         delete_breakpoint (b);
4015         break;
4016
4017       case bp_watchpoint:
4018       case bp_hardware_watchpoint:
4019       case bp_read_watchpoint:
4020       case bp_access_watchpoint:
4021         {
4022           struct watchpoint *w = (struct watchpoint *) b;
4023
4024           /* Likewise for watchpoints on local expressions.  */
4025           if (w->exp_valid_block != NULL)
4026             delete_breakpoint (b);
4027           else if (context == inf_starting)
4028             {
4029               /* Reset val field to force reread of starting value in
4030                  insert_breakpoints.  */
4031               if (w->val)
4032                 value_free (w->val);
4033               w->val = NULL;
4034               w->val_valid = 0;
4035           }
4036         }
4037         break;
4038       default:
4039         break;
4040       }
4041   }
4042
4043   /* Get rid of the moribund locations.  */
4044   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4045     decref_bp_location (&bl);
4046   VEC_free (bp_location_p, moribund_locations);
4047 }
4048
4049 /* These functions concern about actual breakpoints inserted in the
4050    target --- to e.g. check if we need to do decr_pc adjustment or if
4051    we need to hop over the bkpt --- so we check for address space
4052    match, not program space.  */
4053
4054 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4055    exists at PC.  It returns ordinary_breakpoint_here if it's an
4056    ordinary breakpoint, or permanent_breakpoint_here if it's a
4057    permanent breakpoint.
4058    - When continuing from a location with an ordinary breakpoint, we
4059      actually single step once before calling insert_breakpoints.
4060    - When continuing from a location with a permanent breakpoint, we
4061      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4062      the target, to advance the PC past the breakpoint.  */
4063
4064 enum breakpoint_here
4065 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4066 {
4067   struct bp_location *bl, **blp_tmp;
4068   int any_breakpoint_here = 0;
4069
4070   ALL_BP_LOCATIONS (bl, blp_tmp)
4071     {
4072       if (bl->loc_type != bp_loc_software_breakpoint
4073           && bl->loc_type != bp_loc_hardware_breakpoint)
4074         continue;
4075
4076       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4077       if ((breakpoint_enabled (bl->owner)
4078            || bl->owner->enable_state == bp_permanent)
4079           && breakpoint_location_address_match (bl, aspace, pc))
4080         {
4081           if (overlay_debugging 
4082               && section_is_overlay (bl->section)
4083               && !section_is_mapped (bl->section))
4084             continue;           /* unmapped overlay -- can't be a match */
4085           else if (bl->owner->enable_state == bp_permanent)
4086             return permanent_breakpoint_here;
4087           else
4088             any_breakpoint_here = 1;
4089         }
4090     }
4091
4092   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4093 }
4094
4095 /* Return true if there's a moribund breakpoint at PC.  */
4096
4097 int
4098 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4099 {
4100   struct bp_location *loc;
4101   int ix;
4102
4103   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4104     if (breakpoint_location_address_match (loc, aspace, pc))
4105       return 1;
4106
4107   return 0;
4108 }
4109
4110 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4111    inserted using regular breakpoint_chain / bp_location array
4112    mechanism.  This does not check for single-step breakpoints, which
4113    are inserted and removed using direct target manipulation.  */
4114
4115 int
4116 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4117                                     CORE_ADDR pc)
4118 {
4119   struct bp_location *bl, **blp_tmp;
4120
4121   ALL_BP_LOCATIONS (bl, blp_tmp)
4122     {
4123       if (bl->loc_type != bp_loc_software_breakpoint
4124           && bl->loc_type != bp_loc_hardware_breakpoint)
4125         continue;
4126
4127       if (bl->inserted
4128           && breakpoint_location_address_match (bl, aspace, pc))
4129         {
4130           if (overlay_debugging 
4131               && section_is_overlay (bl->section)
4132               && !section_is_mapped (bl->section))
4133             continue;           /* unmapped overlay -- can't be a match */
4134           else
4135             return 1;
4136         }
4137     }
4138   return 0;
4139 }
4140
4141 /* Returns non-zero iff there's either regular breakpoint
4142    or a single step breakpoint inserted at PC.  */
4143
4144 int
4145 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4146 {
4147   if (regular_breakpoint_inserted_here_p (aspace, pc))
4148     return 1;
4149
4150   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4151     return 1;
4152
4153   return 0;
4154 }
4155
4156 /* This function returns non-zero iff there is a software breakpoint
4157    inserted at PC.  */
4158
4159 int
4160 software_breakpoint_inserted_here_p (struct address_space *aspace,
4161                                      CORE_ADDR pc)
4162 {
4163   struct bp_location *bl, **blp_tmp;
4164
4165   ALL_BP_LOCATIONS (bl, blp_tmp)
4166     {
4167       if (bl->loc_type != bp_loc_software_breakpoint)
4168         continue;
4169
4170       if (bl->inserted
4171           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4172                                        aspace, pc))
4173         {
4174           if (overlay_debugging 
4175               && section_is_overlay (bl->section)
4176               && !section_is_mapped (bl->section))
4177             continue;           /* unmapped overlay -- can't be a match */
4178           else
4179             return 1;
4180         }
4181     }
4182
4183   /* Also check for software single-step breakpoints.  */
4184   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4185     return 1;
4186
4187   return 0;
4188 }
4189
4190 int
4191 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4192                                        CORE_ADDR addr, ULONGEST len)
4193 {
4194   struct breakpoint *bpt;
4195
4196   ALL_BREAKPOINTS (bpt)
4197     {
4198       struct bp_location *loc;
4199
4200       if (bpt->type != bp_hardware_watchpoint
4201           && bpt->type != bp_access_watchpoint)
4202         continue;
4203
4204       if (!breakpoint_enabled (bpt))
4205         continue;
4206
4207       for (loc = bpt->loc; loc; loc = loc->next)
4208         if (loc->pspace->aspace == aspace && loc->inserted)
4209           {
4210             CORE_ADDR l, h;
4211
4212             /* Check for intersection.  */
4213             l = max (loc->address, addr);
4214             h = min (loc->address + loc->length, addr + len);
4215             if (l < h)
4216               return 1;
4217           }
4218     }
4219   return 0;
4220 }
4221
4222 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4223    PC is valid for process/thread PTID.  */
4224
4225 int
4226 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4227                          ptid_t ptid)
4228 {
4229   struct bp_location *bl, **blp_tmp;
4230   /* The thread and task IDs associated to PTID, computed lazily.  */
4231   int thread = -1;
4232   int task = 0;
4233   
4234   ALL_BP_LOCATIONS (bl, blp_tmp)
4235     {
4236       if (bl->loc_type != bp_loc_software_breakpoint
4237           && bl->loc_type != bp_loc_hardware_breakpoint)
4238         continue;
4239
4240       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4241       if (!breakpoint_enabled (bl->owner)
4242           && bl->owner->enable_state != bp_permanent)
4243         continue;
4244
4245       if (!breakpoint_location_address_match (bl, aspace, pc))
4246         continue;
4247
4248       if (bl->owner->thread != -1)
4249         {
4250           /* This is a thread-specific breakpoint.  Check that ptid
4251              matches that thread.  If thread hasn't been computed yet,
4252              it is now time to do so.  */
4253           if (thread == -1)
4254             thread = pid_to_thread_id (ptid);
4255           if (bl->owner->thread != thread)
4256             continue;
4257         }
4258
4259       if (bl->owner->task != 0)
4260         {
4261           /* This is a task-specific breakpoint.  Check that ptid
4262              matches that task.  If task hasn't been computed yet,
4263              it is now time to do so.  */
4264           if (task == 0)
4265             task = ada_get_task_number (ptid);
4266           if (bl->owner->task != task)
4267             continue;
4268         }
4269
4270       if (overlay_debugging 
4271           && section_is_overlay (bl->section)
4272           && !section_is_mapped (bl->section))
4273         continue;           /* unmapped overlay -- can't be a match */
4274
4275       return 1;
4276     }
4277
4278   return 0;
4279 }
4280 \f
4281
4282 /* bpstat stuff.  External routines' interfaces are documented
4283    in breakpoint.h.  */
4284
4285 int
4286 is_catchpoint (struct breakpoint *ep)
4287 {
4288   return (ep->type == bp_catchpoint);
4289 }
4290
4291 /* Frees any storage that is part of a bpstat.  Does not walk the
4292    'next' chain.  */
4293
4294 static void
4295 bpstat_free (bpstat bs)
4296 {
4297   if (bs->old_val != NULL)
4298     value_free (bs->old_val);
4299   decref_counted_command_line (&bs->commands);
4300   decref_bp_location (&bs->bp_location_at);
4301   xfree (bs);
4302 }
4303
4304 /* Clear a bpstat so that it says we are not at any breakpoint.
4305    Also free any storage that is part of a bpstat.  */
4306
4307 void
4308 bpstat_clear (bpstat *bsp)
4309 {
4310   bpstat p;
4311   bpstat q;
4312
4313   if (bsp == 0)
4314     return;
4315   p = *bsp;
4316   while (p != NULL)
4317     {
4318       q = p->next;
4319       bpstat_free (p);
4320       p = q;
4321     }
4322   *bsp = NULL;
4323 }
4324
4325 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4326    is part of the bpstat is copied as well.  */
4327
4328 bpstat
4329 bpstat_copy (bpstat bs)
4330 {
4331   bpstat p = NULL;
4332   bpstat tmp;
4333   bpstat retval = NULL;
4334
4335   if (bs == NULL)
4336     return bs;
4337
4338   for (; bs != NULL; bs = bs->next)
4339     {
4340       tmp = (bpstat) xmalloc (sizeof (*tmp));
4341       memcpy (tmp, bs, sizeof (*tmp));
4342       incref_counted_command_line (tmp->commands);
4343       incref_bp_location (tmp->bp_location_at);
4344       if (bs->old_val != NULL)
4345         {
4346           tmp->old_val = value_copy (bs->old_val);
4347           release_value (tmp->old_val);
4348         }
4349
4350       if (p == NULL)
4351         /* This is the first thing in the chain.  */
4352         retval = tmp;
4353       else
4354         p->next = tmp;
4355       p = tmp;
4356     }
4357   p->next = NULL;
4358   return retval;
4359 }
4360
4361 /* Find the bpstat associated with this breakpoint.  */
4362
4363 bpstat
4364 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4365 {
4366   if (bsp == NULL)
4367     return NULL;
4368
4369   for (; bsp != NULL; bsp = bsp->next)
4370     {
4371       if (bsp->breakpoint_at == breakpoint)
4372         return bsp;
4373     }
4374   return NULL;
4375 }
4376
4377 /* See breakpoint.h.  */
4378
4379 int
4380 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4381 {
4382   for (; bsp != NULL; bsp = bsp->next)
4383     {
4384       if (bsp->breakpoint_at == NULL)
4385         {
4386           /* A moribund location can never explain a signal other than
4387              GDB_SIGNAL_TRAP.  */
4388           if (sig == GDB_SIGNAL_TRAP)
4389             return 1;
4390         }
4391       else
4392         {
4393           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4394                                                         sig))
4395             return 1;
4396         }
4397     }
4398
4399   return 0;
4400 }
4401
4402 /* Put in *NUM the breakpoint number of the first breakpoint we are
4403    stopped at.  *BSP upon return is a bpstat which points to the
4404    remaining breakpoints stopped at (but which is not guaranteed to be
4405    good for anything but further calls to bpstat_num).
4406
4407    Return 0 if passed a bpstat which does not indicate any breakpoints.
4408    Return -1 if stopped at a breakpoint that has been deleted since
4409    we set it.
4410    Return 1 otherwise.  */
4411
4412 int
4413 bpstat_num (bpstat *bsp, int *num)
4414 {
4415   struct breakpoint *b;
4416
4417   if ((*bsp) == NULL)
4418     return 0;                   /* No more breakpoint values */
4419
4420   /* We assume we'll never have several bpstats that correspond to a
4421      single breakpoint -- otherwise, this function might return the
4422      same number more than once and this will look ugly.  */
4423   b = (*bsp)->breakpoint_at;
4424   *bsp = (*bsp)->next;
4425   if (b == NULL)
4426     return -1;                  /* breakpoint that's been deleted since */
4427
4428   *num = b->number;             /* We have its number */
4429   return 1;
4430 }
4431
4432 /* See breakpoint.h.  */
4433
4434 void
4435 bpstat_clear_actions (void)
4436 {
4437   struct thread_info *tp;
4438   bpstat bs;
4439
4440   if (ptid_equal (inferior_ptid, null_ptid))
4441     return;
4442
4443   tp = find_thread_ptid (inferior_ptid);
4444   if (tp == NULL)
4445     return;
4446
4447   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4448     {
4449       decref_counted_command_line (&bs->commands);
4450
4451       if (bs->old_val != NULL)
4452         {
4453           value_free (bs->old_val);
4454           bs->old_val = NULL;
4455         }
4456     }
4457 }
4458
4459 /* Called when a command is about to proceed the inferior.  */
4460
4461 static void
4462 breakpoint_about_to_proceed (void)
4463 {
4464   if (!ptid_equal (inferior_ptid, null_ptid))
4465     {
4466       struct thread_info *tp = inferior_thread ();
4467
4468       /* Allow inferior function calls in breakpoint commands to not
4469          interrupt the command list.  When the call finishes
4470          successfully, the inferior will be standing at the same
4471          breakpoint as if nothing happened.  */
4472       if (tp->control.in_infcall)
4473         return;
4474     }
4475
4476   breakpoint_proceeded = 1;
4477 }
4478
4479 /* Stub for cleaning up our state if we error-out of a breakpoint
4480    command.  */
4481 static void
4482 cleanup_executing_breakpoints (void *ignore)
4483 {
4484   executing_breakpoint_commands = 0;
4485 }
4486
4487 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4488    or its equivalent.  */
4489
4490 static int
4491 command_line_is_silent (struct command_line *cmd)
4492 {
4493   return cmd && (strcmp ("silent", cmd->line) == 0
4494                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4495 }
4496
4497 /* Execute all the commands associated with all the breakpoints at
4498    this location.  Any of these commands could cause the process to
4499    proceed beyond this point, etc.  We look out for such changes by
4500    checking the global "breakpoint_proceeded" after each command.
4501
4502    Returns true if a breakpoint command resumed the inferior.  In that
4503    case, it is the caller's responsibility to recall it again with the
4504    bpstat of the current thread.  */
4505
4506 static int
4507 bpstat_do_actions_1 (bpstat *bsp)
4508 {
4509   bpstat bs;
4510   struct cleanup *old_chain;
4511   int again = 0;
4512
4513   /* Avoid endless recursion if a `source' command is contained
4514      in bs->commands.  */
4515   if (executing_breakpoint_commands)
4516     return 0;
4517
4518   executing_breakpoint_commands = 1;
4519   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4520
4521   prevent_dont_repeat ();
4522
4523   /* This pointer will iterate over the list of bpstat's.  */
4524   bs = *bsp;
4525
4526   breakpoint_proceeded = 0;
4527   for (; bs != NULL; bs = bs->next)
4528     {
4529       struct counted_command_line *ccmd;
4530       struct command_line *cmd;
4531       struct cleanup *this_cmd_tree_chain;
4532
4533       /* Take ownership of the BSP's command tree, if it has one.
4534
4535          The command tree could legitimately contain commands like
4536          'step' and 'next', which call clear_proceed_status, which
4537          frees stop_bpstat's command tree.  To make sure this doesn't
4538          free the tree we're executing out from under us, we need to
4539          take ownership of the tree ourselves.  Since a given bpstat's
4540          commands are only executed once, we don't need to copy it; we
4541          can clear the pointer in the bpstat, and make sure we free
4542          the tree when we're done.  */
4543       ccmd = bs->commands;
4544       bs->commands = NULL;
4545       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4546       cmd = ccmd ? ccmd->commands : NULL;
4547       if (command_line_is_silent (cmd))
4548         {
4549           /* The action has been already done by bpstat_stop_status.  */
4550           cmd = cmd->next;
4551         }
4552
4553       while (cmd != NULL)
4554         {
4555           execute_control_command (cmd);
4556
4557           if (breakpoint_proceeded)
4558             break;
4559           else
4560             cmd = cmd->next;
4561         }
4562
4563       /* We can free this command tree now.  */
4564       do_cleanups (this_cmd_tree_chain);
4565
4566       if (breakpoint_proceeded)
4567         {
4568           if (target_can_async_p ())
4569             /* If we are in async mode, then the target might be still
4570                running, not stopped at any breakpoint, so nothing for
4571                us to do here -- just return to the event loop.  */
4572             ;
4573           else
4574             /* In sync mode, when execute_control_command returns
4575                we're already standing on the next breakpoint.
4576                Breakpoint commands for that stop were not run, since
4577                execute_command does not run breakpoint commands --
4578                only command_line_handler does, but that one is not
4579                involved in execution of breakpoint commands.  So, we
4580                can now execute breakpoint commands.  It should be
4581                noted that making execute_command do bpstat actions is
4582                not an option -- in this case we'll have recursive
4583                invocation of bpstat for each breakpoint with a
4584                command, and can easily blow up GDB stack.  Instead, we
4585                return true, which will trigger the caller to recall us
4586                with the new stop_bpstat.  */
4587             again = 1;
4588           break;
4589         }
4590     }
4591   do_cleanups (old_chain);
4592   return again;
4593 }
4594
4595 void
4596 bpstat_do_actions (void)
4597 {
4598   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4599
4600   /* Do any commands attached to breakpoint we are stopped at.  */
4601   while (!ptid_equal (inferior_ptid, null_ptid)
4602          && target_has_execution
4603          && !is_exited (inferior_ptid)
4604          && !is_executing (inferior_ptid))
4605     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4606        and only return when it is stopped at the next breakpoint, we
4607        keep doing breakpoint actions until it returns false to
4608        indicate the inferior was not resumed.  */
4609     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4610       break;
4611
4612   discard_cleanups (cleanup_if_error);
4613 }
4614
4615 /* Print out the (old or new) value associated with a watchpoint.  */
4616
4617 static void
4618 watchpoint_value_print (struct value *val, struct ui_file *stream)
4619 {
4620   if (val == NULL)
4621     fprintf_unfiltered (stream, _("<unreadable>"));
4622   else
4623     {
4624       struct value_print_options opts;
4625       get_user_print_options (&opts);
4626       value_print (val, stream, &opts);
4627     }
4628 }
4629
4630 /* Generic routine for printing messages indicating why we
4631    stopped.  The behavior of this function depends on the value
4632    'print_it' in the bpstat structure.  Under some circumstances we
4633    may decide not to print anything here and delegate the task to
4634    normal_stop().  */
4635
4636 static enum print_stop_action
4637 print_bp_stop_message (bpstat bs)
4638 {
4639   switch (bs->print_it)
4640     {
4641     case print_it_noop:
4642       /* Nothing should be printed for this bpstat entry.  */
4643       return PRINT_UNKNOWN;
4644       break;
4645
4646     case print_it_done:
4647       /* We still want to print the frame, but we already printed the
4648          relevant messages.  */
4649       return PRINT_SRC_AND_LOC;
4650       break;
4651
4652     case print_it_normal:
4653       {
4654         struct breakpoint *b = bs->breakpoint_at;
4655
4656         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4657            which has since been deleted.  */
4658         if (b == NULL)
4659           return PRINT_UNKNOWN;
4660
4661         /* Normal case.  Call the breakpoint's print_it method.  */
4662         return b->ops->print_it (bs);
4663       }
4664       break;
4665
4666     default:
4667       internal_error (__FILE__, __LINE__,
4668                       _("print_bp_stop_message: unrecognized enum value"));
4669       break;
4670     }
4671 }
4672
4673 /* A helper function that prints a shared library stopped event.  */
4674
4675 static void
4676 print_solib_event (int is_catchpoint)
4677 {
4678   int any_deleted
4679     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4680   int any_added
4681     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4682
4683   if (!is_catchpoint)
4684     {
4685       if (any_added || any_deleted)
4686         ui_out_text (current_uiout,
4687                      _("Stopped due to shared library event:\n"));
4688       else
4689         ui_out_text (current_uiout,
4690                      _("Stopped due to shared library event (no "
4691                        "libraries added or removed)\n"));
4692     }
4693
4694   if (ui_out_is_mi_like_p (current_uiout))
4695     ui_out_field_string (current_uiout, "reason",
4696                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4697
4698   if (any_deleted)
4699     {
4700       struct cleanup *cleanup;
4701       char *name;
4702       int ix;
4703
4704       ui_out_text (current_uiout, _("  Inferior unloaded "));
4705       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4706                                                     "removed");
4707       for (ix = 0;
4708            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4709                         ix, name);
4710            ++ix)
4711         {
4712           if (ix > 0)
4713             ui_out_text (current_uiout, "    ");
4714           ui_out_field_string (current_uiout, "library", name);
4715           ui_out_text (current_uiout, "\n");
4716         }
4717
4718       do_cleanups (cleanup);
4719     }
4720
4721   if (any_added)
4722     {
4723       struct so_list *iter;
4724       int ix;
4725       struct cleanup *cleanup;
4726
4727       ui_out_text (current_uiout, _("  Inferior loaded "));
4728       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4729                                                     "added");
4730       for (ix = 0;
4731            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4732                         ix, iter);
4733            ++ix)
4734         {
4735           if (ix > 0)
4736             ui_out_text (current_uiout, "    ");
4737           ui_out_field_string (current_uiout, "library", iter->so_name);
4738           ui_out_text (current_uiout, "\n");
4739         }
4740
4741       do_cleanups (cleanup);
4742     }
4743 }
4744
4745 /* Print a message indicating what happened.  This is called from
4746    normal_stop().  The input to this routine is the head of the bpstat
4747    list - a list of the eventpoints that caused this stop.  KIND is
4748    the target_waitkind for the stopping event.  This
4749    routine calls the generic print routine for printing a message
4750    about reasons for stopping.  This will print (for example) the
4751    "Breakpoint n," part of the output.  The return value of this
4752    routine is one of:
4753
4754    PRINT_UNKNOWN: Means we printed nothing.
4755    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4756    code to print the location.  An example is 
4757    "Breakpoint 1, " which should be followed by
4758    the location.
4759    PRINT_SRC_ONLY: Means we printed something, but there is no need
4760    to also print the location part of the message.
4761    An example is the catch/throw messages, which
4762    don't require a location appended to the end.
4763    PRINT_NOTHING: We have done some printing and we don't need any 
4764    further info to be printed.  */
4765
4766 enum print_stop_action
4767 bpstat_print (bpstat bs, int kind)
4768 {
4769   int val;
4770
4771   /* Maybe another breakpoint in the chain caused us to stop.
4772      (Currently all watchpoints go on the bpstat whether hit or not.
4773      That probably could (should) be changed, provided care is taken
4774      with respect to bpstat_explains_signal).  */
4775   for (; bs; bs = bs->next)
4776     {
4777       val = print_bp_stop_message (bs);
4778       if (val == PRINT_SRC_ONLY 
4779           || val == PRINT_SRC_AND_LOC 
4780           || val == PRINT_NOTHING)
4781         return val;
4782     }
4783
4784   /* If we had hit a shared library event breakpoint,
4785      print_bp_stop_message would print out this message.  If we hit an
4786      OS-level shared library event, do the same thing.  */
4787   if (kind == TARGET_WAITKIND_LOADED)
4788     {
4789       print_solib_event (0);
4790       return PRINT_NOTHING;
4791     }
4792
4793   /* We reached the end of the chain, or we got a null BS to start
4794      with and nothing was printed.  */
4795   return PRINT_UNKNOWN;
4796 }
4797
4798 /* Evaluate the expression EXP and return 1 if value is zero.
4799    This returns the inverse of the condition because it is called
4800    from catch_errors which returns 0 if an exception happened, and if an
4801    exception happens we want execution to stop.
4802    The argument is a "struct expression *" that has been cast to a
4803    "void *" to make it pass through catch_errors.  */
4804
4805 static int
4806 breakpoint_cond_eval (void *exp)
4807 {
4808   struct value *mark = value_mark ();
4809   int i = !value_true (evaluate_expression ((struct expression *) exp));
4810
4811   value_free_to_mark (mark);
4812   return i;
4813 }
4814
4815 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4816
4817 static bpstat
4818 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4819 {
4820   bpstat bs;
4821
4822   bs = (bpstat) xmalloc (sizeof (*bs));
4823   bs->next = NULL;
4824   **bs_link_pointer = bs;
4825   *bs_link_pointer = &bs->next;
4826   bs->breakpoint_at = bl->owner;
4827   bs->bp_location_at = bl;
4828   incref_bp_location (bl);
4829   /* If the condition is false, etc., don't do the commands.  */
4830   bs->commands = NULL;
4831   bs->old_val = NULL;
4832   bs->print_it = print_it_normal;
4833   return bs;
4834 }
4835 \f
4836 /* The target has stopped with waitstatus WS.  Check if any hardware
4837    watchpoints have triggered, according to the target.  */
4838
4839 int
4840 watchpoints_triggered (struct target_waitstatus *ws)
4841 {
4842   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4843   CORE_ADDR addr;
4844   struct breakpoint *b;
4845
4846   if (!stopped_by_watchpoint)
4847     {
4848       /* We were not stopped by a watchpoint.  Mark all watchpoints
4849          as not triggered.  */
4850       ALL_BREAKPOINTS (b)
4851         if (is_hardware_watchpoint (b))
4852           {
4853             struct watchpoint *w = (struct watchpoint *) b;
4854
4855             w->watchpoint_triggered = watch_triggered_no;
4856           }
4857
4858       return 0;
4859     }
4860
4861   if (!target_stopped_data_address (&current_target, &addr))
4862     {
4863       /* We were stopped by a watchpoint, but we don't know where.
4864          Mark all watchpoints as unknown.  */
4865       ALL_BREAKPOINTS (b)
4866         if (is_hardware_watchpoint (b))
4867           {
4868             struct watchpoint *w = (struct watchpoint *) b;
4869
4870             w->watchpoint_triggered = watch_triggered_unknown;
4871           }
4872
4873       return 1;
4874     }
4875
4876   /* The target could report the data address.  Mark watchpoints
4877      affected by this data address as triggered, and all others as not
4878      triggered.  */
4879
4880   ALL_BREAKPOINTS (b)
4881     if (is_hardware_watchpoint (b))
4882       {
4883         struct watchpoint *w = (struct watchpoint *) b;
4884         struct bp_location *loc;
4885
4886         w->watchpoint_triggered = watch_triggered_no;
4887         for (loc = b->loc; loc; loc = loc->next)
4888           {
4889             if (is_masked_watchpoint (b))
4890               {
4891                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4892                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4893
4894                 if (newaddr == start)
4895                   {
4896                     w->watchpoint_triggered = watch_triggered_yes;
4897                     break;
4898                   }
4899               }
4900             /* Exact match not required.  Within range is sufficient.  */
4901             else if (target_watchpoint_addr_within_range (&current_target,
4902                                                          addr, loc->address,
4903                                                          loc->length))
4904               {
4905                 w->watchpoint_triggered = watch_triggered_yes;
4906                 break;
4907               }
4908           }
4909       }
4910
4911   return 1;
4912 }
4913
4914 /* Possible return values for watchpoint_check (this can't be an enum
4915    because of check_errors).  */
4916 /* The watchpoint has been deleted.  */
4917 #define WP_DELETED 1
4918 /* The value has changed.  */
4919 #define WP_VALUE_CHANGED 2
4920 /* The value has not changed.  */
4921 #define WP_VALUE_NOT_CHANGED 3
4922 /* Ignore this watchpoint, no matter if the value changed or not.  */
4923 #define WP_IGNORE 4
4924
4925 #define BP_TEMPFLAG 1
4926 #define BP_HARDWAREFLAG 2
4927
4928 /* Evaluate watchpoint condition expression and check if its value
4929    changed.
4930
4931    P should be a pointer to struct bpstat, but is defined as a void *
4932    in order for this function to be usable with catch_errors.  */
4933
4934 static int
4935 watchpoint_check (void *p)
4936 {
4937   bpstat bs = (bpstat) p;
4938   struct watchpoint *b;
4939   struct frame_info *fr;
4940   int within_current_scope;
4941
4942   /* BS is built from an existing struct breakpoint.  */
4943   gdb_assert (bs->breakpoint_at != NULL);
4944   b = (struct watchpoint *) bs->breakpoint_at;
4945
4946   /* If this is a local watchpoint, we only want to check if the
4947      watchpoint frame is in scope if the current thread is the thread
4948      that was used to create the watchpoint.  */
4949   if (!watchpoint_in_thread_scope (b))
4950     return WP_IGNORE;
4951
4952   if (b->exp_valid_block == NULL)
4953     within_current_scope = 1;
4954   else
4955     {
4956       struct frame_info *frame = get_current_frame ();
4957       struct gdbarch *frame_arch = get_frame_arch (frame);
4958       CORE_ADDR frame_pc = get_frame_pc (frame);
4959
4960       /* in_function_epilogue_p() returns a non-zero value if we're
4961          still in the function but the stack frame has already been
4962          invalidated.  Since we can't rely on the values of local
4963          variables after the stack has been destroyed, we are treating
4964          the watchpoint in that state as `not changed' without further
4965          checking.  Don't mark watchpoints as changed if the current
4966          frame is in an epilogue - even if they are in some other
4967          frame, our view of the stack is likely to be wrong and
4968          frame_find_by_id could error out.  */
4969       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4970         return WP_IGNORE;
4971
4972       fr = frame_find_by_id (b->watchpoint_frame);
4973       within_current_scope = (fr != NULL);
4974
4975       /* If we've gotten confused in the unwinder, we might have
4976          returned a frame that can't describe this variable.  */
4977       if (within_current_scope)
4978         {
4979           struct symbol *function;
4980
4981           function = get_frame_function (fr);
4982           if (function == NULL
4983               || !contained_in (b->exp_valid_block,
4984                                 SYMBOL_BLOCK_VALUE (function)))
4985             within_current_scope = 0;
4986         }
4987
4988       if (within_current_scope)
4989         /* If we end up stopping, the current frame will get selected
4990            in normal_stop.  So this call to select_frame won't affect
4991            the user.  */
4992         select_frame (fr);
4993     }
4994
4995   if (within_current_scope)
4996     {
4997       /* We use value_{,free_to_}mark because it could be a *long*
4998          time before we return to the command level and call
4999          free_all_values.  We can't call free_all_values because we
5000          might be in the middle of evaluating a function call.  */
5001
5002       int pc = 0;
5003       struct value *mark;
5004       struct value *new_val;
5005
5006       if (is_masked_watchpoint (&b->base))
5007         /* Since we don't know the exact trigger address (from
5008            stopped_data_address), just tell the user we've triggered
5009            a mask watchpoint.  */
5010         return WP_VALUE_CHANGED;
5011
5012       mark = value_mark ();
5013       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5014
5015       /* We use value_equal_contents instead of value_equal because
5016          the latter coerces an array to a pointer, thus comparing just
5017          the address of the array instead of its contents.  This is
5018          not what we want.  */
5019       if ((b->val != NULL) != (new_val != NULL)
5020           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5021         {
5022           if (new_val != NULL)
5023             {
5024               release_value (new_val);
5025               value_free_to_mark (mark);
5026             }
5027           bs->old_val = b->val;
5028           b->val = new_val;
5029           b->val_valid = 1;
5030           return WP_VALUE_CHANGED;
5031         }
5032       else
5033         {
5034           /* Nothing changed.  */
5035           value_free_to_mark (mark);
5036           return WP_VALUE_NOT_CHANGED;
5037         }
5038     }
5039   else
5040     {
5041       struct ui_out *uiout = current_uiout;
5042
5043       /* This seems like the only logical thing to do because
5044          if we temporarily ignored the watchpoint, then when
5045          we reenter the block in which it is valid it contains
5046          garbage (in the case of a function, it may have two
5047          garbage values, one before and one after the prologue).
5048          So we can't even detect the first assignment to it and
5049          watch after that (since the garbage may or may not equal
5050          the first value assigned).  */
5051       /* We print all the stop information in
5052          breakpoint_ops->print_it, but in this case, by the time we
5053          call breakpoint_ops->print_it this bp will be deleted
5054          already.  So we have no choice but print the information
5055          here.  */
5056       if (ui_out_is_mi_like_p (uiout))
5057         ui_out_field_string
5058           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5059       ui_out_text (uiout, "\nWatchpoint ");
5060       ui_out_field_int (uiout, "wpnum", b->base.number);
5061       ui_out_text (uiout,
5062                    " deleted because the program has left the block in\n\
5063 which its expression is valid.\n");     
5064
5065       /* Make sure the watchpoint's commands aren't executed.  */
5066       decref_counted_command_line (&b->base.commands);
5067       watchpoint_del_at_next_stop (b);
5068
5069       return WP_DELETED;
5070     }
5071 }
5072
5073 /* Return true if it looks like target has stopped due to hitting
5074    breakpoint location BL.  This function does not check if we should
5075    stop, only if BL explains the stop.  */
5076
5077 static int
5078 bpstat_check_location (const struct bp_location *bl,
5079                        struct address_space *aspace, CORE_ADDR bp_addr,
5080                        const struct target_waitstatus *ws)
5081 {
5082   struct breakpoint *b = bl->owner;
5083
5084   /* BL is from an existing breakpoint.  */
5085   gdb_assert (b != NULL);
5086
5087   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5088 }
5089
5090 /* Determine if the watched values have actually changed, and we
5091    should stop.  If not, set BS->stop to 0.  */
5092
5093 static void
5094 bpstat_check_watchpoint (bpstat bs)
5095 {
5096   const struct bp_location *bl;
5097   struct watchpoint *b;
5098
5099   /* BS is built for existing struct breakpoint.  */
5100   bl = bs->bp_location_at;
5101   gdb_assert (bl != NULL);
5102   b = (struct watchpoint *) bs->breakpoint_at;
5103   gdb_assert (b != NULL);
5104
5105     {
5106       int must_check_value = 0;
5107       
5108       if (b->base.type == bp_watchpoint)
5109         /* For a software watchpoint, we must always check the
5110            watched value.  */
5111         must_check_value = 1;
5112       else if (b->watchpoint_triggered == watch_triggered_yes)
5113         /* We have a hardware watchpoint (read, write, or access)
5114            and the target earlier reported an address watched by
5115            this watchpoint.  */
5116         must_check_value = 1;
5117       else if (b->watchpoint_triggered == watch_triggered_unknown
5118                && b->base.type == bp_hardware_watchpoint)
5119         /* We were stopped by a hardware watchpoint, but the target could
5120            not report the data address.  We must check the watchpoint's
5121            value.  Access and read watchpoints are out of luck; without
5122            a data address, we can't figure it out.  */
5123         must_check_value = 1;
5124
5125       if (must_check_value)
5126         {
5127           char *message
5128             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5129                           b->base.number);
5130           struct cleanup *cleanups = make_cleanup (xfree, message);
5131           int e = catch_errors (watchpoint_check, bs, message,
5132                                 RETURN_MASK_ALL);
5133           do_cleanups (cleanups);
5134           switch (e)
5135             {
5136             case WP_DELETED:
5137               /* We've already printed what needs to be printed.  */
5138               bs->print_it = print_it_done;
5139               /* Stop.  */
5140               break;
5141             case WP_IGNORE:
5142               bs->print_it = print_it_noop;
5143               bs->stop = 0;
5144               break;
5145             case WP_VALUE_CHANGED:
5146               if (b->base.type == bp_read_watchpoint)
5147                 {
5148                   /* There are two cases to consider here:
5149
5150                      1. We're watching the triggered memory for reads.
5151                      In that case, trust the target, and always report
5152                      the watchpoint hit to the user.  Even though
5153                      reads don't cause value changes, the value may
5154                      have changed since the last time it was read, and
5155                      since we're not trapping writes, we will not see
5156                      those, and as such we should ignore our notion of
5157                      old value.
5158
5159                      2. We're watching the triggered memory for both
5160                      reads and writes.  There are two ways this may
5161                      happen:
5162
5163                      2.1. This is a target that can't break on data
5164                      reads only, but can break on accesses (reads or
5165                      writes), such as e.g., x86.  We detect this case
5166                      at the time we try to insert read watchpoints.
5167
5168                      2.2. Otherwise, the target supports read
5169                      watchpoints, but, the user set an access or write
5170                      watchpoint watching the same memory as this read
5171                      watchpoint.
5172
5173                      If we're watching memory writes as well as reads,
5174                      ignore watchpoint hits when we find that the
5175                      value hasn't changed, as reads don't cause
5176                      changes.  This still gives false positives when
5177                      the program writes the same value to memory as
5178                      what there was already in memory (we will confuse
5179                      it for a read), but it's much better than
5180                      nothing.  */
5181
5182                   int other_write_watchpoint = 0;
5183
5184                   if (bl->watchpoint_type == hw_read)
5185                     {
5186                       struct breakpoint *other_b;
5187
5188                       ALL_BREAKPOINTS (other_b)
5189                         if (other_b->type == bp_hardware_watchpoint
5190                             || other_b->type == bp_access_watchpoint)
5191                           {
5192                             struct watchpoint *other_w =
5193                               (struct watchpoint *) other_b;
5194
5195                             if (other_w->watchpoint_triggered
5196                                 == watch_triggered_yes)
5197                               {
5198                                 other_write_watchpoint = 1;
5199                                 break;
5200                               }
5201                           }
5202                     }
5203
5204                   if (other_write_watchpoint
5205                       || bl->watchpoint_type == hw_access)
5206                     {
5207                       /* We're watching the same memory for writes,
5208                          and the value changed since the last time we
5209                          updated it, so this trap must be for a write.
5210                          Ignore it.  */
5211                       bs->print_it = print_it_noop;
5212                       bs->stop = 0;
5213                     }
5214                 }
5215               break;
5216             case WP_VALUE_NOT_CHANGED:
5217               if (b->base.type == bp_hardware_watchpoint
5218                   || b->base.type == bp_watchpoint)
5219                 {
5220                   /* Don't stop: write watchpoints shouldn't fire if
5221                      the value hasn't changed.  */
5222                   bs->print_it = print_it_noop;
5223                   bs->stop = 0;
5224                 }
5225               /* Stop.  */
5226               break;
5227             default:
5228               /* Can't happen.  */
5229             case 0:
5230               /* Error from catch_errors.  */
5231               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5232               watchpoint_del_at_next_stop (b);
5233               /* We've already printed what needs to be printed.  */
5234               bs->print_it = print_it_done;
5235               break;
5236             }
5237         }
5238       else      /* must_check_value == 0 */
5239         {
5240           /* This is a case where some watchpoint(s) triggered, but
5241              not at the address of this watchpoint, or else no
5242              watchpoint triggered after all.  So don't print
5243              anything for this watchpoint.  */
5244           bs->print_it = print_it_noop;
5245           bs->stop = 0;
5246         }
5247     }
5248 }
5249
5250 /* For breakpoints that are currently marked as telling gdb to stop,
5251    check conditions (condition proper, frame, thread and ignore count)
5252    of breakpoint referred to by BS.  If we should not stop for this
5253    breakpoint, set BS->stop to 0.  */
5254
5255 static void
5256 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5257 {
5258   const struct bp_location *bl;
5259   struct breakpoint *b;
5260   int value_is_zero = 0;
5261   struct expression *cond;
5262
5263   gdb_assert (bs->stop);
5264
5265   /* BS is built for existing struct breakpoint.  */
5266   bl = bs->bp_location_at;
5267   gdb_assert (bl != NULL);
5268   b = bs->breakpoint_at;
5269   gdb_assert (b != NULL);
5270
5271   /* Even if the target evaluated the condition on its end and notified GDB, we
5272      need to do so again since GDB does not know if we stopped due to a
5273      breakpoint or a single step breakpoint.  */
5274
5275   if (frame_id_p (b->frame_id)
5276       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5277     {
5278       bs->stop = 0;
5279       return;
5280     }
5281
5282   /* If this is a thread/task-specific breakpoint, don't waste cpu
5283      evaluating the condition if this isn't the specified
5284      thread/task.  */
5285   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5286       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5287
5288     {
5289       bs->stop = 0;
5290       return;
5291     }
5292
5293   /* Evaluate extension language breakpoints that have a "stop" method
5294      implemented.  */
5295   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5296
5297   if (is_watchpoint (b))
5298     {
5299       struct watchpoint *w = (struct watchpoint *) b;
5300
5301       cond = w->cond_exp;
5302     }
5303   else
5304     cond = bl->cond;
5305
5306   if (cond && b->disposition != disp_del_at_next_stop)
5307     {
5308       int within_current_scope = 1;
5309       struct watchpoint * w;
5310
5311       /* We use value_mark and value_free_to_mark because it could
5312          be a long time before we return to the command level and
5313          call free_all_values.  We can't call free_all_values
5314          because we might be in the middle of evaluating a
5315          function call.  */
5316       struct value *mark = value_mark ();
5317
5318       if (is_watchpoint (b))
5319         w = (struct watchpoint *) b;
5320       else
5321         w = NULL;
5322
5323       /* Need to select the frame, with all that implies so that
5324          the conditions will have the right context.  Because we
5325          use the frame, we will not see an inlined function's
5326          variables when we arrive at a breakpoint at the start
5327          of the inlined function; the current frame will be the
5328          call site.  */
5329       if (w == NULL || w->cond_exp_valid_block == NULL)
5330         select_frame (get_current_frame ());
5331       else
5332         {
5333           struct frame_info *frame;
5334
5335           /* For local watchpoint expressions, which particular
5336              instance of a local is being watched matters, so we
5337              keep track of the frame to evaluate the expression
5338              in.  To evaluate the condition however, it doesn't
5339              really matter which instantiation of the function
5340              where the condition makes sense triggers the
5341              watchpoint.  This allows an expression like "watch
5342              global if q > 10" set in `func', catch writes to
5343              global on all threads that call `func', or catch
5344              writes on all recursive calls of `func' by a single
5345              thread.  We simply always evaluate the condition in
5346              the innermost frame that's executing where it makes
5347              sense to evaluate the condition.  It seems
5348              intuitive.  */
5349           frame = block_innermost_frame (w->cond_exp_valid_block);
5350           if (frame != NULL)
5351             select_frame (frame);
5352           else
5353             within_current_scope = 0;
5354         }
5355       if (within_current_scope)
5356         value_is_zero
5357           = catch_errors (breakpoint_cond_eval, cond,
5358                           "Error in testing breakpoint condition:\n",
5359                           RETURN_MASK_ALL);
5360       else
5361         {
5362           warning (_("Watchpoint condition cannot be tested "
5363                      "in the current scope"));
5364           /* If we failed to set the right context for this
5365              watchpoint, unconditionally report it.  */
5366           value_is_zero = 0;
5367         }
5368       /* FIXME-someday, should give breakpoint #.  */
5369       value_free_to_mark (mark);
5370     }
5371
5372   if (cond && value_is_zero)
5373     {
5374       bs->stop = 0;
5375     }
5376   else if (b->ignore_count > 0)
5377     {
5378       b->ignore_count--;
5379       bs->stop = 0;
5380       /* Increase the hit count even though we don't stop.  */
5381       ++(b->hit_count);
5382       observer_notify_breakpoint_modified (b);
5383     }   
5384 }
5385
5386
5387 /* Get a bpstat associated with having just stopped at address
5388    BP_ADDR in thread PTID.
5389
5390    Determine whether we stopped at a breakpoint, etc, or whether we
5391    don't understand this stop.  Result is a chain of bpstat's such
5392    that:
5393
5394    if we don't understand the stop, the result is a null pointer.
5395
5396    if we understand why we stopped, the result is not null.
5397
5398    Each element of the chain refers to a particular breakpoint or
5399    watchpoint at which we have stopped.  (We may have stopped for
5400    several reasons concurrently.)
5401
5402    Each element of the chain has valid next, breakpoint_at,
5403    commands, FIXME??? fields.  */
5404
5405 bpstat
5406 bpstat_stop_status (struct address_space *aspace,
5407                     CORE_ADDR bp_addr, ptid_t ptid,
5408                     const struct target_waitstatus *ws)
5409 {
5410   struct breakpoint *b = NULL;
5411   struct bp_location *bl;
5412   struct bp_location *loc;
5413   /* First item of allocated bpstat's.  */
5414   bpstat bs_head = NULL, *bs_link = &bs_head;
5415   /* Pointer to the last thing in the chain currently.  */
5416   bpstat bs;
5417   int ix;
5418   int need_remove_insert;
5419   int removed_any;
5420
5421   /* First, build the bpstat chain with locations that explain a
5422      target stop, while being careful to not set the target running,
5423      as that may invalidate locations (in particular watchpoint
5424      locations are recreated).  Resuming will happen here with
5425      breakpoint conditions or watchpoint expressions that include
5426      inferior function calls.  */
5427
5428   ALL_BREAKPOINTS (b)
5429     {
5430       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5431         continue;
5432
5433       for (bl = b->loc; bl != NULL; bl = bl->next)
5434         {
5435           /* For hardware watchpoints, we look only at the first
5436              location.  The watchpoint_check function will work on the
5437              entire expression, not the individual locations.  For
5438              read watchpoints, the watchpoints_triggered function has
5439              checked all locations already.  */
5440           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5441             break;
5442
5443           if (!bl->enabled || bl->shlib_disabled)
5444             continue;
5445
5446           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5447             continue;
5448
5449           /* Come here if it's a watchpoint, or if the break address
5450              matches.  */
5451
5452           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5453                                                    explain stop.  */
5454
5455           /* Assume we stop.  Should we find a watchpoint that is not
5456              actually triggered, or if the condition of the breakpoint
5457              evaluates as false, we'll reset 'stop' to 0.  */
5458           bs->stop = 1;
5459           bs->print = 1;
5460
5461           /* If this is a scope breakpoint, mark the associated
5462              watchpoint as triggered so that we will handle the
5463              out-of-scope event.  We'll get to the watchpoint next
5464              iteration.  */
5465           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5466             {
5467               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5468
5469               w->watchpoint_triggered = watch_triggered_yes;
5470             }
5471         }
5472     }
5473
5474   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5475     {
5476       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5477         {
5478           bs = bpstat_alloc (loc, &bs_link);
5479           /* For hits of moribund locations, we should just proceed.  */
5480           bs->stop = 0;
5481           bs->print = 0;
5482           bs->print_it = print_it_noop;
5483         }
5484     }
5485
5486   /* A bit of special processing for shlib breakpoints.  We need to
5487      process solib loading here, so that the lists of loaded and
5488      unloaded libraries are correct before we handle "catch load" and
5489      "catch unload".  */
5490   for (bs = bs_head; bs != NULL; bs = bs->next)
5491     {
5492       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5493         {
5494           handle_solib_event ();
5495           break;
5496         }
5497     }
5498
5499   /* Now go through the locations that caused the target to stop, and
5500      check whether we're interested in reporting this stop to higher
5501      layers, or whether we should resume the target transparently.  */
5502
5503   removed_any = 0;
5504
5505   for (bs = bs_head; bs != NULL; bs = bs->next)
5506     {
5507       if (!bs->stop)
5508         continue;
5509
5510       b = bs->breakpoint_at;
5511       b->ops->check_status (bs);
5512       if (bs->stop)
5513         {
5514           bpstat_check_breakpoint_conditions (bs, ptid);
5515
5516           if (bs->stop)
5517             {
5518               ++(b->hit_count);
5519               observer_notify_breakpoint_modified (b);
5520
5521               /* We will stop here.  */
5522               if (b->disposition == disp_disable)
5523                 {
5524                   --(b->enable_count);
5525                   if (b->enable_count <= 0
5526                       && b->enable_state != bp_permanent)
5527                     b->enable_state = bp_disabled;
5528                   removed_any = 1;
5529                 }
5530               if (b->silent)
5531                 bs->print = 0;
5532               bs->commands = b->commands;
5533               incref_counted_command_line (bs->commands);
5534               if (command_line_is_silent (bs->commands
5535                                           ? bs->commands->commands : NULL))
5536                 bs->print = 0;
5537
5538               b->ops->after_condition_true (bs);
5539             }
5540
5541         }
5542
5543       /* Print nothing for this entry if we don't stop or don't
5544          print.  */
5545       if (!bs->stop || !bs->print)
5546         bs->print_it = print_it_noop;
5547     }
5548
5549   /* If we aren't stopping, the value of some hardware watchpoint may
5550      not have changed, but the intermediate memory locations we are
5551      watching may have.  Don't bother if we're stopping; this will get
5552      done later.  */
5553   need_remove_insert = 0;
5554   if (! bpstat_causes_stop (bs_head))
5555     for (bs = bs_head; bs != NULL; bs = bs->next)
5556       if (!bs->stop
5557           && bs->breakpoint_at
5558           && is_hardware_watchpoint (bs->breakpoint_at))
5559         {
5560           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5561
5562           update_watchpoint (w, 0 /* don't reparse.  */);
5563           need_remove_insert = 1;
5564         }
5565
5566   if (need_remove_insert)
5567     update_global_location_list (1);
5568   else if (removed_any)
5569     update_global_location_list (0);
5570
5571   return bs_head;
5572 }
5573
5574 static void
5575 handle_jit_event (void)
5576 {
5577   struct frame_info *frame;
5578   struct gdbarch *gdbarch;
5579
5580   /* Switch terminal for any messages produced by
5581      breakpoint_re_set.  */
5582   target_terminal_ours_for_output ();
5583
5584   frame = get_current_frame ();
5585   gdbarch = get_frame_arch (frame);
5586
5587   jit_event_handler (gdbarch);
5588
5589   target_terminal_inferior ();
5590 }
5591
5592 /* Prepare WHAT final decision for infrun.  */
5593
5594 /* Decide what infrun needs to do with this bpstat.  */
5595
5596 struct bpstat_what
5597 bpstat_what (bpstat bs_head)
5598 {
5599   struct bpstat_what retval;
5600   int jit_event = 0;
5601   bpstat bs;
5602
5603   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5604   retval.call_dummy = STOP_NONE;
5605   retval.is_longjmp = 0;
5606
5607   for (bs = bs_head; bs != NULL; bs = bs->next)
5608     {
5609       /* Extract this BS's action.  After processing each BS, we check
5610          if its action overrides all we've seem so far.  */
5611       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5612       enum bptype bptype;
5613
5614       if (bs->breakpoint_at == NULL)
5615         {
5616           /* I suspect this can happen if it was a momentary
5617              breakpoint which has since been deleted.  */
5618           bptype = bp_none;
5619         }
5620       else
5621         bptype = bs->breakpoint_at->type;
5622
5623       switch (bptype)
5624         {
5625         case bp_none:
5626           break;
5627         case bp_breakpoint:
5628         case bp_hardware_breakpoint:
5629         case bp_until:
5630         case bp_finish:
5631         case bp_shlib_event:
5632           if (bs->stop)
5633             {
5634               if (bs->print)
5635                 this_action = BPSTAT_WHAT_STOP_NOISY;
5636               else
5637                 this_action = BPSTAT_WHAT_STOP_SILENT;
5638             }
5639           else
5640             this_action = BPSTAT_WHAT_SINGLE;
5641           break;
5642         case bp_watchpoint:
5643         case bp_hardware_watchpoint:
5644         case bp_read_watchpoint:
5645         case bp_access_watchpoint:
5646           if (bs->stop)
5647             {
5648               if (bs->print)
5649                 this_action = BPSTAT_WHAT_STOP_NOISY;
5650               else
5651                 this_action = BPSTAT_WHAT_STOP_SILENT;
5652             }
5653           else
5654             {
5655               /* There was a watchpoint, but we're not stopping.
5656                  This requires no further action.  */
5657             }
5658           break;
5659         case bp_longjmp:
5660         case bp_longjmp_call_dummy:
5661         case bp_exception:
5662           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5663           retval.is_longjmp = bptype != bp_exception;
5664           break;
5665         case bp_longjmp_resume:
5666         case bp_exception_resume:
5667           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5668           retval.is_longjmp = bptype == bp_longjmp_resume;
5669           break;
5670         case bp_step_resume:
5671           if (bs->stop)
5672             this_action = BPSTAT_WHAT_STEP_RESUME;
5673           else
5674             {
5675               /* It is for the wrong frame.  */
5676               this_action = BPSTAT_WHAT_SINGLE;
5677             }
5678           break;
5679         case bp_hp_step_resume:
5680           if (bs->stop)
5681             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5682           else
5683             {
5684               /* It is for the wrong frame.  */
5685               this_action = BPSTAT_WHAT_SINGLE;
5686             }
5687           break;
5688         case bp_watchpoint_scope:
5689         case bp_thread_event:
5690         case bp_overlay_event:
5691         case bp_longjmp_master:
5692         case bp_std_terminate_master:
5693         case bp_exception_master:
5694           this_action = BPSTAT_WHAT_SINGLE;
5695           break;
5696         case bp_catchpoint:
5697           if (bs->stop)
5698             {
5699               if (bs->print)
5700                 this_action = BPSTAT_WHAT_STOP_NOISY;
5701               else
5702                 this_action = BPSTAT_WHAT_STOP_SILENT;
5703             }
5704           else
5705             {
5706               /* There was a catchpoint, but we're not stopping.
5707                  This requires no further action.  */
5708             }
5709           break;
5710         case bp_jit_event:
5711           jit_event = 1;
5712           this_action = BPSTAT_WHAT_SINGLE;
5713           break;
5714         case bp_call_dummy:
5715           /* Make sure the action is stop (silent or noisy),
5716              so infrun.c pops the dummy frame.  */
5717           retval.call_dummy = STOP_STACK_DUMMY;
5718           this_action = BPSTAT_WHAT_STOP_SILENT;
5719           break;
5720         case bp_std_terminate:
5721           /* Make sure the action is stop (silent or noisy),
5722              so infrun.c pops the dummy frame.  */
5723           retval.call_dummy = STOP_STD_TERMINATE;
5724           this_action = BPSTAT_WHAT_STOP_SILENT;
5725           break;
5726         case bp_tracepoint:
5727         case bp_fast_tracepoint:
5728         case bp_static_tracepoint:
5729           /* Tracepoint hits should not be reported back to GDB, and
5730              if one got through somehow, it should have been filtered
5731              out already.  */
5732           internal_error (__FILE__, __LINE__,
5733                           _("bpstat_what: tracepoint encountered"));
5734           break;
5735         case bp_gnu_ifunc_resolver:
5736           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5737           this_action = BPSTAT_WHAT_SINGLE;
5738           break;
5739         case bp_gnu_ifunc_resolver_return:
5740           /* The breakpoint will be removed, execution will restart from the
5741              PC of the former breakpoint.  */
5742           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5743           break;
5744
5745         case bp_dprintf:
5746           if (bs->stop)
5747             this_action = BPSTAT_WHAT_STOP_SILENT;
5748           else
5749             this_action = BPSTAT_WHAT_SINGLE;
5750           break;
5751
5752         default:
5753           internal_error (__FILE__, __LINE__,
5754                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5755         }
5756
5757       retval.main_action = max (retval.main_action, this_action);
5758     }
5759
5760   /* These operations may affect the bs->breakpoint_at state so they are
5761      delayed after MAIN_ACTION is decided above.  */
5762
5763   if (jit_event)
5764     {
5765       if (debug_infrun)
5766         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5767
5768       handle_jit_event ();
5769     }
5770
5771   for (bs = bs_head; bs != NULL; bs = bs->next)
5772     {
5773       struct breakpoint *b = bs->breakpoint_at;
5774
5775       if (b == NULL)
5776         continue;
5777       switch (b->type)
5778         {
5779         case bp_gnu_ifunc_resolver:
5780           gnu_ifunc_resolver_stop (b);
5781           break;
5782         case bp_gnu_ifunc_resolver_return:
5783           gnu_ifunc_resolver_return_stop (b);
5784           break;
5785         }
5786     }
5787
5788   return retval;
5789 }
5790
5791 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5792    without hardware support).  This isn't related to a specific bpstat,
5793    just to things like whether watchpoints are set.  */
5794
5795 int
5796 bpstat_should_step (void)
5797 {
5798   struct breakpoint *b;
5799
5800   ALL_BREAKPOINTS (b)
5801     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5802       return 1;
5803   return 0;
5804 }
5805
5806 int
5807 bpstat_causes_stop (bpstat bs)
5808 {
5809   for (; bs != NULL; bs = bs->next)
5810     if (bs->stop)
5811       return 1;
5812
5813   return 0;
5814 }
5815
5816 \f
5817
5818 /* Compute a string of spaces suitable to indent the next line
5819    so it starts at the position corresponding to the table column
5820    named COL_NAME in the currently active table of UIOUT.  */
5821
5822 static char *
5823 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5824 {
5825   static char wrap_indent[80];
5826   int i, total_width, width, align;
5827   char *text;
5828
5829   total_width = 0;
5830   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5831     {
5832       if (strcmp (text, col_name) == 0)
5833         {
5834           gdb_assert (total_width < sizeof wrap_indent);
5835           memset (wrap_indent, ' ', total_width);
5836           wrap_indent[total_width] = 0;
5837
5838           return wrap_indent;
5839         }
5840
5841       total_width += width + 1;
5842     }
5843
5844   return NULL;
5845 }
5846
5847 /* Determine if the locations of this breakpoint will have their conditions
5848    evaluated by the target, host or a mix of both.  Returns the following:
5849
5850     "host": Host evals condition.
5851     "host or target": Host or Target evals condition.
5852     "target": Target evals condition.
5853 */
5854
5855 static const char *
5856 bp_condition_evaluator (struct breakpoint *b)
5857 {
5858   struct bp_location *bl;
5859   char host_evals = 0;
5860   char target_evals = 0;
5861
5862   if (!b)
5863     return NULL;
5864
5865   if (!is_breakpoint (b))
5866     return NULL;
5867
5868   if (gdb_evaluates_breakpoint_condition_p ()
5869       || !target_supports_evaluation_of_breakpoint_conditions ())
5870     return condition_evaluation_host;
5871
5872   for (bl = b->loc; bl; bl = bl->next)
5873     {
5874       if (bl->cond_bytecode)
5875         target_evals++;
5876       else
5877         host_evals++;
5878     }
5879
5880   if (host_evals && target_evals)
5881     return condition_evaluation_both;
5882   else if (target_evals)
5883     return condition_evaluation_target;
5884   else
5885     return condition_evaluation_host;
5886 }
5887
5888 /* Determine the breakpoint location's condition evaluator.  This is
5889    similar to bp_condition_evaluator, but for locations.  */
5890
5891 static const char *
5892 bp_location_condition_evaluator (struct bp_location *bl)
5893 {
5894   if (bl && !is_breakpoint (bl->owner))
5895     return NULL;
5896
5897   if (gdb_evaluates_breakpoint_condition_p ()
5898       || !target_supports_evaluation_of_breakpoint_conditions ())
5899     return condition_evaluation_host;
5900
5901   if (bl && bl->cond_bytecode)
5902     return condition_evaluation_target;
5903   else
5904     return condition_evaluation_host;
5905 }
5906
5907 /* Print the LOC location out of the list of B->LOC locations.  */
5908
5909 static void
5910 print_breakpoint_location (struct breakpoint *b,
5911                            struct bp_location *loc)
5912 {
5913   struct ui_out *uiout = current_uiout;
5914   struct cleanup *old_chain = save_current_program_space ();
5915
5916   if (loc != NULL && loc->shlib_disabled)
5917     loc = NULL;
5918
5919   if (loc != NULL)
5920     set_current_program_space (loc->pspace);
5921
5922   if (b->display_canonical)
5923     ui_out_field_string (uiout, "what", b->addr_string);
5924   else if (loc && loc->symtab)
5925     {
5926       struct symbol *sym 
5927         = find_pc_sect_function (loc->address, loc->section);
5928       if (sym)
5929         {
5930           ui_out_text (uiout, "in ");
5931           ui_out_field_string (uiout, "func",
5932                                SYMBOL_PRINT_NAME (sym));
5933           ui_out_text (uiout, " ");
5934           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5935           ui_out_text (uiout, "at ");
5936         }
5937       ui_out_field_string (uiout, "file",
5938                            symtab_to_filename_for_display (loc->symtab));
5939       ui_out_text (uiout, ":");
5940
5941       if (ui_out_is_mi_like_p (uiout))
5942         ui_out_field_string (uiout, "fullname",
5943                              symtab_to_fullname (loc->symtab));
5944       
5945       ui_out_field_int (uiout, "line", loc->line_number);
5946     }
5947   else if (loc)
5948     {
5949       struct ui_file *stb = mem_fileopen ();
5950       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5951
5952       print_address_symbolic (loc->gdbarch, loc->address, stb,
5953                               demangle, "");
5954       ui_out_field_stream (uiout, "at", stb);
5955
5956       do_cleanups (stb_chain);
5957     }
5958   else
5959     ui_out_field_string (uiout, "pending", b->addr_string);
5960
5961   if (loc && is_breakpoint (b)
5962       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5963       && bp_condition_evaluator (b) == condition_evaluation_both)
5964     {
5965       ui_out_text (uiout, " (");
5966       ui_out_field_string (uiout, "evaluated-by",
5967                            bp_location_condition_evaluator (loc));
5968       ui_out_text (uiout, ")");
5969     }
5970
5971   do_cleanups (old_chain);
5972 }
5973
5974 static const char *
5975 bptype_string (enum bptype type)
5976 {
5977   struct ep_type_description
5978     {
5979       enum bptype type;
5980       char *description;
5981     };
5982   static struct ep_type_description bptypes[] =
5983   {
5984     {bp_none, "?deleted?"},
5985     {bp_breakpoint, "breakpoint"},
5986     {bp_hardware_breakpoint, "hw breakpoint"},
5987     {bp_until, "until"},
5988     {bp_finish, "finish"},
5989     {bp_watchpoint, "watchpoint"},
5990     {bp_hardware_watchpoint, "hw watchpoint"},
5991     {bp_read_watchpoint, "read watchpoint"},
5992     {bp_access_watchpoint, "acc watchpoint"},
5993     {bp_longjmp, "longjmp"},
5994     {bp_longjmp_resume, "longjmp resume"},
5995     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5996     {bp_exception, "exception"},
5997     {bp_exception_resume, "exception resume"},
5998     {bp_step_resume, "step resume"},
5999     {bp_hp_step_resume, "high-priority step resume"},
6000     {bp_watchpoint_scope, "watchpoint scope"},
6001     {bp_call_dummy, "call dummy"},
6002     {bp_std_terminate, "std::terminate"},
6003     {bp_shlib_event, "shlib events"},
6004     {bp_thread_event, "thread events"},
6005     {bp_overlay_event, "overlay events"},
6006     {bp_longjmp_master, "longjmp master"},
6007     {bp_std_terminate_master, "std::terminate master"},
6008     {bp_exception_master, "exception master"},
6009     {bp_catchpoint, "catchpoint"},
6010     {bp_tracepoint, "tracepoint"},
6011     {bp_fast_tracepoint, "fast tracepoint"},
6012     {bp_static_tracepoint, "static tracepoint"},
6013     {bp_dprintf, "dprintf"},
6014     {bp_jit_event, "jit events"},
6015     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6016     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6017   };
6018
6019   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6020       || ((int) type != bptypes[(int) type].type))
6021     internal_error (__FILE__, __LINE__,
6022                     _("bptypes table does not describe type #%d."),
6023                     (int) type);
6024
6025   return bptypes[(int) type].description;
6026 }
6027
6028 /* For MI, output a field named 'thread-groups' with a list as the value.
6029    For CLI, prefix the list with the string 'inf'. */
6030
6031 static void
6032 output_thread_groups (struct ui_out *uiout,
6033                       const char *field_name,
6034                       VEC(int) *inf_num,
6035                       int mi_only)
6036 {
6037   struct cleanup *back_to;
6038   int is_mi = ui_out_is_mi_like_p (uiout);
6039   int inf;
6040   int i;
6041
6042   /* For backward compatibility, don't display inferiors in CLI unless
6043      there are several.  Always display them for MI. */
6044   if (!is_mi && mi_only)
6045     return;
6046
6047   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6048
6049   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6050     {
6051       if (is_mi)
6052         {
6053           char mi_group[10];
6054
6055           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6056           ui_out_field_string (uiout, NULL, mi_group);
6057         }
6058       else
6059         {
6060           if (i == 0)
6061             ui_out_text (uiout, " inf ");
6062           else
6063             ui_out_text (uiout, ", ");
6064         
6065           ui_out_text (uiout, plongest (inf));
6066         }
6067     }
6068
6069   do_cleanups (back_to);
6070 }
6071
6072 /* Print B to gdb_stdout.  */
6073
6074 static void
6075 print_one_breakpoint_location (struct breakpoint *b,
6076                                struct bp_location *loc,
6077                                int loc_number,
6078                                struct bp_location **last_loc,
6079                                int allflag)
6080 {
6081   struct command_line *l;
6082   static char bpenables[] = "nynny";
6083
6084   struct ui_out *uiout = current_uiout;
6085   int header_of_multiple = 0;
6086   int part_of_multiple = (loc != NULL);
6087   struct value_print_options opts;
6088
6089   get_user_print_options (&opts);
6090
6091   gdb_assert (!loc || loc_number != 0);
6092   /* See comment in print_one_breakpoint concerning treatment of
6093      breakpoints with single disabled location.  */
6094   if (loc == NULL 
6095       && (b->loc != NULL 
6096           && (b->loc->next != NULL || !b->loc->enabled)))
6097     header_of_multiple = 1;
6098   if (loc == NULL)
6099     loc = b->loc;
6100
6101   annotate_record ();
6102
6103   /* 1 */
6104   annotate_field (0);
6105   if (part_of_multiple)
6106     {
6107       char *formatted;
6108       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6109       ui_out_field_string (uiout, "number", formatted);
6110       xfree (formatted);
6111     }
6112   else
6113     {
6114       ui_out_field_int (uiout, "number", b->number);
6115     }
6116
6117   /* 2 */
6118   annotate_field (1);
6119   if (part_of_multiple)
6120     ui_out_field_skip (uiout, "type");
6121   else
6122     ui_out_field_string (uiout, "type", bptype_string (b->type));
6123
6124   /* 3 */
6125   annotate_field (2);
6126   if (part_of_multiple)
6127     ui_out_field_skip (uiout, "disp");
6128   else
6129     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6130
6131
6132   /* 4 */
6133   annotate_field (3);
6134   if (part_of_multiple)
6135     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6136   else
6137     ui_out_field_fmt (uiout, "enabled", "%c", 
6138                       bpenables[(int) b->enable_state]);
6139   ui_out_spaces (uiout, 2);
6140
6141   
6142   /* 5 and 6 */
6143   if (b->ops != NULL && b->ops->print_one != NULL)
6144     {
6145       /* Although the print_one can possibly print all locations,
6146          calling it here is not likely to get any nice result.  So,
6147          make sure there's just one location.  */
6148       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6149       b->ops->print_one (b, last_loc);
6150     }
6151   else
6152     switch (b->type)
6153       {
6154       case bp_none:
6155         internal_error (__FILE__, __LINE__,
6156                         _("print_one_breakpoint: bp_none encountered\n"));
6157         break;
6158
6159       case bp_watchpoint:
6160       case bp_hardware_watchpoint:
6161       case bp_read_watchpoint:
6162       case bp_access_watchpoint:
6163         {
6164           struct watchpoint *w = (struct watchpoint *) b;
6165
6166           /* Field 4, the address, is omitted (which makes the columns
6167              not line up too nicely with the headers, but the effect
6168              is relatively readable).  */
6169           if (opts.addressprint)
6170             ui_out_field_skip (uiout, "addr");
6171           annotate_field (5);
6172           ui_out_field_string (uiout, "what", w->exp_string);
6173         }
6174         break;
6175
6176       case bp_breakpoint:
6177       case bp_hardware_breakpoint:
6178       case bp_until:
6179       case bp_finish:
6180       case bp_longjmp:
6181       case bp_longjmp_resume:
6182       case bp_longjmp_call_dummy:
6183       case bp_exception:
6184       case bp_exception_resume:
6185       case bp_step_resume:
6186       case bp_hp_step_resume:
6187       case bp_watchpoint_scope:
6188       case bp_call_dummy:
6189       case bp_std_terminate:
6190       case bp_shlib_event:
6191       case bp_thread_event:
6192       case bp_overlay_event:
6193       case bp_longjmp_master:
6194       case bp_std_terminate_master:
6195       case bp_exception_master:
6196       case bp_tracepoint:
6197       case bp_fast_tracepoint:
6198       case bp_static_tracepoint:
6199       case bp_dprintf:
6200       case bp_jit_event:
6201       case bp_gnu_ifunc_resolver:
6202       case bp_gnu_ifunc_resolver_return:
6203         if (opts.addressprint)
6204           {
6205             annotate_field (4);
6206             if (header_of_multiple)
6207               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6208             else if (b->loc == NULL || loc->shlib_disabled)
6209               ui_out_field_string (uiout, "addr", "<PENDING>");
6210             else
6211               ui_out_field_core_addr (uiout, "addr",
6212                                       loc->gdbarch, loc->address);
6213           }
6214         annotate_field (5);
6215         if (!header_of_multiple)
6216           print_breakpoint_location (b, loc);
6217         if (b->loc)
6218           *last_loc = b->loc;
6219         break;
6220       }
6221
6222
6223   if (loc != NULL && !header_of_multiple)
6224     {
6225       struct inferior *inf;
6226       VEC(int) *inf_num = NULL;
6227       int mi_only = 1;
6228
6229       ALL_INFERIORS (inf)
6230         {
6231           if (inf->pspace == loc->pspace)
6232             VEC_safe_push (int, inf_num, inf->num);
6233         }
6234
6235         /* For backward compatibility, don't display inferiors in CLI unless
6236            there are several.  Always display for MI. */
6237         if (allflag
6238             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6239                 && (number_of_program_spaces () > 1
6240                     || number_of_inferiors () > 1)
6241                 /* LOC is for existing B, it cannot be in
6242                    moribund_locations and thus having NULL OWNER.  */
6243                 && loc->owner->type != bp_catchpoint))
6244         mi_only = 0;
6245       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6246       VEC_free (int, inf_num);
6247     }
6248
6249   if (!part_of_multiple)
6250     {
6251       if (b->thread != -1)
6252         {
6253           /* FIXME: This seems to be redundant and lost here; see the
6254              "stop only in" line a little further down.  */
6255           ui_out_text (uiout, " thread ");
6256           ui_out_field_int (uiout, "thread", b->thread);
6257         }
6258       else if (b->task != 0)
6259         {
6260           ui_out_text (uiout, " task ");
6261           ui_out_field_int (uiout, "task", b->task);
6262         }
6263     }
6264
6265   ui_out_text (uiout, "\n");
6266
6267   if (!part_of_multiple)
6268     b->ops->print_one_detail (b, uiout);
6269
6270   if (part_of_multiple && frame_id_p (b->frame_id))
6271     {
6272       annotate_field (6);
6273       ui_out_text (uiout, "\tstop only in stack frame at ");
6274       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6275          the frame ID.  */
6276       ui_out_field_core_addr (uiout, "frame",
6277                               b->gdbarch, b->frame_id.stack_addr);
6278       ui_out_text (uiout, "\n");
6279     }
6280   
6281   if (!part_of_multiple && b->cond_string)
6282     {
6283       annotate_field (7);
6284       if (is_tracepoint (b))
6285         ui_out_text (uiout, "\ttrace only if ");
6286       else
6287         ui_out_text (uiout, "\tstop only if ");
6288       ui_out_field_string (uiout, "cond", b->cond_string);
6289
6290       /* Print whether the target is doing the breakpoint's condition
6291          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6292       if (is_breakpoint (b)
6293           && breakpoint_condition_evaluation_mode ()
6294           == condition_evaluation_target)
6295         {
6296           ui_out_text (uiout, " (");
6297           ui_out_field_string (uiout, "evaluated-by",
6298                                bp_condition_evaluator (b));
6299           ui_out_text (uiout, " evals)");
6300         }
6301       ui_out_text (uiout, "\n");
6302     }
6303
6304   if (!part_of_multiple && b->thread != -1)
6305     {
6306       /* FIXME should make an annotation for this.  */
6307       ui_out_text (uiout, "\tstop only in thread ");
6308       ui_out_field_int (uiout, "thread", b->thread);
6309       ui_out_text (uiout, "\n");
6310     }
6311   
6312   if (!part_of_multiple)
6313     {
6314       if (b->hit_count)
6315         {
6316           /* FIXME should make an annotation for this.  */
6317           if (is_catchpoint (b))
6318             ui_out_text (uiout, "\tcatchpoint");
6319           else if (is_tracepoint (b))
6320             ui_out_text (uiout, "\ttracepoint");
6321           else
6322             ui_out_text (uiout, "\tbreakpoint");
6323           ui_out_text (uiout, " already hit ");
6324           ui_out_field_int (uiout, "times", b->hit_count);
6325           if (b->hit_count == 1)
6326             ui_out_text (uiout, " time\n");
6327           else
6328             ui_out_text (uiout, " times\n");
6329         }
6330       else
6331         {
6332           /* Output the count also if it is zero, but only if this is mi.  */
6333           if (ui_out_is_mi_like_p (uiout))
6334             ui_out_field_int (uiout, "times", b->hit_count);
6335         }
6336     }
6337
6338   if (!part_of_multiple && b->ignore_count)
6339     {
6340       annotate_field (8);
6341       ui_out_text (uiout, "\tignore next ");
6342       ui_out_field_int (uiout, "ignore", b->ignore_count);
6343       ui_out_text (uiout, " hits\n");
6344     }
6345
6346   /* Note that an enable count of 1 corresponds to "enable once"
6347      behavior, which is reported by the combination of enablement and
6348      disposition, so we don't need to mention it here.  */
6349   if (!part_of_multiple && b->enable_count > 1)
6350     {
6351       annotate_field (8);
6352       ui_out_text (uiout, "\tdisable after ");
6353       /* Tweak the wording to clarify that ignore and enable counts
6354          are distinct, and have additive effect.  */
6355       if (b->ignore_count)
6356         ui_out_text (uiout, "additional ");
6357       else
6358         ui_out_text (uiout, "next ");
6359       ui_out_field_int (uiout, "enable", b->enable_count);
6360       ui_out_text (uiout, " hits\n");
6361     }
6362
6363   if (!part_of_multiple && is_tracepoint (b))
6364     {
6365       struct tracepoint *tp = (struct tracepoint *) b;
6366
6367       if (tp->traceframe_usage)
6368         {
6369           ui_out_text (uiout, "\ttrace buffer usage ");
6370           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6371           ui_out_text (uiout, " bytes\n");
6372         }
6373     }
6374
6375   l = b->commands ? b->commands->commands : NULL;
6376   if (!part_of_multiple && l)
6377     {
6378       struct cleanup *script_chain;
6379
6380       annotate_field (9);
6381       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6382       print_command_lines (uiout, l, 4);
6383       do_cleanups (script_chain);
6384     }
6385
6386   if (is_tracepoint (b))
6387     {
6388       struct tracepoint *t = (struct tracepoint *) b;
6389
6390       if (!part_of_multiple && t->pass_count)
6391         {
6392           annotate_field (10);
6393           ui_out_text (uiout, "\tpass count ");
6394           ui_out_field_int (uiout, "pass", t->pass_count);
6395           ui_out_text (uiout, " \n");
6396         }
6397
6398       /* Don't display it when tracepoint or tracepoint location is
6399          pending.   */
6400       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6401         {
6402           annotate_field (11);
6403
6404           if (ui_out_is_mi_like_p (uiout))
6405             ui_out_field_string (uiout, "installed",
6406                                  loc->inserted ? "y" : "n");
6407           else
6408             {
6409               if (loc->inserted)
6410                 ui_out_text (uiout, "\t");
6411               else
6412                 ui_out_text (uiout, "\tnot ");
6413               ui_out_text (uiout, "installed on target\n");
6414             }
6415         }
6416     }
6417
6418   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6419     {
6420       if (is_watchpoint (b))
6421         {
6422           struct watchpoint *w = (struct watchpoint *) b;
6423
6424           ui_out_field_string (uiout, "original-location", w->exp_string);
6425         }
6426       else if (b->addr_string)
6427         ui_out_field_string (uiout, "original-location", b->addr_string);
6428     }
6429 }
6430
6431 static void
6432 print_one_breakpoint (struct breakpoint *b,
6433                       struct bp_location **last_loc, 
6434                       int allflag)
6435 {
6436   struct cleanup *bkpt_chain;
6437   struct ui_out *uiout = current_uiout;
6438
6439   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6440
6441   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6442   do_cleanups (bkpt_chain);
6443
6444   /* If this breakpoint has custom print function,
6445      it's already printed.  Otherwise, print individual
6446      locations, if any.  */
6447   if (b->ops == NULL || b->ops->print_one == NULL)
6448     {
6449       /* If breakpoint has a single location that is disabled, we
6450          print it as if it had several locations, since otherwise it's
6451          hard to represent "breakpoint enabled, location disabled"
6452          situation.
6453
6454          Note that while hardware watchpoints have several locations
6455          internally, that's not a property exposed to user.  */
6456       if (b->loc 
6457           && !is_hardware_watchpoint (b)
6458           && (b->loc->next || !b->loc->enabled))
6459         {
6460           struct bp_location *loc;
6461           int n = 1;
6462
6463           for (loc = b->loc; loc; loc = loc->next, ++n)
6464             {
6465               struct cleanup *inner2 =
6466                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6467               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6468               do_cleanups (inner2);
6469             }
6470         }
6471     }
6472 }
6473
6474 static int
6475 breakpoint_address_bits (struct breakpoint *b)
6476 {
6477   int print_address_bits = 0;
6478   struct bp_location *loc;
6479
6480   for (loc = b->loc; loc; loc = loc->next)
6481     {
6482       int addr_bit;
6483
6484       /* Software watchpoints that aren't watching memory don't have
6485          an address to print.  */
6486       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6487         continue;
6488
6489       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6490       if (addr_bit > print_address_bits)
6491         print_address_bits = addr_bit;
6492     }
6493
6494   return print_address_bits;
6495 }
6496
6497 struct captured_breakpoint_query_args
6498   {
6499     int bnum;
6500   };
6501
6502 static int
6503 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6504 {
6505   struct captured_breakpoint_query_args *args = data;
6506   struct breakpoint *b;
6507   struct bp_location *dummy_loc = NULL;
6508
6509   ALL_BREAKPOINTS (b)
6510     {
6511       if (args->bnum == b->number)
6512         {
6513           print_one_breakpoint (b, &dummy_loc, 0);
6514           return GDB_RC_OK;
6515         }
6516     }
6517   return GDB_RC_NONE;
6518 }
6519
6520 enum gdb_rc
6521 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6522                       char **error_message)
6523 {
6524   struct captured_breakpoint_query_args args;
6525
6526   args.bnum = bnum;
6527   /* For the moment we don't trust print_one_breakpoint() to not throw
6528      an error.  */
6529   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6530                                  error_message, RETURN_MASK_ALL) < 0)
6531     return GDB_RC_FAIL;
6532   else
6533     return GDB_RC_OK;
6534 }
6535
6536 /* Return true if this breakpoint was set by the user, false if it is
6537    internal or momentary.  */
6538
6539 int
6540 user_breakpoint_p (struct breakpoint *b)
6541 {
6542   return b->number > 0;
6543 }
6544
6545 /* Print information on user settable breakpoint (watchpoint, etc)
6546    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6547    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6548    FILTER is non-NULL, call it on each breakpoint and only include the
6549    ones for which it returns non-zero.  Return the total number of
6550    breakpoints listed.  */
6551
6552 static int
6553 breakpoint_1 (char *args, int allflag, 
6554               int (*filter) (const struct breakpoint *))
6555 {
6556   struct breakpoint *b;
6557   struct bp_location *last_loc = NULL;
6558   int nr_printable_breakpoints;
6559   struct cleanup *bkpttbl_chain;
6560   struct value_print_options opts;
6561   int print_address_bits = 0;
6562   int print_type_col_width = 14;
6563   struct ui_out *uiout = current_uiout;
6564
6565   get_user_print_options (&opts);
6566
6567   /* Compute the number of rows in the table, as well as the size
6568      required for address fields.  */
6569   nr_printable_breakpoints = 0;
6570   ALL_BREAKPOINTS (b)
6571     {
6572       /* If we have a filter, only list the breakpoints it accepts.  */
6573       if (filter && !filter (b))
6574         continue;
6575
6576       /* If we have an "args" string, it is a list of breakpoints to 
6577          accept.  Skip the others.  */
6578       if (args != NULL && *args != '\0')
6579         {
6580           if (allflag && parse_and_eval_long (args) != b->number)
6581             continue;
6582           if (!allflag && !number_is_in_list (args, b->number))
6583             continue;
6584         }
6585
6586       if (allflag || user_breakpoint_p (b))
6587         {
6588           int addr_bit, type_len;
6589
6590           addr_bit = breakpoint_address_bits (b);
6591           if (addr_bit > print_address_bits)
6592             print_address_bits = addr_bit;
6593
6594           type_len = strlen (bptype_string (b->type));
6595           if (type_len > print_type_col_width)
6596             print_type_col_width = type_len;
6597
6598           nr_printable_breakpoints++;
6599         }
6600     }
6601
6602   if (opts.addressprint)
6603     bkpttbl_chain 
6604       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6605                                              nr_printable_breakpoints,
6606                                              "BreakpointTable");
6607   else
6608     bkpttbl_chain 
6609       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6610                                              nr_printable_breakpoints,
6611                                              "BreakpointTable");
6612
6613   if (nr_printable_breakpoints > 0)
6614     annotate_breakpoints_headers ();
6615   if (nr_printable_breakpoints > 0)
6616     annotate_field (0);
6617   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6618   if (nr_printable_breakpoints > 0)
6619     annotate_field (1);
6620   ui_out_table_header (uiout, print_type_col_width, ui_left,
6621                        "type", "Type");                         /* 2 */
6622   if (nr_printable_breakpoints > 0)
6623     annotate_field (2);
6624   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6625   if (nr_printable_breakpoints > 0)
6626     annotate_field (3);
6627   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6628   if (opts.addressprint)
6629     {
6630       if (nr_printable_breakpoints > 0)
6631         annotate_field (4);
6632       if (print_address_bits <= 32)
6633         ui_out_table_header (uiout, 10, ui_left, 
6634                              "addr", "Address");                /* 5 */
6635       else
6636         ui_out_table_header (uiout, 18, ui_left, 
6637                              "addr", "Address");                /* 5 */
6638     }
6639   if (nr_printable_breakpoints > 0)
6640     annotate_field (5);
6641   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6642   ui_out_table_body (uiout);
6643   if (nr_printable_breakpoints > 0)
6644     annotate_breakpoints_table ();
6645
6646   ALL_BREAKPOINTS (b)
6647     {
6648       QUIT;
6649       /* If we have a filter, only list the breakpoints it accepts.  */
6650       if (filter && !filter (b))
6651         continue;
6652
6653       /* If we have an "args" string, it is a list of breakpoints to 
6654          accept.  Skip the others.  */
6655
6656       if (args != NULL && *args != '\0')
6657         {
6658           if (allflag)  /* maintenance info breakpoint */
6659             {
6660               if (parse_and_eval_long (args) != b->number)
6661                 continue;
6662             }
6663           else          /* all others */
6664             {
6665               if (!number_is_in_list (args, b->number))
6666                 continue;
6667             }
6668         }
6669       /* We only print out user settable breakpoints unless the
6670          allflag is set.  */
6671       if (allflag || user_breakpoint_p (b))
6672         print_one_breakpoint (b, &last_loc, allflag);
6673     }
6674
6675   do_cleanups (bkpttbl_chain);
6676
6677   if (nr_printable_breakpoints == 0)
6678     {
6679       /* If there's a filter, let the caller decide how to report
6680          empty list.  */
6681       if (!filter)
6682         {
6683           if (args == NULL || *args == '\0')
6684             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6685           else
6686             ui_out_message (uiout, 0, 
6687                             "No breakpoint or watchpoint matching '%s'.\n",
6688                             args);
6689         }
6690     }
6691   else
6692     {
6693       if (last_loc && !server_command)
6694         set_next_address (last_loc->gdbarch, last_loc->address);
6695     }
6696
6697   /* FIXME?  Should this be moved up so that it is only called when
6698      there have been breakpoints? */
6699   annotate_breakpoints_table_end ();
6700
6701   return nr_printable_breakpoints;
6702 }
6703
6704 /* Display the value of default-collect in a way that is generally
6705    compatible with the breakpoint list.  */
6706
6707 static void
6708 default_collect_info (void)
6709 {
6710   struct ui_out *uiout = current_uiout;
6711
6712   /* If it has no value (which is frequently the case), say nothing; a
6713      message like "No default-collect." gets in user's face when it's
6714      not wanted.  */
6715   if (!*default_collect)
6716     return;
6717
6718   /* The following phrase lines up nicely with per-tracepoint collect
6719      actions.  */
6720   ui_out_text (uiout, "default collect ");
6721   ui_out_field_string (uiout, "default-collect", default_collect);
6722   ui_out_text (uiout, " \n");
6723 }
6724   
6725 static void
6726 breakpoints_info (char *args, int from_tty)
6727 {
6728   breakpoint_1 (args, 0, NULL);
6729
6730   default_collect_info ();
6731 }
6732
6733 static void
6734 watchpoints_info (char *args, int from_tty)
6735 {
6736   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6737   struct ui_out *uiout = current_uiout;
6738
6739   if (num_printed == 0)
6740     {
6741       if (args == NULL || *args == '\0')
6742         ui_out_message (uiout, 0, "No watchpoints.\n");
6743       else
6744         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6745     }
6746 }
6747
6748 static void
6749 maintenance_info_breakpoints (char *args, int from_tty)
6750 {
6751   breakpoint_1 (args, 1, NULL);
6752
6753   default_collect_info ();
6754 }
6755
6756 static int
6757 breakpoint_has_pc (struct breakpoint *b,
6758                    struct program_space *pspace,
6759                    CORE_ADDR pc, struct obj_section *section)
6760 {
6761   struct bp_location *bl = b->loc;
6762
6763   for (; bl; bl = bl->next)
6764     {
6765       if (bl->pspace == pspace
6766           && bl->address == pc
6767           && (!overlay_debugging || bl->section == section))
6768         return 1;         
6769     }
6770   return 0;
6771 }
6772
6773 /* Print a message describing any user-breakpoints set at PC.  This
6774    concerns with logical breakpoints, so we match program spaces, not
6775    address spaces.  */
6776
6777 static void
6778 describe_other_breakpoints (struct gdbarch *gdbarch,
6779                             struct program_space *pspace, CORE_ADDR pc,
6780                             struct obj_section *section, int thread)
6781 {
6782   int others = 0;
6783   struct breakpoint *b;
6784
6785   ALL_BREAKPOINTS (b)
6786     others += (user_breakpoint_p (b)
6787                && breakpoint_has_pc (b, pspace, pc, section));
6788   if (others > 0)
6789     {
6790       if (others == 1)
6791         printf_filtered (_("Note: breakpoint "));
6792       else /* if (others == ???) */
6793         printf_filtered (_("Note: breakpoints "));
6794       ALL_BREAKPOINTS (b)
6795         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6796           {
6797             others--;
6798             printf_filtered ("%d", b->number);
6799             if (b->thread == -1 && thread != -1)
6800               printf_filtered (" (all threads)");
6801             else if (b->thread != -1)
6802               printf_filtered (" (thread %d)", b->thread);
6803             printf_filtered ("%s%s ",
6804                              ((b->enable_state == bp_disabled
6805                                || b->enable_state == bp_call_disabled)
6806                               ? " (disabled)"
6807                               : b->enable_state == bp_permanent 
6808                               ? " (permanent)"
6809                               : ""),
6810                              (others > 1) ? "," 
6811                              : ((others == 1) ? " and" : ""));
6812           }
6813       printf_filtered (_("also set at pc "));
6814       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6815       printf_filtered (".\n");
6816     }
6817 }
6818 \f
6819
6820 /* Return true iff it is meaningful to use the address member of
6821    BPT.  For some breakpoint types, the address member is irrelevant
6822    and it makes no sense to attempt to compare it to other addresses
6823    (or use it for any other purpose either).
6824
6825    More specifically, each of the following breakpoint types will
6826    always have a zero valued address and we don't want to mark
6827    breakpoints of any of these types to be a duplicate of an actual
6828    breakpoint at address zero:
6829
6830       bp_watchpoint
6831       bp_catchpoint
6832
6833 */
6834
6835 static int
6836 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6837 {
6838   enum bptype type = bpt->type;
6839
6840   return (type != bp_watchpoint && type != bp_catchpoint);
6841 }
6842
6843 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6844    true if LOC1 and LOC2 represent the same watchpoint location.  */
6845
6846 static int
6847 watchpoint_locations_match (struct bp_location *loc1, 
6848                             struct bp_location *loc2)
6849 {
6850   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6851   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6852
6853   /* Both of them must exist.  */
6854   gdb_assert (w1 != NULL);
6855   gdb_assert (w2 != NULL);
6856
6857   /* If the target can evaluate the condition expression in hardware,
6858      then we we need to insert both watchpoints even if they are at
6859      the same place.  Otherwise the watchpoint will only trigger when
6860      the condition of whichever watchpoint was inserted evaluates to
6861      true, not giving a chance for GDB to check the condition of the
6862      other watchpoint.  */
6863   if ((w1->cond_exp
6864        && target_can_accel_watchpoint_condition (loc1->address, 
6865                                                  loc1->length,
6866                                                  loc1->watchpoint_type,
6867                                                  w1->cond_exp))
6868       || (w2->cond_exp
6869           && target_can_accel_watchpoint_condition (loc2->address, 
6870                                                     loc2->length,
6871                                                     loc2->watchpoint_type,
6872                                                     w2->cond_exp)))
6873     return 0;
6874
6875   /* Note that this checks the owner's type, not the location's.  In
6876      case the target does not support read watchpoints, but does
6877      support access watchpoints, we'll have bp_read_watchpoint
6878      watchpoints with hw_access locations.  Those should be considered
6879      duplicates of hw_read locations.  The hw_read locations will
6880      become hw_access locations later.  */
6881   return (loc1->owner->type == loc2->owner->type
6882           && loc1->pspace->aspace == loc2->pspace->aspace
6883           && loc1->address == loc2->address
6884           && loc1->length == loc2->length);
6885 }
6886
6887 /* See breakpoint.h.  */
6888
6889 int
6890 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6891                           struct address_space *aspace2, CORE_ADDR addr2)
6892 {
6893   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6894            || aspace1 == aspace2)
6895           && addr1 == addr2);
6896 }
6897
6898 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6899    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6900    matches ASPACE2.  On targets that have global breakpoints, the address
6901    space doesn't really matter.  */
6902
6903 static int
6904 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6905                                 int len1, struct address_space *aspace2,
6906                                 CORE_ADDR addr2)
6907 {
6908   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6909            || aspace1 == aspace2)
6910           && addr2 >= addr1 && addr2 < addr1 + len1);
6911 }
6912
6913 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6914    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6915    matches the breakpoint's address space.  On targets that have global
6916    breakpoints, the address space doesn't really matter.  */
6917
6918 static int
6919 breakpoint_location_address_match (struct bp_location *bl,
6920                                    struct address_space *aspace,
6921                                    CORE_ADDR addr)
6922 {
6923   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6924                                     aspace, addr)
6925           || (bl->length
6926               && breakpoint_address_match_range (bl->pspace->aspace,
6927                                                  bl->address, bl->length,
6928                                                  aspace, addr)));
6929 }
6930
6931 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6932    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6933    true, otherwise returns false.  */
6934
6935 static int
6936 tracepoint_locations_match (struct bp_location *loc1,
6937                             struct bp_location *loc2)
6938 {
6939   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6940     /* Since tracepoint locations are never duplicated with others', tracepoint
6941        locations at the same address of different tracepoints are regarded as
6942        different locations.  */
6943     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6944   else
6945     return 0;
6946 }
6947
6948 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6949    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6950    represent the same location.  */
6951
6952 static int
6953 breakpoint_locations_match (struct bp_location *loc1, 
6954                             struct bp_location *loc2)
6955 {
6956   int hw_point1, hw_point2;
6957
6958   /* Both of them must not be in moribund_locations.  */
6959   gdb_assert (loc1->owner != NULL);
6960   gdb_assert (loc2->owner != NULL);
6961
6962   hw_point1 = is_hardware_watchpoint (loc1->owner);
6963   hw_point2 = is_hardware_watchpoint (loc2->owner);
6964
6965   if (hw_point1 != hw_point2)
6966     return 0;
6967   else if (hw_point1)
6968     return watchpoint_locations_match (loc1, loc2);
6969   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6970     return tracepoint_locations_match (loc1, loc2);
6971   else
6972     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6973     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6974                                      loc2->pspace->aspace, loc2->address)
6975             && loc1->length == loc2->length);
6976 }
6977
6978 static void
6979 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6980                                int bnum, int have_bnum)
6981 {
6982   /* The longest string possibly returned by hex_string_custom
6983      is 50 chars.  These must be at least that big for safety.  */
6984   char astr1[64];
6985   char astr2[64];
6986
6987   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6988   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6989   if (have_bnum)
6990     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6991              bnum, astr1, astr2);
6992   else
6993     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6994 }
6995
6996 /* Adjust a breakpoint's address to account for architectural
6997    constraints on breakpoint placement.  Return the adjusted address.
6998    Note: Very few targets require this kind of adjustment.  For most
6999    targets, this function is simply the identity function.  */
7000
7001 static CORE_ADDR
7002 adjust_breakpoint_address (struct gdbarch *gdbarch,
7003                            CORE_ADDR bpaddr, enum bptype bptype)
7004 {
7005   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7006     {
7007       /* Very few targets need any kind of breakpoint adjustment.  */
7008       return bpaddr;
7009     }
7010   else if (bptype == bp_watchpoint
7011            || bptype == bp_hardware_watchpoint
7012            || bptype == bp_read_watchpoint
7013            || bptype == bp_access_watchpoint
7014            || bptype == bp_catchpoint)
7015     {
7016       /* Watchpoints and the various bp_catch_* eventpoints should not
7017          have their addresses modified.  */
7018       return bpaddr;
7019     }
7020   else
7021     {
7022       CORE_ADDR adjusted_bpaddr;
7023
7024       /* Some targets have architectural constraints on the placement
7025          of breakpoint instructions.  Obtain the adjusted address.  */
7026       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7027
7028       /* An adjusted breakpoint address can significantly alter
7029          a user's expectations.  Print a warning if an adjustment
7030          is required.  */
7031       if (adjusted_bpaddr != bpaddr)
7032         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7033
7034       return adjusted_bpaddr;
7035     }
7036 }
7037
7038 void
7039 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7040                   struct breakpoint *owner)
7041 {
7042   memset (loc, 0, sizeof (*loc));
7043
7044   gdb_assert (ops != NULL);
7045
7046   loc->ops = ops;
7047   loc->owner = owner;
7048   loc->cond = NULL;
7049   loc->cond_bytecode = NULL;
7050   loc->shlib_disabled = 0;
7051   loc->enabled = 1;
7052
7053   switch (owner->type)
7054     {
7055     case bp_breakpoint:
7056     case bp_until:
7057     case bp_finish:
7058     case bp_longjmp:
7059     case bp_longjmp_resume:
7060     case bp_longjmp_call_dummy:
7061     case bp_exception:
7062     case bp_exception_resume:
7063     case bp_step_resume:
7064     case bp_hp_step_resume:
7065     case bp_watchpoint_scope:
7066     case bp_call_dummy:
7067     case bp_std_terminate:
7068     case bp_shlib_event:
7069     case bp_thread_event:
7070     case bp_overlay_event:
7071     case bp_jit_event:
7072     case bp_longjmp_master:
7073     case bp_std_terminate_master:
7074     case bp_exception_master:
7075     case bp_gnu_ifunc_resolver:
7076     case bp_gnu_ifunc_resolver_return:
7077     case bp_dprintf:
7078       loc->loc_type = bp_loc_software_breakpoint;
7079       mark_breakpoint_location_modified (loc);
7080       break;
7081     case bp_hardware_breakpoint:
7082       loc->loc_type = bp_loc_hardware_breakpoint;
7083       mark_breakpoint_location_modified (loc);
7084       break;
7085     case bp_hardware_watchpoint:
7086     case bp_read_watchpoint:
7087     case bp_access_watchpoint:
7088       loc->loc_type = bp_loc_hardware_watchpoint;
7089       break;
7090     case bp_watchpoint:
7091     case bp_catchpoint:
7092     case bp_tracepoint:
7093     case bp_fast_tracepoint:
7094     case bp_static_tracepoint:
7095       loc->loc_type = bp_loc_other;
7096       break;
7097     default:
7098       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7099     }
7100
7101   loc->refc = 1;
7102 }
7103
7104 /* Allocate a struct bp_location.  */
7105
7106 static struct bp_location *
7107 allocate_bp_location (struct breakpoint *bpt)
7108 {
7109   return bpt->ops->allocate_location (bpt);
7110 }
7111
7112 static void
7113 free_bp_location (struct bp_location *loc)
7114 {
7115   loc->ops->dtor (loc);
7116   xfree (loc);
7117 }
7118
7119 /* Increment reference count.  */
7120
7121 static void
7122 incref_bp_location (struct bp_location *bl)
7123 {
7124   ++bl->refc;
7125 }
7126
7127 /* Decrement reference count.  If the reference count reaches 0,
7128    destroy the bp_location.  Sets *BLP to NULL.  */
7129
7130 static void
7131 decref_bp_location (struct bp_location **blp)
7132 {
7133   gdb_assert ((*blp)->refc > 0);
7134
7135   if (--(*blp)->refc == 0)
7136     free_bp_location (*blp);
7137   *blp = NULL;
7138 }
7139
7140 /* Add breakpoint B at the end of the global breakpoint chain.  */
7141
7142 static void
7143 add_to_breakpoint_chain (struct breakpoint *b)
7144 {
7145   struct breakpoint *b1;
7146
7147   /* Add this breakpoint to the end of the chain so that a list of
7148      breakpoints will come out in order of increasing numbers.  */
7149
7150   b1 = breakpoint_chain;
7151   if (b1 == 0)
7152     breakpoint_chain = b;
7153   else
7154     {
7155       while (b1->next)
7156         b1 = b1->next;
7157       b1->next = b;
7158     }
7159 }
7160
7161 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7162
7163 static void
7164 init_raw_breakpoint_without_location (struct breakpoint *b,
7165                                       struct gdbarch *gdbarch,
7166                                       enum bptype bptype,
7167                                       const struct breakpoint_ops *ops)
7168 {
7169   memset (b, 0, sizeof (*b));
7170
7171   gdb_assert (ops != NULL);
7172
7173   b->ops = ops;
7174   b->type = bptype;
7175   b->gdbarch = gdbarch;
7176   b->language = current_language->la_language;
7177   b->input_radix = input_radix;
7178   b->thread = -1;
7179   b->enable_state = bp_enabled;
7180   b->next = 0;
7181   b->silent = 0;
7182   b->ignore_count = 0;
7183   b->commands = NULL;
7184   b->frame_id = null_frame_id;
7185   b->condition_not_parsed = 0;
7186   b->py_bp_object = NULL;
7187   b->related_breakpoint = b;
7188 }
7189
7190 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7191    that has type BPTYPE and has no locations as yet.  */
7192
7193 static struct breakpoint *
7194 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7195                                      enum bptype bptype,
7196                                      const struct breakpoint_ops *ops)
7197 {
7198   struct breakpoint *b = XNEW (struct breakpoint);
7199
7200   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7201   add_to_breakpoint_chain (b);
7202   return b;
7203 }
7204
7205 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7206    resolutions should be made as the user specified the location explicitly
7207    enough.  */
7208
7209 static void
7210 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7211 {
7212   gdb_assert (loc->owner != NULL);
7213
7214   if (loc->owner->type == bp_breakpoint
7215       || loc->owner->type == bp_hardware_breakpoint
7216       || is_tracepoint (loc->owner))
7217     {
7218       int is_gnu_ifunc;
7219       const char *function_name;
7220       CORE_ADDR func_addr;
7221
7222       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7223                                           &func_addr, NULL, &is_gnu_ifunc);
7224
7225       if (is_gnu_ifunc && !explicit_loc)
7226         {
7227           struct breakpoint *b = loc->owner;
7228
7229           gdb_assert (loc->pspace == current_program_space);
7230           if (gnu_ifunc_resolve_name (function_name,
7231                                       &loc->requested_address))
7232             {
7233               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7234               loc->address = adjust_breakpoint_address (loc->gdbarch,
7235                                                         loc->requested_address,
7236                                                         b->type);
7237             }
7238           else if (b->type == bp_breakpoint && b->loc == loc
7239                    && loc->next == NULL && b->related_breakpoint == b)
7240             {
7241               /* Create only the whole new breakpoint of this type but do not
7242                  mess more complicated breakpoints with multiple locations.  */
7243               b->type = bp_gnu_ifunc_resolver;
7244               /* Remember the resolver's address for use by the return
7245                  breakpoint.  */
7246               loc->related_address = func_addr;
7247             }
7248         }
7249
7250       if (function_name)
7251         loc->function_name = xstrdup (function_name);
7252     }
7253 }
7254
7255 /* Attempt to determine architecture of location identified by SAL.  */
7256 struct gdbarch *
7257 get_sal_arch (struct symtab_and_line sal)
7258 {
7259   if (sal.section)
7260     return get_objfile_arch (sal.section->objfile);
7261   if (sal.symtab)
7262     return get_objfile_arch (sal.symtab->objfile);
7263
7264   return NULL;
7265 }
7266
7267 /* Low level routine for partially initializing a breakpoint of type
7268    BPTYPE.  The newly created breakpoint's address, section, source
7269    file name, and line number are provided by SAL.
7270
7271    It is expected that the caller will complete the initialization of
7272    the newly created breakpoint struct as well as output any status
7273    information regarding the creation of a new breakpoint.  */
7274
7275 static void
7276 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7277                      struct symtab_and_line sal, enum bptype bptype,
7278                      const struct breakpoint_ops *ops)
7279 {
7280   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7281
7282   add_location_to_breakpoint (b, &sal);
7283
7284   if (bptype != bp_catchpoint)
7285     gdb_assert (sal.pspace != NULL);
7286
7287   /* Store the program space that was used to set the breakpoint,
7288      except for ordinary breakpoints, which are independent of the
7289      program space.  */
7290   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7291     b->pspace = sal.pspace;
7292 }
7293
7294 /* set_raw_breakpoint is a low level routine for allocating and
7295    partially initializing a breakpoint of type BPTYPE.  The newly
7296    created breakpoint's address, section, source file name, and line
7297    number are provided by SAL.  The newly created and partially
7298    initialized breakpoint is added to the breakpoint chain and
7299    is also returned as the value of this function.
7300
7301    It is expected that the caller will complete the initialization of
7302    the newly created breakpoint struct as well as output any status
7303    information regarding the creation of a new breakpoint.  In
7304    particular, set_raw_breakpoint does NOT set the breakpoint
7305    number!  Care should be taken to not allow an error to occur
7306    prior to completing the initialization of the breakpoint.  If this
7307    should happen, a bogus breakpoint will be left on the chain.  */
7308
7309 struct breakpoint *
7310 set_raw_breakpoint (struct gdbarch *gdbarch,
7311                     struct symtab_and_line sal, enum bptype bptype,
7312                     const struct breakpoint_ops *ops)
7313 {
7314   struct breakpoint *b = XNEW (struct breakpoint);
7315
7316   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7317   add_to_breakpoint_chain (b);
7318   return b;
7319 }
7320
7321
7322 /* Note that the breakpoint object B describes a permanent breakpoint
7323    instruction, hard-wired into the inferior's code.  */
7324 void
7325 make_breakpoint_permanent (struct breakpoint *b)
7326 {
7327   struct bp_location *bl;
7328
7329   b->enable_state = bp_permanent;
7330
7331   /* By definition, permanent breakpoints are already present in the
7332      code.  Mark all locations as inserted.  For now,
7333      make_breakpoint_permanent is called in just one place, so it's
7334      hard to say if it's reasonable to have permanent breakpoint with
7335      multiple locations or not, but it's easy to implement.  */
7336   for (bl = b->loc; bl; bl = bl->next)
7337     bl->inserted = 1;
7338 }
7339
7340 /* Call this routine when stepping and nexting to enable a breakpoint
7341    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7342    initiated the operation.  */
7343
7344 void
7345 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7346 {
7347   struct breakpoint *b, *b_tmp;
7348   int thread = tp->num;
7349
7350   /* To avoid having to rescan all objfile symbols at every step,
7351      we maintain a list of continually-inserted but always disabled
7352      longjmp "master" breakpoints.  Here, we simply create momentary
7353      clones of those and enable them for the requested thread.  */
7354   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7355     if (b->pspace == current_program_space
7356         && (b->type == bp_longjmp_master
7357             || b->type == bp_exception_master))
7358       {
7359         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7360         struct breakpoint *clone;
7361
7362         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7363            after their removal.  */
7364         clone = momentary_breakpoint_from_master (b, type,
7365                                                   &longjmp_breakpoint_ops);
7366         clone->thread = thread;
7367       }
7368
7369   tp->initiating_frame = frame;
7370 }
7371
7372 /* Delete all longjmp breakpoints from THREAD.  */
7373 void
7374 delete_longjmp_breakpoint (int thread)
7375 {
7376   struct breakpoint *b, *b_tmp;
7377
7378   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7379     if (b->type == bp_longjmp || b->type == bp_exception)
7380       {
7381         if (b->thread == thread)
7382           delete_breakpoint (b);
7383       }
7384 }
7385
7386 void
7387 delete_longjmp_breakpoint_at_next_stop (int thread)
7388 {
7389   struct breakpoint *b, *b_tmp;
7390
7391   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7392     if (b->type == bp_longjmp || b->type == bp_exception)
7393       {
7394         if (b->thread == thread)
7395           b->disposition = disp_del_at_next_stop;
7396       }
7397 }
7398
7399 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7400    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7401    pointer to any of them.  Return NULL if this system cannot place longjmp
7402    breakpoints.  */
7403
7404 struct breakpoint *
7405 set_longjmp_breakpoint_for_call_dummy (void)
7406 {
7407   struct breakpoint *b, *retval = NULL;
7408
7409   ALL_BREAKPOINTS (b)
7410     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7411       {
7412         struct breakpoint *new_b;
7413
7414         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7415                                                   &momentary_breakpoint_ops);
7416         new_b->thread = pid_to_thread_id (inferior_ptid);
7417
7418         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7419
7420         gdb_assert (new_b->related_breakpoint == new_b);
7421         if (retval == NULL)
7422           retval = new_b;
7423         new_b->related_breakpoint = retval;
7424         while (retval->related_breakpoint != new_b->related_breakpoint)
7425           retval = retval->related_breakpoint;
7426         retval->related_breakpoint = new_b;
7427       }
7428
7429   return retval;
7430 }
7431
7432 /* Verify all existing dummy frames and their associated breakpoints for
7433    THREAD.  Remove those which can no longer be found in the current frame
7434    stack.
7435
7436    You should call this function only at places where it is safe to currently
7437    unwind the whole stack.  Failed stack unwind would discard live dummy
7438    frames.  */
7439
7440 void
7441 check_longjmp_breakpoint_for_call_dummy (int thread)
7442 {
7443   struct breakpoint *b, *b_tmp;
7444
7445   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7446     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7447       {
7448         struct breakpoint *dummy_b = b->related_breakpoint;
7449
7450         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7451           dummy_b = dummy_b->related_breakpoint;
7452         if (dummy_b->type != bp_call_dummy
7453             || frame_find_by_id (dummy_b->frame_id) != NULL)
7454           continue;
7455         
7456         dummy_frame_discard (dummy_b->frame_id);
7457
7458         while (b->related_breakpoint != b)
7459           {
7460             if (b_tmp == b->related_breakpoint)
7461               b_tmp = b->related_breakpoint->next;
7462             delete_breakpoint (b->related_breakpoint);
7463           }
7464         delete_breakpoint (b);
7465       }
7466 }
7467
7468 void
7469 enable_overlay_breakpoints (void)
7470 {
7471   struct breakpoint *b;
7472
7473   ALL_BREAKPOINTS (b)
7474     if (b->type == bp_overlay_event)
7475     {
7476       b->enable_state = bp_enabled;
7477       update_global_location_list (1);
7478       overlay_events_enabled = 1;
7479     }
7480 }
7481
7482 void
7483 disable_overlay_breakpoints (void)
7484 {
7485   struct breakpoint *b;
7486
7487   ALL_BREAKPOINTS (b)
7488     if (b->type == bp_overlay_event)
7489     {
7490       b->enable_state = bp_disabled;
7491       update_global_location_list (0);
7492       overlay_events_enabled = 0;
7493     }
7494 }
7495
7496 /* Set an active std::terminate breakpoint for each std::terminate
7497    master breakpoint.  */
7498 void
7499 set_std_terminate_breakpoint (void)
7500 {
7501   struct breakpoint *b, *b_tmp;
7502
7503   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7504     if (b->pspace == current_program_space
7505         && b->type == bp_std_terminate_master)
7506       {
7507         momentary_breakpoint_from_master (b, bp_std_terminate,
7508                                           &momentary_breakpoint_ops);
7509       }
7510 }
7511
7512 /* Delete all the std::terminate breakpoints.  */
7513 void
7514 delete_std_terminate_breakpoint (void)
7515 {
7516   struct breakpoint *b, *b_tmp;
7517
7518   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7519     if (b->type == bp_std_terminate)
7520       delete_breakpoint (b);
7521 }
7522
7523 struct breakpoint *
7524 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7525 {
7526   struct breakpoint *b;
7527
7528   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7529                                   &internal_breakpoint_ops);
7530
7531   b->enable_state = bp_enabled;
7532   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7533   b->addr_string
7534     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7535
7536   update_global_location_list_nothrow (1);
7537
7538   return b;
7539 }
7540
7541 void
7542 remove_thread_event_breakpoints (void)
7543 {
7544   struct breakpoint *b, *b_tmp;
7545
7546   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7547     if (b->type == bp_thread_event
7548         && b->loc->pspace == current_program_space)
7549       delete_breakpoint (b);
7550 }
7551
7552 struct lang_and_radix
7553   {
7554     enum language lang;
7555     int radix;
7556   };
7557
7558 /* Create a breakpoint for JIT code registration and unregistration.  */
7559
7560 struct breakpoint *
7561 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7562 {
7563   struct breakpoint *b;
7564
7565   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7566                                   &internal_breakpoint_ops);
7567   update_global_location_list_nothrow (1);
7568   return b;
7569 }
7570
7571 /* Remove JIT code registration and unregistration breakpoint(s).  */
7572
7573 void
7574 remove_jit_event_breakpoints (void)
7575 {
7576   struct breakpoint *b, *b_tmp;
7577
7578   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7579     if (b->type == bp_jit_event
7580         && b->loc->pspace == current_program_space)
7581       delete_breakpoint (b);
7582 }
7583
7584 void
7585 remove_solib_event_breakpoints (void)
7586 {
7587   struct breakpoint *b, *b_tmp;
7588
7589   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7590     if (b->type == bp_shlib_event
7591         && b->loc->pspace == current_program_space)
7592       delete_breakpoint (b);
7593 }
7594
7595 struct breakpoint *
7596 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7597 {
7598   struct breakpoint *b;
7599
7600   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7601                                   &internal_breakpoint_ops);
7602   update_global_location_list_nothrow (1);
7603   return b;
7604 }
7605
7606 /* Disable any breakpoints that are on code in shared libraries.  Only
7607    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7608
7609 void
7610 disable_breakpoints_in_shlibs (void)
7611 {
7612   struct bp_location *loc, **locp_tmp;
7613
7614   ALL_BP_LOCATIONS (loc, locp_tmp)
7615   {
7616     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7617     struct breakpoint *b = loc->owner;
7618
7619     /* We apply the check to all breakpoints, including disabled for
7620        those with loc->duplicate set.  This is so that when breakpoint
7621        becomes enabled, or the duplicate is removed, gdb will try to
7622        insert all breakpoints.  If we don't set shlib_disabled here,
7623        we'll try to insert those breakpoints and fail.  */
7624     if (((b->type == bp_breakpoint)
7625          || (b->type == bp_jit_event)
7626          || (b->type == bp_hardware_breakpoint)
7627          || (is_tracepoint (b)))
7628         && loc->pspace == current_program_space
7629         && !loc->shlib_disabled
7630         && solib_name_from_address (loc->pspace, loc->address)
7631         )
7632       {
7633         loc->shlib_disabled = 1;
7634       }
7635   }
7636 }
7637
7638 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7639    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7640    disabled ones can just stay disabled.  */
7641
7642 static void
7643 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7644 {
7645   struct bp_location *loc, **locp_tmp;
7646   int disabled_shlib_breaks = 0;
7647
7648   /* SunOS a.out shared libraries are always mapped, so do not
7649      disable breakpoints; they will only be reported as unloaded
7650      through clear_solib when GDB discards its shared library
7651      list.  See clear_solib for more information.  */
7652   if (exec_bfd != NULL
7653       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7654     return;
7655
7656   ALL_BP_LOCATIONS (loc, locp_tmp)
7657   {
7658     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7659     struct breakpoint *b = loc->owner;
7660
7661     if (solib->pspace == loc->pspace
7662         && !loc->shlib_disabled
7663         && (((b->type == bp_breakpoint
7664               || b->type == bp_jit_event
7665               || b->type == bp_hardware_breakpoint)
7666              && (loc->loc_type == bp_loc_hardware_breakpoint
7667                  || loc->loc_type == bp_loc_software_breakpoint))
7668             || is_tracepoint (b))
7669         && solib_contains_address_p (solib, loc->address))
7670       {
7671         loc->shlib_disabled = 1;
7672         /* At this point, we cannot rely on remove_breakpoint
7673            succeeding so we must mark the breakpoint as not inserted
7674            to prevent future errors occurring in remove_breakpoints.  */
7675         loc->inserted = 0;
7676
7677         /* This may cause duplicate notifications for the same breakpoint.  */
7678         observer_notify_breakpoint_modified (b);
7679
7680         if (!disabled_shlib_breaks)
7681           {
7682             target_terminal_ours_for_output ();
7683             warning (_("Temporarily disabling breakpoints "
7684                        "for unloaded shared library \"%s\""),
7685                      solib->so_name);
7686           }
7687         disabled_shlib_breaks = 1;
7688       }
7689   }
7690 }
7691
7692 /* Disable any breakpoints and tracepoints in OBJFILE upon
7693    notification of free_objfile.  Only apply to enabled breakpoints,
7694    disabled ones can just stay disabled.  */
7695
7696 static void
7697 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7698 {
7699   struct breakpoint *b;
7700
7701   if (objfile == NULL)
7702     return;
7703
7704   /* OBJF_USERLOADED are dynamic modules manually managed by the user
7705      with add-symbol-file/remove-symbol-file.  Similarly to how
7706      breakpoints in shared libraries are handled in response to
7707      "nosharedlibrary", mark breakpoints in OBJF_USERLOADED modules
7708      shlib_disabled so they end up uninserted on the next global
7709      location list update.  Shared libraries not loaded by the user
7710      aren't handled here -- they're already handled in
7711      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7712      solib_unloaded observer.  We skip objfiles that are not
7713      OBJF_USERLOADED (nor OBJF_SHARED) as those aren't considered
7714      dynamic objects (e.g. the main objfile).  */
7715   if ((objfile->flags & OBJF_USERLOADED) == 0)
7716     return;
7717
7718   ALL_BREAKPOINTS (b)
7719     {
7720       struct bp_location *loc;
7721       int bp_modified = 0;
7722
7723       if (!is_breakpoint (b) && !is_tracepoint (b))
7724         continue;
7725
7726       for (loc = b->loc; loc != NULL; loc = loc->next)
7727         {
7728           CORE_ADDR loc_addr = loc->address;
7729
7730           if (loc->loc_type != bp_loc_hardware_breakpoint
7731               && loc->loc_type != bp_loc_software_breakpoint)
7732             continue;
7733
7734           if (loc->shlib_disabled != 0)
7735             continue;
7736
7737           if (objfile->pspace != loc->pspace)
7738             continue;
7739
7740           if (loc->loc_type != bp_loc_hardware_breakpoint
7741               && loc->loc_type != bp_loc_software_breakpoint)
7742             continue;
7743
7744           if (is_addr_in_objfile (loc_addr, objfile))
7745             {
7746               loc->shlib_disabled = 1;
7747               /* At this point, we don't know whether the object was
7748                  unmapped from the inferior or not, so leave the
7749                  inserted flag alone.  We'll handle failure to
7750                  uninsert quietly, in case the object was indeed
7751                  unmapped.  */
7752
7753               mark_breakpoint_location_modified (loc);
7754
7755               bp_modified = 1;
7756             }
7757         }
7758
7759       if (bp_modified)
7760         observer_notify_breakpoint_modified (b);
7761     }
7762 }
7763
7764 /* FORK & VFORK catchpoints.  */
7765
7766 /* An instance of this type is used to represent a fork or vfork
7767    catchpoint.  It includes a "struct breakpoint" as a kind of base
7768    class; users downcast to "struct breakpoint *" when needed.  A
7769    breakpoint is really of this type iff its ops pointer points to
7770    CATCH_FORK_BREAKPOINT_OPS.  */
7771
7772 struct fork_catchpoint
7773 {
7774   /* The base class.  */
7775   struct breakpoint base;
7776
7777   /* Process id of a child process whose forking triggered this
7778      catchpoint.  This field is only valid immediately after this
7779      catchpoint has triggered.  */
7780   ptid_t forked_inferior_pid;
7781 };
7782
7783 /* Implement the "insert" breakpoint_ops method for fork
7784    catchpoints.  */
7785
7786 static int
7787 insert_catch_fork (struct bp_location *bl)
7788 {
7789   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7790 }
7791
7792 /* Implement the "remove" breakpoint_ops method for fork
7793    catchpoints.  */
7794
7795 static int
7796 remove_catch_fork (struct bp_location *bl)
7797 {
7798   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7799 }
7800
7801 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7802    catchpoints.  */
7803
7804 static int
7805 breakpoint_hit_catch_fork (const struct bp_location *bl,
7806                            struct address_space *aspace, CORE_ADDR bp_addr,
7807                            const struct target_waitstatus *ws)
7808 {
7809   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7810
7811   if (ws->kind != TARGET_WAITKIND_FORKED)
7812     return 0;
7813
7814   c->forked_inferior_pid = ws->value.related_pid;
7815   return 1;
7816 }
7817
7818 /* Implement the "print_it" breakpoint_ops method for fork
7819    catchpoints.  */
7820
7821 static enum print_stop_action
7822 print_it_catch_fork (bpstat bs)
7823 {
7824   struct ui_out *uiout = current_uiout;
7825   struct breakpoint *b = bs->breakpoint_at;
7826   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7827
7828   annotate_catchpoint (b->number);
7829   if (b->disposition == disp_del)
7830     ui_out_text (uiout, "\nTemporary catchpoint ");
7831   else
7832     ui_out_text (uiout, "\nCatchpoint ");
7833   if (ui_out_is_mi_like_p (uiout))
7834     {
7835       ui_out_field_string (uiout, "reason",
7836                            async_reason_lookup (EXEC_ASYNC_FORK));
7837       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7838     }
7839   ui_out_field_int (uiout, "bkptno", b->number);
7840   ui_out_text (uiout, " (forked process ");
7841   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7842   ui_out_text (uiout, "), ");
7843   return PRINT_SRC_AND_LOC;
7844 }
7845
7846 /* Implement the "print_one" breakpoint_ops method for fork
7847    catchpoints.  */
7848
7849 static void
7850 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7851 {
7852   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7853   struct value_print_options opts;
7854   struct ui_out *uiout = current_uiout;
7855
7856   get_user_print_options (&opts);
7857
7858   /* Field 4, the address, is omitted (which makes the columns not
7859      line up too nicely with the headers, but the effect is relatively
7860      readable).  */
7861   if (opts.addressprint)
7862     ui_out_field_skip (uiout, "addr");
7863   annotate_field (5);
7864   ui_out_text (uiout, "fork");
7865   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7866     {
7867       ui_out_text (uiout, ", process ");
7868       ui_out_field_int (uiout, "what",
7869                         ptid_get_pid (c->forked_inferior_pid));
7870       ui_out_spaces (uiout, 1);
7871     }
7872
7873   if (ui_out_is_mi_like_p (uiout))
7874     ui_out_field_string (uiout, "catch-type", "fork");
7875 }
7876
7877 /* Implement the "print_mention" breakpoint_ops method for fork
7878    catchpoints.  */
7879
7880 static void
7881 print_mention_catch_fork (struct breakpoint *b)
7882 {
7883   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7884 }
7885
7886 /* Implement the "print_recreate" breakpoint_ops method for fork
7887    catchpoints.  */
7888
7889 static void
7890 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7891 {
7892   fprintf_unfiltered (fp, "catch fork");
7893   print_recreate_thread (b, fp);
7894 }
7895
7896 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7897
7898 static struct breakpoint_ops catch_fork_breakpoint_ops;
7899
7900 /* Implement the "insert" breakpoint_ops method for vfork
7901    catchpoints.  */
7902
7903 static int
7904 insert_catch_vfork (struct bp_location *bl)
7905 {
7906   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7907 }
7908
7909 /* Implement the "remove" breakpoint_ops method for vfork
7910    catchpoints.  */
7911
7912 static int
7913 remove_catch_vfork (struct bp_location *bl)
7914 {
7915   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7916 }
7917
7918 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7919    catchpoints.  */
7920
7921 static int
7922 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7923                             struct address_space *aspace, CORE_ADDR bp_addr,
7924                             const struct target_waitstatus *ws)
7925 {
7926   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7927
7928   if (ws->kind != TARGET_WAITKIND_VFORKED)
7929     return 0;
7930
7931   c->forked_inferior_pid = ws->value.related_pid;
7932   return 1;
7933 }
7934
7935 /* Implement the "print_it" breakpoint_ops method for vfork
7936    catchpoints.  */
7937
7938 static enum print_stop_action
7939 print_it_catch_vfork (bpstat bs)
7940 {
7941   struct ui_out *uiout = current_uiout;
7942   struct breakpoint *b = bs->breakpoint_at;
7943   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7944
7945   annotate_catchpoint (b->number);
7946   if (b->disposition == disp_del)
7947     ui_out_text (uiout, "\nTemporary catchpoint ");
7948   else
7949     ui_out_text (uiout, "\nCatchpoint ");
7950   if (ui_out_is_mi_like_p (uiout))
7951     {
7952       ui_out_field_string (uiout, "reason",
7953                            async_reason_lookup (EXEC_ASYNC_VFORK));
7954       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7955     }
7956   ui_out_field_int (uiout, "bkptno", b->number);
7957   ui_out_text (uiout, " (vforked process ");
7958   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7959   ui_out_text (uiout, "), ");
7960   return PRINT_SRC_AND_LOC;
7961 }
7962
7963 /* Implement the "print_one" breakpoint_ops method for vfork
7964    catchpoints.  */
7965
7966 static void
7967 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7968 {
7969   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7970   struct value_print_options opts;
7971   struct ui_out *uiout = current_uiout;
7972
7973   get_user_print_options (&opts);
7974   /* Field 4, the address, is omitted (which makes the columns not
7975      line up too nicely with the headers, but the effect is relatively
7976      readable).  */
7977   if (opts.addressprint)
7978     ui_out_field_skip (uiout, "addr");
7979   annotate_field (5);
7980   ui_out_text (uiout, "vfork");
7981   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7982     {
7983       ui_out_text (uiout, ", process ");
7984       ui_out_field_int (uiout, "what",
7985                         ptid_get_pid (c->forked_inferior_pid));
7986       ui_out_spaces (uiout, 1);
7987     }
7988
7989   if (ui_out_is_mi_like_p (uiout))
7990     ui_out_field_string (uiout, "catch-type", "vfork");
7991 }
7992
7993 /* Implement the "print_mention" breakpoint_ops method for vfork
7994    catchpoints.  */
7995
7996 static void
7997 print_mention_catch_vfork (struct breakpoint *b)
7998 {
7999   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8000 }
8001
8002 /* Implement the "print_recreate" breakpoint_ops method for vfork
8003    catchpoints.  */
8004
8005 static void
8006 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8007 {
8008   fprintf_unfiltered (fp, "catch vfork");
8009   print_recreate_thread (b, fp);
8010 }
8011
8012 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8013
8014 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8015
8016 /* An instance of this type is used to represent an solib catchpoint.
8017    It includes a "struct breakpoint" as a kind of base class; users
8018    downcast to "struct breakpoint *" when needed.  A breakpoint is
8019    really of this type iff its ops pointer points to
8020    CATCH_SOLIB_BREAKPOINT_OPS.  */
8021
8022 struct solib_catchpoint
8023 {
8024   /* The base class.  */
8025   struct breakpoint base;
8026
8027   /* True for "catch load", false for "catch unload".  */
8028   unsigned char is_load;
8029
8030   /* Regular expression to match, if any.  COMPILED is only valid when
8031      REGEX is non-NULL.  */
8032   char *regex;
8033   regex_t compiled;
8034 };
8035
8036 static void
8037 dtor_catch_solib (struct breakpoint *b)
8038 {
8039   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8040
8041   if (self->regex)
8042     regfree (&self->compiled);
8043   xfree (self->regex);
8044
8045   base_breakpoint_ops.dtor (b);
8046 }
8047
8048 static int
8049 insert_catch_solib (struct bp_location *ignore)
8050 {
8051   return 0;
8052 }
8053
8054 static int
8055 remove_catch_solib (struct bp_location *ignore)
8056 {
8057   return 0;
8058 }
8059
8060 static int
8061 breakpoint_hit_catch_solib (const struct bp_location *bl,
8062                             struct address_space *aspace,
8063                             CORE_ADDR bp_addr,
8064                             const struct target_waitstatus *ws)
8065 {
8066   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8067   struct breakpoint *other;
8068
8069   if (ws->kind == TARGET_WAITKIND_LOADED)
8070     return 1;
8071
8072   ALL_BREAKPOINTS (other)
8073   {
8074     struct bp_location *other_bl;
8075
8076     if (other == bl->owner)
8077       continue;
8078
8079     if (other->type != bp_shlib_event)
8080       continue;
8081
8082     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8083       continue;
8084
8085     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8086       {
8087         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8088           return 1;
8089       }
8090   }
8091
8092   return 0;
8093 }
8094
8095 static void
8096 check_status_catch_solib (struct bpstats *bs)
8097 {
8098   struct solib_catchpoint *self
8099     = (struct solib_catchpoint *) bs->breakpoint_at;
8100   int ix;
8101
8102   if (self->is_load)
8103     {
8104       struct so_list *iter;
8105
8106       for (ix = 0;
8107            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8108                         ix, iter);
8109            ++ix)
8110         {
8111           if (!self->regex
8112               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8113             return;
8114         }
8115     }
8116   else
8117     {
8118       char *iter;
8119
8120       for (ix = 0;
8121            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8122                         ix, iter);
8123            ++ix)
8124         {
8125           if (!self->regex
8126               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8127             return;
8128         }
8129     }
8130
8131   bs->stop = 0;
8132   bs->print_it = print_it_noop;
8133 }
8134
8135 static enum print_stop_action
8136 print_it_catch_solib (bpstat bs)
8137 {
8138   struct breakpoint *b = bs->breakpoint_at;
8139   struct ui_out *uiout = current_uiout;
8140
8141   annotate_catchpoint (b->number);
8142   if (b->disposition == disp_del)
8143     ui_out_text (uiout, "\nTemporary catchpoint ");
8144   else
8145     ui_out_text (uiout, "\nCatchpoint ");
8146   ui_out_field_int (uiout, "bkptno", b->number);
8147   ui_out_text (uiout, "\n");
8148   if (ui_out_is_mi_like_p (uiout))
8149     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8150   print_solib_event (1);
8151   return PRINT_SRC_AND_LOC;
8152 }
8153
8154 static void
8155 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8156 {
8157   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8158   struct value_print_options opts;
8159   struct ui_out *uiout = current_uiout;
8160   char *msg;
8161
8162   get_user_print_options (&opts);
8163   /* Field 4, the address, is omitted (which makes the columns not
8164      line up too nicely with the headers, but the effect is relatively
8165      readable).  */
8166   if (opts.addressprint)
8167     {
8168       annotate_field (4);
8169       ui_out_field_skip (uiout, "addr");
8170     }
8171
8172   annotate_field (5);
8173   if (self->is_load)
8174     {
8175       if (self->regex)
8176         msg = xstrprintf (_("load of library matching %s"), self->regex);
8177       else
8178         msg = xstrdup (_("load of library"));
8179     }
8180   else
8181     {
8182       if (self->regex)
8183         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8184       else
8185         msg = xstrdup (_("unload of library"));
8186     }
8187   ui_out_field_string (uiout, "what", msg);
8188   xfree (msg);
8189
8190   if (ui_out_is_mi_like_p (uiout))
8191     ui_out_field_string (uiout, "catch-type",
8192                          self->is_load ? "load" : "unload");
8193 }
8194
8195 static void
8196 print_mention_catch_solib (struct breakpoint *b)
8197 {
8198   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8199
8200   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8201                    self->is_load ? "load" : "unload");
8202 }
8203
8204 static void
8205 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8206 {
8207   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8208
8209   fprintf_unfiltered (fp, "%s %s",
8210                       b->disposition == disp_del ? "tcatch" : "catch",
8211                       self->is_load ? "load" : "unload");
8212   if (self->regex)
8213     fprintf_unfiltered (fp, " %s", self->regex);
8214   fprintf_unfiltered (fp, "\n");
8215 }
8216
8217 static struct breakpoint_ops catch_solib_breakpoint_ops;
8218
8219 /* Shared helper function (MI and CLI) for creating and installing
8220    a shared object event catchpoint.  If IS_LOAD is non-zero then
8221    the events to be caught are load events, otherwise they are
8222    unload events.  If IS_TEMP is non-zero the catchpoint is a
8223    temporary one.  If ENABLED is non-zero the catchpoint is
8224    created in an enabled state.  */
8225
8226 void
8227 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8228 {
8229   struct solib_catchpoint *c;
8230   struct gdbarch *gdbarch = get_current_arch ();
8231   struct cleanup *cleanup;
8232
8233   if (!arg)
8234     arg = "";
8235   arg = skip_spaces (arg);
8236
8237   c = XCNEW (struct solib_catchpoint);
8238   cleanup = make_cleanup (xfree, c);
8239
8240   if (*arg != '\0')
8241     {
8242       int errcode;
8243
8244       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8245       if (errcode != 0)
8246         {
8247           char *err = get_regcomp_error (errcode, &c->compiled);
8248
8249           make_cleanup (xfree, err);
8250           error (_("Invalid regexp (%s): %s"), err, arg);
8251         }
8252       c->regex = xstrdup (arg);
8253     }
8254
8255   c->is_load = is_load;
8256   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8257                    &catch_solib_breakpoint_ops);
8258
8259   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8260
8261   discard_cleanups (cleanup);
8262   install_breakpoint (0, &c->base, 1);
8263 }
8264
8265 /* A helper function that does all the work for "catch load" and
8266    "catch unload".  */
8267
8268 static void
8269 catch_load_or_unload (char *arg, int from_tty, int is_load,
8270                       struct cmd_list_element *command)
8271 {
8272   int tempflag;
8273   const int enabled = 1;
8274
8275   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8276
8277   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8278 }
8279
8280 static void
8281 catch_load_command_1 (char *arg, int from_tty,
8282                       struct cmd_list_element *command)
8283 {
8284   catch_load_or_unload (arg, from_tty, 1, command);
8285 }
8286
8287 static void
8288 catch_unload_command_1 (char *arg, int from_tty,
8289                         struct cmd_list_element *command)
8290 {
8291   catch_load_or_unload (arg, from_tty, 0, command);
8292 }
8293
8294 /* An instance of this type is used to represent a syscall catchpoint.
8295    It includes a "struct breakpoint" as a kind of base class; users
8296    downcast to "struct breakpoint *" when needed.  A breakpoint is
8297    really of this type iff its ops pointer points to
8298    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8299
8300 struct syscall_catchpoint
8301 {
8302   /* The base class.  */
8303   struct breakpoint base;
8304
8305   /* Syscall numbers used for the 'catch syscall' feature.  If no
8306      syscall has been specified for filtering, its value is NULL.
8307      Otherwise, it holds a list of all syscalls to be caught.  The
8308      list elements are allocated with xmalloc.  */
8309   VEC(int) *syscalls_to_be_caught;
8310 };
8311
8312 /* Implement the "dtor" breakpoint_ops method for syscall
8313    catchpoints.  */
8314
8315 static void
8316 dtor_catch_syscall (struct breakpoint *b)
8317 {
8318   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8319
8320   VEC_free (int, c->syscalls_to_be_caught);
8321
8322   base_breakpoint_ops.dtor (b);
8323 }
8324
8325 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8326
8327 struct catch_syscall_inferior_data
8328 {
8329   /* We keep a count of the number of times the user has requested a
8330      particular syscall to be tracked, and pass this information to the
8331      target.  This lets capable targets implement filtering directly.  */
8332
8333   /* Number of times that "any" syscall is requested.  */
8334   int any_syscall_count;
8335
8336   /* Count of each system call.  */
8337   VEC(int) *syscalls_counts;
8338
8339   /* This counts all syscall catch requests, so we can readily determine
8340      if any catching is necessary.  */
8341   int total_syscalls_count;
8342 };
8343
8344 static struct catch_syscall_inferior_data*
8345 get_catch_syscall_inferior_data (struct inferior *inf)
8346 {
8347   struct catch_syscall_inferior_data *inf_data;
8348
8349   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8350   if (inf_data == NULL)
8351     {
8352       inf_data = XCNEW (struct catch_syscall_inferior_data);
8353       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8354     }
8355
8356   return inf_data;
8357 }
8358
8359 static void
8360 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8361 {
8362   xfree (arg);
8363 }
8364
8365
8366 /* Implement the "insert" breakpoint_ops method for syscall
8367    catchpoints.  */
8368
8369 static int
8370 insert_catch_syscall (struct bp_location *bl)
8371 {
8372   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8373   struct inferior *inf = current_inferior ();
8374   struct catch_syscall_inferior_data *inf_data
8375     = get_catch_syscall_inferior_data (inf);
8376
8377   ++inf_data->total_syscalls_count;
8378   if (!c->syscalls_to_be_caught)
8379     ++inf_data->any_syscall_count;
8380   else
8381     {
8382       int i, iter;
8383
8384       for (i = 0;
8385            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8386            i++)
8387         {
8388           int elem;
8389
8390           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8391             {
8392               int old_size = VEC_length (int, inf_data->syscalls_counts);
8393               uintptr_t vec_addr_offset
8394                 = old_size * ((uintptr_t) sizeof (int));
8395               uintptr_t vec_addr;
8396               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8397               vec_addr = ((uintptr_t) VEC_address (int,
8398                                                   inf_data->syscalls_counts)
8399                           + vec_addr_offset);
8400               memset ((void *) vec_addr, 0,
8401                       (iter + 1 - old_size) * sizeof (int));
8402             }
8403           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8404           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8405         }
8406     }
8407
8408   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8409                                         inf_data->total_syscalls_count != 0,
8410                                         inf_data->any_syscall_count,
8411                                         VEC_length (int,
8412                                                     inf_data->syscalls_counts),
8413                                         VEC_address (int,
8414                                                      inf_data->syscalls_counts));
8415 }
8416
8417 /* Implement the "remove" breakpoint_ops method for syscall
8418    catchpoints.  */
8419
8420 static int
8421 remove_catch_syscall (struct bp_location *bl)
8422 {
8423   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8424   struct inferior *inf = current_inferior ();
8425   struct catch_syscall_inferior_data *inf_data
8426     = get_catch_syscall_inferior_data (inf);
8427
8428   --inf_data->total_syscalls_count;
8429   if (!c->syscalls_to_be_caught)
8430     --inf_data->any_syscall_count;
8431   else
8432     {
8433       int i, iter;
8434
8435       for (i = 0;
8436            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8437            i++)
8438         {
8439           int elem;
8440           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8441             /* Shouldn't happen.  */
8442             continue;
8443           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8444           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8445         }
8446     }
8447
8448   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8449                                         inf_data->total_syscalls_count != 0,
8450                                         inf_data->any_syscall_count,
8451                                         VEC_length (int,
8452                                                     inf_data->syscalls_counts),
8453                                         VEC_address (int,
8454                                                      inf_data->syscalls_counts));
8455 }
8456
8457 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8458    catchpoints.  */
8459
8460 static int
8461 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8462                               struct address_space *aspace, CORE_ADDR bp_addr,
8463                               const struct target_waitstatus *ws)
8464 {
8465   /* We must check if we are catching specific syscalls in this
8466      breakpoint.  If we are, then we must guarantee that the called
8467      syscall is the same syscall we are catching.  */
8468   int syscall_number = 0;
8469   const struct syscall_catchpoint *c
8470     = (const struct syscall_catchpoint *) bl->owner;
8471
8472   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8473       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8474     return 0;
8475
8476   syscall_number = ws->value.syscall_number;
8477
8478   /* Now, checking if the syscall is the same.  */
8479   if (c->syscalls_to_be_caught)
8480     {
8481       int i, iter;
8482
8483       for (i = 0;
8484            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8485            i++)
8486         if (syscall_number == iter)
8487           return 1;
8488
8489       return 0;
8490     }
8491
8492   return 1;
8493 }
8494
8495 /* Implement the "print_it" breakpoint_ops method for syscall
8496    catchpoints.  */
8497
8498 static enum print_stop_action
8499 print_it_catch_syscall (bpstat bs)
8500 {
8501   struct ui_out *uiout = current_uiout;
8502   struct breakpoint *b = bs->breakpoint_at;
8503   /* These are needed because we want to know in which state a
8504      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8505      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8506      must print "called syscall" or "returned from syscall".  */
8507   ptid_t ptid;
8508   struct target_waitstatus last;
8509   struct syscall s;
8510
8511   get_last_target_status (&ptid, &last);
8512
8513   get_syscall_by_number (last.value.syscall_number, &s);
8514
8515   annotate_catchpoint (b->number);
8516
8517   if (b->disposition == disp_del)
8518     ui_out_text (uiout, "\nTemporary catchpoint ");
8519   else
8520     ui_out_text (uiout, "\nCatchpoint ");
8521   if (ui_out_is_mi_like_p (uiout))
8522     {
8523       ui_out_field_string (uiout, "reason",
8524                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8525                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8526                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8527       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8528     }
8529   ui_out_field_int (uiout, "bkptno", b->number);
8530
8531   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8532     ui_out_text (uiout, " (call to syscall ");
8533   else
8534     ui_out_text (uiout, " (returned from syscall ");
8535
8536   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8537     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8538   if (s.name != NULL)
8539     ui_out_field_string (uiout, "syscall-name", s.name);
8540
8541   ui_out_text (uiout, "), ");
8542
8543   return PRINT_SRC_AND_LOC;
8544 }
8545
8546 /* Implement the "print_one" breakpoint_ops method for syscall
8547    catchpoints.  */
8548
8549 static void
8550 print_one_catch_syscall (struct breakpoint *b,
8551                          struct bp_location **last_loc)
8552 {
8553   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8554   struct value_print_options opts;
8555   struct ui_out *uiout = current_uiout;
8556
8557   get_user_print_options (&opts);
8558   /* Field 4, the address, is omitted (which makes the columns not
8559      line up too nicely with the headers, but the effect is relatively
8560      readable).  */
8561   if (opts.addressprint)
8562     ui_out_field_skip (uiout, "addr");
8563   annotate_field (5);
8564
8565   if (c->syscalls_to_be_caught
8566       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8567     ui_out_text (uiout, "syscalls \"");
8568   else
8569     ui_out_text (uiout, "syscall \"");
8570
8571   if (c->syscalls_to_be_caught)
8572     {
8573       int i, iter;
8574       char *text = xstrprintf ("%s", "");
8575
8576       for (i = 0;
8577            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8578            i++)
8579         {
8580           char *x = text;
8581           struct syscall s;
8582           get_syscall_by_number (iter, &s);
8583
8584           if (s.name != NULL)
8585             text = xstrprintf ("%s%s, ", text, s.name);
8586           else
8587             text = xstrprintf ("%s%d, ", text, iter);
8588
8589           /* We have to xfree the last 'text' (now stored at 'x')
8590              because xstrprintf dynamically allocates new space for it
8591              on every call.  */
8592           xfree (x);
8593         }
8594       /* Remove the last comma.  */
8595       text[strlen (text) - 2] = '\0';
8596       ui_out_field_string (uiout, "what", text);
8597     }
8598   else
8599     ui_out_field_string (uiout, "what", "<any syscall>");
8600   ui_out_text (uiout, "\" ");
8601
8602   if (ui_out_is_mi_like_p (uiout))
8603     ui_out_field_string (uiout, "catch-type", "syscall");
8604 }
8605
8606 /* Implement the "print_mention" breakpoint_ops method for syscall
8607    catchpoints.  */
8608
8609 static void
8610 print_mention_catch_syscall (struct breakpoint *b)
8611 {
8612   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8613
8614   if (c->syscalls_to_be_caught)
8615     {
8616       int i, iter;
8617
8618       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8619         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8620       else
8621         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8622
8623       for (i = 0;
8624            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8625            i++)
8626         {
8627           struct syscall s;
8628           get_syscall_by_number (iter, &s);
8629
8630           if (s.name)
8631             printf_filtered (" '%s' [%d]", s.name, s.number);
8632           else
8633             printf_filtered (" %d", s.number);
8634         }
8635       printf_filtered (")");
8636     }
8637   else
8638     printf_filtered (_("Catchpoint %d (any syscall)"),
8639                      b->number);
8640 }
8641
8642 /* Implement the "print_recreate" breakpoint_ops method for syscall
8643    catchpoints.  */
8644
8645 static void
8646 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8647 {
8648   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8649
8650   fprintf_unfiltered (fp, "catch syscall");
8651
8652   if (c->syscalls_to_be_caught)
8653     {
8654       int i, iter;
8655
8656       for (i = 0;
8657            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8658            i++)
8659         {
8660           struct syscall s;
8661
8662           get_syscall_by_number (iter, &s);
8663           if (s.name)
8664             fprintf_unfiltered (fp, " %s", s.name);
8665           else
8666             fprintf_unfiltered (fp, " %d", s.number);
8667         }
8668     }
8669   print_recreate_thread (b, fp);
8670 }
8671
8672 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8673
8674 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8675
8676 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8677
8678 static int
8679 syscall_catchpoint_p (struct breakpoint *b)
8680 {
8681   return (b->ops == &catch_syscall_breakpoint_ops);
8682 }
8683
8684 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8685    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8686    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8687    the breakpoint_ops structure associated to the catchpoint.  */
8688
8689 void
8690 init_catchpoint (struct breakpoint *b,
8691                  struct gdbarch *gdbarch, int tempflag,
8692                  char *cond_string,
8693                  const struct breakpoint_ops *ops)
8694 {
8695   struct symtab_and_line sal;
8696
8697   init_sal (&sal);
8698   sal.pspace = current_program_space;
8699
8700   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8701
8702   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8703   b->disposition = tempflag ? disp_del : disp_donttouch;
8704 }
8705
8706 void
8707 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8708 {
8709   add_to_breakpoint_chain (b);
8710   set_breakpoint_number (internal, b);
8711   if (is_tracepoint (b))
8712     set_tracepoint_count (breakpoint_count);
8713   if (!internal)
8714     mention (b);
8715   observer_notify_breakpoint_created (b);
8716
8717   if (update_gll)
8718     update_global_location_list (1);
8719 }
8720
8721 static void
8722 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8723                                     int tempflag, char *cond_string,
8724                                     const struct breakpoint_ops *ops)
8725 {
8726   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8727
8728   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8729
8730   c->forked_inferior_pid = null_ptid;
8731
8732   install_breakpoint (0, &c->base, 1);
8733 }
8734
8735 /* Exec catchpoints.  */
8736
8737 /* An instance of this type is used to represent an exec catchpoint.
8738    It includes a "struct breakpoint" as a kind of base class; users
8739    downcast to "struct breakpoint *" when needed.  A breakpoint is
8740    really of this type iff its ops pointer points to
8741    CATCH_EXEC_BREAKPOINT_OPS.  */
8742
8743 struct exec_catchpoint
8744 {
8745   /* The base class.  */
8746   struct breakpoint base;
8747
8748   /* Filename of a program whose exec triggered this catchpoint.
8749      This field is only valid immediately after this catchpoint has
8750      triggered.  */
8751   char *exec_pathname;
8752 };
8753
8754 /* Implement the "dtor" breakpoint_ops method for exec
8755    catchpoints.  */
8756
8757 static void
8758 dtor_catch_exec (struct breakpoint *b)
8759 {
8760   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8761
8762   xfree (c->exec_pathname);
8763
8764   base_breakpoint_ops.dtor (b);
8765 }
8766
8767 static int
8768 insert_catch_exec (struct bp_location *bl)
8769 {
8770   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8771 }
8772
8773 static int
8774 remove_catch_exec (struct bp_location *bl)
8775 {
8776   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8777 }
8778
8779 static int
8780 breakpoint_hit_catch_exec (const struct bp_location *bl,
8781                            struct address_space *aspace, CORE_ADDR bp_addr,
8782                            const struct target_waitstatus *ws)
8783 {
8784   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8785
8786   if (ws->kind != TARGET_WAITKIND_EXECD)
8787     return 0;
8788
8789   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8790   return 1;
8791 }
8792
8793 static enum print_stop_action
8794 print_it_catch_exec (bpstat bs)
8795 {
8796   struct ui_out *uiout = current_uiout;
8797   struct breakpoint *b = bs->breakpoint_at;
8798   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8799
8800   annotate_catchpoint (b->number);
8801   if (b->disposition == disp_del)
8802     ui_out_text (uiout, "\nTemporary catchpoint ");
8803   else
8804     ui_out_text (uiout, "\nCatchpoint ");
8805   if (ui_out_is_mi_like_p (uiout))
8806     {
8807       ui_out_field_string (uiout, "reason",
8808                            async_reason_lookup (EXEC_ASYNC_EXEC));
8809       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8810     }
8811   ui_out_field_int (uiout, "bkptno", b->number);
8812   ui_out_text (uiout, " (exec'd ");
8813   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8814   ui_out_text (uiout, "), ");
8815
8816   return PRINT_SRC_AND_LOC;
8817 }
8818
8819 static void
8820 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8821 {
8822   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8823   struct value_print_options opts;
8824   struct ui_out *uiout = current_uiout;
8825
8826   get_user_print_options (&opts);
8827
8828   /* Field 4, the address, is omitted (which makes the columns
8829      not line up too nicely with the headers, but the effect
8830      is relatively readable).  */
8831   if (opts.addressprint)
8832     ui_out_field_skip (uiout, "addr");
8833   annotate_field (5);
8834   ui_out_text (uiout, "exec");
8835   if (c->exec_pathname != NULL)
8836     {
8837       ui_out_text (uiout, ", program \"");
8838       ui_out_field_string (uiout, "what", c->exec_pathname);
8839       ui_out_text (uiout, "\" ");
8840     }
8841
8842   if (ui_out_is_mi_like_p (uiout))
8843     ui_out_field_string (uiout, "catch-type", "exec");
8844 }
8845
8846 static void
8847 print_mention_catch_exec (struct breakpoint *b)
8848 {
8849   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8850 }
8851
8852 /* Implement the "print_recreate" breakpoint_ops method for exec
8853    catchpoints.  */
8854
8855 static void
8856 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8857 {
8858   fprintf_unfiltered (fp, "catch exec");
8859   print_recreate_thread (b, fp);
8860 }
8861
8862 static struct breakpoint_ops catch_exec_breakpoint_ops;
8863
8864 static void
8865 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8866                                  const struct breakpoint_ops *ops)
8867 {
8868   struct syscall_catchpoint *c;
8869   struct gdbarch *gdbarch = get_current_arch ();
8870
8871   c = XNEW (struct syscall_catchpoint);
8872   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8873   c->syscalls_to_be_caught = filter;
8874
8875   install_breakpoint (0, &c->base, 1);
8876 }
8877
8878 static int
8879 hw_breakpoint_used_count (void)
8880 {
8881   int i = 0;
8882   struct breakpoint *b;
8883   struct bp_location *bl;
8884
8885   ALL_BREAKPOINTS (b)
8886   {
8887     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8888       for (bl = b->loc; bl; bl = bl->next)
8889         {
8890           /* Special types of hardware breakpoints may use more than
8891              one register.  */
8892           i += b->ops->resources_needed (bl);
8893         }
8894   }
8895
8896   return i;
8897 }
8898
8899 /* Returns the resources B would use if it were a hardware
8900    watchpoint.  */
8901
8902 static int
8903 hw_watchpoint_use_count (struct breakpoint *b)
8904 {
8905   int i = 0;
8906   struct bp_location *bl;
8907
8908   if (!breakpoint_enabled (b))
8909     return 0;
8910
8911   for (bl = b->loc; bl; bl = bl->next)
8912     {
8913       /* Special types of hardware watchpoints may use more than
8914          one register.  */
8915       i += b->ops->resources_needed (bl);
8916     }
8917
8918   return i;
8919 }
8920
8921 /* Returns the sum the used resources of all hardware watchpoints of
8922    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8923    the sum of the used resources of all hardware watchpoints of other
8924    types _not_ TYPE.  */
8925
8926 static int
8927 hw_watchpoint_used_count_others (struct breakpoint *except,
8928                                  enum bptype type, int *other_type_used)
8929 {
8930   int i = 0;
8931   struct breakpoint *b;
8932
8933   *other_type_used = 0;
8934   ALL_BREAKPOINTS (b)
8935     {
8936       if (b == except)
8937         continue;
8938       if (!breakpoint_enabled (b))
8939         continue;
8940
8941       if (b->type == type)
8942         i += hw_watchpoint_use_count (b);
8943       else if (is_hardware_watchpoint (b))
8944         *other_type_used = 1;
8945     }
8946
8947   return i;
8948 }
8949
8950 void
8951 disable_watchpoints_before_interactive_call_start (void)
8952 {
8953   struct breakpoint *b;
8954
8955   ALL_BREAKPOINTS (b)
8956   {
8957     if (is_watchpoint (b) && breakpoint_enabled (b))
8958       {
8959         b->enable_state = bp_call_disabled;
8960         update_global_location_list (0);
8961       }
8962   }
8963 }
8964
8965 void
8966 enable_watchpoints_after_interactive_call_stop (void)
8967 {
8968   struct breakpoint *b;
8969
8970   ALL_BREAKPOINTS (b)
8971   {
8972     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8973       {
8974         b->enable_state = bp_enabled;
8975         update_global_location_list (1);
8976       }
8977   }
8978 }
8979
8980 void
8981 disable_breakpoints_before_startup (void)
8982 {
8983   current_program_space->executing_startup = 1;
8984   update_global_location_list (0);
8985 }
8986
8987 void
8988 enable_breakpoints_after_startup (void)
8989 {
8990   current_program_space->executing_startup = 0;
8991   breakpoint_re_set ();
8992 }
8993
8994
8995 /* Set a breakpoint that will evaporate an end of command
8996    at address specified by SAL.
8997    Restrict it to frame FRAME if FRAME is nonzero.  */
8998
8999 struct breakpoint *
9000 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9001                           struct frame_id frame_id, enum bptype type)
9002 {
9003   struct breakpoint *b;
9004
9005   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9006      tail-called one.  */
9007   gdb_assert (!frame_id_artificial_p (frame_id));
9008
9009   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9010   b->enable_state = bp_enabled;
9011   b->disposition = disp_donttouch;
9012   b->frame_id = frame_id;
9013
9014   /* If we're debugging a multi-threaded program, then we want
9015      momentary breakpoints to be active in only a single thread of
9016      control.  */
9017   if (in_thread_list (inferior_ptid))
9018     b->thread = pid_to_thread_id (inferior_ptid);
9019
9020   update_global_location_list_nothrow (1);
9021
9022   return b;
9023 }
9024
9025 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9026    The new breakpoint will have type TYPE, and use OPS as it
9027    breakpoint_ops.  */
9028
9029 static struct breakpoint *
9030 momentary_breakpoint_from_master (struct breakpoint *orig,
9031                                   enum bptype type,
9032                                   const struct breakpoint_ops *ops)
9033 {
9034   struct breakpoint *copy;
9035
9036   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9037   copy->loc = allocate_bp_location (copy);
9038   set_breakpoint_location_function (copy->loc, 1);
9039
9040   copy->loc->gdbarch = orig->loc->gdbarch;
9041   copy->loc->requested_address = orig->loc->requested_address;
9042   copy->loc->address = orig->loc->address;
9043   copy->loc->section = orig->loc->section;
9044   copy->loc->pspace = orig->loc->pspace;
9045   copy->loc->probe = orig->loc->probe;
9046   copy->loc->line_number = orig->loc->line_number;
9047   copy->loc->symtab = orig->loc->symtab;
9048   copy->frame_id = orig->frame_id;
9049   copy->thread = orig->thread;
9050   copy->pspace = orig->pspace;
9051
9052   copy->enable_state = bp_enabled;
9053   copy->disposition = disp_donttouch;
9054   copy->number = internal_breakpoint_number--;
9055
9056   update_global_location_list_nothrow (0);
9057   return copy;
9058 }
9059
9060 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9061    ORIG is NULL.  */
9062
9063 struct breakpoint *
9064 clone_momentary_breakpoint (struct breakpoint *orig)
9065 {
9066   /* If there's nothing to clone, then return nothing.  */
9067   if (orig == NULL)
9068     return NULL;
9069
9070   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
9071 }
9072
9073 struct breakpoint *
9074 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9075                                 enum bptype type)
9076 {
9077   struct symtab_and_line sal;
9078
9079   sal = find_pc_line (pc, 0);
9080   sal.pc = pc;
9081   sal.section = find_pc_overlay (pc);
9082   sal.explicit_pc = 1;
9083
9084   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9085 }
9086 \f
9087
9088 /* Tell the user we have just set a breakpoint B.  */
9089
9090 static void
9091 mention (struct breakpoint *b)
9092 {
9093   b->ops->print_mention (b);
9094   if (ui_out_is_mi_like_p (current_uiout))
9095     return;
9096   printf_filtered ("\n");
9097 }
9098 \f
9099
9100 static struct bp_location *
9101 add_location_to_breakpoint (struct breakpoint *b,
9102                             const struct symtab_and_line *sal)
9103 {
9104   struct bp_location *loc, **tmp;
9105   CORE_ADDR adjusted_address;
9106   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9107
9108   if (loc_gdbarch == NULL)
9109     loc_gdbarch = b->gdbarch;
9110
9111   /* Adjust the breakpoint's address prior to allocating a location.
9112      Once we call allocate_bp_location(), that mostly uninitialized
9113      location will be placed on the location chain.  Adjustment of the
9114      breakpoint may cause target_read_memory() to be called and we do
9115      not want its scan of the location chain to find a breakpoint and
9116      location that's only been partially initialized.  */
9117   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9118                                                 sal->pc, b->type);
9119
9120   /* Sort the locations by their ADDRESS.  */
9121   loc = allocate_bp_location (b);
9122   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9123        tmp = &((*tmp)->next))
9124     ;
9125   loc->next = *tmp;
9126   *tmp = loc;
9127
9128   loc->requested_address = sal->pc;
9129   loc->address = adjusted_address;
9130   loc->pspace = sal->pspace;
9131   loc->probe.probe = sal->probe;
9132   loc->probe.objfile = sal->objfile;
9133   gdb_assert (loc->pspace != NULL);
9134   loc->section = sal->section;
9135   loc->gdbarch = loc_gdbarch;
9136   loc->line_number = sal->line;
9137   loc->symtab = sal->symtab;
9138
9139   set_breakpoint_location_function (loc,
9140                                     sal->explicit_pc || sal->explicit_line);
9141   return loc;
9142 }
9143 \f
9144
9145 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9146    return 0 otherwise.  */
9147
9148 static int
9149 bp_loc_is_permanent (struct bp_location *loc)
9150 {
9151   int len;
9152   CORE_ADDR addr;
9153   const gdb_byte *bpoint;
9154   gdb_byte *target_mem;
9155   struct cleanup *cleanup;
9156   int retval = 0;
9157
9158   gdb_assert (loc != NULL);
9159
9160   addr = loc->address;
9161   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9162
9163   /* Software breakpoints unsupported?  */
9164   if (bpoint == NULL)
9165     return 0;
9166
9167   target_mem = alloca (len);
9168
9169   /* Enable the automatic memory restoration from breakpoints while
9170      we read the memory.  Otherwise we could say about our temporary
9171      breakpoints they are permanent.  */
9172   cleanup = save_current_space_and_thread ();
9173
9174   switch_to_program_space_and_thread (loc->pspace);
9175   make_show_memory_breakpoints_cleanup (0);
9176
9177   if (target_read_memory (loc->address, target_mem, len) == 0
9178       && memcmp (target_mem, bpoint, len) == 0)
9179     retval = 1;
9180
9181   do_cleanups (cleanup);
9182
9183   return retval;
9184 }
9185
9186 /* Build a command list for the dprintf corresponding to the current
9187    settings of the dprintf style options.  */
9188
9189 static void
9190 update_dprintf_command_list (struct breakpoint *b)
9191 {
9192   char *dprintf_args = b->extra_string;
9193   char *printf_line = NULL;
9194
9195   if (!dprintf_args)
9196     return;
9197
9198   dprintf_args = skip_spaces (dprintf_args);
9199
9200   /* Allow a comma, as it may have terminated a location, but don't
9201      insist on it.  */
9202   if (*dprintf_args == ',')
9203     ++dprintf_args;
9204   dprintf_args = skip_spaces (dprintf_args);
9205
9206   if (*dprintf_args != '"')
9207     error (_("Bad format string, missing '\"'."));
9208
9209   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9210     printf_line = xstrprintf ("printf %s", dprintf_args);
9211   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9212     {
9213       if (!dprintf_function)
9214         error (_("No function supplied for dprintf call"));
9215
9216       if (dprintf_channel && strlen (dprintf_channel) > 0)
9217         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9218                                   dprintf_function,
9219                                   dprintf_channel,
9220                                   dprintf_args);
9221       else
9222         printf_line = xstrprintf ("call (void) %s (%s)",
9223                                   dprintf_function,
9224                                   dprintf_args);
9225     }
9226   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9227     {
9228       if (target_can_run_breakpoint_commands ())
9229         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9230       else
9231         {
9232           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9233           printf_line = xstrprintf ("printf %s", dprintf_args);
9234         }
9235     }
9236   else
9237     internal_error (__FILE__, __LINE__,
9238                     _("Invalid dprintf style."));
9239
9240   gdb_assert (printf_line != NULL);
9241   /* Manufacture a printf sequence.  */
9242   {
9243     struct command_line *printf_cmd_line
9244       = xmalloc (sizeof (struct command_line));
9245
9246     printf_cmd_line = xmalloc (sizeof (struct command_line));
9247     printf_cmd_line->control_type = simple_control;
9248     printf_cmd_line->body_count = 0;
9249     printf_cmd_line->body_list = NULL;
9250     printf_cmd_line->next = NULL;
9251     printf_cmd_line->line = printf_line;
9252
9253     breakpoint_set_commands (b, printf_cmd_line);
9254   }
9255 }
9256
9257 /* Update all dprintf commands, making their command lists reflect
9258    current style settings.  */
9259
9260 static void
9261 update_dprintf_commands (char *args, int from_tty,
9262                          struct cmd_list_element *c)
9263 {
9264   struct breakpoint *b;
9265
9266   ALL_BREAKPOINTS (b)
9267     {
9268       if (b->type == bp_dprintf)
9269         update_dprintf_command_list (b);
9270     }
9271 }
9272
9273 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9274    as textual description of the location, and COND_STRING
9275    as condition expression.  */
9276
9277 static void
9278 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9279                      struct symtabs_and_lines sals, char *addr_string,
9280                      char *filter, char *cond_string,
9281                      char *extra_string,
9282                      enum bptype type, enum bpdisp disposition,
9283                      int thread, int task, int ignore_count,
9284                      const struct breakpoint_ops *ops, int from_tty,
9285                      int enabled, int internal, unsigned flags,
9286                      int display_canonical)
9287 {
9288   int i;
9289
9290   if (type == bp_hardware_breakpoint)
9291     {
9292       int target_resources_ok;
9293
9294       i = hw_breakpoint_used_count ();
9295       target_resources_ok =
9296         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9297                                             i + 1, 0);
9298       if (target_resources_ok == 0)
9299         error (_("No hardware breakpoint support in the target."));
9300       else if (target_resources_ok < 0)
9301         error (_("Hardware breakpoints used exceeds limit."));
9302     }
9303
9304   gdb_assert (sals.nelts > 0);
9305
9306   for (i = 0; i < sals.nelts; ++i)
9307     {
9308       struct symtab_and_line sal = sals.sals[i];
9309       struct bp_location *loc;
9310
9311       if (from_tty)
9312         {
9313           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9314           if (!loc_gdbarch)
9315             loc_gdbarch = gdbarch;
9316
9317           describe_other_breakpoints (loc_gdbarch,
9318                                       sal.pspace, sal.pc, sal.section, thread);
9319         }
9320
9321       if (i == 0)
9322         {
9323           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9324           b->thread = thread;
9325           b->task = task;
9326
9327           b->cond_string = cond_string;
9328           b->extra_string = extra_string;
9329           b->ignore_count = ignore_count;
9330           b->enable_state = enabled ? bp_enabled : bp_disabled;
9331           b->disposition = disposition;
9332
9333           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9334             b->loc->inserted = 1;
9335
9336           if (type == bp_static_tracepoint)
9337             {
9338               struct tracepoint *t = (struct tracepoint *) b;
9339               struct static_tracepoint_marker marker;
9340
9341               if (strace_marker_p (b))
9342                 {
9343                   /* We already know the marker exists, otherwise, we
9344                      wouldn't see a sal for it.  */
9345                   char *p = &addr_string[3];
9346                   char *endp;
9347                   char *marker_str;
9348
9349                   p = skip_spaces (p);
9350
9351                   endp = skip_to_space (p);
9352
9353                   marker_str = savestring (p, endp - p);
9354                   t->static_trace_marker_id = marker_str;
9355
9356                   printf_filtered (_("Probed static tracepoint "
9357                                      "marker \"%s\"\n"),
9358                                    t->static_trace_marker_id);
9359                 }
9360               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9361                 {
9362                   t->static_trace_marker_id = xstrdup (marker.str_id);
9363                   release_static_tracepoint_marker (&marker);
9364
9365                   printf_filtered (_("Probed static tracepoint "
9366                                      "marker \"%s\"\n"),
9367                                    t->static_trace_marker_id);
9368                 }
9369               else
9370                 warning (_("Couldn't determine the static "
9371                            "tracepoint marker to probe"));
9372             }
9373
9374           loc = b->loc;
9375         }
9376       else
9377         {
9378           loc = add_location_to_breakpoint (b, &sal);
9379           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9380             loc->inserted = 1;
9381         }
9382
9383       if (bp_loc_is_permanent (loc))
9384         make_breakpoint_permanent (b);
9385
9386       if (b->cond_string)
9387         {
9388           const char *arg = b->cond_string;
9389
9390           loc->cond = parse_exp_1 (&arg, loc->address,
9391                                    block_for_pc (loc->address), 0);
9392           if (*arg)
9393               error (_("Garbage '%s' follows condition"), arg);
9394         }
9395
9396       /* Dynamic printf requires and uses additional arguments on the
9397          command line, otherwise it's an error.  */
9398       if (type == bp_dprintf)
9399         {
9400           if (b->extra_string)
9401             update_dprintf_command_list (b);
9402           else
9403             error (_("Format string required"));
9404         }
9405       else if (b->extra_string)
9406         error (_("Garbage '%s' at end of command"), b->extra_string);
9407     }
9408
9409   b->display_canonical = display_canonical;
9410   if (addr_string)
9411     b->addr_string = addr_string;
9412   else
9413     /* addr_string has to be used or breakpoint_re_set will delete
9414        me.  */
9415     b->addr_string
9416       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9417   b->filter = filter;
9418 }
9419
9420 static void
9421 create_breakpoint_sal (struct gdbarch *gdbarch,
9422                        struct symtabs_and_lines sals, char *addr_string,
9423                        char *filter, char *cond_string,
9424                        char *extra_string,
9425                        enum bptype type, enum bpdisp disposition,
9426                        int thread, int task, int ignore_count,
9427                        const struct breakpoint_ops *ops, int from_tty,
9428                        int enabled, int internal, unsigned flags,
9429                        int display_canonical)
9430 {
9431   struct breakpoint *b;
9432   struct cleanup *old_chain;
9433
9434   if (is_tracepoint_type (type))
9435     {
9436       struct tracepoint *t;
9437
9438       t = XCNEW (struct tracepoint);
9439       b = &t->base;
9440     }
9441   else
9442     b = XNEW (struct breakpoint);
9443
9444   old_chain = make_cleanup (xfree, b);
9445
9446   init_breakpoint_sal (b, gdbarch,
9447                        sals, addr_string,
9448                        filter, cond_string, extra_string,
9449                        type, disposition,
9450                        thread, task, ignore_count,
9451                        ops, from_tty,
9452                        enabled, internal, flags,
9453                        display_canonical);
9454   discard_cleanups (old_chain);
9455
9456   install_breakpoint (internal, b, 0);
9457 }
9458
9459 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9460    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9461    value.  COND_STRING, if not NULL, specified the condition to be
9462    used for all breakpoints.  Essentially the only case where
9463    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9464    function.  In that case, it's still not possible to specify
9465    separate conditions for different overloaded functions, so
9466    we take just a single condition string.
9467    
9468    NOTE: If the function succeeds, the caller is expected to cleanup
9469    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9470    array contents).  If the function fails (error() is called), the
9471    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9472    COND and SALS arrays and each of those arrays contents.  */
9473
9474 static void
9475 create_breakpoints_sal (struct gdbarch *gdbarch,
9476                         struct linespec_result *canonical,
9477                         char *cond_string, char *extra_string,
9478                         enum bptype type, enum bpdisp disposition,
9479                         int thread, int task, int ignore_count,
9480                         const struct breakpoint_ops *ops, int from_tty,
9481                         int enabled, int internal, unsigned flags)
9482 {
9483   int i;
9484   struct linespec_sals *lsal;
9485
9486   if (canonical->pre_expanded)
9487     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9488
9489   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9490     {
9491       /* Note that 'addr_string' can be NULL in the case of a plain
9492          'break', without arguments.  */
9493       char *addr_string = (canonical->addr_string
9494                            ? xstrdup (canonical->addr_string)
9495                            : NULL);
9496       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9497       struct cleanup *inner = make_cleanup (xfree, addr_string);
9498
9499       make_cleanup (xfree, filter_string);
9500       create_breakpoint_sal (gdbarch, lsal->sals,
9501                              addr_string,
9502                              filter_string,
9503                              cond_string, extra_string,
9504                              type, disposition,
9505                              thread, task, ignore_count, ops,
9506                              from_tty, enabled, internal, flags,
9507                              canonical->special_display);
9508       discard_cleanups (inner);
9509     }
9510 }
9511
9512 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9513    followed by conditionals.  On return, SALS contains an array of SAL
9514    addresses found.  ADDR_STRING contains a vector of (canonical)
9515    address strings.  ADDRESS points to the end of the SAL.
9516
9517    The array and the line spec strings are allocated on the heap, it is
9518    the caller's responsibility to free them.  */
9519
9520 static void
9521 parse_breakpoint_sals (char **address,
9522                        struct linespec_result *canonical)
9523 {
9524   /* If no arg given, or if first arg is 'if ', use the default
9525      breakpoint.  */
9526   if ((*address) == NULL
9527       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9528     {
9529       /* The last displayed codepoint, if it's valid, is our default breakpoint
9530          address.  */
9531       if (last_displayed_sal_is_valid ())
9532         {
9533           struct linespec_sals lsal;
9534           struct symtab_and_line sal;
9535           CORE_ADDR pc;
9536
9537           init_sal (&sal);              /* Initialize to zeroes.  */
9538           lsal.sals.sals = (struct symtab_and_line *)
9539             xmalloc (sizeof (struct symtab_and_line));
9540
9541           /* Set sal's pspace, pc, symtab, and line to the values
9542              corresponding to the last call to print_frame_info.
9543              Be sure to reinitialize LINE with NOTCURRENT == 0
9544              as the breakpoint line number is inappropriate otherwise.
9545              find_pc_line would adjust PC, re-set it back.  */
9546           get_last_displayed_sal (&sal);
9547           pc = sal.pc;
9548           sal = find_pc_line (pc, 0);
9549
9550           /* "break" without arguments is equivalent to "break *PC"
9551              where PC is the last displayed codepoint's address.  So
9552              make sure to set sal.explicit_pc to prevent GDB from
9553              trying to expand the list of sals to include all other
9554              instances with the same symtab and line.  */
9555           sal.pc = pc;
9556           sal.explicit_pc = 1;
9557
9558           lsal.sals.sals[0] = sal;
9559           lsal.sals.nelts = 1;
9560           lsal.canonical = NULL;
9561
9562           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9563         }
9564       else
9565         error (_("No default breakpoint address now."));
9566     }
9567   else
9568     {
9569       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9570
9571       /* Force almost all breakpoints to be in terms of the
9572          current_source_symtab (which is decode_line_1's default).
9573          This should produce the results we want almost all of the
9574          time while leaving default_breakpoint_* alone.
9575
9576          ObjC: However, don't match an Objective-C method name which
9577          may have a '+' or '-' succeeded by a '['.  */
9578       if (last_displayed_sal_is_valid ()
9579           && (!cursal.symtab
9580               || ((strchr ("+-", (*address)[0]) != NULL)
9581                   && ((*address)[1] != '['))))
9582         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9583                           get_last_displayed_symtab (),
9584                           get_last_displayed_line (),
9585                           canonical, NULL, NULL);
9586       else
9587         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9588                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9589     }
9590 }
9591
9592
9593 /* Convert each SAL into a real PC.  Verify that the PC can be
9594    inserted as a breakpoint.  If it can't throw an error.  */
9595
9596 static void
9597 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9598 {    
9599   int i;
9600
9601   for (i = 0; i < sals->nelts; i++)
9602     resolve_sal_pc (&sals->sals[i]);
9603 }
9604
9605 /* Fast tracepoints may have restrictions on valid locations.  For
9606    instance, a fast tracepoint using a jump instead of a trap will
9607    likely have to overwrite more bytes than a trap would, and so can
9608    only be placed where the instruction is longer than the jump, or a
9609    multi-instruction sequence does not have a jump into the middle of
9610    it, etc.  */
9611
9612 static void
9613 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9614                             struct symtabs_and_lines *sals)
9615 {
9616   int i, rslt;
9617   struct symtab_and_line *sal;
9618   char *msg;
9619   struct cleanup *old_chain;
9620
9621   for (i = 0; i < sals->nelts; i++)
9622     {
9623       struct gdbarch *sarch;
9624
9625       sal = &sals->sals[i];
9626
9627       sarch = get_sal_arch (*sal);
9628       /* We fall back to GDBARCH if there is no architecture
9629          associated with SAL.  */
9630       if (sarch == NULL)
9631         sarch = gdbarch;
9632       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9633                                                NULL, &msg);
9634       old_chain = make_cleanup (xfree, msg);
9635
9636       if (!rslt)
9637         error (_("May not have a fast tracepoint at 0x%s%s"),
9638                paddress (sarch, sal->pc), (msg ? msg : ""));
9639
9640       do_cleanups (old_chain);
9641     }
9642 }
9643
9644 /* Issue an invalid thread ID error.  */
9645
9646 static void ATTRIBUTE_NORETURN
9647 invalid_thread_id_error (int id)
9648 {
9649   error (_("Unknown thread %d."), id);
9650 }
9651
9652 /* Given TOK, a string specification of condition and thread, as
9653    accepted by the 'break' command, extract the condition
9654    string and thread number and set *COND_STRING and *THREAD.
9655    PC identifies the context at which the condition should be parsed.
9656    If no condition is found, *COND_STRING is set to NULL.
9657    If no thread is found, *THREAD is set to -1.  */
9658
9659 static void
9660 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9661                            char **cond_string, int *thread, int *task,
9662                            char **rest)
9663 {
9664   *cond_string = NULL;
9665   *thread = -1;
9666   *task = 0;
9667   *rest = NULL;
9668
9669   while (tok && *tok)
9670     {
9671       const char *end_tok;
9672       int toklen;
9673       const char *cond_start = NULL;
9674       const char *cond_end = NULL;
9675
9676       tok = skip_spaces_const (tok);
9677
9678       if ((*tok == '"' || *tok == ',') && rest)
9679         {
9680           *rest = savestring (tok, strlen (tok));
9681           return;
9682         }
9683
9684       end_tok = skip_to_space_const (tok);
9685
9686       toklen = end_tok - tok;
9687
9688       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9689         {
9690           struct expression *expr;
9691
9692           tok = cond_start = end_tok + 1;
9693           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9694           xfree (expr);
9695           cond_end = tok;
9696           *cond_string = savestring (cond_start, cond_end - cond_start);
9697         }
9698       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9699         {
9700           char *tmptok;
9701
9702           tok = end_tok + 1;
9703           *thread = strtol (tok, &tmptok, 0);
9704           if (tok == tmptok)
9705             error (_("Junk after thread keyword."));
9706           if (!valid_thread_id (*thread))
9707             invalid_thread_id_error (*thread);
9708           tok = tmptok;
9709         }
9710       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9711         {
9712           char *tmptok;
9713
9714           tok = end_tok + 1;
9715           *task = strtol (tok, &tmptok, 0);
9716           if (tok == tmptok)
9717             error (_("Junk after task keyword."));
9718           if (!valid_task_id (*task))
9719             error (_("Unknown task %d."), *task);
9720           tok = tmptok;
9721         }
9722       else if (rest)
9723         {
9724           *rest = savestring (tok, strlen (tok));
9725           return;
9726         }
9727       else
9728         error (_("Junk at end of arguments."));
9729     }
9730 }
9731
9732 /* Decode a static tracepoint marker spec.  */
9733
9734 static struct symtabs_and_lines
9735 decode_static_tracepoint_spec (char **arg_p)
9736 {
9737   VEC(static_tracepoint_marker_p) *markers = NULL;
9738   struct symtabs_and_lines sals;
9739   struct cleanup *old_chain;
9740   char *p = &(*arg_p)[3];
9741   char *endp;
9742   char *marker_str;
9743   int i;
9744
9745   p = skip_spaces (p);
9746
9747   endp = skip_to_space (p);
9748
9749   marker_str = savestring (p, endp - p);
9750   old_chain = make_cleanup (xfree, marker_str);
9751
9752   markers = target_static_tracepoint_markers_by_strid (marker_str);
9753   if (VEC_empty(static_tracepoint_marker_p, markers))
9754     error (_("No known static tracepoint marker named %s"), marker_str);
9755
9756   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9757   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9758
9759   for (i = 0; i < sals.nelts; i++)
9760     {
9761       struct static_tracepoint_marker *marker;
9762
9763       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9764
9765       init_sal (&sals.sals[i]);
9766
9767       sals.sals[i] = find_pc_line (marker->address, 0);
9768       sals.sals[i].pc = marker->address;
9769
9770       release_static_tracepoint_marker (marker);
9771     }
9772
9773   do_cleanups (old_chain);
9774
9775   *arg_p = endp;
9776   return sals;
9777 }
9778
9779 /* Set a breakpoint.  This function is shared between CLI and MI
9780    functions for setting a breakpoint.  This function has two major
9781    modes of operations, selected by the PARSE_ARG parameter.  If
9782    non-zero, the function will parse ARG, extracting location,
9783    condition, thread and extra string.  Otherwise, ARG is just the
9784    breakpoint's location, with condition, thread, and extra string
9785    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9786    If INTERNAL is non-zero, the breakpoint number will be allocated
9787    from the internal breakpoint count.  Returns true if any breakpoint
9788    was created; false otherwise.  */
9789
9790 int
9791 create_breakpoint (struct gdbarch *gdbarch,
9792                    char *arg, char *cond_string,
9793                    int thread, char *extra_string,
9794                    int parse_arg,
9795                    int tempflag, enum bptype type_wanted,
9796                    int ignore_count,
9797                    enum auto_boolean pending_break_support,
9798                    const struct breakpoint_ops *ops,
9799                    int from_tty, int enabled, int internal,
9800                    unsigned flags)
9801 {
9802   volatile struct gdb_exception e;
9803   char *copy_arg = NULL;
9804   char *addr_start = arg;
9805   struct linespec_result canonical;
9806   struct cleanup *old_chain;
9807   struct cleanup *bkpt_chain = NULL;
9808   int pending = 0;
9809   int task = 0;
9810   int prev_bkpt_count = breakpoint_count;
9811
9812   gdb_assert (ops != NULL);
9813
9814   init_linespec_result (&canonical);
9815
9816   TRY_CATCH (e, RETURN_MASK_ALL)
9817     {
9818       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9819                                      addr_start, &copy_arg);
9820     }
9821
9822   /* If caller is interested in rc value from parse, set value.  */
9823   switch (e.reason)
9824     {
9825     case GDB_NO_ERROR:
9826       if (VEC_empty (linespec_sals, canonical.sals))
9827         return 0;
9828       break;
9829     case RETURN_ERROR:
9830       switch (e.error)
9831         {
9832         case NOT_FOUND_ERROR:
9833
9834           /* If pending breakpoint support is turned off, throw
9835              error.  */
9836
9837           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9838             throw_exception (e);
9839
9840           exception_print (gdb_stderr, e);
9841
9842           /* If pending breakpoint support is auto query and the user
9843              selects no, then simply return the error code.  */
9844           if (pending_break_support == AUTO_BOOLEAN_AUTO
9845               && !nquery (_("Make %s pending on future shared library load? "),
9846                           bptype_string (type_wanted)))
9847             return 0;
9848
9849           /* At this point, either the user was queried about setting
9850              a pending breakpoint and selected yes, or pending
9851              breakpoint behavior is on and thus a pending breakpoint
9852              is defaulted on behalf of the user.  */
9853           {
9854             struct linespec_sals lsal;
9855
9856             copy_arg = xstrdup (addr_start);
9857             lsal.canonical = xstrdup (copy_arg);
9858             lsal.sals.nelts = 1;
9859             lsal.sals.sals = XNEW (struct symtab_and_line);
9860             init_sal (&lsal.sals.sals[0]);
9861             pending = 1;
9862             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9863           }
9864           break;
9865         default:
9866           throw_exception (e);
9867         }
9868       break;
9869     default:
9870       throw_exception (e);
9871     }
9872
9873   /* Create a chain of things that always need to be cleaned up.  */
9874   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9875
9876   /* ----------------------------- SNIP -----------------------------
9877      Anything added to the cleanup chain beyond this point is assumed
9878      to be part of a breakpoint.  If the breakpoint create succeeds
9879      then the memory is not reclaimed.  */
9880   bkpt_chain = make_cleanup (null_cleanup, 0);
9881
9882   /* Resolve all line numbers to PC's and verify that the addresses
9883      are ok for the target.  */
9884   if (!pending)
9885     {
9886       int ix;
9887       struct linespec_sals *iter;
9888
9889       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9890         breakpoint_sals_to_pc (&iter->sals);
9891     }
9892
9893   /* Fast tracepoints may have additional restrictions on location.  */
9894   if (!pending && type_wanted == bp_fast_tracepoint)
9895     {
9896       int ix;
9897       struct linespec_sals *iter;
9898
9899       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9900         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9901     }
9902
9903   /* Verify that condition can be parsed, before setting any
9904      breakpoints.  Allocate a separate condition expression for each
9905      breakpoint.  */
9906   if (!pending)
9907     {
9908       if (parse_arg)
9909         {
9910           char *rest;
9911           struct linespec_sals *lsal;
9912
9913           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9914
9915           /* Here we only parse 'arg' to separate condition
9916              from thread number, so parsing in context of first
9917              sal is OK.  When setting the breakpoint we'll
9918              re-parse it in context of each sal.  */
9919
9920           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9921                                      &thread, &task, &rest);
9922           if (cond_string)
9923             make_cleanup (xfree, cond_string);
9924           if (rest)
9925             make_cleanup (xfree, rest);
9926           if (rest)
9927             extra_string = rest;
9928         }
9929       else
9930         {
9931           if (*arg != '\0')
9932             error (_("Garbage '%s' at end of location"), arg);
9933
9934           /* Create a private copy of condition string.  */
9935           if (cond_string)
9936             {
9937               cond_string = xstrdup (cond_string);
9938               make_cleanup (xfree, cond_string);
9939             }
9940           /* Create a private copy of any extra string.  */
9941           if (extra_string)
9942             {
9943               extra_string = xstrdup (extra_string);
9944               make_cleanup (xfree, extra_string);
9945             }
9946         }
9947
9948       ops->create_breakpoints_sal (gdbarch, &canonical,
9949                                    cond_string, extra_string, type_wanted,
9950                                    tempflag ? disp_del : disp_donttouch,
9951                                    thread, task, ignore_count, ops,
9952                                    from_tty, enabled, internal, flags);
9953     }
9954   else
9955     {
9956       struct breakpoint *b;
9957
9958       make_cleanup (xfree, copy_arg);
9959
9960       if (is_tracepoint_type (type_wanted))
9961         {
9962           struct tracepoint *t;
9963
9964           t = XCNEW (struct tracepoint);
9965           b = &t->base;
9966         }
9967       else
9968         b = XNEW (struct breakpoint);
9969
9970       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9971
9972       b->addr_string = copy_arg;
9973       if (parse_arg)
9974         b->cond_string = NULL;
9975       else
9976         {
9977           /* Create a private copy of condition string.  */
9978           if (cond_string)
9979             {
9980               cond_string = xstrdup (cond_string);
9981               make_cleanup (xfree, cond_string);
9982             }
9983           b->cond_string = cond_string;
9984         }
9985       b->extra_string = NULL;
9986       b->ignore_count = ignore_count;
9987       b->disposition = tempflag ? disp_del : disp_donttouch;
9988       b->condition_not_parsed = 1;
9989       b->enable_state = enabled ? bp_enabled : bp_disabled;
9990       if ((type_wanted != bp_breakpoint
9991            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9992         b->pspace = current_program_space;
9993
9994       install_breakpoint (internal, b, 0);
9995     }
9996   
9997   if (VEC_length (linespec_sals, canonical.sals) > 1)
9998     {
9999       warning (_("Multiple breakpoints were set.\nUse the "
10000                  "\"delete\" command to delete unwanted breakpoints."));
10001       prev_breakpoint_count = prev_bkpt_count;
10002     }
10003
10004   /* That's it.  Discard the cleanups for data inserted into the
10005      breakpoint.  */
10006   discard_cleanups (bkpt_chain);
10007   /* But cleanup everything else.  */
10008   do_cleanups (old_chain);
10009
10010   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10011   update_global_location_list (1);
10012
10013   return 1;
10014 }
10015
10016 /* Set a breakpoint.
10017    ARG is a string describing breakpoint address,
10018    condition, and thread.
10019    FLAG specifies if a breakpoint is hardware on,
10020    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10021    and BP_TEMPFLAG.  */
10022
10023 static void
10024 break_command_1 (char *arg, int flag, int from_tty)
10025 {
10026   int tempflag = flag & BP_TEMPFLAG;
10027   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10028                              ? bp_hardware_breakpoint
10029                              : bp_breakpoint);
10030   struct breakpoint_ops *ops;
10031   const char *arg_cp = arg;
10032
10033   /* Matching breakpoints on probes.  */
10034   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10035     ops = &bkpt_probe_breakpoint_ops;
10036   else
10037     ops = &bkpt_breakpoint_ops;
10038
10039   create_breakpoint (get_current_arch (),
10040                      arg,
10041                      NULL, 0, NULL, 1 /* parse arg */,
10042                      tempflag, type_wanted,
10043                      0 /* Ignore count */,
10044                      pending_break_support,
10045                      ops,
10046                      from_tty,
10047                      1 /* enabled */,
10048                      0 /* internal */,
10049                      0);
10050 }
10051
10052 /* Helper function for break_command_1 and disassemble_command.  */
10053
10054 void
10055 resolve_sal_pc (struct symtab_and_line *sal)
10056 {
10057   CORE_ADDR pc;
10058
10059   if (sal->pc == 0 && sal->symtab != NULL)
10060     {
10061       if (!find_line_pc (sal->symtab, sal->line, &pc))
10062         error (_("No line %d in file \"%s\"."),
10063                sal->line, symtab_to_filename_for_display (sal->symtab));
10064       sal->pc = pc;
10065
10066       /* If this SAL corresponds to a breakpoint inserted using a line
10067          number, then skip the function prologue if necessary.  */
10068       if (sal->explicit_line)
10069         skip_prologue_sal (sal);
10070     }
10071
10072   if (sal->section == 0 && sal->symtab != NULL)
10073     {
10074       struct blockvector *bv;
10075       struct block *b;
10076       struct symbol *sym;
10077
10078       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10079       if (bv != NULL)
10080         {
10081           sym = block_linkage_function (b);
10082           if (sym != NULL)
10083             {
10084               fixup_symbol_section (sym, sal->symtab->objfile);
10085               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10086             }
10087           else
10088             {
10089               /* It really is worthwhile to have the section, so we'll
10090                  just have to look harder. This case can be executed
10091                  if we have line numbers but no functions (as can
10092                  happen in assembly source).  */
10093
10094               struct bound_minimal_symbol msym;
10095               struct cleanup *old_chain = save_current_space_and_thread ();
10096
10097               switch_to_program_space_and_thread (sal->pspace);
10098
10099               msym = lookup_minimal_symbol_by_pc (sal->pc);
10100               if (msym.minsym)
10101                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10102
10103               do_cleanups (old_chain);
10104             }
10105         }
10106     }
10107 }
10108
10109 void
10110 break_command (char *arg, int from_tty)
10111 {
10112   break_command_1 (arg, 0, from_tty);
10113 }
10114
10115 void
10116 tbreak_command (char *arg, int from_tty)
10117 {
10118   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10119 }
10120
10121 static void
10122 hbreak_command (char *arg, int from_tty)
10123 {
10124   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10125 }
10126
10127 static void
10128 thbreak_command (char *arg, int from_tty)
10129 {
10130   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10131 }
10132
10133 static void
10134 stop_command (char *arg, int from_tty)
10135 {
10136   printf_filtered (_("Specify the type of breakpoint to set.\n\
10137 Usage: stop in <function | address>\n\
10138        stop at <line>\n"));
10139 }
10140
10141 static void
10142 stopin_command (char *arg, int from_tty)
10143 {
10144   int badInput = 0;
10145
10146   if (arg == (char *) NULL)
10147     badInput = 1;
10148   else if (*arg != '*')
10149     {
10150       char *argptr = arg;
10151       int hasColon = 0;
10152
10153       /* Look for a ':'.  If this is a line number specification, then
10154          say it is bad, otherwise, it should be an address or
10155          function/method name.  */
10156       while (*argptr && !hasColon)
10157         {
10158           hasColon = (*argptr == ':');
10159           argptr++;
10160         }
10161
10162       if (hasColon)
10163         badInput = (*argptr != ':');    /* Not a class::method */
10164       else
10165         badInput = isdigit (*arg);      /* a simple line number */
10166     }
10167
10168   if (badInput)
10169     printf_filtered (_("Usage: stop in <function | address>\n"));
10170   else
10171     break_command_1 (arg, 0, from_tty);
10172 }
10173
10174 static void
10175 stopat_command (char *arg, int from_tty)
10176 {
10177   int badInput = 0;
10178
10179   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10180     badInput = 1;
10181   else
10182     {
10183       char *argptr = arg;
10184       int hasColon = 0;
10185
10186       /* Look for a ':'.  If there is a '::' then get out, otherwise
10187          it is probably a line number.  */
10188       while (*argptr && !hasColon)
10189         {
10190           hasColon = (*argptr == ':');
10191           argptr++;
10192         }
10193
10194       if (hasColon)
10195         badInput = (*argptr == ':');    /* we have class::method */
10196       else
10197         badInput = !isdigit (*arg);     /* not a line number */
10198     }
10199
10200   if (badInput)
10201     printf_filtered (_("Usage: stop at <line>\n"));
10202   else
10203     break_command_1 (arg, 0, from_tty);
10204 }
10205
10206 /* The dynamic printf command is mostly like a regular breakpoint, but
10207    with a prewired command list consisting of a single output command,
10208    built from extra arguments supplied on the dprintf command
10209    line.  */
10210
10211 static void
10212 dprintf_command (char *arg, int from_tty)
10213 {
10214   create_breakpoint (get_current_arch (),
10215                      arg,
10216                      NULL, 0, NULL, 1 /* parse arg */,
10217                      0, bp_dprintf,
10218                      0 /* Ignore count */,
10219                      pending_break_support,
10220                      &dprintf_breakpoint_ops,
10221                      from_tty,
10222                      1 /* enabled */,
10223                      0 /* internal */,
10224                      0);
10225 }
10226
10227 static void
10228 agent_printf_command (char *arg, int from_tty)
10229 {
10230   error (_("May only run agent-printf on the target"));
10231 }
10232
10233 /* Implement the "breakpoint_hit" breakpoint_ops method for
10234    ranged breakpoints.  */
10235
10236 static int
10237 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10238                                   struct address_space *aspace,
10239                                   CORE_ADDR bp_addr,
10240                                   const struct target_waitstatus *ws)
10241 {
10242   if (ws->kind != TARGET_WAITKIND_STOPPED
10243       || ws->value.sig != GDB_SIGNAL_TRAP)
10244     return 0;
10245
10246   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10247                                          bl->length, aspace, bp_addr);
10248 }
10249
10250 /* Implement the "resources_needed" breakpoint_ops method for
10251    ranged breakpoints.  */
10252
10253 static int
10254 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10255 {
10256   return target_ranged_break_num_registers ();
10257 }
10258
10259 /* Implement the "print_it" breakpoint_ops method for
10260    ranged breakpoints.  */
10261
10262 static enum print_stop_action
10263 print_it_ranged_breakpoint (bpstat bs)
10264 {
10265   struct breakpoint *b = bs->breakpoint_at;
10266   struct bp_location *bl = b->loc;
10267   struct ui_out *uiout = current_uiout;
10268
10269   gdb_assert (b->type == bp_hardware_breakpoint);
10270
10271   /* Ranged breakpoints have only one location.  */
10272   gdb_assert (bl && bl->next == NULL);
10273
10274   annotate_breakpoint (b->number);
10275   if (b->disposition == disp_del)
10276     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10277   else
10278     ui_out_text (uiout, "\nRanged breakpoint ");
10279   if (ui_out_is_mi_like_p (uiout))
10280     {
10281       ui_out_field_string (uiout, "reason",
10282                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10283       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10284     }
10285   ui_out_field_int (uiout, "bkptno", b->number);
10286   ui_out_text (uiout, ", ");
10287
10288   return PRINT_SRC_AND_LOC;
10289 }
10290
10291 /* Implement the "print_one" breakpoint_ops method for
10292    ranged breakpoints.  */
10293
10294 static void
10295 print_one_ranged_breakpoint (struct breakpoint *b,
10296                              struct bp_location **last_loc)
10297 {
10298   struct bp_location *bl = b->loc;
10299   struct value_print_options opts;
10300   struct ui_out *uiout = current_uiout;
10301
10302   /* Ranged breakpoints have only one location.  */
10303   gdb_assert (bl && bl->next == NULL);
10304
10305   get_user_print_options (&opts);
10306
10307   if (opts.addressprint)
10308     /* We don't print the address range here, it will be printed later
10309        by print_one_detail_ranged_breakpoint.  */
10310     ui_out_field_skip (uiout, "addr");
10311   annotate_field (5);
10312   print_breakpoint_location (b, bl);
10313   *last_loc = bl;
10314 }
10315
10316 /* Implement the "print_one_detail" breakpoint_ops method for
10317    ranged breakpoints.  */
10318
10319 static void
10320 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10321                                     struct ui_out *uiout)
10322 {
10323   CORE_ADDR address_start, address_end;
10324   struct bp_location *bl = b->loc;
10325   struct ui_file *stb = mem_fileopen ();
10326   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10327
10328   gdb_assert (bl);
10329
10330   address_start = bl->address;
10331   address_end = address_start + bl->length - 1;
10332
10333   ui_out_text (uiout, "\taddress range: ");
10334   fprintf_unfiltered (stb, "[%s, %s]",
10335                       print_core_address (bl->gdbarch, address_start),
10336                       print_core_address (bl->gdbarch, address_end));
10337   ui_out_field_stream (uiout, "addr", stb);
10338   ui_out_text (uiout, "\n");
10339
10340   do_cleanups (cleanup);
10341 }
10342
10343 /* Implement the "print_mention" breakpoint_ops method for
10344    ranged breakpoints.  */
10345
10346 static void
10347 print_mention_ranged_breakpoint (struct breakpoint *b)
10348 {
10349   struct bp_location *bl = b->loc;
10350   struct ui_out *uiout = current_uiout;
10351
10352   gdb_assert (bl);
10353   gdb_assert (b->type == bp_hardware_breakpoint);
10354
10355   if (ui_out_is_mi_like_p (uiout))
10356     return;
10357
10358   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10359                    b->number, paddress (bl->gdbarch, bl->address),
10360                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10361 }
10362
10363 /* Implement the "print_recreate" breakpoint_ops method for
10364    ranged breakpoints.  */
10365
10366 static void
10367 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10368 {
10369   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10370                       b->addr_string_range_end);
10371   print_recreate_thread (b, fp);
10372 }
10373
10374 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10375
10376 static struct breakpoint_ops ranged_breakpoint_ops;
10377
10378 /* Find the address where the end of the breakpoint range should be
10379    placed, given the SAL of the end of the range.  This is so that if
10380    the user provides a line number, the end of the range is set to the
10381    last instruction of the given line.  */
10382
10383 static CORE_ADDR
10384 find_breakpoint_range_end (struct symtab_and_line sal)
10385 {
10386   CORE_ADDR end;
10387
10388   /* If the user provided a PC value, use it.  Otherwise,
10389      find the address of the end of the given location.  */
10390   if (sal.explicit_pc)
10391     end = sal.pc;
10392   else
10393     {
10394       int ret;
10395       CORE_ADDR start;
10396
10397       ret = find_line_pc_range (sal, &start, &end);
10398       if (!ret)
10399         error (_("Could not find location of the end of the range."));
10400
10401       /* find_line_pc_range returns the start of the next line.  */
10402       end--;
10403     }
10404
10405   return end;
10406 }
10407
10408 /* Implement the "break-range" CLI command.  */
10409
10410 static void
10411 break_range_command (char *arg, int from_tty)
10412 {
10413   char *arg_start, *addr_string_start, *addr_string_end;
10414   struct linespec_result canonical_start, canonical_end;
10415   int bp_count, can_use_bp, length;
10416   CORE_ADDR end;
10417   struct breakpoint *b;
10418   struct symtab_and_line sal_start, sal_end;
10419   struct cleanup *cleanup_bkpt;
10420   struct linespec_sals *lsal_start, *lsal_end;
10421
10422   /* We don't support software ranged breakpoints.  */
10423   if (target_ranged_break_num_registers () < 0)
10424     error (_("This target does not support hardware ranged breakpoints."));
10425
10426   bp_count = hw_breakpoint_used_count ();
10427   bp_count += target_ranged_break_num_registers ();
10428   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10429                                                    bp_count, 0);
10430   if (can_use_bp < 0)
10431     error (_("Hardware breakpoints used exceeds limit."));
10432
10433   arg = skip_spaces (arg);
10434   if (arg == NULL || arg[0] == '\0')
10435     error(_("No address range specified."));
10436
10437   init_linespec_result (&canonical_start);
10438
10439   arg_start = arg;
10440   parse_breakpoint_sals (&arg, &canonical_start);
10441
10442   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10443
10444   if (arg[0] != ',')
10445     error (_("Too few arguments."));
10446   else if (VEC_empty (linespec_sals, canonical_start.sals))
10447     error (_("Could not find location of the beginning of the range."));
10448
10449   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10450
10451   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10452       || lsal_start->sals.nelts != 1)
10453     error (_("Cannot create a ranged breakpoint with multiple locations."));
10454
10455   sal_start = lsal_start->sals.sals[0];
10456   addr_string_start = savestring (arg_start, arg - arg_start);
10457   make_cleanup (xfree, addr_string_start);
10458
10459   arg++;        /* Skip the comma.  */
10460   arg = skip_spaces (arg);
10461
10462   /* Parse the end location.  */
10463
10464   init_linespec_result (&canonical_end);
10465   arg_start = arg;
10466
10467   /* We call decode_line_full directly here instead of using
10468      parse_breakpoint_sals because we need to specify the start location's
10469      symtab and line as the default symtab and line for the end of the
10470      range.  This makes it possible to have ranges like "foo.c:27, +14",
10471      where +14 means 14 lines from the start location.  */
10472   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10473                     sal_start.symtab, sal_start.line,
10474                     &canonical_end, NULL, NULL);
10475
10476   make_cleanup_destroy_linespec_result (&canonical_end);
10477
10478   if (VEC_empty (linespec_sals, canonical_end.sals))
10479     error (_("Could not find location of the end of the range."));
10480
10481   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10482   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10483       || lsal_end->sals.nelts != 1)
10484     error (_("Cannot create a ranged breakpoint with multiple locations."));
10485
10486   sal_end = lsal_end->sals.sals[0];
10487   addr_string_end = savestring (arg_start, arg - arg_start);
10488   make_cleanup (xfree, addr_string_end);
10489
10490   end = find_breakpoint_range_end (sal_end);
10491   if (sal_start.pc > end)
10492     error (_("Invalid address range, end precedes start."));
10493
10494   length = end - sal_start.pc + 1;
10495   if (length < 0)
10496     /* Length overflowed.  */
10497     error (_("Address range too large."));
10498   else if (length == 1)
10499     {
10500       /* This range is simple enough to be handled by
10501          the `hbreak' command.  */
10502       hbreak_command (addr_string_start, 1);
10503
10504       do_cleanups (cleanup_bkpt);
10505
10506       return;
10507     }
10508
10509   /* Now set up the breakpoint.  */
10510   b = set_raw_breakpoint (get_current_arch (), sal_start,
10511                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10512   set_breakpoint_count (breakpoint_count + 1);
10513   b->number = breakpoint_count;
10514   b->disposition = disp_donttouch;
10515   b->addr_string = xstrdup (addr_string_start);
10516   b->addr_string_range_end = xstrdup (addr_string_end);
10517   b->loc->length = length;
10518
10519   do_cleanups (cleanup_bkpt);
10520
10521   mention (b);
10522   observer_notify_breakpoint_created (b);
10523   update_global_location_list (1);
10524 }
10525
10526 /*  Return non-zero if EXP is verified as constant.  Returned zero
10527     means EXP is variable.  Also the constant detection may fail for
10528     some constant expressions and in such case still falsely return
10529     zero.  */
10530
10531 static int
10532 watchpoint_exp_is_const (const struct expression *exp)
10533 {
10534   int i = exp->nelts;
10535
10536   while (i > 0)
10537     {
10538       int oplenp, argsp;
10539
10540       /* We are only interested in the descriptor of each element.  */
10541       operator_length (exp, i, &oplenp, &argsp);
10542       i -= oplenp;
10543
10544       switch (exp->elts[i].opcode)
10545         {
10546         case BINOP_ADD:
10547         case BINOP_SUB:
10548         case BINOP_MUL:
10549         case BINOP_DIV:
10550         case BINOP_REM:
10551         case BINOP_MOD:
10552         case BINOP_LSH:
10553         case BINOP_RSH:
10554         case BINOP_LOGICAL_AND:
10555         case BINOP_LOGICAL_OR:
10556         case BINOP_BITWISE_AND:
10557         case BINOP_BITWISE_IOR:
10558         case BINOP_BITWISE_XOR:
10559         case BINOP_EQUAL:
10560         case BINOP_NOTEQUAL:
10561         case BINOP_LESS:
10562         case BINOP_GTR:
10563         case BINOP_LEQ:
10564         case BINOP_GEQ:
10565         case BINOP_REPEAT:
10566         case BINOP_COMMA:
10567         case BINOP_EXP:
10568         case BINOP_MIN:
10569         case BINOP_MAX:
10570         case BINOP_INTDIV:
10571         case BINOP_CONCAT:
10572         case BINOP_IN:
10573         case BINOP_RANGE:
10574         case TERNOP_COND:
10575         case TERNOP_SLICE:
10576
10577         case OP_LONG:
10578         case OP_DOUBLE:
10579         case OP_DECFLOAT:
10580         case OP_LAST:
10581         case OP_COMPLEX:
10582         case OP_STRING:
10583         case OP_ARRAY:
10584         case OP_TYPE:
10585         case OP_TYPEOF:
10586         case OP_DECLTYPE:
10587         case OP_TYPEID:
10588         case OP_NAME:
10589         case OP_OBJC_NSSTRING:
10590
10591         case UNOP_NEG:
10592         case UNOP_LOGICAL_NOT:
10593         case UNOP_COMPLEMENT:
10594         case UNOP_ADDR:
10595         case UNOP_HIGH:
10596         case UNOP_CAST:
10597
10598         case UNOP_CAST_TYPE:
10599         case UNOP_REINTERPRET_CAST:
10600         case UNOP_DYNAMIC_CAST:
10601           /* Unary, binary and ternary operators: We have to check
10602              their operands.  If they are constant, then so is the
10603              result of that operation.  For instance, if A and B are
10604              determined to be constants, then so is "A + B".
10605
10606              UNOP_IND is one exception to the rule above, because the
10607              value of *ADDR is not necessarily a constant, even when
10608              ADDR is.  */
10609           break;
10610
10611         case OP_VAR_VALUE:
10612           /* Check whether the associated symbol is a constant.
10613
10614              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10615              possible that a buggy compiler could mark a variable as
10616              constant even when it is not, and TYPE_CONST would return
10617              true in this case, while SYMBOL_CLASS wouldn't.
10618
10619              We also have to check for function symbols because they
10620              are always constant.  */
10621           {
10622             struct symbol *s = exp->elts[i + 2].symbol;
10623
10624             if (SYMBOL_CLASS (s) != LOC_BLOCK
10625                 && SYMBOL_CLASS (s) != LOC_CONST
10626                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10627               return 0;
10628             break;
10629           }
10630
10631         /* The default action is to return 0 because we are using
10632            the optimistic approach here: If we don't know something,
10633            then it is not a constant.  */
10634         default:
10635           return 0;
10636         }
10637     }
10638
10639   return 1;
10640 }
10641
10642 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10643
10644 static void
10645 dtor_watchpoint (struct breakpoint *self)
10646 {
10647   struct watchpoint *w = (struct watchpoint *) self;
10648
10649   xfree (w->cond_exp);
10650   xfree (w->exp);
10651   xfree (w->exp_string);
10652   xfree (w->exp_string_reparse);
10653   value_free (w->val);
10654
10655   base_breakpoint_ops.dtor (self);
10656 }
10657
10658 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10659
10660 static void
10661 re_set_watchpoint (struct breakpoint *b)
10662 {
10663   struct watchpoint *w = (struct watchpoint *) b;
10664
10665   /* Watchpoint can be either on expression using entirely global
10666      variables, or it can be on local variables.
10667
10668      Watchpoints of the first kind are never auto-deleted, and even
10669      persist across program restarts.  Since they can use variables
10670      from shared libraries, we need to reparse expression as libraries
10671      are loaded and unloaded.
10672
10673      Watchpoints on local variables can also change meaning as result
10674      of solib event.  For example, if a watchpoint uses both a local
10675      and a global variables in expression, it's a local watchpoint,
10676      but unloading of a shared library will make the expression
10677      invalid.  This is not a very common use case, but we still
10678      re-evaluate expression, to avoid surprises to the user.
10679
10680      Note that for local watchpoints, we re-evaluate it only if
10681      watchpoints frame id is still valid.  If it's not, it means the
10682      watchpoint is out of scope and will be deleted soon.  In fact,
10683      I'm not sure we'll ever be called in this case.
10684
10685      If a local watchpoint's frame id is still valid, then
10686      w->exp_valid_block is likewise valid, and we can safely use it.
10687
10688      Don't do anything about disabled watchpoints, since they will be
10689      reevaluated again when enabled.  */
10690   update_watchpoint (w, 1 /* reparse */);
10691 }
10692
10693 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10694
10695 static int
10696 insert_watchpoint (struct bp_location *bl)
10697 {
10698   struct watchpoint *w = (struct watchpoint *) bl->owner;
10699   int length = w->exact ? 1 : bl->length;
10700
10701   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10702                                    w->cond_exp);
10703 }
10704
10705 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10706
10707 static int
10708 remove_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_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10714                                    w->cond_exp);
10715 }
10716
10717 static int
10718 breakpoint_hit_watchpoint (const struct bp_location *bl,
10719                            struct address_space *aspace, CORE_ADDR bp_addr,
10720                            const struct target_waitstatus *ws)
10721 {
10722   struct breakpoint *b = bl->owner;
10723   struct watchpoint *w = (struct watchpoint *) b;
10724
10725   /* Continuable hardware watchpoints are treated as non-existent if the
10726      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10727      some data address).  Otherwise gdb won't stop on a break instruction
10728      in the code (not from a breakpoint) when a hardware watchpoint has
10729      been defined.  Also skip watchpoints which we know did not trigger
10730      (did not match the data address).  */
10731   if (is_hardware_watchpoint (b)
10732       && w->watchpoint_triggered == watch_triggered_no)
10733     return 0;
10734
10735   return 1;
10736 }
10737
10738 static void
10739 check_status_watchpoint (bpstat bs)
10740 {
10741   gdb_assert (is_watchpoint (bs->breakpoint_at));
10742
10743   bpstat_check_watchpoint (bs);
10744 }
10745
10746 /* Implement the "resources_needed" breakpoint_ops method for
10747    hardware watchpoints.  */
10748
10749 static int
10750 resources_needed_watchpoint (const struct bp_location *bl)
10751 {
10752   struct watchpoint *w = (struct watchpoint *) bl->owner;
10753   int length = w->exact? 1 : bl->length;
10754
10755   return target_region_ok_for_hw_watchpoint (bl->address, length);
10756 }
10757
10758 /* Implement the "works_in_software_mode" breakpoint_ops method for
10759    hardware watchpoints.  */
10760
10761 static int
10762 works_in_software_mode_watchpoint (const struct breakpoint *b)
10763 {
10764   /* Read and access watchpoints only work with hardware support.  */
10765   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10766 }
10767
10768 static enum print_stop_action
10769 print_it_watchpoint (bpstat bs)
10770 {
10771   struct cleanup *old_chain;
10772   struct breakpoint *b;
10773   struct ui_file *stb;
10774   enum print_stop_action result;
10775   struct watchpoint *w;
10776   struct ui_out *uiout = current_uiout;
10777
10778   gdb_assert (bs->bp_location_at != NULL);
10779
10780   b = bs->breakpoint_at;
10781   w = (struct watchpoint *) b;
10782
10783   stb = mem_fileopen ();
10784   old_chain = make_cleanup_ui_file_delete (stb);
10785
10786   switch (b->type)
10787     {
10788     case bp_watchpoint:
10789     case bp_hardware_watchpoint:
10790       annotate_watchpoint (b->number);
10791       if (ui_out_is_mi_like_p (uiout))
10792         ui_out_field_string
10793           (uiout, "reason",
10794            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10795       mention (b);
10796       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10797       ui_out_text (uiout, "\nOld value = ");
10798       watchpoint_value_print (bs->old_val, stb);
10799       ui_out_field_stream (uiout, "old", stb);
10800       ui_out_text (uiout, "\nNew value = ");
10801       watchpoint_value_print (w->val, stb);
10802       ui_out_field_stream (uiout, "new", stb);
10803       ui_out_text (uiout, "\n");
10804       /* More than one watchpoint may have been triggered.  */
10805       result = PRINT_UNKNOWN;
10806       break;
10807
10808     case bp_read_watchpoint:
10809       if (ui_out_is_mi_like_p (uiout))
10810         ui_out_field_string
10811           (uiout, "reason",
10812            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10813       mention (b);
10814       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10815       ui_out_text (uiout, "\nValue = ");
10816       watchpoint_value_print (w->val, stb);
10817       ui_out_field_stream (uiout, "value", stb);
10818       ui_out_text (uiout, "\n");
10819       result = PRINT_UNKNOWN;
10820       break;
10821
10822     case bp_access_watchpoint:
10823       if (bs->old_val != NULL)
10824         {
10825           annotate_watchpoint (b->number);
10826           if (ui_out_is_mi_like_p (uiout))
10827             ui_out_field_string
10828               (uiout, "reason",
10829                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10830           mention (b);
10831           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10832           ui_out_text (uiout, "\nOld value = ");
10833           watchpoint_value_print (bs->old_val, stb);
10834           ui_out_field_stream (uiout, "old", stb);
10835           ui_out_text (uiout, "\nNew value = ");
10836         }
10837       else
10838         {
10839           mention (b);
10840           if (ui_out_is_mi_like_p (uiout))
10841             ui_out_field_string
10842               (uiout, "reason",
10843                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10844           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10845           ui_out_text (uiout, "\nValue = ");
10846         }
10847       watchpoint_value_print (w->val, stb);
10848       ui_out_field_stream (uiout, "new", stb);
10849       ui_out_text (uiout, "\n");
10850       result = PRINT_UNKNOWN;
10851       break;
10852     default:
10853       result = PRINT_UNKNOWN;
10854     }
10855
10856   do_cleanups (old_chain);
10857   return result;
10858 }
10859
10860 /* Implement the "print_mention" breakpoint_ops method for hardware
10861    watchpoints.  */
10862
10863 static void
10864 print_mention_watchpoint (struct breakpoint *b)
10865 {
10866   struct cleanup *ui_out_chain;
10867   struct watchpoint *w = (struct watchpoint *) b;
10868   struct ui_out *uiout = current_uiout;
10869
10870   switch (b->type)
10871     {
10872     case bp_watchpoint:
10873       ui_out_text (uiout, "Watchpoint ");
10874       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10875       break;
10876     case bp_hardware_watchpoint:
10877       ui_out_text (uiout, "Hardware watchpoint ");
10878       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10879       break;
10880     case bp_read_watchpoint:
10881       ui_out_text (uiout, "Hardware read watchpoint ");
10882       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10883       break;
10884     case bp_access_watchpoint:
10885       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10886       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10887       break;
10888     default:
10889       internal_error (__FILE__, __LINE__,
10890                       _("Invalid hardware watchpoint type."));
10891     }
10892
10893   ui_out_field_int (uiout, "number", b->number);
10894   ui_out_text (uiout, ": ");
10895   ui_out_field_string (uiout, "exp", w->exp_string);
10896   do_cleanups (ui_out_chain);
10897 }
10898
10899 /* Implement the "print_recreate" breakpoint_ops method for
10900    watchpoints.  */
10901
10902 static void
10903 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10904 {
10905   struct watchpoint *w = (struct watchpoint *) b;
10906
10907   switch (b->type)
10908     {
10909     case bp_watchpoint:
10910     case bp_hardware_watchpoint:
10911       fprintf_unfiltered (fp, "watch");
10912       break;
10913     case bp_read_watchpoint:
10914       fprintf_unfiltered (fp, "rwatch");
10915       break;
10916     case bp_access_watchpoint:
10917       fprintf_unfiltered (fp, "awatch");
10918       break;
10919     default:
10920       internal_error (__FILE__, __LINE__,
10921                       _("Invalid watchpoint type."));
10922     }
10923
10924   fprintf_unfiltered (fp, " %s", w->exp_string);
10925   print_recreate_thread (b, fp);
10926 }
10927
10928 /* Implement the "explains_signal" breakpoint_ops method for
10929    watchpoints.  */
10930
10931 static int
10932 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10933 {
10934   /* A software watchpoint cannot cause a signal other than
10935      GDB_SIGNAL_TRAP.  */
10936   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10937     return 0;
10938
10939   return 1;
10940 }
10941
10942 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10943
10944 static struct breakpoint_ops watchpoint_breakpoint_ops;
10945
10946 /* Implement the "insert" breakpoint_ops method for
10947    masked hardware watchpoints.  */
10948
10949 static int
10950 insert_masked_watchpoint (struct bp_location *bl)
10951 {
10952   struct watchpoint *w = (struct watchpoint *) bl->owner;
10953
10954   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10955                                         bl->watchpoint_type);
10956 }
10957
10958 /* Implement the "remove" breakpoint_ops method for
10959    masked hardware watchpoints.  */
10960
10961 static int
10962 remove_masked_watchpoint (struct bp_location *bl)
10963 {
10964   struct watchpoint *w = (struct watchpoint *) bl->owner;
10965
10966   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10967                                         bl->watchpoint_type);
10968 }
10969
10970 /* Implement the "resources_needed" breakpoint_ops method for
10971    masked hardware watchpoints.  */
10972
10973 static int
10974 resources_needed_masked_watchpoint (const struct bp_location *bl)
10975 {
10976   struct watchpoint *w = (struct watchpoint *) bl->owner;
10977
10978   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10979 }
10980
10981 /* Implement the "works_in_software_mode" breakpoint_ops method for
10982    masked hardware watchpoints.  */
10983
10984 static int
10985 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10986 {
10987   return 0;
10988 }
10989
10990 /* Implement the "print_it" breakpoint_ops method for
10991    masked hardware watchpoints.  */
10992
10993 static enum print_stop_action
10994 print_it_masked_watchpoint (bpstat bs)
10995 {
10996   struct breakpoint *b = bs->breakpoint_at;
10997   struct ui_out *uiout = current_uiout;
10998
10999   /* Masked watchpoints have only one location.  */
11000   gdb_assert (b->loc && b->loc->next == NULL);
11001
11002   switch (b->type)
11003     {
11004     case bp_hardware_watchpoint:
11005       annotate_watchpoint (b->number);
11006       if (ui_out_is_mi_like_p (uiout))
11007         ui_out_field_string
11008           (uiout, "reason",
11009            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11010       break;
11011
11012     case bp_read_watchpoint:
11013       if (ui_out_is_mi_like_p (uiout))
11014         ui_out_field_string
11015           (uiout, "reason",
11016            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11017       break;
11018
11019     case bp_access_watchpoint:
11020       if (ui_out_is_mi_like_p (uiout))
11021         ui_out_field_string
11022           (uiout, "reason",
11023            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11024       break;
11025     default:
11026       internal_error (__FILE__, __LINE__,
11027                       _("Invalid hardware watchpoint type."));
11028     }
11029
11030   mention (b);
11031   ui_out_text (uiout, _("\n\
11032 Check the underlying instruction at PC for the memory\n\
11033 address and value which triggered this watchpoint.\n"));
11034   ui_out_text (uiout, "\n");
11035
11036   /* More than one watchpoint may have been triggered.  */
11037   return PRINT_UNKNOWN;
11038 }
11039
11040 /* Implement the "print_one_detail" breakpoint_ops method for
11041    masked hardware watchpoints.  */
11042
11043 static void
11044 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11045                                     struct ui_out *uiout)
11046 {
11047   struct watchpoint *w = (struct watchpoint *) b;
11048
11049   /* Masked watchpoints have only one location.  */
11050   gdb_assert (b->loc && b->loc->next == NULL);
11051
11052   ui_out_text (uiout, "\tmask ");
11053   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11054   ui_out_text (uiout, "\n");
11055 }
11056
11057 /* Implement the "print_mention" breakpoint_ops method for
11058    masked hardware watchpoints.  */
11059
11060 static void
11061 print_mention_masked_watchpoint (struct breakpoint *b)
11062 {
11063   struct watchpoint *w = (struct watchpoint *) b;
11064   struct ui_out *uiout = current_uiout;
11065   struct cleanup *ui_out_chain;
11066
11067   switch (b->type)
11068     {
11069     case bp_hardware_watchpoint:
11070       ui_out_text (uiout, "Masked hardware watchpoint ");
11071       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11072       break;
11073     case bp_read_watchpoint:
11074       ui_out_text (uiout, "Masked hardware read watchpoint ");
11075       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11076       break;
11077     case bp_access_watchpoint:
11078       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11079       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11080       break;
11081     default:
11082       internal_error (__FILE__, __LINE__,
11083                       _("Invalid hardware watchpoint type."));
11084     }
11085
11086   ui_out_field_int (uiout, "number", b->number);
11087   ui_out_text (uiout, ": ");
11088   ui_out_field_string (uiout, "exp", w->exp_string);
11089   do_cleanups (ui_out_chain);
11090 }
11091
11092 /* Implement the "print_recreate" breakpoint_ops method for
11093    masked hardware watchpoints.  */
11094
11095 static void
11096 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11097 {
11098   struct watchpoint *w = (struct watchpoint *) b;
11099   char tmp[40];
11100
11101   switch (b->type)
11102     {
11103     case bp_hardware_watchpoint:
11104       fprintf_unfiltered (fp, "watch");
11105       break;
11106     case bp_read_watchpoint:
11107       fprintf_unfiltered (fp, "rwatch");
11108       break;
11109     case bp_access_watchpoint:
11110       fprintf_unfiltered (fp, "awatch");
11111       break;
11112     default:
11113       internal_error (__FILE__, __LINE__,
11114                       _("Invalid hardware watchpoint type."));
11115     }
11116
11117   sprintf_vma (tmp, w->hw_wp_mask);
11118   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11119   print_recreate_thread (b, fp);
11120 }
11121
11122 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11123
11124 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11125
11126 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11127
11128 static int
11129 is_masked_watchpoint (const struct breakpoint *b)
11130 {
11131   return b->ops == &masked_watchpoint_breakpoint_ops;
11132 }
11133
11134 /* accessflag:  hw_write:  watch write, 
11135                 hw_read:   watch read, 
11136                 hw_access: watch access (read or write) */
11137 static void
11138 watch_command_1 (const char *arg, int accessflag, int from_tty,
11139                  int just_location, int internal)
11140 {
11141   volatile struct gdb_exception e;
11142   struct breakpoint *b, *scope_breakpoint = NULL;
11143   struct expression *exp;
11144   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11145   struct value *val, *mark, *result;
11146   struct frame_info *frame;
11147   const char *exp_start = NULL;
11148   const char *exp_end = NULL;
11149   const char *tok, *end_tok;
11150   int toklen = -1;
11151   const char *cond_start = NULL;
11152   const char *cond_end = NULL;
11153   enum bptype bp_type;
11154   int thread = -1;
11155   int pc = 0;
11156   /* Flag to indicate whether we are going to use masks for
11157      the hardware watchpoint.  */
11158   int use_mask = 0;
11159   CORE_ADDR mask = 0;
11160   struct watchpoint *w;
11161   char *expression;
11162   struct cleanup *back_to;
11163
11164   /* Make sure that we actually have parameters to parse.  */
11165   if (arg != NULL && arg[0] != '\0')
11166     {
11167       const char *value_start;
11168
11169       exp_end = arg + strlen (arg);
11170
11171       /* Look for "parameter value" pairs at the end
11172          of the arguments string.  */
11173       for (tok = exp_end - 1; tok > arg; tok--)
11174         {
11175           /* Skip whitespace at the end of the argument list.  */
11176           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11177             tok--;
11178
11179           /* Find the beginning of the last token.
11180              This is the value of the parameter.  */
11181           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11182             tok--;
11183           value_start = tok + 1;
11184
11185           /* Skip whitespace.  */
11186           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11187             tok--;
11188
11189           end_tok = tok;
11190
11191           /* Find the beginning of the second to last token.
11192              This is the parameter itself.  */
11193           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11194             tok--;
11195           tok++;
11196           toklen = end_tok - tok + 1;
11197
11198           if (toklen == 6 && !strncmp (tok, "thread", 6))
11199             {
11200               /* At this point we've found a "thread" token, which means
11201                  the user is trying to set a watchpoint that triggers
11202                  only in a specific thread.  */
11203               char *endp;
11204
11205               if (thread != -1)
11206                 error(_("You can specify only one thread."));
11207
11208               /* Extract the thread ID from the next token.  */
11209               thread = strtol (value_start, &endp, 0);
11210
11211               /* Check if the user provided a valid numeric value for the
11212                  thread ID.  */
11213               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11214                 error (_("Invalid thread ID specification %s."), value_start);
11215
11216               /* Check if the thread actually exists.  */
11217               if (!valid_thread_id (thread))
11218                 invalid_thread_id_error (thread);
11219             }
11220           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11221             {
11222               /* We've found a "mask" token, which means the user wants to
11223                  create a hardware watchpoint that is going to have the mask
11224                  facility.  */
11225               struct value *mask_value, *mark;
11226
11227               if (use_mask)
11228                 error(_("You can specify only one mask."));
11229
11230               use_mask = just_location = 1;
11231
11232               mark = value_mark ();
11233               mask_value = parse_to_comma_and_eval (&value_start);
11234               mask = value_as_address (mask_value);
11235               value_free_to_mark (mark);
11236             }
11237           else
11238             /* We didn't recognize what we found.  We should stop here.  */
11239             break;
11240
11241           /* Truncate the string and get rid of the "parameter value" pair before
11242              the arguments string is parsed by the parse_exp_1 function.  */
11243           exp_end = tok;
11244         }
11245     }
11246   else
11247     exp_end = arg;
11248
11249   /* Parse the rest of the arguments.  From here on out, everything
11250      is in terms of a newly allocated string instead of the original
11251      ARG.  */
11252   innermost_block = NULL;
11253   expression = savestring (arg, exp_end - arg);
11254   back_to = make_cleanup (xfree, expression);
11255   exp_start = arg = expression;
11256   exp = parse_exp_1 (&arg, 0, 0, 0);
11257   exp_end = arg;
11258   /* Remove trailing whitespace from the expression before saving it.
11259      This makes the eventual display of the expression string a bit
11260      prettier.  */
11261   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11262     --exp_end;
11263
11264   /* Checking if the expression is not constant.  */
11265   if (watchpoint_exp_is_const (exp))
11266     {
11267       int len;
11268
11269       len = exp_end - exp_start;
11270       while (len > 0 && isspace (exp_start[len - 1]))
11271         len--;
11272       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11273     }
11274
11275   exp_valid_block = innermost_block;
11276   mark = value_mark ();
11277   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11278
11279   if (just_location)
11280     {
11281       int ret;
11282
11283       exp_valid_block = NULL;
11284       val = value_addr (result);
11285       release_value (val);
11286       value_free_to_mark (mark);
11287
11288       if (use_mask)
11289         {
11290           ret = target_masked_watch_num_registers (value_as_address (val),
11291                                                    mask);
11292           if (ret == -1)
11293             error (_("This target does not support masked watchpoints."));
11294           else if (ret == -2)
11295             error (_("Invalid mask or memory region."));
11296         }
11297     }
11298   else if (val != NULL)
11299     release_value (val);
11300
11301   tok = skip_spaces_const (arg);
11302   end_tok = skip_to_space_const (tok);
11303
11304   toklen = end_tok - tok;
11305   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11306     {
11307       struct expression *cond;
11308
11309       innermost_block = NULL;
11310       tok = cond_start = end_tok + 1;
11311       cond = parse_exp_1 (&tok, 0, 0, 0);
11312
11313       /* The watchpoint expression may not be local, but the condition
11314          may still be.  E.g.: `watch global if local > 0'.  */
11315       cond_exp_valid_block = innermost_block;
11316
11317       xfree (cond);
11318       cond_end = tok;
11319     }
11320   if (*tok)
11321     error (_("Junk at end of command."));
11322
11323   frame = block_innermost_frame (exp_valid_block);
11324
11325   /* If the expression is "local", then set up a "watchpoint scope"
11326      breakpoint at the point where we've left the scope of the watchpoint
11327      expression.  Create the scope breakpoint before the watchpoint, so
11328      that we will encounter it first in bpstat_stop_status.  */
11329   if (exp_valid_block && frame)
11330     {
11331       if (frame_id_p (frame_unwind_caller_id (frame)))
11332         {
11333           scope_breakpoint
11334             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11335                                           frame_unwind_caller_pc (frame),
11336                                           bp_watchpoint_scope,
11337                                           &momentary_breakpoint_ops);
11338
11339           scope_breakpoint->enable_state = bp_enabled;
11340
11341           /* Automatically delete the breakpoint when it hits.  */
11342           scope_breakpoint->disposition = disp_del;
11343
11344           /* Only break in the proper frame (help with recursion).  */
11345           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11346
11347           /* Set the address at which we will stop.  */
11348           scope_breakpoint->loc->gdbarch
11349             = frame_unwind_caller_arch (frame);
11350           scope_breakpoint->loc->requested_address
11351             = frame_unwind_caller_pc (frame);
11352           scope_breakpoint->loc->address
11353             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11354                                          scope_breakpoint->loc->requested_address,
11355                                          scope_breakpoint->type);
11356         }
11357     }
11358
11359   /* Now set up the breakpoint.  We create all watchpoints as hardware
11360      watchpoints here even if hardware watchpoints are turned off, a call
11361      to update_watchpoint later in this function will cause the type to
11362      drop back to bp_watchpoint (software watchpoint) if required.  */
11363
11364   if (accessflag == hw_read)
11365     bp_type = bp_read_watchpoint;
11366   else if (accessflag == hw_access)
11367     bp_type = bp_access_watchpoint;
11368   else
11369     bp_type = bp_hardware_watchpoint;
11370
11371   w = XCNEW (struct watchpoint);
11372   b = &w->base;
11373   if (use_mask)
11374     init_raw_breakpoint_without_location (b, NULL, bp_type,
11375                                           &masked_watchpoint_breakpoint_ops);
11376   else
11377     init_raw_breakpoint_without_location (b, NULL, bp_type,
11378                                           &watchpoint_breakpoint_ops);
11379   b->thread = thread;
11380   b->disposition = disp_donttouch;
11381   b->pspace = current_program_space;
11382   w->exp = exp;
11383   w->exp_valid_block = exp_valid_block;
11384   w->cond_exp_valid_block = cond_exp_valid_block;
11385   if (just_location)
11386     {
11387       struct type *t = value_type (val);
11388       CORE_ADDR addr = value_as_address (val);
11389       char *name;
11390
11391       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11392       name = type_to_string (t);
11393
11394       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11395                                           core_addr_to_string (addr));
11396       xfree (name);
11397
11398       w->exp_string = xstrprintf ("-location %.*s",
11399                                   (int) (exp_end - exp_start), exp_start);
11400
11401       /* The above expression is in C.  */
11402       b->language = language_c;
11403     }
11404   else
11405     w->exp_string = savestring (exp_start, exp_end - exp_start);
11406
11407   if (use_mask)
11408     {
11409       w->hw_wp_mask = mask;
11410     }
11411   else
11412     {
11413       w->val = val;
11414       w->val_valid = 1;
11415     }
11416
11417   if (cond_start)
11418     b->cond_string = savestring (cond_start, cond_end - cond_start);
11419   else
11420     b->cond_string = 0;
11421
11422   if (frame)
11423     {
11424       w->watchpoint_frame = get_frame_id (frame);
11425       w->watchpoint_thread = inferior_ptid;
11426     }
11427   else
11428     {
11429       w->watchpoint_frame = null_frame_id;
11430       w->watchpoint_thread = null_ptid;
11431     }
11432
11433   if (scope_breakpoint != NULL)
11434     {
11435       /* The scope breakpoint is related to the watchpoint.  We will
11436          need to act on them together.  */
11437       b->related_breakpoint = scope_breakpoint;
11438       scope_breakpoint->related_breakpoint = b;
11439     }
11440
11441   if (!just_location)
11442     value_free_to_mark (mark);
11443
11444   TRY_CATCH (e, RETURN_MASK_ALL)
11445     {
11446       /* Finally update the new watchpoint.  This creates the locations
11447          that should be inserted.  */
11448       update_watchpoint (w, 1);
11449     }
11450   if (e.reason < 0)
11451     {
11452       delete_breakpoint (b);
11453       throw_exception (e);
11454     }
11455
11456   install_breakpoint (internal, b, 1);
11457   do_cleanups (back_to);
11458 }
11459
11460 /* Return count of debug registers needed to watch the given expression.
11461    If the watchpoint cannot be handled in hardware return zero.  */
11462
11463 static int
11464 can_use_hardware_watchpoint (struct value *v)
11465 {
11466   int found_memory_cnt = 0;
11467   struct value *head = v;
11468
11469   /* Did the user specifically forbid us to use hardware watchpoints? */
11470   if (!can_use_hw_watchpoints)
11471     return 0;
11472
11473   /* Make sure that the value of the expression depends only upon
11474      memory contents, and values computed from them within GDB.  If we
11475      find any register references or function calls, we can't use a
11476      hardware watchpoint.
11477
11478      The idea here is that evaluating an expression generates a series
11479      of values, one holding the value of every subexpression.  (The
11480      expression a*b+c has five subexpressions: a, b, a*b, c, and
11481      a*b+c.)  GDB's values hold almost enough information to establish
11482      the criteria given above --- they identify memory lvalues,
11483      register lvalues, computed values, etcetera.  So we can evaluate
11484      the expression, and then scan the chain of values that leaves
11485      behind to decide whether we can detect any possible change to the
11486      expression's final value using only hardware watchpoints.
11487
11488      However, I don't think that the values returned by inferior
11489      function calls are special in any way.  So this function may not
11490      notice that an expression involving an inferior function call
11491      can't be watched with hardware watchpoints.  FIXME.  */
11492   for (; v; v = value_next (v))
11493     {
11494       if (VALUE_LVAL (v) == lval_memory)
11495         {
11496           if (v != head && value_lazy (v))
11497             /* A lazy memory lvalue in the chain is one that GDB never
11498                needed to fetch; we either just used its address (e.g.,
11499                `a' in `a.b') or we never needed it at all (e.g., `a'
11500                in `a,b').  This doesn't apply to HEAD; if that is
11501                lazy then it was not readable, but watch it anyway.  */
11502             ;
11503           else
11504             {
11505               /* Ahh, memory we actually used!  Check if we can cover
11506                  it with hardware watchpoints.  */
11507               struct type *vtype = check_typedef (value_type (v));
11508
11509               /* We only watch structs and arrays if user asked for it
11510                  explicitly, never if they just happen to appear in a
11511                  middle of some value chain.  */
11512               if (v == head
11513                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11514                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11515                 {
11516                   CORE_ADDR vaddr = value_address (v);
11517                   int len;
11518                   int num_regs;
11519
11520                   len = (target_exact_watchpoints
11521                          && is_scalar_type_recursive (vtype))?
11522                     1 : TYPE_LENGTH (value_type (v));
11523
11524                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11525                   if (!num_regs)
11526                     return 0;
11527                   else
11528                     found_memory_cnt += num_regs;
11529                 }
11530             }
11531         }
11532       else if (VALUE_LVAL (v) != not_lval
11533                && deprecated_value_modifiable (v) == 0)
11534         return 0;       /* These are values from the history (e.g., $1).  */
11535       else if (VALUE_LVAL (v) == lval_register)
11536         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11537     }
11538
11539   /* The expression itself looks suitable for using a hardware
11540      watchpoint, but give the target machine a chance to reject it.  */
11541   return found_memory_cnt;
11542 }
11543
11544 void
11545 watch_command_wrapper (char *arg, int from_tty, int internal)
11546 {
11547   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11548 }
11549
11550 /* A helper function that looks for the "-location" argument and then
11551    calls watch_command_1.  */
11552
11553 static void
11554 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11555 {
11556   int just_location = 0;
11557
11558   if (arg
11559       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11560           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11561     {
11562       arg = skip_spaces (arg);
11563       just_location = 1;
11564     }
11565
11566   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11567 }
11568
11569 static void
11570 watch_command (char *arg, int from_tty)
11571 {
11572   watch_maybe_just_location (arg, hw_write, from_tty);
11573 }
11574
11575 void
11576 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11577 {
11578   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11579 }
11580
11581 static void
11582 rwatch_command (char *arg, int from_tty)
11583 {
11584   watch_maybe_just_location (arg, hw_read, from_tty);
11585 }
11586
11587 void
11588 awatch_command_wrapper (char *arg, int from_tty, int internal)
11589 {
11590   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11591 }
11592
11593 static void
11594 awatch_command (char *arg, int from_tty)
11595 {
11596   watch_maybe_just_location (arg, hw_access, from_tty);
11597 }
11598 \f
11599
11600 /* Helper routines for the until_command routine in infcmd.c.  Here
11601    because it uses the mechanisms of breakpoints.  */
11602
11603 struct until_break_command_continuation_args
11604 {
11605   struct breakpoint *breakpoint;
11606   struct breakpoint *breakpoint2;
11607   int thread_num;
11608 };
11609
11610 /* This function is called by fetch_inferior_event via the
11611    cmd_continuation pointer, to complete the until command.  It takes
11612    care of cleaning up the temporary breakpoints set up by the until
11613    command.  */
11614 static void
11615 until_break_command_continuation (void *arg, int err)
11616 {
11617   struct until_break_command_continuation_args *a = arg;
11618
11619   delete_breakpoint (a->breakpoint);
11620   if (a->breakpoint2)
11621     delete_breakpoint (a->breakpoint2);
11622   delete_longjmp_breakpoint (a->thread_num);
11623 }
11624
11625 void
11626 until_break_command (char *arg, int from_tty, int anywhere)
11627 {
11628   struct symtabs_and_lines sals;
11629   struct symtab_and_line sal;
11630   struct frame_info *frame;
11631   struct gdbarch *frame_gdbarch;
11632   struct frame_id stack_frame_id;
11633   struct frame_id caller_frame_id;
11634   struct breakpoint *breakpoint;
11635   struct breakpoint *breakpoint2 = NULL;
11636   struct cleanup *old_chain;
11637   int thread;
11638   struct thread_info *tp;
11639
11640   clear_proceed_status ();
11641
11642   /* Set a breakpoint where the user wants it and at return from
11643      this function.  */
11644
11645   if (last_displayed_sal_is_valid ())
11646     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11647                           get_last_displayed_symtab (),
11648                           get_last_displayed_line ());
11649   else
11650     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11651                           (struct symtab *) NULL, 0);
11652
11653   if (sals.nelts != 1)
11654     error (_("Couldn't get information on specified line."));
11655
11656   sal = sals.sals[0];
11657   xfree (sals.sals);    /* malloc'd, so freed.  */
11658
11659   if (*arg)
11660     error (_("Junk at end of arguments."));
11661
11662   resolve_sal_pc (&sal);
11663
11664   tp = inferior_thread ();
11665   thread = tp->num;
11666
11667   old_chain = make_cleanup (null_cleanup, NULL);
11668
11669   /* Note linespec handling above invalidates the frame chain.
11670      Installing a breakpoint also invalidates the frame chain (as it
11671      may need to switch threads), so do any frame handling before
11672      that.  */
11673
11674   frame = get_selected_frame (NULL);
11675   frame_gdbarch = get_frame_arch (frame);
11676   stack_frame_id = get_stack_frame_id (frame);
11677   caller_frame_id = frame_unwind_caller_id (frame);
11678
11679   /* Keep within the current frame, or in frames called by the current
11680      one.  */
11681
11682   if (frame_id_p (caller_frame_id))
11683     {
11684       struct symtab_and_line sal2;
11685
11686       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11687       sal2.pc = frame_unwind_caller_pc (frame);
11688       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11689                                               sal2,
11690                                               caller_frame_id,
11691                                               bp_until);
11692       make_cleanup_delete_breakpoint (breakpoint2);
11693
11694       set_longjmp_breakpoint (tp, caller_frame_id);
11695       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11696     }
11697
11698   /* set_momentary_breakpoint could invalidate FRAME.  */
11699   frame = NULL;
11700
11701   if (anywhere)
11702     /* If the user told us to continue until a specified location,
11703        we don't specify a frame at which we need to stop.  */
11704     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11705                                            null_frame_id, bp_until);
11706   else
11707     /* Otherwise, specify the selected frame, because we want to stop
11708        only at the very same frame.  */
11709     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11710                                            stack_frame_id, bp_until);
11711   make_cleanup_delete_breakpoint (breakpoint);
11712
11713   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11714
11715   /* If we are running asynchronously, and proceed call above has
11716      actually managed to start the target, arrange for breakpoints to
11717      be deleted when the target stops.  Otherwise, we're already
11718      stopped and delete breakpoints via cleanup chain.  */
11719
11720   if (target_can_async_p () && is_running (inferior_ptid))
11721     {
11722       struct until_break_command_continuation_args *args;
11723       args = xmalloc (sizeof (*args));
11724
11725       args->breakpoint = breakpoint;
11726       args->breakpoint2 = breakpoint2;
11727       args->thread_num = thread;
11728
11729       discard_cleanups (old_chain);
11730       add_continuation (inferior_thread (),
11731                         until_break_command_continuation, args,
11732                         xfree);
11733     }
11734   else
11735     do_cleanups (old_chain);
11736 }
11737
11738 /* This function attempts to parse an optional "if <cond>" clause
11739    from the arg string.  If one is not found, it returns NULL.
11740
11741    Else, it returns a pointer to the condition string.  (It does not
11742    attempt to evaluate the string against a particular block.)  And,
11743    it updates arg to point to the first character following the parsed
11744    if clause in the arg string.  */
11745
11746 char *
11747 ep_parse_optional_if_clause (char **arg)
11748 {
11749   char *cond_string;
11750
11751   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11752     return NULL;
11753
11754   /* Skip the "if" keyword.  */
11755   (*arg) += 2;
11756
11757   /* Skip any extra leading whitespace, and record the start of the
11758      condition string.  */
11759   *arg = skip_spaces (*arg);
11760   cond_string = *arg;
11761
11762   /* Assume that the condition occupies the remainder of the arg
11763      string.  */
11764   (*arg) += strlen (cond_string);
11765
11766   return cond_string;
11767 }
11768
11769 /* Commands to deal with catching events, such as signals, exceptions,
11770    process start/exit, etc.  */
11771
11772 typedef enum
11773 {
11774   catch_fork_temporary, catch_vfork_temporary,
11775   catch_fork_permanent, catch_vfork_permanent
11776 }
11777 catch_fork_kind;
11778
11779 static void
11780 catch_fork_command_1 (char *arg, int from_tty, 
11781                       struct cmd_list_element *command)
11782 {
11783   struct gdbarch *gdbarch = get_current_arch ();
11784   char *cond_string = NULL;
11785   catch_fork_kind fork_kind;
11786   int tempflag;
11787
11788   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11789   tempflag = (fork_kind == catch_fork_temporary
11790               || fork_kind == catch_vfork_temporary);
11791
11792   if (!arg)
11793     arg = "";
11794   arg = skip_spaces (arg);
11795
11796   /* The allowed syntax is:
11797      catch [v]fork
11798      catch [v]fork if <cond>
11799
11800      First, check if there's an if clause.  */
11801   cond_string = ep_parse_optional_if_clause (&arg);
11802
11803   if ((*arg != '\0') && !isspace (*arg))
11804     error (_("Junk at end of arguments."));
11805
11806   /* If this target supports it, create a fork or vfork catchpoint
11807      and enable reporting of such events.  */
11808   switch (fork_kind)
11809     {
11810     case catch_fork_temporary:
11811     case catch_fork_permanent:
11812       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11813                                           &catch_fork_breakpoint_ops);
11814       break;
11815     case catch_vfork_temporary:
11816     case catch_vfork_permanent:
11817       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11818                                           &catch_vfork_breakpoint_ops);
11819       break;
11820     default:
11821       error (_("unsupported or unknown fork kind; cannot catch it"));
11822       break;
11823     }
11824 }
11825
11826 static void
11827 catch_exec_command_1 (char *arg, int from_tty, 
11828                       struct cmd_list_element *command)
11829 {
11830   struct exec_catchpoint *c;
11831   struct gdbarch *gdbarch = get_current_arch ();
11832   int tempflag;
11833   char *cond_string = NULL;
11834
11835   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11836
11837   if (!arg)
11838     arg = "";
11839   arg = skip_spaces (arg);
11840
11841   /* The allowed syntax is:
11842      catch exec
11843      catch exec if <cond>
11844
11845      First, check if there's an if clause.  */
11846   cond_string = ep_parse_optional_if_clause (&arg);
11847
11848   if ((*arg != '\0') && !isspace (*arg))
11849     error (_("Junk at end of arguments."));
11850
11851   c = XNEW (struct exec_catchpoint);
11852   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11853                    &catch_exec_breakpoint_ops);
11854   c->exec_pathname = NULL;
11855
11856   install_breakpoint (0, &c->base, 1);
11857 }
11858
11859 void
11860 init_ada_exception_breakpoint (struct breakpoint *b,
11861                                struct gdbarch *gdbarch,
11862                                struct symtab_and_line sal,
11863                                char *addr_string,
11864                                const struct breakpoint_ops *ops,
11865                                int tempflag,
11866                                int enabled,
11867                                int from_tty)
11868 {
11869   if (from_tty)
11870     {
11871       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11872       if (!loc_gdbarch)
11873         loc_gdbarch = gdbarch;
11874
11875       describe_other_breakpoints (loc_gdbarch,
11876                                   sal.pspace, sal.pc, sal.section, -1);
11877       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11878          version for exception catchpoints, because two catchpoints
11879          used for different exception names will use the same address.
11880          In this case, a "breakpoint ... also set at..." warning is
11881          unproductive.  Besides, the warning phrasing is also a bit
11882          inappropriate, we should use the word catchpoint, and tell
11883          the user what type of catchpoint it is.  The above is good
11884          enough for now, though.  */
11885     }
11886
11887   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11888
11889   b->enable_state = enabled ? bp_enabled : bp_disabled;
11890   b->disposition = tempflag ? disp_del : disp_donttouch;
11891   b->addr_string = addr_string;
11892   b->language = language_ada;
11893 }
11894
11895 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11896    filter list, or NULL if no filtering is required.  */
11897 static VEC(int) *
11898 catch_syscall_split_args (char *arg)
11899 {
11900   VEC(int) *result = NULL;
11901   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11902
11903   while (*arg != '\0')
11904     {
11905       int i, syscall_number;
11906       char *endptr;
11907       char cur_name[128];
11908       struct syscall s;
11909
11910       /* Skip whitespace.  */
11911       arg = skip_spaces (arg);
11912
11913       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11914         cur_name[i] = arg[i];
11915       cur_name[i] = '\0';
11916       arg += i;
11917
11918       /* Check if the user provided a syscall name or a number.  */
11919       syscall_number = (int) strtol (cur_name, &endptr, 0);
11920       if (*endptr == '\0')
11921         get_syscall_by_number (syscall_number, &s);
11922       else
11923         {
11924           /* We have a name.  Let's check if it's valid and convert it
11925              to a number.  */
11926           get_syscall_by_name (cur_name, &s);
11927
11928           if (s.number == UNKNOWN_SYSCALL)
11929             /* Here we have to issue an error instead of a warning,
11930                because GDB cannot do anything useful if there's no
11931                syscall number to be caught.  */
11932             error (_("Unknown syscall name '%s'."), cur_name);
11933         }
11934
11935       /* Ok, it's valid.  */
11936       VEC_safe_push (int, result, s.number);
11937     }
11938
11939   discard_cleanups (cleanup);
11940   return result;
11941 }
11942
11943 /* Implement the "catch syscall" command.  */
11944
11945 static void
11946 catch_syscall_command_1 (char *arg, int from_tty, 
11947                          struct cmd_list_element *command)
11948 {
11949   int tempflag;
11950   VEC(int) *filter;
11951   struct syscall s;
11952   struct gdbarch *gdbarch = get_current_arch ();
11953
11954   /* Checking if the feature if supported.  */
11955   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11956     error (_("The feature 'catch syscall' is not supported on \
11957 this architecture yet."));
11958
11959   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11960
11961   arg = skip_spaces (arg);
11962
11963   /* We need to do this first "dummy" translation in order
11964      to get the syscall XML file loaded or, most important,
11965      to display a warning to the user if there's no XML file
11966      for his/her architecture.  */
11967   get_syscall_by_number (0, &s);
11968
11969   /* The allowed syntax is:
11970      catch syscall
11971      catch syscall <name | number> [<name | number> ... <name | number>]
11972
11973      Let's check if there's a syscall name.  */
11974
11975   if (arg != NULL)
11976     filter = catch_syscall_split_args (arg);
11977   else
11978     filter = NULL;
11979
11980   create_syscall_event_catchpoint (tempflag, filter,
11981                                    &catch_syscall_breakpoint_ops);
11982 }
11983
11984 static void
11985 catch_command (char *arg, int from_tty)
11986 {
11987   error (_("Catch requires an event name."));
11988 }
11989 \f
11990
11991 static void
11992 tcatch_command (char *arg, int from_tty)
11993 {
11994   error (_("Catch requires an event name."));
11995 }
11996
11997 /* A qsort comparison function that sorts breakpoints in order.  */
11998
11999 static int
12000 compare_breakpoints (const void *a, const void *b)
12001 {
12002   const breakpoint_p *ba = a;
12003   uintptr_t ua = (uintptr_t) *ba;
12004   const breakpoint_p *bb = b;
12005   uintptr_t ub = (uintptr_t) *bb;
12006
12007   if ((*ba)->number < (*bb)->number)
12008     return -1;
12009   else if ((*ba)->number > (*bb)->number)
12010     return 1;
12011
12012   /* Now sort by address, in case we see, e..g, two breakpoints with
12013      the number 0.  */
12014   if (ua < ub)
12015     return -1;
12016   return ua > ub ? 1 : 0;
12017 }
12018
12019 /* Delete breakpoints by address or line.  */
12020
12021 static void
12022 clear_command (char *arg, int from_tty)
12023 {
12024   struct breakpoint *b, *prev;
12025   VEC(breakpoint_p) *found = 0;
12026   int ix;
12027   int default_match;
12028   struct symtabs_and_lines sals;
12029   struct symtab_and_line sal;
12030   int i;
12031   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12032
12033   if (arg)
12034     {
12035       sals = decode_line_with_current_source (arg,
12036                                               (DECODE_LINE_FUNFIRSTLINE
12037                                                | DECODE_LINE_LIST_MODE));
12038       make_cleanup (xfree, sals.sals);
12039       default_match = 0;
12040     }
12041   else
12042     {
12043       sals.sals = (struct symtab_and_line *)
12044         xmalloc (sizeof (struct symtab_and_line));
12045       make_cleanup (xfree, sals.sals);
12046       init_sal (&sal);          /* Initialize to zeroes.  */
12047
12048       /* Set sal's line, symtab, pc, and pspace to the values
12049          corresponding to the last call to print_frame_info.  If the
12050          codepoint is not valid, this will set all the fields to 0.  */
12051       get_last_displayed_sal (&sal);
12052       if (sal.symtab == 0)
12053         error (_("No source file specified."));
12054
12055       sals.sals[0] = sal;
12056       sals.nelts = 1;
12057
12058       default_match = 1;
12059     }
12060
12061   /* We don't call resolve_sal_pc here.  That's not as bad as it
12062      seems, because all existing breakpoints typically have both
12063      file/line and pc set.  So, if clear is given file/line, we can
12064      match this to existing breakpoint without obtaining pc at all.
12065
12066      We only support clearing given the address explicitly 
12067      present in breakpoint table.  Say, we've set breakpoint 
12068      at file:line.  There were several PC values for that file:line,
12069      due to optimization, all in one block.
12070
12071      We've picked one PC value.  If "clear" is issued with another
12072      PC corresponding to the same file:line, the breakpoint won't
12073      be cleared.  We probably can still clear the breakpoint, but 
12074      since the other PC value is never presented to user, user
12075      can only find it by guessing, and it does not seem important
12076      to support that.  */
12077
12078   /* For each line spec given, delete bps which correspond to it.  Do
12079      it in two passes, solely to preserve the current behavior that
12080      from_tty is forced true if we delete more than one
12081      breakpoint.  */
12082
12083   found = NULL;
12084   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12085   for (i = 0; i < sals.nelts; i++)
12086     {
12087       const char *sal_fullname;
12088
12089       /* If exact pc given, clear bpts at that pc.
12090          If line given (pc == 0), clear all bpts on specified line.
12091          If defaulting, clear all bpts on default line
12092          or at default pc.
12093
12094          defaulting    sal.pc != 0    tests to do
12095
12096          0              1             pc
12097          1              1             pc _and_ line
12098          0              0             line
12099          1              0             <can't happen> */
12100
12101       sal = sals.sals[i];
12102       sal_fullname = (sal.symtab == NULL
12103                       ? NULL : symtab_to_fullname (sal.symtab));
12104
12105       /* Find all matching breakpoints and add them to 'found'.  */
12106       ALL_BREAKPOINTS (b)
12107         {
12108           int match = 0;
12109           /* Are we going to delete b?  */
12110           if (b->type != bp_none && !is_watchpoint (b))
12111             {
12112               struct bp_location *loc = b->loc;
12113               for (; loc; loc = loc->next)
12114                 {
12115                   /* If the user specified file:line, don't allow a PC
12116                      match.  This matches historical gdb behavior.  */
12117                   int pc_match = (!sal.explicit_line
12118                                   && sal.pc
12119                                   && (loc->pspace == sal.pspace)
12120                                   && (loc->address == sal.pc)
12121                                   && (!section_is_overlay (loc->section)
12122                                       || loc->section == sal.section));
12123                   int line_match = 0;
12124
12125                   if ((default_match || sal.explicit_line)
12126                       && loc->symtab != NULL
12127                       && sal_fullname != NULL
12128                       && sal.pspace == loc->pspace
12129                       && loc->line_number == sal.line
12130                       && filename_cmp (symtab_to_fullname (loc->symtab),
12131                                        sal_fullname) == 0)
12132                     line_match = 1;
12133
12134                   if (pc_match || line_match)
12135                     {
12136                       match = 1;
12137                       break;
12138                     }
12139                 }
12140             }
12141
12142           if (match)
12143             VEC_safe_push(breakpoint_p, found, b);
12144         }
12145     }
12146
12147   /* Now go thru the 'found' chain and delete them.  */
12148   if (VEC_empty(breakpoint_p, found))
12149     {
12150       if (arg)
12151         error (_("No breakpoint at %s."), arg);
12152       else
12153         error (_("No breakpoint at this line."));
12154     }
12155
12156   /* Remove duplicates from the vec.  */
12157   qsort (VEC_address (breakpoint_p, found),
12158          VEC_length (breakpoint_p, found),
12159          sizeof (breakpoint_p),
12160          compare_breakpoints);
12161   prev = VEC_index (breakpoint_p, found, 0);
12162   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12163     {
12164       if (b == prev)
12165         {
12166           VEC_ordered_remove (breakpoint_p, found, ix);
12167           --ix;
12168         }
12169     }
12170
12171   if (VEC_length(breakpoint_p, found) > 1)
12172     from_tty = 1;       /* Always report if deleted more than one.  */
12173   if (from_tty)
12174     {
12175       if (VEC_length(breakpoint_p, found) == 1)
12176         printf_unfiltered (_("Deleted breakpoint "));
12177       else
12178         printf_unfiltered (_("Deleted breakpoints "));
12179     }
12180
12181   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12182     {
12183       if (from_tty)
12184         printf_unfiltered ("%d ", b->number);
12185       delete_breakpoint (b);
12186     }
12187   if (from_tty)
12188     putchar_unfiltered ('\n');
12189
12190   do_cleanups (cleanups);
12191 }
12192 \f
12193 /* Delete breakpoint in BS if they are `delete' breakpoints and
12194    all breakpoints that are marked for deletion, whether hit or not.
12195    This is called after any breakpoint is hit, or after errors.  */
12196
12197 void
12198 breakpoint_auto_delete (bpstat bs)
12199 {
12200   struct breakpoint *b, *b_tmp;
12201
12202   for (; bs; bs = bs->next)
12203     if (bs->breakpoint_at
12204         && bs->breakpoint_at->disposition == disp_del
12205         && bs->stop)
12206       delete_breakpoint (bs->breakpoint_at);
12207
12208   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12209   {
12210     if (b->disposition == disp_del_at_next_stop)
12211       delete_breakpoint (b);
12212   }
12213 }
12214
12215 /* A comparison function for bp_location AP and BP being interfaced to
12216    qsort.  Sort elements primarily by their ADDRESS (no matter what
12217    does breakpoint_address_is_meaningful say for its OWNER),
12218    secondarily by ordering first bp_permanent OWNERed elements and
12219    terciarily just ensuring the array is sorted stable way despite
12220    qsort being an unstable algorithm.  */
12221
12222 static int
12223 bp_location_compare (const void *ap, const void *bp)
12224 {
12225   struct bp_location *a = *(void **) ap;
12226   struct bp_location *b = *(void **) bp;
12227   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12228   int a_perm = a->owner->enable_state == bp_permanent;
12229   int b_perm = b->owner->enable_state == bp_permanent;
12230
12231   if (a->address != b->address)
12232     return (a->address > b->address) - (a->address < b->address);
12233
12234   /* Sort locations at the same address by their pspace number, keeping
12235      locations of the same inferior (in a multi-inferior environment)
12236      grouped.  */
12237
12238   if (a->pspace->num != b->pspace->num)
12239     return ((a->pspace->num > b->pspace->num)
12240             - (a->pspace->num < b->pspace->num));
12241
12242   /* Sort permanent breakpoints first.  */
12243   if (a_perm != b_perm)
12244     return (a_perm < b_perm) - (a_perm > b_perm);
12245
12246   /* Make the internal GDB representation stable across GDB runs
12247      where A and B memory inside GDB can differ.  Breakpoint locations of
12248      the same type at the same address can be sorted in arbitrary order.  */
12249
12250   if (a->owner->number != b->owner->number)
12251     return ((a->owner->number > b->owner->number)
12252             - (a->owner->number < b->owner->number));
12253
12254   return (a > b) - (a < b);
12255 }
12256
12257 /* Set bp_location_placed_address_before_address_max and
12258    bp_location_shadow_len_after_address_max according to the current
12259    content of the bp_location array.  */
12260
12261 static void
12262 bp_location_target_extensions_update (void)
12263 {
12264   struct bp_location *bl, **blp_tmp;
12265
12266   bp_location_placed_address_before_address_max = 0;
12267   bp_location_shadow_len_after_address_max = 0;
12268
12269   ALL_BP_LOCATIONS (bl, blp_tmp)
12270     {
12271       CORE_ADDR start, end, addr;
12272
12273       if (!bp_location_has_shadow (bl))
12274         continue;
12275
12276       start = bl->target_info.placed_address;
12277       end = start + bl->target_info.shadow_len;
12278
12279       gdb_assert (bl->address >= start);
12280       addr = bl->address - start;
12281       if (addr > bp_location_placed_address_before_address_max)
12282         bp_location_placed_address_before_address_max = addr;
12283
12284       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12285
12286       gdb_assert (bl->address < end);
12287       addr = end - bl->address;
12288       if (addr > bp_location_shadow_len_after_address_max)
12289         bp_location_shadow_len_after_address_max = addr;
12290     }
12291 }
12292
12293 /* Download tracepoint locations if they haven't been.  */
12294
12295 static void
12296 download_tracepoint_locations (void)
12297 {
12298   struct breakpoint *b;
12299   struct cleanup *old_chain;
12300
12301   if (!target_can_download_tracepoint ())
12302     return;
12303
12304   old_chain = save_current_space_and_thread ();
12305
12306   ALL_TRACEPOINTS (b)
12307     {
12308       struct bp_location *bl;
12309       struct tracepoint *t;
12310       int bp_location_downloaded = 0;
12311
12312       if ((b->type == bp_fast_tracepoint
12313            ? !may_insert_fast_tracepoints
12314            : !may_insert_tracepoints))
12315         continue;
12316
12317       for (bl = b->loc; bl; bl = bl->next)
12318         {
12319           /* In tracepoint, locations are _never_ duplicated, so
12320              should_be_inserted is equivalent to
12321              unduplicated_should_be_inserted.  */
12322           if (!should_be_inserted (bl) || bl->inserted)
12323             continue;
12324
12325           switch_to_program_space_and_thread (bl->pspace);
12326
12327           target_download_tracepoint (bl);
12328
12329           bl->inserted = 1;
12330           bp_location_downloaded = 1;
12331         }
12332       t = (struct tracepoint *) b;
12333       t->number_on_target = b->number;
12334       if (bp_location_downloaded)
12335         observer_notify_breakpoint_modified (b);
12336     }
12337
12338   do_cleanups (old_chain);
12339 }
12340
12341 /* Swap the insertion/duplication state between two locations.  */
12342
12343 static void
12344 swap_insertion (struct bp_location *left, struct bp_location *right)
12345 {
12346   const int left_inserted = left->inserted;
12347   const int left_duplicate = left->duplicate;
12348   const int left_needs_update = left->needs_update;
12349   const struct bp_target_info left_target_info = left->target_info;
12350
12351   /* Locations of tracepoints can never be duplicated.  */
12352   if (is_tracepoint (left->owner))
12353     gdb_assert (!left->duplicate);
12354   if (is_tracepoint (right->owner))
12355     gdb_assert (!right->duplicate);
12356
12357   left->inserted = right->inserted;
12358   left->duplicate = right->duplicate;
12359   left->needs_update = right->needs_update;
12360   left->target_info = right->target_info;
12361   right->inserted = left_inserted;
12362   right->duplicate = left_duplicate;
12363   right->needs_update = left_needs_update;
12364   right->target_info = left_target_info;
12365 }
12366
12367 /* Force the re-insertion of the locations at ADDRESS.  This is called
12368    once a new/deleted/modified duplicate location is found and we are evaluating
12369    conditions on the target's side.  Such conditions need to be updated on
12370    the target.  */
12371
12372 static void
12373 force_breakpoint_reinsertion (struct bp_location *bl)
12374 {
12375   struct bp_location **locp = NULL, **loc2p;
12376   struct bp_location *loc;
12377   CORE_ADDR address = 0;
12378   int pspace_num;
12379
12380   address = bl->address;
12381   pspace_num = bl->pspace->num;
12382
12383   /* This is only meaningful if the target is
12384      evaluating conditions and if the user has
12385      opted for condition evaluation on the target's
12386      side.  */
12387   if (gdb_evaluates_breakpoint_condition_p ()
12388       || !target_supports_evaluation_of_breakpoint_conditions ())
12389     return;
12390
12391   /* Flag all breakpoint locations with this address and
12392      the same program space as the location
12393      as "its condition has changed".  We need to
12394      update the conditions on the target's side.  */
12395   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12396     {
12397       loc = *loc2p;
12398
12399       if (!is_breakpoint (loc->owner)
12400           || pspace_num != loc->pspace->num)
12401         continue;
12402
12403       /* Flag the location appropriately.  We use a different state to
12404          let everyone know that we already updated the set of locations
12405          with addr bl->address and program space bl->pspace.  This is so
12406          we don't have to keep calling these functions just to mark locations
12407          that have already been marked.  */
12408       loc->condition_changed = condition_updated;
12409
12410       /* Free the agent expression bytecode as well.  We will compute
12411          it later on.  */
12412       if (loc->cond_bytecode)
12413         {
12414           free_agent_expr (loc->cond_bytecode);
12415           loc->cond_bytecode = NULL;
12416         }
12417     }
12418 }
12419
12420 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12421    into the inferior, only remove already-inserted locations that no
12422    longer should be inserted.  Functions that delete a breakpoint or
12423    breakpoints should pass false, so that deleting a breakpoint
12424    doesn't have the side effect of inserting the locations of other
12425    breakpoints that are marked not-inserted, but should_be_inserted
12426    returns true on them.
12427
12428    This behaviour is useful is situations close to tear-down -- e.g.,
12429    after an exec, while the target still has execution, but breakpoint
12430    shadows of the previous executable image should *NOT* be restored
12431    to the new image; or before detaching, where the target still has
12432    execution and wants to delete breakpoints from GDB's lists, and all
12433    breakpoints had already been removed from the inferior.  */
12434
12435 static void
12436 update_global_location_list (int should_insert)
12437 {
12438   struct breakpoint *b;
12439   struct bp_location **locp, *loc;
12440   struct cleanup *cleanups;
12441   /* Last breakpoint location address that was marked for update.  */
12442   CORE_ADDR last_addr = 0;
12443   /* Last breakpoint location program space that was marked for update.  */
12444   int last_pspace_num = -1;
12445
12446   /* Used in the duplicates detection below.  When iterating over all
12447      bp_locations, points to the first bp_location of a given address.
12448      Breakpoints and watchpoints of different types are never
12449      duplicates of each other.  Keep one pointer for each type of
12450      breakpoint/watchpoint, so we only need to loop over all locations
12451      once.  */
12452   struct bp_location *bp_loc_first;  /* breakpoint */
12453   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12454   struct bp_location *awp_loc_first; /* access watchpoint */
12455   struct bp_location *rwp_loc_first; /* read watchpoint */
12456
12457   /* Saved former bp_location array which we compare against the newly
12458      built bp_location from the current state of ALL_BREAKPOINTS.  */
12459   struct bp_location **old_location, **old_locp;
12460   unsigned old_location_count;
12461
12462   old_location = bp_location;
12463   old_location_count = bp_location_count;
12464   bp_location = NULL;
12465   bp_location_count = 0;
12466   cleanups = make_cleanup (xfree, old_location);
12467
12468   ALL_BREAKPOINTS (b)
12469     for (loc = b->loc; loc; loc = loc->next)
12470       bp_location_count++;
12471
12472   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12473   locp = bp_location;
12474   ALL_BREAKPOINTS (b)
12475     for (loc = b->loc; loc; loc = loc->next)
12476       *locp++ = loc;
12477   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12478          bp_location_compare);
12479
12480   bp_location_target_extensions_update ();
12481
12482   /* Identify bp_location instances that are no longer present in the
12483      new list, and therefore should be freed.  Note that it's not
12484      necessary that those locations should be removed from inferior --
12485      if there's another location at the same address (previously
12486      marked as duplicate), we don't need to remove/insert the
12487      location.
12488      
12489      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12490      and former bp_location array state respectively.  */
12491
12492   locp = bp_location;
12493   for (old_locp = old_location; old_locp < old_location + old_location_count;
12494        old_locp++)
12495     {
12496       struct bp_location *old_loc = *old_locp;
12497       struct bp_location **loc2p;
12498
12499       /* Tells if 'old_loc' is found among the new locations.  If
12500          not, we have to free it.  */
12501       int found_object = 0;
12502       /* Tells if the location should remain inserted in the target.  */
12503       int keep_in_target = 0;
12504       int removed = 0;
12505
12506       /* Skip LOCP entries which will definitely never be needed.
12507          Stop either at or being the one matching OLD_LOC.  */
12508       while (locp < bp_location + bp_location_count
12509              && (*locp)->address < old_loc->address)
12510         locp++;
12511
12512       for (loc2p = locp;
12513            (loc2p < bp_location + bp_location_count
12514             && (*loc2p)->address == old_loc->address);
12515            loc2p++)
12516         {
12517           /* Check if this is a new/duplicated location or a duplicated
12518              location that had its condition modified.  If so, we want to send
12519              its condition to the target if evaluation of conditions is taking
12520              place there.  */
12521           if ((*loc2p)->condition_changed == condition_modified
12522               && (last_addr != old_loc->address
12523                   || last_pspace_num != old_loc->pspace->num))
12524             {
12525               force_breakpoint_reinsertion (*loc2p);
12526               last_pspace_num = old_loc->pspace->num;
12527             }
12528
12529           if (*loc2p == old_loc)
12530             found_object = 1;
12531         }
12532
12533       /* We have already handled this address, update it so that we don't
12534          have to go through updates again.  */
12535       last_addr = old_loc->address;
12536
12537       /* Target-side condition evaluation: Handle deleted locations.  */
12538       if (!found_object)
12539         force_breakpoint_reinsertion (old_loc);
12540
12541       /* If this location is no longer present, and inserted, look if
12542          there's maybe a new location at the same address.  If so,
12543          mark that one inserted, and don't remove this one.  This is
12544          needed so that we don't have a time window where a breakpoint
12545          at certain location is not inserted.  */
12546
12547       if (old_loc->inserted)
12548         {
12549           /* If the location is inserted now, we might have to remove
12550              it.  */
12551
12552           if (found_object && should_be_inserted (old_loc))
12553             {
12554               /* The location is still present in the location list,
12555                  and still should be inserted.  Don't do anything.  */
12556               keep_in_target = 1;
12557             }
12558           else
12559             {
12560               /* This location still exists, but it won't be kept in the
12561                  target since it may have been disabled.  We proceed to
12562                  remove its target-side condition.  */
12563
12564               /* The location is either no longer present, or got
12565                  disabled.  See if there's another location at the
12566                  same address, in which case we don't need to remove
12567                  this one from the target.  */
12568
12569               /* OLD_LOC comes from existing struct breakpoint.  */
12570               if (breakpoint_address_is_meaningful (old_loc->owner))
12571                 {
12572                   for (loc2p = locp;
12573                        (loc2p < bp_location + bp_location_count
12574                         && (*loc2p)->address == old_loc->address);
12575                        loc2p++)
12576                     {
12577                       struct bp_location *loc2 = *loc2p;
12578
12579                       if (breakpoint_locations_match (loc2, old_loc))
12580                         {
12581                           /* Read watchpoint locations are switched to
12582                              access watchpoints, if the former are not
12583                              supported, but the latter are.  */
12584                           if (is_hardware_watchpoint (old_loc->owner))
12585                             {
12586                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12587                               loc2->watchpoint_type = old_loc->watchpoint_type;
12588                             }
12589
12590                           /* loc2 is a duplicated location. We need to check
12591                              if it should be inserted in case it will be
12592                              unduplicated.  */
12593                           if (loc2 != old_loc
12594                               && unduplicated_should_be_inserted (loc2))
12595                             {
12596                               swap_insertion (old_loc, loc2);
12597                               keep_in_target = 1;
12598                               break;
12599                             }
12600                         }
12601                     }
12602                 }
12603             }
12604
12605           if (!keep_in_target)
12606             {
12607               if (remove_breakpoint (old_loc, mark_uninserted))
12608                 {
12609                   /* This is just about all we can do.  We could keep
12610                      this location on the global list, and try to
12611                      remove it next time, but there's no particular
12612                      reason why we will succeed next time.
12613                      
12614                      Note that at this point, old_loc->owner is still
12615                      valid, as delete_breakpoint frees the breakpoint
12616                      only after calling us.  */
12617                   printf_filtered (_("warning: Error removing "
12618                                      "breakpoint %d\n"), 
12619                                    old_loc->owner->number);
12620                 }
12621               removed = 1;
12622             }
12623         }
12624
12625       if (!found_object)
12626         {
12627           if (removed && non_stop
12628               && breakpoint_address_is_meaningful (old_loc->owner)
12629               && !is_hardware_watchpoint (old_loc->owner))
12630             {
12631               /* This location was removed from the target.  In
12632                  non-stop mode, a race condition is possible where
12633                  we've removed a breakpoint, but stop events for that
12634                  breakpoint are already queued and will arrive later.
12635                  We apply an heuristic to be able to distinguish such
12636                  SIGTRAPs from other random SIGTRAPs: we keep this
12637                  breakpoint location for a bit, and will retire it
12638                  after we see some number of events.  The theory here
12639                  is that reporting of events should, "on the average",
12640                  be fair, so after a while we'll see events from all
12641                  threads that have anything of interest, and no longer
12642                  need to keep this breakpoint location around.  We
12643                  don't hold locations forever so to reduce chances of
12644                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12645                  SIGTRAP.
12646
12647                  The heuristic failing can be disastrous on
12648                  decr_pc_after_break targets.
12649
12650                  On decr_pc_after_break targets, like e.g., x86-linux,
12651                  if we fail to recognize a late breakpoint SIGTRAP,
12652                  because events_till_retirement has reached 0 too
12653                  soon, we'll fail to do the PC adjustment, and report
12654                  a random SIGTRAP to the user.  When the user resumes
12655                  the inferior, it will most likely immediately crash
12656                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12657                  corrupted, because of being resumed e.g., in the
12658                  middle of a multi-byte instruction, or skipped a
12659                  one-byte instruction.  This was actually seen happen
12660                  on native x86-linux, and should be less rare on
12661                  targets that do not support new thread events, like
12662                  remote, due to the heuristic depending on
12663                  thread_count.
12664
12665                  Mistaking a random SIGTRAP for a breakpoint trap
12666                  causes similar symptoms (PC adjustment applied when
12667                  it shouldn't), but then again, playing with SIGTRAPs
12668                  behind the debugger's back is asking for trouble.
12669
12670                  Since hardware watchpoint traps are always
12671                  distinguishable from other traps, so we don't need to
12672                  apply keep hardware watchpoint moribund locations
12673                  around.  We simply always ignore hardware watchpoint
12674                  traps we can no longer explain.  */
12675
12676               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12677               old_loc->owner = NULL;
12678
12679               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12680             }
12681           else
12682             {
12683               old_loc->owner = NULL;
12684               decref_bp_location (&old_loc);
12685             }
12686         }
12687     }
12688
12689   /* Rescan breakpoints at the same address and section, marking the
12690      first one as "first" and any others as "duplicates".  This is so
12691      that the bpt instruction is only inserted once.  If we have a
12692      permanent breakpoint at the same place as BPT, make that one the
12693      official one, and the rest as duplicates.  Permanent breakpoints
12694      are sorted first for the same address.
12695
12696      Do the same for hardware watchpoints, but also considering the
12697      watchpoint's type (regular/access/read) and length.  */
12698
12699   bp_loc_first = NULL;
12700   wp_loc_first = NULL;
12701   awp_loc_first = NULL;
12702   rwp_loc_first = NULL;
12703   ALL_BP_LOCATIONS (loc, locp)
12704     {
12705       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12706          non-NULL.  */
12707       struct bp_location **loc_first_p;
12708       b = loc->owner;
12709
12710       if (!unduplicated_should_be_inserted (loc)
12711           || !breakpoint_address_is_meaningful (b)
12712           /* Don't detect duplicate for tracepoint locations because they are
12713            never duplicated.  See the comments in field `duplicate' of
12714            `struct bp_location'.  */
12715           || is_tracepoint (b))
12716         {
12717           /* Clear the condition modification flag.  */
12718           loc->condition_changed = condition_unchanged;
12719           continue;
12720         }
12721
12722       /* Permanent breakpoint should always be inserted.  */
12723       if (b->enable_state == bp_permanent && ! loc->inserted)
12724         internal_error (__FILE__, __LINE__,
12725                         _("allegedly permanent breakpoint is not "
12726                         "actually inserted"));
12727
12728       if (b->type == bp_hardware_watchpoint)
12729         loc_first_p = &wp_loc_first;
12730       else if (b->type == bp_read_watchpoint)
12731         loc_first_p = &rwp_loc_first;
12732       else if (b->type == bp_access_watchpoint)
12733         loc_first_p = &awp_loc_first;
12734       else
12735         loc_first_p = &bp_loc_first;
12736
12737       if (*loc_first_p == NULL
12738           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12739           || !breakpoint_locations_match (loc, *loc_first_p))
12740         {
12741           *loc_first_p = loc;
12742           loc->duplicate = 0;
12743
12744           if (is_breakpoint (loc->owner) && loc->condition_changed)
12745             {
12746               loc->needs_update = 1;
12747               /* Clear the condition modification flag.  */
12748               loc->condition_changed = condition_unchanged;
12749             }
12750           continue;
12751         }
12752
12753
12754       /* This and the above ensure the invariant that the first location
12755          is not duplicated, and is the inserted one.
12756          All following are marked as duplicated, and are not inserted.  */
12757       if (loc->inserted)
12758         swap_insertion (loc, *loc_first_p);
12759       loc->duplicate = 1;
12760
12761       /* Clear the condition modification flag.  */
12762       loc->condition_changed = condition_unchanged;
12763
12764       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12765           && b->enable_state != bp_permanent)
12766         internal_error (__FILE__, __LINE__,
12767                         _("another breakpoint was inserted on top of "
12768                         "a permanent breakpoint"));
12769     }
12770
12771   if (breakpoints_always_inserted_mode ()
12772       && (have_live_inferiors ()
12773           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12774     {
12775       if (should_insert)
12776         insert_breakpoint_locations ();
12777       else
12778         {
12779           /* Though should_insert is false, we may need to update conditions
12780              on the target's side if it is evaluating such conditions.  We
12781              only update conditions for locations that are marked
12782              "needs_update".  */
12783           update_inserted_breakpoint_locations ();
12784         }
12785     }
12786
12787   if (should_insert)
12788     download_tracepoint_locations ();
12789
12790   do_cleanups (cleanups);
12791 }
12792
12793 void
12794 breakpoint_retire_moribund (void)
12795 {
12796   struct bp_location *loc;
12797   int ix;
12798
12799   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12800     if (--(loc->events_till_retirement) == 0)
12801       {
12802         decref_bp_location (&loc);
12803         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12804         --ix;
12805       }
12806 }
12807
12808 static void
12809 update_global_location_list_nothrow (int inserting)
12810 {
12811   volatile struct gdb_exception e;
12812
12813   TRY_CATCH (e, RETURN_MASK_ERROR)
12814     update_global_location_list (inserting);
12815 }
12816
12817 /* Clear BKP from a BPS.  */
12818
12819 static void
12820 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12821 {
12822   bpstat bs;
12823
12824   for (bs = bps; bs; bs = bs->next)
12825     if (bs->breakpoint_at == bpt)
12826       {
12827         bs->breakpoint_at = NULL;
12828         bs->old_val = NULL;
12829         /* bs->commands will be freed later.  */
12830       }
12831 }
12832
12833 /* Callback for iterate_over_threads.  */
12834 static int
12835 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12836 {
12837   struct breakpoint *bpt = data;
12838
12839   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12840   return 0;
12841 }
12842
12843 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12844    callbacks.  */
12845
12846 static void
12847 say_where (struct breakpoint *b)
12848 {
12849   struct value_print_options opts;
12850
12851   get_user_print_options (&opts);
12852
12853   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12854      single string.  */
12855   if (b->loc == NULL)
12856     {
12857       printf_filtered (_(" (%s) pending."), b->addr_string);
12858     }
12859   else
12860     {
12861       if (opts.addressprint || b->loc->symtab == NULL)
12862         {
12863           printf_filtered (" at ");
12864           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12865                           gdb_stdout);
12866         }
12867       if (b->loc->symtab != NULL)
12868         {
12869           /* If there is a single location, we can print the location
12870              more nicely.  */
12871           if (b->loc->next == NULL)
12872             printf_filtered (": file %s, line %d.",
12873                              symtab_to_filename_for_display (b->loc->symtab),
12874                              b->loc->line_number);
12875           else
12876             /* This is not ideal, but each location may have a
12877                different file name, and this at least reflects the
12878                real situation somewhat.  */
12879             printf_filtered (": %s.", b->addr_string);
12880         }
12881
12882       if (b->loc->next)
12883         {
12884           struct bp_location *loc = b->loc;
12885           int n = 0;
12886           for (; loc; loc = loc->next)
12887             ++n;
12888           printf_filtered (" (%d locations)", n);
12889         }
12890     }
12891 }
12892
12893 /* Default bp_location_ops methods.  */
12894
12895 static void
12896 bp_location_dtor (struct bp_location *self)
12897 {
12898   xfree (self->cond);
12899   if (self->cond_bytecode)
12900     free_agent_expr (self->cond_bytecode);
12901   xfree (self->function_name);
12902
12903   VEC_free (agent_expr_p, self->target_info.conditions);
12904   VEC_free (agent_expr_p, self->target_info.tcommands);
12905 }
12906
12907 static const struct bp_location_ops bp_location_ops =
12908 {
12909   bp_location_dtor
12910 };
12911
12912 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12913    inherit from.  */
12914
12915 static void
12916 base_breakpoint_dtor (struct breakpoint *self)
12917 {
12918   decref_counted_command_line (&self->commands);
12919   xfree (self->cond_string);
12920   xfree (self->extra_string);
12921   xfree (self->addr_string);
12922   xfree (self->filter);
12923   xfree (self->addr_string_range_end);
12924 }
12925
12926 static struct bp_location *
12927 base_breakpoint_allocate_location (struct breakpoint *self)
12928 {
12929   struct bp_location *loc;
12930
12931   loc = XNEW (struct bp_location);
12932   init_bp_location (loc, &bp_location_ops, self);
12933   return loc;
12934 }
12935
12936 static void
12937 base_breakpoint_re_set (struct breakpoint *b)
12938 {
12939   /* Nothing to re-set. */
12940 }
12941
12942 #define internal_error_pure_virtual_called() \
12943   gdb_assert_not_reached ("pure virtual function called")
12944
12945 static int
12946 base_breakpoint_insert_location (struct bp_location *bl)
12947 {
12948   internal_error_pure_virtual_called ();
12949 }
12950
12951 static int
12952 base_breakpoint_remove_location (struct bp_location *bl)
12953 {
12954   internal_error_pure_virtual_called ();
12955 }
12956
12957 static int
12958 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12959                                 struct address_space *aspace,
12960                                 CORE_ADDR bp_addr,
12961                                 const struct target_waitstatus *ws)
12962 {
12963   internal_error_pure_virtual_called ();
12964 }
12965
12966 static void
12967 base_breakpoint_check_status (bpstat bs)
12968 {
12969   /* Always stop.   */
12970 }
12971
12972 /* A "works_in_software_mode" breakpoint_ops method that just internal
12973    errors.  */
12974
12975 static int
12976 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12977 {
12978   internal_error_pure_virtual_called ();
12979 }
12980
12981 /* A "resources_needed" breakpoint_ops method that just internal
12982    errors.  */
12983
12984 static int
12985 base_breakpoint_resources_needed (const struct bp_location *bl)
12986 {
12987   internal_error_pure_virtual_called ();
12988 }
12989
12990 static enum print_stop_action
12991 base_breakpoint_print_it (bpstat bs)
12992 {
12993   internal_error_pure_virtual_called ();
12994 }
12995
12996 static void
12997 base_breakpoint_print_one_detail (const struct breakpoint *self,
12998                                   struct ui_out *uiout)
12999 {
13000   /* nothing */
13001 }
13002
13003 static void
13004 base_breakpoint_print_mention (struct breakpoint *b)
13005 {
13006   internal_error_pure_virtual_called ();
13007 }
13008
13009 static void
13010 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13011 {
13012   internal_error_pure_virtual_called ();
13013 }
13014
13015 static void
13016 base_breakpoint_create_sals_from_address (char **arg,
13017                                           struct linespec_result *canonical,
13018                                           enum bptype type_wanted,
13019                                           char *addr_start,
13020                                           char **copy_arg)
13021 {
13022   internal_error_pure_virtual_called ();
13023 }
13024
13025 static void
13026 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13027                                         struct linespec_result *c,
13028                                         char *cond_string,
13029                                         char *extra_string,
13030                                         enum bptype type_wanted,
13031                                         enum bpdisp disposition,
13032                                         int thread,
13033                                         int task, int ignore_count,
13034                                         const struct breakpoint_ops *o,
13035                                         int from_tty, int enabled,
13036                                         int internal, unsigned flags)
13037 {
13038   internal_error_pure_virtual_called ();
13039 }
13040
13041 static void
13042 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13043                                  struct symtabs_and_lines *sals)
13044 {
13045   internal_error_pure_virtual_called ();
13046 }
13047
13048 /* The default 'explains_signal' method.  */
13049
13050 static int
13051 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13052 {
13053   return 1;
13054 }
13055
13056 /* The default "after_condition_true" method.  */
13057
13058 static void
13059 base_breakpoint_after_condition_true (struct bpstats *bs)
13060 {
13061   /* Nothing to do.   */
13062 }
13063
13064 struct breakpoint_ops base_breakpoint_ops =
13065 {
13066   base_breakpoint_dtor,
13067   base_breakpoint_allocate_location,
13068   base_breakpoint_re_set,
13069   base_breakpoint_insert_location,
13070   base_breakpoint_remove_location,
13071   base_breakpoint_breakpoint_hit,
13072   base_breakpoint_check_status,
13073   base_breakpoint_resources_needed,
13074   base_breakpoint_works_in_software_mode,
13075   base_breakpoint_print_it,
13076   NULL,
13077   base_breakpoint_print_one_detail,
13078   base_breakpoint_print_mention,
13079   base_breakpoint_print_recreate,
13080   base_breakpoint_create_sals_from_address,
13081   base_breakpoint_create_breakpoints_sal,
13082   base_breakpoint_decode_linespec,
13083   base_breakpoint_explains_signal,
13084   base_breakpoint_after_condition_true,
13085 };
13086
13087 /* Default breakpoint_ops methods.  */
13088
13089 static void
13090 bkpt_re_set (struct breakpoint *b)
13091 {
13092   /* FIXME: is this still reachable?  */
13093   if (b->addr_string == NULL)
13094     {
13095       /* Anything without a string can't be re-set.  */
13096       delete_breakpoint (b);
13097       return;
13098     }
13099
13100   breakpoint_re_set_default (b);
13101 }
13102
13103 static int
13104 bkpt_insert_location (struct bp_location *bl)
13105 {
13106   if (bl->loc_type == bp_loc_hardware_breakpoint)
13107     return target_insert_hw_breakpoint (bl->gdbarch,
13108                                         &bl->target_info);
13109   else
13110     return target_insert_breakpoint (bl->gdbarch,
13111                                      &bl->target_info);
13112 }
13113
13114 static int
13115 bkpt_remove_location (struct bp_location *bl)
13116 {
13117   if (bl->loc_type == bp_loc_hardware_breakpoint)
13118     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13119   else
13120     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13121 }
13122
13123 static int
13124 bkpt_breakpoint_hit (const struct bp_location *bl,
13125                      struct address_space *aspace, CORE_ADDR bp_addr,
13126                      const struct target_waitstatus *ws)
13127 {
13128   if (ws->kind != TARGET_WAITKIND_STOPPED
13129       || ws->value.sig != GDB_SIGNAL_TRAP)
13130     return 0;
13131
13132   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13133                                  aspace, bp_addr))
13134     return 0;
13135
13136   if (overlay_debugging         /* unmapped overlay section */
13137       && section_is_overlay (bl->section)
13138       && !section_is_mapped (bl->section))
13139     return 0;
13140
13141   return 1;
13142 }
13143
13144 static int
13145 dprintf_breakpoint_hit (const struct bp_location *bl,
13146                         struct address_space *aspace, CORE_ADDR bp_addr,
13147                         const struct target_waitstatus *ws)
13148 {
13149   if (dprintf_style == dprintf_style_agent
13150       && target_can_run_breakpoint_commands ())
13151     {
13152       /* An agent-style dprintf never causes a stop.  If we see a trap
13153          for this address it must be for a breakpoint that happens to
13154          be set at the same address.  */
13155       return 0;
13156     }
13157
13158   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13159 }
13160
13161 static int
13162 bkpt_resources_needed (const struct bp_location *bl)
13163 {
13164   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13165
13166   return 1;
13167 }
13168
13169 static enum print_stop_action
13170 bkpt_print_it (bpstat bs)
13171 {
13172   struct breakpoint *b;
13173   const struct bp_location *bl;
13174   int bp_temp;
13175   struct ui_out *uiout = current_uiout;
13176
13177   gdb_assert (bs->bp_location_at != NULL);
13178
13179   bl = bs->bp_location_at;
13180   b = bs->breakpoint_at;
13181
13182   bp_temp = b->disposition == disp_del;
13183   if (bl->address != bl->requested_address)
13184     breakpoint_adjustment_warning (bl->requested_address,
13185                                    bl->address,
13186                                    b->number, 1);
13187   annotate_breakpoint (b->number);
13188   if (bp_temp)
13189     ui_out_text (uiout, "\nTemporary breakpoint ");
13190   else
13191     ui_out_text (uiout, "\nBreakpoint ");
13192   if (ui_out_is_mi_like_p (uiout))
13193     {
13194       ui_out_field_string (uiout, "reason",
13195                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13196       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13197     }
13198   ui_out_field_int (uiout, "bkptno", b->number);
13199   ui_out_text (uiout, ", ");
13200
13201   return PRINT_SRC_AND_LOC;
13202 }
13203
13204 static void
13205 bkpt_print_mention (struct breakpoint *b)
13206 {
13207   if (ui_out_is_mi_like_p (current_uiout))
13208     return;
13209
13210   switch (b->type)
13211     {
13212     case bp_breakpoint:
13213     case bp_gnu_ifunc_resolver:
13214       if (b->disposition == disp_del)
13215         printf_filtered (_("Temporary breakpoint"));
13216       else
13217         printf_filtered (_("Breakpoint"));
13218       printf_filtered (_(" %d"), b->number);
13219       if (b->type == bp_gnu_ifunc_resolver)
13220         printf_filtered (_(" at gnu-indirect-function resolver"));
13221       break;
13222     case bp_hardware_breakpoint:
13223       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13224       break;
13225     case bp_dprintf:
13226       printf_filtered (_("Dprintf %d"), b->number);
13227       break;
13228     }
13229
13230   say_where (b);
13231 }
13232
13233 static void
13234 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13235 {
13236   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13237     fprintf_unfiltered (fp, "tbreak");
13238   else if (tp->type == bp_breakpoint)
13239     fprintf_unfiltered (fp, "break");
13240   else if (tp->type == bp_hardware_breakpoint
13241            && tp->disposition == disp_del)
13242     fprintf_unfiltered (fp, "thbreak");
13243   else if (tp->type == bp_hardware_breakpoint)
13244     fprintf_unfiltered (fp, "hbreak");
13245   else
13246     internal_error (__FILE__, __LINE__,
13247                     _("unhandled breakpoint type %d"), (int) tp->type);
13248
13249   fprintf_unfiltered (fp, " %s", tp->addr_string);
13250   print_recreate_thread (tp, fp);
13251 }
13252
13253 static void
13254 bkpt_create_sals_from_address (char **arg,
13255                                struct linespec_result *canonical,
13256                                enum bptype type_wanted,
13257                                char *addr_start, char **copy_arg)
13258 {
13259   create_sals_from_address_default (arg, canonical, type_wanted,
13260                                     addr_start, copy_arg);
13261 }
13262
13263 static void
13264 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13265                              struct linespec_result *canonical,
13266                              char *cond_string,
13267                              char *extra_string,
13268                              enum bptype type_wanted,
13269                              enum bpdisp disposition,
13270                              int thread,
13271                              int task, int ignore_count,
13272                              const struct breakpoint_ops *ops,
13273                              int from_tty, int enabled,
13274                              int internal, unsigned flags)
13275 {
13276   create_breakpoints_sal_default (gdbarch, canonical,
13277                                   cond_string, extra_string,
13278                                   type_wanted,
13279                                   disposition, thread, task,
13280                                   ignore_count, ops, from_tty,
13281                                   enabled, internal, flags);
13282 }
13283
13284 static void
13285 bkpt_decode_linespec (struct breakpoint *b, char **s,
13286                       struct symtabs_and_lines *sals)
13287 {
13288   decode_linespec_default (b, s, sals);
13289 }
13290
13291 /* Virtual table for internal breakpoints.  */
13292
13293 static void
13294 internal_bkpt_re_set (struct breakpoint *b)
13295 {
13296   switch (b->type)
13297     {
13298       /* Delete overlay event and longjmp master breakpoints; they
13299          will be reset later by breakpoint_re_set.  */
13300     case bp_overlay_event:
13301     case bp_longjmp_master:
13302     case bp_std_terminate_master:
13303     case bp_exception_master:
13304       delete_breakpoint (b);
13305       break;
13306
13307       /* This breakpoint is special, it's set up when the inferior
13308          starts and we really don't want to touch it.  */
13309     case bp_shlib_event:
13310
13311       /* Like bp_shlib_event, this breakpoint type is special.  Once
13312          it is set up, we do not want to touch it.  */
13313     case bp_thread_event:
13314       break;
13315     }
13316 }
13317
13318 static void
13319 internal_bkpt_check_status (bpstat bs)
13320 {
13321   if (bs->breakpoint_at->type == bp_shlib_event)
13322     {
13323       /* If requested, stop when the dynamic linker notifies GDB of
13324          events.  This allows the user to get control and place
13325          breakpoints in initializer routines for dynamically loaded
13326          objects (among other things).  */
13327       bs->stop = stop_on_solib_events;
13328       bs->print = stop_on_solib_events;
13329     }
13330   else
13331     bs->stop = 0;
13332 }
13333
13334 static enum print_stop_action
13335 internal_bkpt_print_it (bpstat bs)
13336 {
13337   struct breakpoint *b;
13338
13339   b = bs->breakpoint_at;
13340
13341   switch (b->type)
13342     {
13343     case bp_shlib_event:
13344       /* Did we stop because the user set the stop_on_solib_events
13345          variable?  (If so, we report this as a generic, "Stopped due
13346          to shlib event" message.) */
13347       print_solib_event (0);
13348       break;
13349
13350     case bp_thread_event:
13351       /* Not sure how we will get here.
13352          GDB should not stop for these breakpoints.  */
13353       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13354       break;
13355
13356     case bp_overlay_event:
13357       /* By analogy with the thread event, GDB should not stop for these.  */
13358       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13359       break;
13360
13361     case bp_longjmp_master:
13362       /* These should never be enabled.  */
13363       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13364       break;
13365
13366     case bp_std_terminate_master:
13367       /* These should never be enabled.  */
13368       printf_filtered (_("std::terminate Master Breakpoint: "
13369                          "gdb should not stop!\n"));
13370       break;
13371
13372     case bp_exception_master:
13373       /* These should never be enabled.  */
13374       printf_filtered (_("Exception Master Breakpoint: "
13375                          "gdb should not stop!\n"));
13376       break;
13377     }
13378
13379   return PRINT_NOTHING;
13380 }
13381
13382 static void
13383 internal_bkpt_print_mention (struct breakpoint *b)
13384 {
13385   /* Nothing to mention.  These breakpoints are internal.  */
13386 }
13387
13388 /* Virtual table for momentary breakpoints  */
13389
13390 static void
13391 momentary_bkpt_re_set (struct breakpoint *b)
13392 {
13393   /* Keep temporary breakpoints, which can be encountered when we step
13394      over a dlopen call and solib_add is resetting the breakpoints.
13395      Otherwise these should have been blown away via the cleanup chain
13396      or by breakpoint_init_inferior when we rerun the executable.  */
13397 }
13398
13399 static void
13400 momentary_bkpt_check_status (bpstat bs)
13401 {
13402   /* Nothing.  The point of these breakpoints is causing a stop.  */
13403 }
13404
13405 static enum print_stop_action
13406 momentary_bkpt_print_it (bpstat bs)
13407 {
13408   struct ui_out *uiout = current_uiout;
13409
13410   if (ui_out_is_mi_like_p (uiout))
13411     {
13412       struct breakpoint *b = bs->breakpoint_at;
13413
13414       switch (b->type)
13415         {
13416         case bp_finish:
13417           ui_out_field_string
13418             (uiout, "reason",
13419              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13420           break;
13421
13422         case bp_until:
13423           ui_out_field_string
13424             (uiout, "reason",
13425              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13426           break;
13427         }
13428     }
13429
13430   return PRINT_UNKNOWN;
13431 }
13432
13433 static void
13434 momentary_bkpt_print_mention (struct breakpoint *b)
13435 {
13436   /* Nothing to mention.  These breakpoints are internal.  */
13437 }
13438
13439 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13440
13441    It gets cleared already on the removal of the first one of such placed
13442    breakpoints.  This is OK as they get all removed altogether.  */
13443
13444 static void
13445 longjmp_bkpt_dtor (struct breakpoint *self)
13446 {
13447   struct thread_info *tp = find_thread_id (self->thread);
13448
13449   if (tp)
13450     tp->initiating_frame = null_frame_id;
13451
13452   momentary_breakpoint_ops.dtor (self);
13453 }
13454
13455 /* Specific methods for probe breakpoints.  */
13456
13457 static int
13458 bkpt_probe_insert_location (struct bp_location *bl)
13459 {
13460   int v = bkpt_insert_location (bl);
13461
13462   if (v == 0)
13463     {
13464       /* The insertion was successful, now let's set the probe's semaphore
13465          if needed.  */
13466       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13467                                             bl->probe.objfile,
13468                                             bl->gdbarch);
13469     }
13470
13471   return v;
13472 }
13473
13474 static int
13475 bkpt_probe_remove_location (struct bp_location *bl)
13476 {
13477   /* Let's clear the semaphore before removing the location.  */
13478   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13479                                           bl->probe.objfile,
13480                                           bl->gdbarch);
13481
13482   return bkpt_remove_location (bl);
13483 }
13484
13485 static void
13486 bkpt_probe_create_sals_from_address (char **arg,
13487                                      struct linespec_result *canonical,
13488                                      enum bptype type_wanted,
13489                                      char *addr_start, char **copy_arg)
13490 {
13491   struct linespec_sals lsal;
13492
13493   lsal.sals = parse_probes (arg, canonical);
13494
13495   *copy_arg = xstrdup (canonical->addr_string);
13496   lsal.canonical = xstrdup (*copy_arg);
13497
13498   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13499 }
13500
13501 static void
13502 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13503                             struct symtabs_and_lines *sals)
13504 {
13505   *sals = parse_probes (s, NULL);
13506   if (!sals->sals)
13507     error (_("probe not found"));
13508 }
13509
13510 /* The breakpoint_ops structure to be used in tracepoints.  */
13511
13512 static void
13513 tracepoint_re_set (struct breakpoint *b)
13514 {
13515   breakpoint_re_set_default (b);
13516 }
13517
13518 static int
13519 tracepoint_breakpoint_hit (const struct bp_location *bl,
13520                            struct address_space *aspace, CORE_ADDR bp_addr,
13521                            const struct target_waitstatus *ws)
13522 {
13523   /* By definition, the inferior does not report stops at
13524      tracepoints.  */
13525   return 0;
13526 }
13527
13528 static void
13529 tracepoint_print_one_detail (const struct breakpoint *self,
13530                              struct ui_out *uiout)
13531 {
13532   struct tracepoint *tp = (struct tracepoint *) self;
13533   if (tp->static_trace_marker_id)
13534     {
13535       gdb_assert (self->type == bp_static_tracepoint);
13536
13537       ui_out_text (uiout, "\tmarker id is ");
13538       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13539                            tp->static_trace_marker_id);
13540       ui_out_text (uiout, "\n");
13541     }
13542 }
13543
13544 static void
13545 tracepoint_print_mention (struct breakpoint *b)
13546 {
13547   if (ui_out_is_mi_like_p (current_uiout))
13548     return;
13549
13550   switch (b->type)
13551     {
13552     case bp_tracepoint:
13553       printf_filtered (_("Tracepoint"));
13554       printf_filtered (_(" %d"), b->number);
13555       break;
13556     case bp_fast_tracepoint:
13557       printf_filtered (_("Fast tracepoint"));
13558       printf_filtered (_(" %d"), b->number);
13559       break;
13560     case bp_static_tracepoint:
13561       printf_filtered (_("Static tracepoint"));
13562       printf_filtered (_(" %d"), b->number);
13563       break;
13564     default:
13565       internal_error (__FILE__, __LINE__,
13566                       _("unhandled tracepoint type %d"), (int) b->type);
13567     }
13568
13569   say_where (b);
13570 }
13571
13572 static void
13573 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13574 {
13575   struct tracepoint *tp = (struct tracepoint *) self;
13576
13577   if (self->type == bp_fast_tracepoint)
13578     fprintf_unfiltered (fp, "ftrace");
13579   if (self->type == bp_static_tracepoint)
13580     fprintf_unfiltered (fp, "strace");
13581   else if (self->type == bp_tracepoint)
13582     fprintf_unfiltered (fp, "trace");
13583   else
13584     internal_error (__FILE__, __LINE__,
13585                     _("unhandled tracepoint type %d"), (int) self->type);
13586
13587   fprintf_unfiltered (fp, " %s", self->addr_string);
13588   print_recreate_thread (self, fp);
13589
13590   if (tp->pass_count)
13591     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13592 }
13593
13594 static void
13595 tracepoint_create_sals_from_address (char **arg,
13596                                      struct linespec_result *canonical,
13597                                      enum bptype type_wanted,
13598                                      char *addr_start, char **copy_arg)
13599 {
13600   create_sals_from_address_default (arg, canonical, type_wanted,
13601                                     addr_start, copy_arg);
13602 }
13603
13604 static void
13605 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13606                                    struct linespec_result *canonical,
13607                                    char *cond_string,
13608                                    char *extra_string,
13609                                    enum bptype type_wanted,
13610                                    enum bpdisp disposition,
13611                                    int thread,
13612                                    int task, int ignore_count,
13613                                    const struct breakpoint_ops *ops,
13614                                    int from_tty, int enabled,
13615                                    int internal, unsigned flags)
13616 {
13617   create_breakpoints_sal_default (gdbarch, canonical,
13618                                   cond_string, extra_string,
13619                                   type_wanted,
13620                                   disposition, thread, task,
13621                                   ignore_count, ops, from_tty,
13622                                   enabled, internal, flags);
13623 }
13624
13625 static void
13626 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13627                             struct symtabs_and_lines *sals)
13628 {
13629   decode_linespec_default (b, s, sals);
13630 }
13631
13632 struct breakpoint_ops tracepoint_breakpoint_ops;
13633
13634 /* The breakpoint_ops structure to be use on tracepoints placed in a
13635    static probe.  */
13636
13637 static void
13638 tracepoint_probe_create_sals_from_address (char **arg,
13639                                            struct linespec_result *canonical,
13640                                            enum bptype type_wanted,
13641                                            char *addr_start, char **copy_arg)
13642 {
13643   /* We use the same method for breakpoint on probes.  */
13644   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13645                                        addr_start, copy_arg);
13646 }
13647
13648 static void
13649 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13650                                   struct symtabs_and_lines *sals)
13651 {
13652   /* We use the same method for breakpoint on probes.  */
13653   bkpt_probe_decode_linespec (b, s, sals);
13654 }
13655
13656 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13657
13658 /* Dprintf breakpoint_ops methods.  */
13659
13660 static void
13661 dprintf_re_set (struct breakpoint *b)
13662 {
13663   breakpoint_re_set_default (b);
13664
13665   /* This breakpoint could have been pending, and be resolved now, and
13666      if so, we should now have the extra string.  If we don't, the
13667      dprintf was malformed when created, but we couldn't tell because
13668      we can't extract the extra string until the location is
13669      resolved.  */
13670   if (b->loc != NULL && b->extra_string == NULL)
13671     error (_("Format string required"));
13672
13673   /* 1 - connect to target 1, that can run breakpoint commands.
13674      2 - create a dprintf, which resolves fine.
13675      3 - disconnect from target 1
13676      4 - connect to target 2, that can NOT run breakpoint commands.
13677
13678      After steps #3/#4, you'll want the dprintf command list to
13679      be updated, because target 1 and 2 may well return different
13680      answers for target_can_run_breakpoint_commands().
13681      Given absence of finer grained resetting, we get to do
13682      it all the time.  */
13683   if (b->extra_string != NULL)
13684     update_dprintf_command_list (b);
13685 }
13686
13687 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13688
13689 static void
13690 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13691 {
13692   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13693                       tp->extra_string);
13694   print_recreate_thread (tp, fp);
13695 }
13696
13697 /* Implement the "after_condition_true" breakpoint_ops method for
13698    dprintf.
13699
13700    dprintf's are implemented with regular commands in their command
13701    list, but we run the commands here instead of before presenting the
13702    stop to the user, as dprintf's don't actually cause a stop.  This
13703    also makes it so that the commands of multiple dprintfs at the same
13704    address are all handled.  */
13705
13706 static void
13707 dprintf_after_condition_true (struct bpstats *bs)
13708 {
13709   struct cleanup *old_chain;
13710   struct bpstats tmp_bs = { NULL };
13711   struct bpstats *tmp_bs_p = &tmp_bs;
13712
13713   /* dprintf's never cause a stop.  This wasn't set in the
13714      check_status hook instead because that would make the dprintf's
13715      condition not be evaluated.  */
13716   bs->stop = 0;
13717
13718   /* Run the command list here.  Take ownership of it instead of
13719      copying.  We never want these commands to run later in
13720      bpstat_do_actions, if a breakpoint that causes a stop happens to
13721      be set at same address as this dprintf, or even if running the
13722      commands here throws.  */
13723   tmp_bs.commands = bs->commands;
13724   bs->commands = NULL;
13725   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13726
13727   bpstat_do_actions_1 (&tmp_bs_p);
13728
13729   /* 'tmp_bs.commands' will usually be NULL by now, but
13730      bpstat_do_actions_1 may return early without processing the whole
13731      list.  */
13732   do_cleanups (old_chain);
13733 }
13734
13735 /* The breakpoint_ops structure to be used on static tracepoints with
13736    markers (`-m').  */
13737
13738 static void
13739 strace_marker_create_sals_from_address (char **arg,
13740                                         struct linespec_result *canonical,
13741                                         enum bptype type_wanted,
13742                                         char *addr_start, char **copy_arg)
13743 {
13744   struct linespec_sals lsal;
13745
13746   lsal.sals = decode_static_tracepoint_spec (arg);
13747
13748   *copy_arg = savestring (addr_start, *arg - addr_start);
13749
13750   canonical->addr_string = xstrdup (*copy_arg);
13751   lsal.canonical = xstrdup (*copy_arg);
13752   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13753 }
13754
13755 static void
13756 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13757                                       struct linespec_result *canonical,
13758                                       char *cond_string,
13759                                       char *extra_string,
13760                                       enum bptype type_wanted,
13761                                       enum bpdisp disposition,
13762                                       int thread,
13763                                       int task, int ignore_count,
13764                                       const struct breakpoint_ops *ops,
13765                                       int from_tty, int enabled,
13766                                       int internal, unsigned flags)
13767 {
13768   int i;
13769   struct linespec_sals *lsal = VEC_index (linespec_sals,
13770                                           canonical->sals, 0);
13771
13772   /* If the user is creating a static tracepoint by marker id
13773      (strace -m MARKER_ID), then store the sals index, so that
13774      breakpoint_re_set can try to match up which of the newly
13775      found markers corresponds to this one, and, don't try to
13776      expand multiple locations for each sal, given than SALS
13777      already should contain all sals for MARKER_ID.  */
13778
13779   for (i = 0; i < lsal->sals.nelts; ++i)
13780     {
13781       struct symtabs_and_lines expanded;
13782       struct tracepoint *tp;
13783       struct cleanup *old_chain;
13784       char *addr_string;
13785
13786       expanded.nelts = 1;
13787       expanded.sals = &lsal->sals.sals[i];
13788
13789       addr_string = xstrdup (canonical->addr_string);
13790       old_chain = make_cleanup (xfree, addr_string);
13791
13792       tp = XCNEW (struct tracepoint);
13793       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13794                            addr_string, NULL,
13795                            cond_string, extra_string,
13796                            type_wanted, disposition,
13797                            thread, task, ignore_count, ops,
13798                            from_tty, enabled, internal, flags,
13799                            canonical->special_display);
13800       /* Given that its possible to have multiple markers with
13801          the same string id, if the user is creating a static
13802          tracepoint by marker id ("strace -m MARKER_ID"), then
13803          store the sals index, so that breakpoint_re_set can
13804          try to match up which of the newly found markers
13805          corresponds to this one  */
13806       tp->static_trace_marker_id_idx = i;
13807
13808       install_breakpoint (internal, &tp->base, 0);
13809
13810       discard_cleanups (old_chain);
13811     }
13812 }
13813
13814 static void
13815 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13816                                struct symtabs_and_lines *sals)
13817 {
13818   struct tracepoint *tp = (struct tracepoint *) b;
13819
13820   *sals = decode_static_tracepoint_spec (s);
13821   if (sals->nelts > tp->static_trace_marker_id_idx)
13822     {
13823       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13824       sals->nelts = 1;
13825     }
13826   else
13827     error (_("marker %s not found"), tp->static_trace_marker_id);
13828 }
13829
13830 static struct breakpoint_ops strace_marker_breakpoint_ops;
13831
13832 static int
13833 strace_marker_p (struct breakpoint *b)
13834 {
13835   return b->ops == &strace_marker_breakpoint_ops;
13836 }
13837
13838 /* Delete a breakpoint and clean up all traces of it in the data
13839    structures.  */
13840
13841 void
13842 delete_breakpoint (struct breakpoint *bpt)
13843 {
13844   struct breakpoint *b;
13845
13846   gdb_assert (bpt != NULL);
13847
13848   /* Has this bp already been deleted?  This can happen because
13849      multiple lists can hold pointers to bp's.  bpstat lists are
13850      especial culprits.
13851
13852      One example of this happening is a watchpoint's scope bp.  When
13853      the scope bp triggers, we notice that the watchpoint is out of
13854      scope, and delete it.  We also delete its scope bp.  But the
13855      scope bp is marked "auto-deleting", and is already on a bpstat.
13856      That bpstat is then checked for auto-deleting bp's, which are
13857      deleted.
13858
13859      A real solution to this problem might involve reference counts in
13860      bp's, and/or giving them pointers back to their referencing
13861      bpstat's, and teaching delete_breakpoint to only free a bp's
13862      storage when no more references were extent.  A cheaper bandaid
13863      was chosen.  */
13864   if (bpt->type == bp_none)
13865     return;
13866
13867   /* At least avoid this stale reference until the reference counting
13868      of breakpoints gets resolved.  */
13869   if (bpt->related_breakpoint != bpt)
13870     {
13871       struct breakpoint *related;
13872       struct watchpoint *w;
13873
13874       if (bpt->type == bp_watchpoint_scope)
13875         w = (struct watchpoint *) bpt->related_breakpoint;
13876       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13877         w = (struct watchpoint *) bpt;
13878       else
13879         w = NULL;
13880       if (w != NULL)
13881         watchpoint_del_at_next_stop (w);
13882
13883       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13884       for (related = bpt; related->related_breakpoint != bpt;
13885            related = related->related_breakpoint);
13886       related->related_breakpoint = bpt->related_breakpoint;
13887       bpt->related_breakpoint = bpt;
13888     }
13889
13890   /* watch_command_1 creates a watchpoint but only sets its number if
13891      update_watchpoint succeeds in creating its bp_locations.  If there's
13892      a problem in that process, we'll be asked to delete the half-created
13893      watchpoint.  In that case, don't announce the deletion.  */
13894   if (bpt->number)
13895     observer_notify_breakpoint_deleted (bpt);
13896
13897   if (breakpoint_chain == bpt)
13898     breakpoint_chain = bpt->next;
13899
13900   ALL_BREAKPOINTS (b)
13901     if (b->next == bpt)
13902     {
13903       b->next = bpt->next;
13904       break;
13905     }
13906
13907   /* Be sure no bpstat's are pointing at the breakpoint after it's
13908      been freed.  */
13909   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13910      in all threads for now.  Note that we cannot just remove bpstats
13911      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13912      commands are associated with the bpstat; if we remove it here,
13913      then the later call to bpstat_do_actions (&stop_bpstat); in
13914      event-top.c won't do anything, and temporary breakpoints with
13915      commands won't work.  */
13916
13917   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13918
13919   /* Now that breakpoint is removed from breakpoint list, update the
13920      global location list.  This will remove locations that used to
13921      belong to this breakpoint.  Do this before freeing the breakpoint
13922      itself, since remove_breakpoint looks at location's owner.  It
13923      might be better design to have location completely
13924      self-contained, but it's not the case now.  */
13925   update_global_location_list (0);
13926
13927   bpt->ops->dtor (bpt);
13928   /* On the chance that someone will soon try again to delete this
13929      same bp, we mark it as deleted before freeing its storage.  */
13930   bpt->type = bp_none;
13931   xfree (bpt);
13932 }
13933
13934 static void
13935 do_delete_breakpoint_cleanup (void *b)
13936 {
13937   delete_breakpoint (b);
13938 }
13939
13940 struct cleanup *
13941 make_cleanup_delete_breakpoint (struct breakpoint *b)
13942 {
13943   return make_cleanup (do_delete_breakpoint_cleanup, b);
13944 }
13945
13946 /* Iterator function to call a user-provided callback function once
13947    for each of B and its related breakpoints.  */
13948
13949 static void
13950 iterate_over_related_breakpoints (struct breakpoint *b,
13951                                   void (*function) (struct breakpoint *,
13952                                                     void *),
13953                                   void *data)
13954 {
13955   struct breakpoint *related;
13956
13957   related = b;
13958   do
13959     {
13960       struct breakpoint *next;
13961
13962       /* FUNCTION may delete RELATED.  */
13963       next = related->related_breakpoint;
13964
13965       if (next == related)
13966         {
13967           /* RELATED is the last ring entry.  */
13968           function (related, data);
13969
13970           /* FUNCTION may have deleted it, so we'd never reach back to
13971              B.  There's nothing left to do anyway, so just break
13972              out.  */
13973           break;
13974         }
13975       else
13976         function (related, data);
13977
13978       related = next;
13979     }
13980   while (related != b);
13981 }
13982
13983 static void
13984 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13985 {
13986   delete_breakpoint (b);
13987 }
13988
13989 /* A callback for map_breakpoint_numbers that calls
13990    delete_breakpoint.  */
13991
13992 static void
13993 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13994 {
13995   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13996 }
13997
13998 void
13999 delete_command (char *arg, int from_tty)
14000 {
14001   struct breakpoint *b, *b_tmp;
14002
14003   dont_repeat ();
14004
14005   if (arg == 0)
14006     {
14007       int breaks_to_delete = 0;
14008
14009       /* Delete all breakpoints if no argument.  Do not delete
14010          internal breakpoints, these have to be deleted with an
14011          explicit breakpoint number argument.  */
14012       ALL_BREAKPOINTS (b)
14013         if (user_breakpoint_p (b))
14014           {
14015             breaks_to_delete = 1;
14016             break;
14017           }
14018
14019       /* Ask user only if there are some breakpoints to delete.  */
14020       if (!from_tty
14021           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14022         {
14023           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14024             if (user_breakpoint_p (b))
14025               delete_breakpoint (b);
14026         }
14027     }
14028   else
14029     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14030 }
14031
14032 static int
14033 all_locations_are_pending (struct bp_location *loc)
14034 {
14035   for (; loc; loc = loc->next)
14036     if (!loc->shlib_disabled
14037         && !loc->pspace->executing_startup)
14038       return 0;
14039   return 1;
14040 }
14041
14042 /* Subroutine of update_breakpoint_locations to simplify it.
14043    Return non-zero if multiple fns in list LOC have the same name.
14044    Null names are ignored.  */
14045
14046 static int
14047 ambiguous_names_p (struct bp_location *loc)
14048 {
14049   struct bp_location *l;
14050   htab_t htab = htab_create_alloc (13, htab_hash_string,
14051                                    (int (*) (const void *, 
14052                                              const void *)) streq,
14053                                    NULL, xcalloc, xfree);
14054
14055   for (l = loc; l != NULL; l = l->next)
14056     {
14057       const char **slot;
14058       const char *name = l->function_name;
14059
14060       /* Allow for some names to be NULL, ignore them.  */
14061       if (name == NULL)
14062         continue;
14063
14064       slot = (const char **) htab_find_slot (htab, (const void *) name,
14065                                              INSERT);
14066       /* NOTE: We can assume slot != NULL here because xcalloc never
14067          returns NULL.  */
14068       if (*slot != NULL)
14069         {
14070           htab_delete (htab);
14071           return 1;
14072         }
14073       *slot = name;
14074     }
14075
14076   htab_delete (htab);
14077   return 0;
14078 }
14079
14080 /* When symbols change, it probably means the sources changed as well,
14081    and it might mean the static tracepoint markers are no longer at
14082    the same address or line numbers they used to be at last we
14083    checked.  Losing your static tracepoints whenever you rebuild is
14084    undesirable.  This function tries to resync/rematch gdb static
14085    tracepoints with the markers on the target, for static tracepoints
14086    that have not been set by marker id.  Static tracepoint that have
14087    been set by marker id are reset by marker id in breakpoint_re_set.
14088    The heuristic is:
14089
14090    1) For a tracepoint set at a specific address, look for a marker at
14091    the old PC.  If one is found there, assume to be the same marker.
14092    If the name / string id of the marker found is different from the
14093    previous known name, assume that means the user renamed the marker
14094    in the sources, and output a warning.
14095
14096    2) For a tracepoint set at a given line number, look for a marker
14097    at the new address of the old line number.  If one is found there,
14098    assume to be the same marker.  If the name / string id of the
14099    marker found is different from the previous known name, assume that
14100    means the user renamed the marker in the sources, and output a
14101    warning.
14102
14103    3) If a marker is no longer found at the same address or line, it
14104    may mean the marker no longer exists.  But it may also just mean
14105    the code changed a bit.  Maybe the user added a few lines of code
14106    that made the marker move up or down (in line number terms).  Ask
14107    the target for info about the marker with the string id as we knew
14108    it.  If found, update line number and address in the matching
14109    static tracepoint.  This will get confused if there's more than one
14110    marker with the same ID (possible in UST, although unadvised
14111    precisely because it confuses tools).  */
14112
14113 static struct symtab_and_line
14114 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14115 {
14116   struct tracepoint *tp = (struct tracepoint *) b;
14117   struct static_tracepoint_marker marker;
14118   CORE_ADDR pc;
14119
14120   pc = sal.pc;
14121   if (sal.line)
14122     find_line_pc (sal.symtab, sal.line, &pc);
14123
14124   if (target_static_tracepoint_marker_at (pc, &marker))
14125     {
14126       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14127         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14128                  b->number,
14129                  tp->static_trace_marker_id, marker.str_id);
14130
14131       xfree (tp->static_trace_marker_id);
14132       tp->static_trace_marker_id = xstrdup (marker.str_id);
14133       release_static_tracepoint_marker (&marker);
14134
14135       return sal;
14136     }
14137
14138   /* Old marker wasn't found on target at lineno.  Try looking it up
14139      by string ID.  */
14140   if (!sal.explicit_pc
14141       && sal.line != 0
14142       && sal.symtab != NULL
14143       && tp->static_trace_marker_id != NULL)
14144     {
14145       VEC(static_tracepoint_marker_p) *markers;
14146
14147       markers
14148         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14149
14150       if (!VEC_empty(static_tracepoint_marker_p, markers))
14151         {
14152           struct symtab_and_line sal2;
14153           struct symbol *sym;
14154           struct static_tracepoint_marker *tpmarker;
14155           struct ui_out *uiout = current_uiout;
14156
14157           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14158
14159           xfree (tp->static_trace_marker_id);
14160           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14161
14162           warning (_("marker for static tracepoint %d (%s) not "
14163                      "found at previous line number"),
14164                    b->number, tp->static_trace_marker_id);
14165
14166           init_sal (&sal2);
14167
14168           sal2.pc = tpmarker->address;
14169
14170           sal2 = find_pc_line (tpmarker->address, 0);
14171           sym = find_pc_sect_function (tpmarker->address, NULL);
14172           ui_out_text (uiout, "Now in ");
14173           if (sym)
14174             {
14175               ui_out_field_string (uiout, "func",
14176                                    SYMBOL_PRINT_NAME (sym));
14177               ui_out_text (uiout, " at ");
14178             }
14179           ui_out_field_string (uiout, "file",
14180                                symtab_to_filename_for_display (sal2.symtab));
14181           ui_out_text (uiout, ":");
14182
14183           if (ui_out_is_mi_like_p (uiout))
14184             {
14185               const char *fullname = symtab_to_fullname (sal2.symtab);
14186
14187               ui_out_field_string (uiout, "fullname", fullname);
14188             }
14189
14190           ui_out_field_int (uiout, "line", sal2.line);
14191           ui_out_text (uiout, "\n");
14192
14193           b->loc->line_number = sal2.line;
14194           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14195
14196           xfree (b->addr_string);
14197           b->addr_string = xstrprintf ("%s:%d",
14198                                    symtab_to_filename_for_display (sal2.symtab),
14199                                        b->loc->line_number);
14200
14201           /* Might be nice to check if function changed, and warn if
14202              so.  */
14203
14204           release_static_tracepoint_marker (tpmarker);
14205         }
14206     }
14207   return sal;
14208 }
14209
14210 /* Returns 1 iff locations A and B are sufficiently same that
14211    we don't need to report breakpoint as changed.  */
14212
14213 static int
14214 locations_are_equal (struct bp_location *a, struct bp_location *b)
14215 {
14216   while (a && b)
14217     {
14218       if (a->address != b->address)
14219         return 0;
14220
14221       if (a->shlib_disabled != b->shlib_disabled)
14222         return 0;
14223
14224       if (a->enabled != b->enabled)
14225         return 0;
14226
14227       a = a->next;
14228       b = b->next;
14229     }
14230
14231   if ((a == NULL) != (b == NULL))
14232     return 0;
14233
14234   return 1;
14235 }
14236
14237 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14238    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14239    a ranged breakpoint.  */
14240
14241 void
14242 update_breakpoint_locations (struct breakpoint *b,
14243                              struct symtabs_and_lines sals,
14244                              struct symtabs_and_lines sals_end)
14245 {
14246   int i;
14247   struct bp_location *existing_locations = b->loc;
14248
14249   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14250     {
14251       /* Ranged breakpoints have only one start location and one end
14252          location.  */
14253       b->enable_state = bp_disabled;
14254       update_global_location_list (1);
14255       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14256                            "multiple locations found\n"),
14257                          b->number);
14258       return;
14259     }
14260
14261   /* If there's no new locations, and all existing locations are
14262      pending, don't do anything.  This optimizes the common case where
14263      all locations are in the same shared library, that was unloaded.
14264      We'd like to retain the location, so that when the library is
14265      loaded again, we don't loose the enabled/disabled status of the
14266      individual locations.  */
14267   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14268     return;
14269
14270   b->loc = NULL;
14271
14272   for (i = 0; i < sals.nelts; ++i)
14273     {
14274       struct bp_location *new_loc;
14275
14276       switch_to_program_space_and_thread (sals.sals[i].pspace);
14277
14278       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14279
14280       /* Reparse conditions, they might contain references to the
14281          old symtab.  */
14282       if (b->cond_string != NULL)
14283         {
14284           const char *s;
14285           volatile struct gdb_exception e;
14286
14287           s = b->cond_string;
14288           TRY_CATCH (e, RETURN_MASK_ERROR)
14289             {
14290               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14291                                            block_for_pc (sals.sals[i].pc), 
14292                                            0);
14293             }
14294           if (e.reason < 0)
14295             {
14296               warning (_("failed to reevaluate condition "
14297                          "for breakpoint %d: %s"), 
14298                        b->number, e.message);
14299               new_loc->enabled = 0;
14300             }
14301         }
14302
14303       if (sals_end.nelts)
14304         {
14305           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14306
14307           new_loc->length = end - sals.sals[0].pc + 1;
14308         }
14309     }
14310
14311   /* Update locations of permanent breakpoints.  */
14312   if (b->enable_state == bp_permanent)
14313     make_breakpoint_permanent (b);
14314
14315   /* If possible, carry over 'disable' status from existing
14316      breakpoints.  */
14317   {
14318     struct bp_location *e = existing_locations;
14319     /* If there are multiple breakpoints with the same function name,
14320        e.g. for inline functions, comparing function names won't work.
14321        Instead compare pc addresses; this is just a heuristic as things
14322        may have moved, but in practice it gives the correct answer
14323        often enough until a better solution is found.  */
14324     int have_ambiguous_names = ambiguous_names_p (b->loc);
14325
14326     for (; e; e = e->next)
14327       {
14328         if (!e->enabled && e->function_name)
14329           {
14330             struct bp_location *l = b->loc;
14331             if (have_ambiguous_names)
14332               {
14333                 for (; l; l = l->next)
14334                   if (breakpoint_locations_match (e, l))
14335                     {
14336                       l->enabled = 0;
14337                       break;
14338                     }
14339               }
14340             else
14341               {
14342                 for (; l; l = l->next)
14343                   if (l->function_name
14344                       && strcmp (e->function_name, l->function_name) == 0)
14345                     {
14346                       l->enabled = 0;
14347                       break;
14348                     }
14349               }
14350           }
14351       }
14352   }
14353
14354   if (!locations_are_equal (existing_locations, b->loc))
14355     observer_notify_breakpoint_modified (b);
14356
14357   update_global_location_list (1);
14358 }
14359
14360 /* Find the SaL locations corresponding to the given ADDR_STRING.
14361    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14362
14363 static struct symtabs_and_lines
14364 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14365 {
14366   char *s;
14367   struct symtabs_and_lines sals = {0};
14368   volatile struct gdb_exception e;
14369
14370   gdb_assert (b->ops != NULL);
14371   s = addr_string;
14372
14373   TRY_CATCH (e, RETURN_MASK_ERROR)
14374     {
14375       b->ops->decode_linespec (b, &s, &sals);
14376     }
14377   if (e.reason < 0)
14378     {
14379       int not_found_and_ok = 0;
14380       /* For pending breakpoints, it's expected that parsing will
14381          fail until the right shared library is loaded.  User has
14382          already told to create pending breakpoints and don't need
14383          extra messages.  If breakpoint is in bp_shlib_disabled
14384          state, then user already saw the message about that
14385          breakpoint being disabled, and don't want to see more
14386          errors.  */
14387       if (e.error == NOT_FOUND_ERROR
14388           && (b->condition_not_parsed 
14389               || (b->loc && b->loc->shlib_disabled)
14390               || (b->loc && b->loc->pspace->executing_startup)
14391               || b->enable_state == bp_disabled))
14392         not_found_and_ok = 1;
14393
14394       if (!not_found_and_ok)
14395         {
14396           /* We surely don't want to warn about the same breakpoint
14397              10 times.  One solution, implemented here, is disable
14398              the breakpoint on error.  Another solution would be to
14399              have separate 'warning emitted' flag.  Since this
14400              happens only when a binary has changed, I don't know
14401              which approach is better.  */
14402           b->enable_state = bp_disabled;
14403           throw_exception (e);
14404         }
14405     }
14406
14407   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14408     {
14409       int i;
14410
14411       for (i = 0; i < sals.nelts; ++i)
14412         resolve_sal_pc (&sals.sals[i]);
14413       if (b->condition_not_parsed && s && s[0])
14414         {
14415           char *cond_string, *extra_string;
14416           int thread, task;
14417
14418           find_condition_and_thread (s, sals.sals[0].pc,
14419                                      &cond_string, &thread, &task,
14420                                      &extra_string);
14421           if (cond_string)
14422             b->cond_string = cond_string;
14423           b->thread = thread;
14424           b->task = task;
14425           if (extra_string)
14426             b->extra_string = extra_string;
14427           b->condition_not_parsed = 0;
14428         }
14429
14430       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14431         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14432
14433       *found = 1;
14434     }
14435   else
14436     *found = 0;
14437
14438   return sals;
14439 }
14440
14441 /* The default re_set method, for typical hardware or software
14442    breakpoints.  Reevaluate the breakpoint and recreate its
14443    locations.  */
14444
14445 static void
14446 breakpoint_re_set_default (struct breakpoint *b)
14447 {
14448   int found;
14449   struct symtabs_and_lines sals, sals_end;
14450   struct symtabs_and_lines expanded = {0};
14451   struct symtabs_and_lines expanded_end = {0};
14452
14453   sals = addr_string_to_sals (b, b->addr_string, &found);
14454   if (found)
14455     {
14456       make_cleanup (xfree, sals.sals);
14457       expanded = sals;
14458     }
14459
14460   if (b->addr_string_range_end)
14461     {
14462       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14463       if (found)
14464         {
14465           make_cleanup (xfree, sals_end.sals);
14466           expanded_end = sals_end;
14467         }
14468     }
14469
14470   update_breakpoint_locations (b, expanded, expanded_end);
14471 }
14472
14473 /* Default method for creating SALs from an address string.  It basically
14474    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14475
14476 static void
14477 create_sals_from_address_default (char **arg,
14478                                   struct linespec_result *canonical,
14479                                   enum bptype type_wanted,
14480                                   char *addr_start, char **copy_arg)
14481 {
14482   parse_breakpoint_sals (arg, canonical);
14483 }
14484
14485 /* Call create_breakpoints_sal for the given arguments.  This is the default
14486    function for the `create_breakpoints_sal' method of
14487    breakpoint_ops.  */
14488
14489 static void
14490 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14491                                 struct linespec_result *canonical,
14492                                 char *cond_string,
14493                                 char *extra_string,
14494                                 enum bptype type_wanted,
14495                                 enum bpdisp disposition,
14496                                 int thread,
14497                                 int task, int ignore_count,
14498                                 const struct breakpoint_ops *ops,
14499                                 int from_tty, int enabled,
14500                                 int internal, unsigned flags)
14501 {
14502   create_breakpoints_sal (gdbarch, canonical, cond_string,
14503                           extra_string,
14504                           type_wanted, disposition,
14505                           thread, task, ignore_count, ops, from_tty,
14506                           enabled, internal, flags);
14507 }
14508
14509 /* Decode the line represented by S by calling decode_line_full.  This is the
14510    default function for the `decode_linespec' method of breakpoint_ops.  */
14511
14512 static void
14513 decode_linespec_default (struct breakpoint *b, char **s,
14514                          struct symtabs_and_lines *sals)
14515 {
14516   struct linespec_result canonical;
14517
14518   init_linespec_result (&canonical);
14519   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14520                     (struct symtab *) NULL, 0,
14521                     &canonical, multiple_symbols_all,
14522                     b->filter);
14523
14524   /* We should get 0 or 1 resulting SALs.  */
14525   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14526
14527   if (VEC_length (linespec_sals, canonical.sals) > 0)
14528     {
14529       struct linespec_sals *lsal;
14530
14531       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14532       *sals = lsal->sals;
14533       /* Arrange it so the destructor does not free the
14534          contents.  */
14535       lsal->sals.sals = NULL;
14536     }
14537
14538   destroy_linespec_result (&canonical);
14539 }
14540
14541 /* Prepare the global context for a re-set of breakpoint B.  */
14542
14543 static struct cleanup *
14544 prepare_re_set_context (struct breakpoint *b)
14545 {
14546   struct cleanup *cleanups;
14547
14548   input_radix = b->input_radix;
14549   cleanups = save_current_space_and_thread ();
14550   if (b->pspace != NULL)
14551     switch_to_program_space_and_thread (b->pspace);
14552   set_language (b->language);
14553
14554   return cleanups;
14555 }
14556
14557 /* Reset a breakpoint given it's struct breakpoint * BINT.
14558    The value we return ends up being the return value from catch_errors.
14559    Unused in this case.  */
14560
14561 static int
14562 breakpoint_re_set_one (void *bint)
14563 {
14564   /* Get past catch_errs.  */
14565   struct breakpoint *b = (struct breakpoint *) bint;
14566   struct cleanup *cleanups;
14567
14568   cleanups = prepare_re_set_context (b);
14569   b->ops->re_set (b);
14570   do_cleanups (cleanups);
14571   return 0;
14572 }
14573
14574 /* Re-set all breakpoints after symbols have been re-loaded.  */
14575 void
14576 breakpoint_re_set (void)
14577 {
14578   struct breakpoint *b, *b_tmp;
14579   enum language save_language;
14580   int save_input_radix;
14581   struct cleanup *old_chain;
14582
14583   save_language = current_language->la_language;
14584   save_input_radix = input_radix;
14585   old_chain = save_current_program_space ();
14586
14587   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14588   {
14589     /* Format possible error msg.  */
14590     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14591                                 b->number);
14592     struct cleanup *cleanups = make_cleanup (xfree, message);
14593     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14594     do_cleanups (cleanups);
14595   }
14596   set_language (save_language);
14597   input_radix = save_input_radix;
14598
14599   jit_breakpoint_re_set ();
14600
14601   do_cleanups (old_chain);
14602
14603   create_overlay_event_breakpoint ();
14604   create_longjmp_master_breakpoint ();
14605   create_std_terminate_master_breakpoint ();
14606   create_exception_master_breakpoint ();
14607 }
14608 \f
14609 /* Reset the thread number of this breakpoint:
14610
14611    - If the breakpoint is for all threads, leave it as-is.
14612    - Else, reset it to the current thread for inferior_ptid.  */
14613 void
14614 breakpoint_re_set_thread (struct breakpoint *b)
14615 {
14616   if (b->thread != -1)
14617     {
14618       if (in_thread_list (inferior_ptid))
14619         b->thread = pid_to_thread_id (inferior_ptid);
14620
14621       /* We're being called after following a fork.  The new fork is
14622          selected as current, and unless this was a vfork will have a
14623          different program space from the original thread.  Reset that
14624          as well.  */
14625       b->loc->pspace = current_program_space;
14626     }
14627 }
14628
14629 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14630    If from_tty is nonzero, it prints a message to that effect,
14631    which ends with a period (no newline).  */
14632
14633 void
14634 set_ignore_count (int bptnum, int count, int from_tty)
14635 {
14636   struct breakpoint *b;
14637
14638   if (count < 0)
14639     count = 0;
14640
14641   ALL_BREAKPOINTS (b)
14642     if (b->number == bptnum)
14643     {
14644       if (is_tracepoint (b))
14645         {
14646           if (from_tty && count != 0)
14647             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14648                              bptnum);
14649           return;
14650         }
14651       
14652       b->ignore_count = count;
14653       if (from_tty)
14654         {
14655           if (count == 0)
14656             printf_filtered (_("Will stop next time "
14657                                "breakpoint %d is reached."),
14658                              bptnum);
14659           else if (count == 1)
14660             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14661                              bptnum);
14662           else
14663             printf_filtered (_("Will ignore next %d "
14664                                "crossings of breakpoint %d."),
14665                              count, bptnum);
14666         }
14667       observer_notify_breakpoint_modified (b);
14668       return;
14669     }
14670
14671   error (_("No breakpoint number %d."), bptnum);
14672 }
14673
14674 /* Command to set ignore-count of breakpoint N to COUNT.  */
14675
14676 static void
14677 ignore_command (char *args, int from_tty)
14678 {
14679   char *p = args;
14680   int num;
14681
14682   if (p == 0)
14683     error_no_arg (_("a breakpoint number"));
14684
14685   num = get_number (&p);
14686   if (num == 0)
14687     error (_("bad breakpoint number: '%s'"), args);
14688   if (*p == 0)
14689     error (_("Second argument (specified ignore-count) is missing."));
14690
14691   set_ignore_count (num,
14692                     longest_to_int (value_as_long (parse_and_eval (p))),
14693                     from_tty);
14694   if (from_tty)
14695     printf_filtered ("\n");
14696 }
14697 \f
14698 /* Call FUNCTION on each of the breakpoints
14699    whose numbers are given in ARGS.  */
14700
14701 static void
14702 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14703                                                       void *),
14704                         void *data)
14705 {
14706   int num;
14707   struct breakpoint *b, *tmp;
14708   int match;
14709   struct get_number_or_range_state state;
14710
14711   if (args == 0)
14712     error_no_arg (_("one or more breakpoint numbers"));
14713
14714   init_number_or_range (&state, args);
14715
14716   while (!state.finished)
14717     {
14718       char *p = state.string;
14719
14720       match = 0;
14721
14722       num = get_number_or_range (&state);
14723       if (num == 0)
14724         {
14725           warning (_("bad breakpoint number at or near '%s'"), p);
14726         }
14727       else
14728         {
14729           ALL_BREAKPOINTS_SAFE (b, tmp)
14730             if (b->number == num)
14731               {
14732                 match = 1;
14733                 function (b, data);
14734                 break;
14735               }
14736           if (match == 0)
14737             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14738         }
14739     }
14740 }
14741
14742 static struct bp_location *
14743 find_location_by_number (char *number)
14744 {
14745   char *dot = strchr (number, '.');
14746   char *p1;
14747   int bp_num;
14748   int loc_num;
14749   struct breakpoint *b;
14750   struct bp_location *loc;  
14751
14752   *dot = '\0';
14753
14754   p1 = number;
14755   bp_num = get_number (&p1);
14756   if (bp_num == 0)
14757     error (_("Bad breakpoint number '%s'"), number);
14758
14759   ALL_BREAKPOINTS (b)
14760     if (b->number == bp_num)
14761       {
14762         break;
14763       }
14764
14765   if (!b || b->number != bp_num)
14766     error (_("Bad breakpoint number '%s'"), number);
14767   
14768   p1 = dot+1;
14769   loc_num = get_number (&p1);
14770   if (loc_num == 0)
14771     error (_("Bad breakpoint location number '%s'"), number);
14772
14773   --loc_num;
14774   loc = b->loc;
14775   for (;loc_num && loc; --loc_num, loc = loc->next)
14776     ;
14777   if (!loc)
14778     error (_("Bad breakpoint location number '%s'"), dot+1);
14779     
14780   return loc;  
14781 }
14782
14783
14784 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14785    If from_tty is nonzero, it prints a message to that effect,
14786    which ends with a period (no newline).  */
14787
14788 void
14789 disable_breakpoint (struct breakpoint *bpt)
14790 {
14791   /* Never disable a watchpoint scope breakpoint; we want to
14792      hit them when we leave scope so we can delete both the
14793      watchpoint and its scope breakpoint at that time.  */
14794   if (bpt->type == bp_watchpoint_scope)
14795     return;
14796
14797   /* You can't disable permanent breakpoints.  */
14798   if (bpt->enable_state == bp_permanent)
14799     return;
14800
14801   bpt->enable_state = bp_disabled;
14802
14803   /* Mark breakpoint locations modified.  */
14804   mark_breakpoint_modified (bpt);
14805
14806   if (target_supports_enable_disable_tracepoint ()
14807       && current_trace_status ()->running && is_tracepoint (bpt))
14808     {
14809       struct bp_location *location;
14810      
14811       for (location = bpt->loc; location; location = location->next)
14812         target_disable_tracepoint (location);
14813     }
14814
14815   update_global_location_list (0);
14816
14817   observer_notify_breakpoint_modified (bpt);
14818 }
14819
14820 /* A callback for iterate_over_related_breakpoints.  */
14821
14822 static void
14823 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14824 {
14825   disable_breakpoint (b);
14826 }
14827
14828 /* A callback for map_breakpoint_numbers that calls
14829    disable_breakpoint.  */
14830
14831 static void
14832 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14833 {
14834   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14835 }
14836
14837 static void
14838 disable_command (char *args, int from_tty)
14839 {
14840   if (args == 0)
14841     {
14842       struct breakpoint *bpt;
14843
14844       ALL_BREAKPOINTS (bpt)
14845         if (user_breakpoint_p (bpt))
14846           disable_breakpoint (bpt);
14847     }
14848   else
14849     {
14850       char *num = extract_arg (&args);
14851
14852       while (num)
14853         {
14854           if (strchr (num, '.'))
14855             {
14856               struct bp_location *loc = find_location_by_number (num);
14857
14858               if (loc)
14859                 {
14860                   if (loc->enabled)
14861                     {
14862                       loc->enabled = 0;
14863                       mark_breakpoint_location_modified (loc);
14864                     }
14865                   if (target_supports_enable_disable_tracepoint ()
14866                       && current_trace_status ()->running && loc->owner
14867                       && is_tracepoint (loc->owner))
14868                     target_disable_tracepoint (loc);
14869                 }
14870               update_global_location_list (0);
14871             }
14872           else
14873             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14874           num = extract_arg (&args);
14875         }
14876     }
14877 }
14878
14879 static void
14880 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14881                         int count)
14882 {
14883   int target_resources_ok;
14884
14885   if (bpt->type == bp_hardware_breakpoint)
14886     {
14887       int i;
14888       i = hw_breakpoint_used_count ();
14889       target_resources_ok = 
14890         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14891                                             i + 1, 0);
14892       if (target_resources_ok == 0)
14893         error (_("No hardware breakpoint support in the target."));
14894       else if (target_resources_ok < 0)
14895         error (_("Hardware breakpoints used exceeds limit."));
14896     }
14897
14898   if (is_watchpoint (bpt))
14899     {
14900       /* Initialize it just to avoid a GCC false warning.  */
14901       enum enable_state orig_enable_state = 0;
14902       volatile struct gdb_exception e;
14903
14904       TRY_CATCH (e, RETURN_MASK_ALL)
14905         {
14906           struct watchpoint *w = (struct watchpoint *) bpt;
14907
14908           orig_enable_state = bpt->enable_state;
14909           bpt->enable_state = bp_enabled;
14910           update_watchpoint (w, 1 /* reparse */);
14911         }
14912       if (e.reason < 0)
14913         {
14914           bpt->enable_state = orig_enable_state;
14915           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14916                              bpt->number);
14917           return;
14918         }
14919     }
14920
14921   if (bpt->enable_state != bp_permanent)
14922     bpt->enable_state = bp_enabled;
14923
14924   bpt->enable_state = bp_enabled;
14925
14926   /* Mark breakpoint locations modified.  */
14927   mark_breakpoint_modified (bpt);
14928
14929   if (target_supports_enable_disable_tracepoint ()
14930       && current_trace_status ()->running && is_tracepoint (bpt))
14931     {
14932       struct bp_location *location;
14933
14934       for (location = bpt->loc; location; location = location->next)
14935         target_enable_tracepoint (location);
14936     }
14937
14938   bpt->disposition = disposition;
14939   bpt->enable_count = count;
14940   update_global_location_list (1);
14941
14942   observer_notify_breakpoint_modified (bpt);
14943 }
14944
14945
14946 void
14947 enable_breakpoint (struct breakpoint *bpt)
14948 {
14949   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14950 }
14951
14952 static void
14953 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14954 {
14955   enable_breakpoint (bpt);
14956 }
14957
14958 /* A callback for map_breakpoint_numbers that calls
14959    enable_breakpoint.  */
14960
14961 static void
14962 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14963 {
14964   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14965 }
14966
14967 /* The enable command enables the specified breakpoints (or all defined
14968    breakpoints) so they once again become (or continue to be) effective
14969    in stopping the inferior.  */
14970
14971 static void
14972 enable_command (char *args, int from_tty)
14973 {
14974   if (args == 0)
14975     {
14976       struct breakpoint *bpt;
14977
14978       ALL_BREAKPOINTS (bpt)
14979         if (user_breakpoint_p (bpt))
14980           enable_breakpoint (bpt);
14981     }
14982   else
14983     {
14984       char *num = extract_arg (&args);
14985
14986       while (num)
14987         {
14988           if (strchr (num, '.'))
14989             {
14990               struct bp_location *loc = find_location_by_number (num);
14991
14992               if (loc)
14993                 {
14994                   if (!loc->enabled)
14995                     {
14996                       loc->enabled = 1;
14997                       mark_breakpoint_location_modified (loc);
14998                     }
14999                   if (target_supports_enable_disable_tracepoint ()
15000                       && current_trace_status ()->running && loc->owner
15001                       && is_tracepoint (loc->owner))
15002                     target_enable_tracepoint (loc);
15003                 }
15004               update_global_location_list (1);
15005             }
15006           else
15007             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15008           num = extract_arg (&args);
15009         }
15010     }
15011 }
15012
15013 /* This struct packages up disposition data for application to multiple
15014    breakpoints.  */
15015
15016 struct disp_data
15017 {
15018   enum bpdisp disp;
15019   int count;
15020 };
15021
15022 static void
15023 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15024 {
15025   struct disp_data disp_data = *(struct disp_data *) arg;
15026
15027   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15028 }
15029
15030 static void
15031 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15032 {
15033   struct disp_data disp = { disp_disable, 1 };
15034
15035   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15036 }
15037
15038 static void
15039 enable_once_command (char *args, int from_tty)
15040 {
15041   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15042 }
15043
15044 static void
15045 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15046 {
15047   struct disp_data disp = { disp_disable, *(int *) countptr };
15048
15049   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15050 }
15051
15052 static void
15053 enable_count_command (char *args, int from_tty)
15054 {
15055   int count = get_number (&args);
15056
15057   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15058 }
15059
15060 static void
15061 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15062 {
15063   struct disp_data disp = { disp_del, 1 };
15064
15065   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15066 }
15067
15068 static void
15069 enable_delete_command (char *args, int from_tty)
15070 {
15071   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15072 }
15073 \f
15074 static void
15075 set_breakpoint_cmd (char *args, int from_tty)
15076 {
15077 }
15078
15079 static void
15080 show_breakpoint_cmd (char *args, int from_tty)
15081 {
15082 }
15083
15084 /* Invalidate last known value of any hardware watchpoint if
15085    the memory which that value represents has been written to by
15086    GDB itself.  */
15087
15088 static void
15089 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15090                                       CORE_ADDR addr, ssize_t len,
15091                                       const bfd_byte *data)
15092 {
15093   struct breakpoint *bp;
15094
15095   ALL_BREAKPOINTS (bp)
15096     if (bp->enable_state == bp_enabled
15097         && bp->type == bp_hardware_watchpoint)
15098       {
15099         struct watchpoint *wp = (struct watchpoint *) bp;
15100
15101         if (wp->val_valid && wp->val)
15102           {
15103             struct bp_location *loc;
15104
15105             for (loc = bp->loc; loc != NULL; loc = loc->next)
15106               if (loc->loc_type == bp_loc_hardware_watchpoint
15107                   && loc->address + loc->length > addr
15108                   && addr + len > loc->address)
15109                 {
15110                   value_free (wp->val);
15111                   wp->val = NULL;
15112                   wp->val_valid = 0;
15113                 }
15114           }
15115       }
15116 }
15117
15118 /* Create and insert a raw software breakpoint at PC.  Return an
15119    identifier, which should be used to remove the breakpoint later.
15120    In general, places which call this should be using something on the
15121    breakpoint chain instead; this function should be eliminated
15122    someday.  */
15123
15124 void *
15125 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15126                                   struct address_space *aspace, CORE_ADDR pc)
15127 {
15128   struct bp_target_info *bp_tgt;
15129
15130   bp_tgt = XCNEW (struct bp_target_info);
15131
15132   bp_tgt->placed_address_space = aspace;
15133   bp_tgt->placed_address = pc;
15134
15135   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15136     {
15137       /* Could not insert the breakpoint.  */
15138       xfree (bp_tgt);
15139       return NULL;
15140     }
15141
15142   return bp_tgt;
15143 }
15144
15145 /* Remove a breakpoint BP inserted by
15146    deprecated_insert_raw_breakpoint.  */
15147
15148 int
15149 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15150 {
15151   struct bp_target_info *bp_tgt = bp;
15152   int ret;
15153
15154   ret = target_remove_breakpoint (gdbarch, bp_tgt);
15155   xfree (bp_tgt);
15156
15157   return ret;
15158 }
15159
15160 /* Create and insert a breakpoint for software single step.  */
15161
15162 void
15163 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15164                                struct address_space *aspace, 
15165                                CORE_ADDR next_pc)
15166 {
15167   void **bpt_p;
15168
15169   if (single_step_breakpoints[0] == NULL)
15170     {
15171       bpt_p = &single_step_breakpoints[0];
15172       single_step_gdbarch[0] = gdbarch;
15173     }
15174   else
15175     {
15176       gdb_assert (single_step_breakpoints[1] == NULL);
15177       bpt_p = &single_step_breakpoints[1];
15178       single_step_gdbarch[1] = gdbarch;
15179     }
15180
15181   /* NOTE drow/2006-04-11: A future improvement to this function would
15182      be to only create the breakpoints once, and actually put them on
15183      the breakpoint chain.  That would let us use set_raw_breakpoint.
15184      We could adjust the addresses each time they were needed.  Doing
15185      this requires corresponding changes elsewhere where single step
15186      breakpoints are handled, however.  So, for now, we use this.  */
15187
15188   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15189   if (*bpt_p == NULL)
15190     error (_("Could not insert single-step breakpoint at %s"),
15191              paddress (gdbarch, next_pc));
15192 }
15193
15194 /* Check if the breakpoints used for software single stepping
15195    were inserted or not.  */
15196
15197 int
15198 single_step_breakpoints_inserted (void)
15199 {
15200   return (single_step_breakpoints[0] != NULL
15201           || single_step_breakpoints[1] != NULL);
15202 }
15203
15204 /* Remove and delete any breakpoints used for software single step.  */
15205
15206 void
15207 remove_single_step_breakpoints (void)
15208 {
15209   gdb_assert (single_step_breakpoints[0] != NULL);
15210
15211   /* See insert_single_step_breakpoint for more about this deprecated
15212      call.  */
15213   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15214                                     single_step_breakpoints[0]);
15215   single_step_gdbarch[0] = NULL;
15216   single_step_breakpoints[0] = NULL;
15217
15218   if (single_step_breakpoints[1] != NULL)
15219     {
15220       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15221                                         single_step_breakpoints[1]);
15222       single_step_gdbarch[1] = NULL;
15223       single_step_breakpoints[1] = NULL;
15224     }
15225 }
15226
15227 /* Delete software single step breakpoints without removing them from
15228    the inferior.  This is intended to be used if the inferior's address
15229    space where they were inserted is already gone, e.g. after exit or
15230    exec.  */
15231
15232 void
15233 cancel_single_step_breakpoints (void)
15234 {
15235   int i;
15236
15237   for (i = 0; i < 2; i++)
15238     if (single_step_breakpoints[i])
15239       {
15240         xfree (single_step_breakpoints[i]);
15241         single_step_breakpoints[i] = NULL;
15242         single_step_gdbarch[i] = NULL;
15243       }
15244 }
15245
15246 /* Detach software single-step breakpoints from INFERIOR_PTID without
15247    removing them.  */
15248
15249 static void
15250 detach_single_step_breakpoints (void)
15251 {
15252   int i;
15253
15254   for (i = 0; i < 2; i++)
15255     if (single_step_breakpoints[i])
15256       target_remove_breakpoint (single_step_gdbarch[i],
15257                                 single_step_breakpoints[i]);
15258 }
15259
15260 /* Check whether a software single-step breakpoint is inserted at
15261    PC.  */
15262
15263 int
15264 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15265                                         CORE_ADDR pc)
15266 {
15267   int i;
15268
15269   for (i = 0; i < 2; i++)
15270     {
15271       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15272       if (bp_tgt
15273           && breakpoint_address_match (bp_tgt->placed_address_space,
15274                                        bp_tgt->placed_address,
15275                                        aspace, pc))
15276         return 1;
15277     }
15278
15279   return 0;
15280 }
15281
15282 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15283    non-zero otherwise.  */
15284 static int
15285 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15286 {
15287   if (syscall_catchpoint_p (bp)
15288       && bp->enable_state != bp_disabled
15289       && bp->enable_state != bp_call_disabled)
15290     return 1;
15291   else
15292     return 0;
15293 }
15294
15295 int
15296 catch_syscall_enabled (void)
15297 {
15298   struct catch_syscall_inferior_data *inf_data
15299     = get_catch_syscall_inferior_data (current_inferior ());
15300
15301   return inf_data->total_syscalls_count != 0;
15302 }
15303
15304 int
15305 catching_syscall_number (int syscall_number)
15306 {
15307   struct breakpoint *bp;
15308
15309   ALL_BREAKPOINTS (bp)
15310     if (is_syscall_catchpoint_enabled (bp))
15311       {
15312         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15313
15314         if (c->syscalls_to_be_caught)
15315           {
15316             int i, iter;
15317             for (i = 0;
15318                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15319                  i++)
15320               if (syscall_number == iter)
15321                 return 1;
15322           }
15323         else
15324           return 1;
15325       }
15326
15327   return 0;
15328 }
15329
15330 /* Complete syscall names.  Used by "catch syscall".  */
15331 static VEC (char_ptr) *
15332 catch_syscall_completer (struct cmd_list_element *cmd,
15333                          const char *text, const char *word)
15334 {
15335   const char **list = get_syscall_names ();
15336   VEC (char_ptr) *retlist
15337     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15338
15339   xfree (list);
15340   return retlist;
15341 }
15342
15343 /* Tracepoint-specific operations.  */
15344
15345 /* Set tracepoint count to NUM.  */
15346 static void
15347 set_tracepoint_count (int num)
15348 {
15349   tracepoint_count = num;
15350   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15351 }
15352
15353 static void
15354 trace_command (char *arg, int from_tty)
15355 {
15356   struct breakpoint_ops *ops;
15357   const char *arg_cp = arg;
15358
15359   if (arg && probe_linespec_to_ops (&arg_cp))
15360     ops = &tracepoint_probe_breakpoint_ops;
15361   else
15362     ops = &tracepoint_breakpoint_ops;
15363
15364   create_breakpoint (get_current_arch (),
15365                      arg,
15366                      NULL, 0, NULL, 1 /* parse arg */,
15367                      0 /* tempflag */,
15368                      bp_tracepoint /* type_wanted */,
15369                      0 /* Ignore count */,
15370                      pending_break_support,
15371                      ops,
15372                      from_tty,
15373                      1 /* enabled */,
15374                      0 /* internal */, 0);
15375 }
15376
15377 static void
15378 ftrace_command (char *arg, int from_tty)
15379 {
15380   create_breakpoint (get_current_arch (),
15381                      arg,
15382                      NULL, 0, NULL, 1 /* parse arg */,
15383                      0 /* tempflag */,
15384                      bp_fast_tracepoint /* type_wanted */,
15385                      0 /* Ignore count */,
15386                      pending_break_support,
15387                      &tracepoint_breakpoint_ops,
15388                      from_tty,
15389                      1 /* enabled */,
15390                      0 /* internal */, 0);
15391 }
15392
15393 /* strace command implementation.  Creates a static tracepoint.  */
15394
15395 static void
15396 strace_command (char *arg, int from_tty)
15397 {
15398   struct breakpoint_ops *ops;
15399
15400   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15401      or with a normal static tracepoint.  */
15402   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15403     ops = &strace_marker_breakpoint_ops;
15404   else
15405     ops = &tracepoint_breakpoint_ops;
15406
15407   create_breakpoint (get_current_arch (),
15408                      arg,
15409                      NULL, 0, NULL, 1 /* parse arg */,
15410                      0 /* tempflag */,
15411                      bp_static_tracepoint /* type_wanted */,
15412                      0 /* Ignore count */,
15413                      pending_break_support,
15414                      ops,
15415                      from_tty,
15416                      1 /* enabled */,
15417                      0 /* internal */, 0);
15418 }
15419
15420 /* Set up a fake reader function that gets command lines from a linked
15421    list that was acquired during tracepoint uploading.  */
15422
15423 static struct uploaded_tp *this_utp;
15424 static int next_cmd;
15425
15426 static char *
15427 read_uploaded_action (void)
15428 {
15429   char *rslt;
15430
15431   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15432
15433   next_cmd++;
15434
15435   return rslt;
15436 }
15437
15438 /* Given information about a tracepoint as recorded on a target (which
15439    can be either a live system or a trace file), attempt to create an
15440    equivalent GDB tracepoint.  This is not a reliable process, since
15441    the target does not necessarily have all the information used when
15442    the tracepoint was originally defined.  */
15443   
15444 struct tracepoint *
15445 create_tracepoint_from_upload (struct uploaded_tp *utp)
15446 {
15447   char *addr_str, small_buf[100];
15448   struct tracepoint *tp;
15449
15450   if (utp->at_string)
15451     addr_str = utp->at_string;
15452   else
15453     {
15454       /* In the absence of a source location, fall back to raw
15455          address.  Since there is no way to confirm that the address
15456          means the same thing as when the trace was started, warn the
15457          user.  */
15458       warning (_("Uploaded tracepoint %d has no "
15459                  "source location, using raw address"),
15460                utp->number);
15461       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15462       addr_str = small_buf;
15463     }
15464
15465   /* There's not much we can do with a sequence of bytecodes.  */
15466   if (utp->cond && !utp->cond_string)
15467     warning (_("Uploaded tracepoint %d condition "
15468                "has no source form, ignoring it"),
15469              utp->number);
15470
15471   if (!create_breakpoint (get_current_arch (),
15472                           addr_str,
15473                           utp->cond_string, -1, NULL,
15474                           0 /* parse cond/thread */,
15475                           0 /* tempflag */,
15476                           utp->type /* type_wanted */,
15477                           0 /* Ignore count */,
15478                           pending_break_support,
15479                           &tracepoint_breakpoint_ops,
15480                           0 /* from_tty */,
15481                           utp->enabled /* enabled */,
15482                           0 /* internal */,
15483                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15484     return NULL;
15485
15486   /* Get the tracepoint we just created.  */
15487   tp = get_tracepoint (tracepoint_count);
15488   gdb_assert (tp != NULL);
15489
15490   if (utp->pass > 0)
15491     {
15492       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15493                  tp->base.number);
15494
15495       trace_pass_command (small_buf, 0);
15496     }
15497
15498   /* If we have uploaded versions of the original commands, set up a
15499      special-purpose "reader" function and call the usual command line
15500      reader, then pass the result to the breakpoint command-setting
15501      function.  */
15502   if (!VEC_empty (char_ptr, utp->cmd_strings))
15503     {
15504       struct command_line *cmd_list;
15505
15506       this_utp = utp;
15507       next_cmd = 0;
15508
15509       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15510
15511       breakpoint_set_commands (&tp->base, cmd_list);
15512     }
15513   else if (!VEC_empty (char_ptr, utp->actions)
15514            || !VEC_empty (char_ptr, utp->step_actions))
15515     warning (_("Uploaded tracepoint %d actions "
15516                "have no source form, ignoring them"),
15517              utp->number);
15518
15519   /* Copy any status information that might be available.  */
15520   tp->base.hit_count = utp->hit_count;
15521   tp->traceframe_usage = utp->traceframe_usage;
15522
15523   return tp;
15524 }
15525   
15526 /* Print information on tracepoint number TPNUM_EXP, or all if
15527    omitted.  */
15528
15529 static void
15530 tracepoints_info (char *args, int from_tty)
15531 {
15532   struct ui_out *uiout = current_uiout;
15533   int num_printed;
15534
15535   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15536
15537   if (num_printed == 0)
15538     {
15539       if (args == NULL || *args == '\0')
15540         ui_out_message (uiout, 0, "No tracepoints.\n");
15541       else
15542         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15543     }
15544
15545   default_collect_info ();
15546 }
15547
15548 /* The 'enable trace' command enables tracepoints.
15549    Not supported by all targets.  */
15550 static void
15551 enable_trace_command (char *args, int from_tty)
15552 {
15553   enable_command (args, from_tty);
15554 }
15555
15556 /* The 'disable trace' command disables tracepoints.
15557    Not supported by all targets.  */
15558 static void
15559 disable_trace_command (char *args, int from_tty)
15560 {
15561   disable_command (args, from_tty);
15562 }
15563
15564 /* Remove a tracepoint (or all if no argument).  */
15565 static void
15566 delete_trace_command (char *arg, int from_tty)
15567 {
15568   struct breakpoint *b, *b_tmp;
15569
15570   dont_repeat ();
15571
15572   if (arg == 0)
15573     {
15574       int breaks_to_delete = 0;
15575
15576       /* Delete all breakpoints if no argument.
15577          Do not delete internal or call-dummy breakpoints, these
15578          have to be deleted with an explicit breakpoint number 
15579          argument.  */
15580       ALL_TRACEPOINTS (b)
15581         if (is_tracepoint (b) && user_breakpoint_p (b))
15582           {
15583             breaks_to_delete = 1;
15584             break;
15585           }
15586
15587       /* Ask user only if there are some breakpoints to delete.  */
15588       if (!from_tty
15589           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15590         {
15591           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15592             if (is_tracepoint (b) && user_breakpoint_p (b))
15593               delete_breakpoint (b);
15594         }
15595     }
15596   else
15597     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15598 }
15599
15600 /* Helper function for trace_pass_command.  */
15601
15602 static void
15603 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15604 {
15605   tp->pass_count = count;
15606   observer_notify_breakpoint_modified (&tp->base);
15607   if (from_tty)
15608     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15609                      tp->base.number, count);
15610 }
15611
15612 /* Set passcount for tracepoint.
15613
15614    First command argument is passcount, second is tracepoint number.
15615    If tracepoint number omitted, apply to most recently defined.
15616    Also accepts special argument "all".  */
15617
15618 static void
15619 trace_pass_command (char *args, int from_tty)
15620 {
15621   struct tracepoint *t1;
15622   unsigned int count;
15623
15624   if (args == 0 || *args == 0)
15625     error (_("passcount command requires an "
15626              "argument (count + optional TP num)"));
15627
15628   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15629
15630   args = skip_spaces (args);
15631   if (*args && strncasecmp (args, "all", 3) == 0)
15632     {
15633       struct breakpoint *b;
15634
15635       args += 3;                        /* Skip special argument "all".  */
15636       if (*args)
15637         error (_("Junk at end of arguments."));
15638
15639       ALL_TRACEPOINTS (b)
15640       {
15641         t1 = (struct tracepoint *) b;
15642         trace_pass_set_count (t1, count, from_tty);
15643       }
15644     }
15645   else if (*args == '\0')
15646     {
15647       t1 = get_tracepoint_by_number (&args, NULL);
15648       if (t1)
15649         trace_pass_set_count (t1, count, from_tty);
15650     }
15651   else
15652     {
15653       struct get_number_or_range_state state;
15654
15655       init_number_or_range (&state, args);
15656       while (!state.finished)
15657         {
15658           t1 = get_tracepoint_by_number (&args, &state);
15659           if (t1)
15660             trace_pass_set_count (t1, count, from_tty);
15661         }
15662     }
15663 }
15664
15665 struct tracepoint *
15666 get_tracepoint (int num)
15667 {
15668   struct breakpoint *t;
15669
15670   ALL_TRACEPOINTS (t)
15671     if (t->number == num)
15672       return (struct tracepoint *) t;
15673
15674   return NULL;
15675 }
15676
15677 /* Find the tracepoint with the given target-side number (which may be
15678    different from the tracepoint number after disconnecting and
15679    reconnecting).  */
15680
15681 struct tracepoint *
15682 get_tracepoint_by_number_on_target (int num)
15683 {
15684   struct breakpoint *b;
15685
15686   ALL_TRACEPOINTS (b)
15687     {
15688       struct tracepoint *t = (struct tracepoint *) b;
15689
15690       if (t->number_on_target == num)
15691         return t;
15692     }
15693
15694   return NULL;
15695 }
15696
15697 /* Utility: parse a tracepoint number and look it up in the list.
15698    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15699    If the argument is missing, the most recent tracepoint
15700    (tracepoint_count) is returned.  */
15701
15702 struct tracepoint *
15703 get_tracepoint_by_number (char **arg,
15704                           struct get_number_or_range_state *state)
15705 {
15706   struct breakpoint *t;
15707   int tpnum;
15708   char *instring = arg == NULL ? NULL : *arg;
15709
15710   if (state)
15711     {
15712       gdb_assert (!state->finished);
15713       tpnum = get_number_or_range (state);
15714     }
15715   else if (arg == NULL || *arg == NULL || ! **arg)
15716     tpnum = tracepoint_count;
15717   else
15718     tpnum = get_number (arg);
15719
15720   if (tpnum <= 0)
15721     {
15722       if (instring && *instring)
15723         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15724                          instring);
15725       else
15726         printf_filtered (_("No previous tracepoint\n"));
15727       return NULL;
15728     }
15729
15730   ALL_TRACEPOINTS (t)
15731     if (t->number == tpnum)
15732     {
15733       return (struct tracepoint *) t;
15734     }
15735
15736   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15737   return NULL;
15738 }
15739
15740 void
15741 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15742 {
15743   if (b->thread != -1)
15744     fprintf_unfiltered (fp, " thread %d", b->thread);
15745
15746   if (b->task != 0)
15747     fprintf_unfiltered (fp, " task %d", b->task);
15748
15749   fprintf_unfiltered (fp, "\n");
15750 }
15751
15752 /* Save information on user settable breakpoints (watchpoints, etc) to
15753    a new script file named FILENAME.  If FILTER is non-NULL, call it
15754    on each breakpoint and only include the ones for which it returns
15755    non-zero.  */
15756
15757 static void
15758 save_breakpoints (char *filename, int from_tty,
15759                   int (*filter) (const struct breakpoint *))
15760 {
15761   struct breakpoint *tp;
15762   int any = 0;
15763   struct cleanup *cleanup;
15764   struct ui_file *fp;
15765   int extra_trace_bits = 0;
15766
15767   if (filename == 0 || *filename == 0)
15768     error (_("Argument required (file name in which to save)"));
15769
15770   /* See if we have anything to save.  */
15771   ALL_BREAKPOINTS (tp)
15772   {
15773     /* Skip internal and momentary breakpoints.  */
15774     if (!user_breakpoint_p (tp))
15775       continue;
15776
15777     /* If we have a filter, only save the breakpoints it accepts.  */
15778     if (filter && !filter (tp))
15779       continue;
15780
15781     any = 1;
15782
15783     if (is_tracepoint (tp))
15784       {
15785         extra_trace_bits = 1;
15786
15787         /* We can stop searching.  */
15788         break;
15789       }
15790   }
15791
15792   if (!any)
15793     {
15794       warning (_("Nothing to save."));
15795       return;
15796     }
15797
15798   filename = tilde_expand (filename);
15799   cleanup = make_cleanup (xfree, filename);
15800   fp = gdb_fopen (filename, "w");
15801   if (!fp)
15802     error (_("Unable to open file '%s' for saving (%s)"),
15803            filename, safe_strerror (errno));
15804   make_cleanup_ui_file_delete (fp);
15805
15806   if (extra_trace_bits)
15807     save_trace_state_variables (fp);
15808
15809   ALL_BREAKPOINTS (tp)
15810   {
15811     /* Skip internal and momentary breakpoints.  */
15812     if (!user_breakpoint_p (tp))
15813       continue;
15814
15815     /* If we have a filter, only save the breakpoints it accepts.  */
15816     if (filter && !filter (tp))
15817       continue;
15818
15819     tp->ops->print_recreate (tp, fp);
15820
15821     /* Note, we can't rely on tp->number for anything, as we can't
15822        assume the recreated breakpoint numbers will match.  Use $bpnum
15823        instead.  */
15824
15825     if (tp->cond_string)
15826       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15827
15828     if (tp->ignore_count)
15829       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15830
15831     if (tp->type != bp_dprintf && tp->commands)
15832       {
15833         volatile struct gdb_exception ex;       
15834
15835         fprintf_unfiltered (fp, "  commands\n");
15836         
15837         ui_out_redirect (current_uiout, fp);
15838         TRY_CATCH (ex, RETURN_MASK_ALL)
15839           {
15840             print_command_lines (current_uiout, tp->commands->commands, 2);
15841           }
15842         ui_out_redirect (current_uiout, NULL);
15843
15844         if (ex.reason < 0)
15845           throw_exception (ex);
15846
15847         fprintf_unfiltered (fp, "  end\n");
15848       }
15849
15850     if (tp->enable_state == bp_disabled)
15851       fprintf_unfiltered (fp, "disable\n");
15852
15853     /* If this is a multi-location breakpoint, check if the locations
15854        should be individually disabled.  Watchpoint locations are
15855        special, and not user visible.  */
15856     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15857       {
15858         struct bp_location *loc;
15859         int n = 1;
15860
15861         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15862           if (!loc->enabled)
15863             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15864       }
15865   }
15866
15867   if (extra_trace_bits && *default_collect)
15868     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15869
15870   if (from_tty)
15871     printf_filtered (_("Saved to file '%s'.\n"), filename);
15872   do_cleanups (cleanup);
15873 }
15874
15875 /* The `save breakpoints' command.  */
15876
15877 static void
15878 save_breakpoints_command (char *args, int from_tty)
15879 {
15880   save_breakpoints (args, from_tty, NULL);
15881 }
15882
15883 /* The `save tracepoints' command.  */
15884
15885 static void
15886 save_tracepoints_command (char *args, int from_tty)
15887 {
15888   save_breakpoints (args, from_tty, is_tracepoint);
15889 }
15890
15891 /* Create a vector of all tracepoints.  */
15892
15893 VEC(breakpoint_p) *
15894 all_tracepoints (void)
15895 {
15896   VEC(breakpoint_p) *tp_vec = 0;
15897   struct breakpoint *tp;
15898
15899   ALL_TRACEPOINTS (tp)
15900   {
15901     VEC_safe_push (breakpoint_p, tp_vec, tp);
15902   }
15903
15904   return tp_vec;
15905 }
15906
15907 \f
15908 /* This help string is used for the break, hbreak, tbreak and thbreak
15909    commands.  It is defined as a macro to prevent duplication.
15910    COMMAND should be a string constant containing the name of the
15911    command.  */
15912 #define BREAK_ARGS_HELP(command) \
15913 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15914 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15915 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15916 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15917 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15918 If a line number is specified, break at start of code for that line.\n\
15919 If a function is specified, break at start of code for that function.\n\
15920 If an address is specified, break at that exact address.\n\
15921 With no LOCATION, uses current execution address of the selected\n\
15922 stack frame.  This is useful for breaking on return to a stack frame.\n\
15923 \n\
15924 THREADNUM is the number from \"info threads\".\n\
15925 CONDITION is a boolean expression.\n\
15926 \n\
15927 Multiple breakpoints at one place are permitted, and useful if their\n\
15928 conditions are different.\n\
15929 \n\
15930 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15931
15932 /* List of subcommands for "catch".  */
15933 static struct cmd_list_element *catch_cmdlist;
15934
15935 /* List of subcommands for "tcatch".  */
15936 static struct cmd_list_element *tcatch_cmdlist;
15937
15938 void
15939 add_catch_command (char *name, char *docstring,
15940                    void (*sfunc) (char *args, int from_tty,
15941                                   struct cmd_list_element *command),
15942                    completer_ftype *completer,
15943                    void *user_data_catch,
15944                    void *user_data_tcatch)
15945 {
15946   struct cmd_list_element *command;
15947
15948   command = add_cmd (name, class_breakpoint, NULL, docstring,
15949                      &catch_cmdlist);
15950   set_cmd_sfunc (command, sfunc);
15951   set_cmd_context (command, user_data_catch);
15952   set_cmd_completer (command, completer);
15953
15954   command = add_cmd (name, class_breakpoint, NULL, docstring,
15955                      &tcatch_cmdlist);
15956   set_cmd_sfunc (command, sfunc);
15957   set_cmd_context (command, user_data_tcatch);
15958   set_cmd_completer (command, completer);
15959 }
15960
15961 static void
15962 clear_syscall_counts (struct inferior *inf)
15963 {
15964   struct catch_syscall_inferior_data *inf_data
15965     = get_catch_syscall_inferior_data (inf);
15966
15967   inf_data->total_syscalls_count = 0;
15968   inf_data->any_syscall_count = 0;
15969   VEC_free (int, inf_data->syscalls_counts);
15970 }
15971
15972 static void
15973 save_command (char *arg, int from_tty)
15974 {
15975   printf_unfiltered (_("\"save\" must be followed by "
15976                        "the name of a save subcommand.\n"));
15977   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15978 }
15979
15980 struct breakpoint *
15981 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15982                           void *data)
15983 {
15984   struct breakpoint *b, *b_tmp;
15985
15986   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15987     {
15988       if ((*callback) (b, data))
15989         return b;
15990     }
15991
15992   return NULL;
15993 }
15994
15995 /* Zero if any of the breakpoint's locations could be a location where
15996    functions have been inlined, nonzero otherwise.  */
15997
15998 static int
15999 is_non_inline_function (struct breakpoint *b)
16000 {
16001   /* The shared library event breakpoint is set on the address of a
16002      non-inline function.  */
16003   if (b->type == bp_shlib_event)
16004     return 1;
16005
16006   return 0;
16007 }
16008
16009 /* Nonzero if the specified PC cannot be a location where functions
16010    have been inlined.  */
16011
16012 int
16013 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16014                            const struct target_waitstatus *ws)
16015 {
16016   struct breakpoint *b;
16017   struct bp_location *bl;
16018
16019   ALL_BREAKPOINTS (b)
16020     {
16021       if (!is_non_inline_function (b))
16022         continue;
16023
16024       for (bl = b->loc; bl != NULL; bl = bl->next)
16025         {
16026           if (!bl->shlib_disabled
16027               && bpstat_check_location (bl, aspace, pc, ws))
16028             return 1;
16029         }
16030     }
16031
16032   return 0;
16033 }
16034
16035 /* Remove any references to OBJFILE which is going to be freed.  */
16036
16037 void
16038 breakpoint_free_objfile (struct objfile *objfile)
16039 {
16040   struct bp_location **locp, *loc;
16041
16042   ALL_BP_LOCATIONS (loc, locp)
16043     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16044       loc->symtab = NULL;
16045 }
16046
16047 void
16048 initialize_breakpoint_ops (void)
16049 {
16050   static int initialized = 0;
16051
16052   struct breakpoint_ops *ops;
16053
16054   if (initialized)
16055     return;
16056   initialized = 1;
16057
16058   /* The breakpoint_ops structure to be inherit by all kinds of
16059      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16060      internal and momentary breakpoints, etc.).  */
16061   ops = &bkpt_base_breakpoint_ops;
16062   *ops = base_breakpoint_ops;
16063   ops->re_set = bkpt_re_set;
16064   ops->insert_location = bkpt_insert_location;
16065   ops->remove_location = bkpt_remove_location;
16066   ops->breakpoint_hit = bkpt_breakpoint_hit;
16067   ops->create_sals_from_address = bkpt_create_sals_from_address;
16068   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16069   ops->decode_linespec = bkpt_decode_linespec;
16070
16071   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16072   ops = &bkpt_breakpoint_ops;
16073   *ops = bkpt_base_breakpoint_ops;
16074   ops->re_set = bkpt_re_set;
16075   ops->resources_needed = bkpt_resources_needed;
16076   ops->print_it = bkpt_print_it;
16077   ops->print_mention = bkpt_print_mention;
16078   ops->print_recreate = bkpt_print_recreate;
16079
16080   /* Ranged breakpoints.  */
16081   ops = &ranged_breakpoint_ops;
16082   *ops = bkpt_breakpoint_ops;
16083   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16084   ops->resources_needed = resources_needed_ranged_breakpoint;
16085   ops->print_it = print_it_ranged_breakpoint;
16086   ops->print_one = print_one_ranged_breakpoint;
16087   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16088   ops->print_mention = print_mention_ranged_breakpoint;
16089   ops->print_recreate = print_recreate_ranged_breakpoint;
16090
16091   /* Internal breakpoints.  */
16092   ops = &internal_breakpoint_ops;
16093   *ops = bkpt_base_breakpoint_ops;
16094   ops->re_set = internal_bkpt_re_set;
16095   ops->check_status = internal_bkpt_check_status;
16096   ops->print_it = internal_bkpt_print_it;
16097   ops->print_mention = internal_bkpt_print_mention;
16098
16099   /* Momentary breakpoints.  */
16100   ops = &momentary_breakpoint_ops;
16101   *ops = bkpt_base_breakpoint_ops;
16102   ops->re_set = momentary_bkpt_re_set;
16103   ops->check_status = momentary_bkpt_check_status;
16104   ops->print_it = momentary_bkpt_print_it;
16105   ops->print_mention = momentary_bkpt_print_mention;
16106
16107   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16108   ops = &longjmp_breakpoint_ops;
16109   *ops = momentary_breakpoint_ops;
16110   ops->dtor = longjmp_bkpt_dtor;
16111
16112   /* Probe breakpoints.  */
16113   ops = &bkpt_probe_breakpoint_ops;
16114   *ops = bkpt_breakpoint_ops;
16115   ops->insert_location = bkpt_probe_insert_location;
16116   ops->remove_location = bkpt_probe_remove_location;
16117   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16118   ops->decode_linespec = bkpt_probe_decode_linespec;
16119
16120   /* Watchpoints.  */
16121   ops = &watchpoint_breakpoint_ops;
16122   *ops = base_breakpoint_ops;
16123   ops->dtor = dtor_watchpoint;
16124   ops->re_set = re_set_watchpoint;
16125   ops->insert_location = insert_watchpoint;
16126   ops->remove_location = remove_watchpoint;
16127   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16128   ops->check_status = check_status_watchpoint;
16129   ops->resources_needed = resources_needed_watchpoint;
16130   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16131   ops->print_it = print_it_watchpoint;
16132   ops->print_mention = print_mention_watchpoint;
16133   ops->print_recreate = print_recreate_watchpoint;
16134   ops->explains_signal = explains_signal_watchpoint;
16135
16136   /* Masked watchpoints.  */
16137   ops = &masked_watchpoint_breakpoint_ops;
16138   *ops = watchpoint_breakpoint_ops;
16139   ops->insert_location = insert_masked_watchpoint;
16140   ops->remove_location = remove_masked_watchpoint;
16141   ops->resources_needed = resources_needed_masked_watchpoint;
16142   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16143   ops->print_it = print_it_masked_watchpoint;
16144   ops->print_one_detail = print_one_detail_masked_watchpoint;
16145   ops->print_mention = print_mention_masked_watchpoint;
16146   ops->print_recreate = print_recreate_masked_watchpoint;
16147
16148   /* Tracepoints.  */
16149   ops = &tracepoint_breakpoint_ops;
16150   *ops = base_breakpoint_ops;
16151   ops->re_set = tracepoint_re_set;
16152   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16153   ops->print_one_detail = tracepoint_print_one_detail;
16154   ops->print_mention = tracepoint_print_mention;
16155   ops->print_recreate = tracepoint_print_recreate;
16156   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16157   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16158   ops->decode_linespec = tracepoint_decode_linespec;
16159
16160   /* Probe tracepoints.  */
16161   ops = &tracepoint_probe_breakpoint_ops;
16162   *ops = tracepoint_breakpoint_ops;
16163   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16164   ops->decode_linespec = tracepoint_probe_decode_linespec;
16165
16166   /* Static tracepoints with marker (`-m').  */
16167   ops = &strace_marker_breakpoint_ops;
16168   *ops = tracepoint_breakpoint_ops;
16169   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16170   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16171   ops->decode_linespec = strace_marker_decode_linespec;
16172
16173   /* Fork catchpoints.  */
16174   ops = &catch_fork_breakpoint_ops;
16175   *ops = base_breakpoint_ops;
16176   ops->insert_location = insert_catch_fork;
16177   ops->remove_location = remove_catch_fork;
16178   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16179   ops->print_it = print_it_catch_fork;
16180   ops->print_one = print_one_catch_fork;
16181   ops->print_mention = print_mention_catch_fork;
16182   ops->print_recreate = print_recreate_catch_fork;
16183
16184   /* Vfork catchpoints.  */
16185   ops = &catch_vfork_breakpoint_ops;
16186   *ops = base_breakpoint_ops;
16187   ops->insert_location = insert_catch_vfork;
16188   ops->remove_location = remove_catch_vfork;
16189   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16190   ops->print_it = print_it_catch_vfork;
16191   ops->print_one = print_one_catch_vfork;
16192   ops->print_mention = print_mention_catch_vfork;
16193   ops->print_recreate = print_recreate_catch_vfork;
16194
16195   /* Exec catchpoints.  */
16196   ops = &catch_exec_breakpoint_ops;
16197   *ops = base_breakpoint_ops;
16198   ops->dtor = dtor_catch_exec;
16199   ops->insert_location = insert_catch_exec;
16200   ops->remove_location = remove_catch_exec;
16201   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16202   ops->print_it = print_it_catch_exec;
16203   ops->print_one = print_one_catch_exec;
16204   ops->print_mention = print_mention_catch_exec;
16205   ops->print_recreate = print_recreate_catch_exec;
16206
16207   /* Syscall catchpoints.  */
16208   ops = &catch_syscall_breakpoint_ops;
16209   *ops = base_breakpoint_ops;
16210   ops->dtor = dtor_catch_syscall;
16211   ops->insert_location = insert_catch_syscall;
16212   ops->remove_location = remove_catch_syscall;
16213   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16214   ops->print_it = print_it_catch_syscall;
16215   ops->print_one = print_one_catch_syscall;
16216   ops->print_mention = print_mention_catch_syscall;
16217   ops->print_recreate = print_recreate_catch_syscall;
16218
16219   /* Solib-related catchpoints.  */
16220   ops = &catch_solib_breakpoint_ops;
16221   *ops = base_breakpoint_ops;
16222   ops->dtor = dtor_catch_solib;
16223   ops->insert_location = insert_catch_solib;
16224   ops->remove_location = remove_catch_solib;
16225   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16226   ops->check_status = check_status_catch_solib;
16227   ops->print_it = print_it_catch_solib;
16228   ops->print_one = print_one_catch_solib;
16229   ops->print_mention = print_mention_catch_solib;
16230   ops->print_recreate = print_recreate_catch_solib;
16231
16232   ops = &dprintf_breakpoint_ops;
16233   *ops = bkpt_base_breakpoint_ops;
16234   ops->re_set = dprintf_re_set;
16235   ops->resources_needed = bkpt_resources_needed;
16236   ops->print_it = bkpt_print_it;
16237   ops->print_mention = bkpt_print_mention;
16238   ops->print_recreate = dprintf_print_recreate;
16239   ops->after_condition_true = dprintf_after_condition_true;
16240   ops->breakpoint_hit = dprintf_breakpoint_hit;
16241 }
16242
16243 /* Chain containing all defined "enable breakpoint" subcommands.  */
16244
16245 static struct cmd_list_element *enablebreaklist = NULL;
16246
16247 void
16248 _initialize_breakpoint (void)
16249 {
16250   struct cmd_list_element *c;
16251
16252   initialize_breakpoint_ops ();
16253
16254   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16255   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16256   observer_attach_inferior_exit (clear_syscall_counts);
16257   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16258
16259   breakpoint_objfile_key
16260     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16261
16262   catch_syscall_inferior_data
16263     = register_inferior_data_with_cleanup (NULL,
16264                                            catch_syscall_inferior_data_cleanup);
16265
16266   breakpoint_chain = 0;
16267   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16268      before a breakpoint is set.  */
16269   breakpoint_count = 0;
16270
16271   tracepoint_count = 0;
16272
16273   add_com ("ignore", class_breakpoint, ignore_command, _("\
16274 Set ignore-count of breakpoint number N to COUNT.\n\
16275 Usage is `ignore N COUNT'."));
16276   if (xdb_commands)
16277     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16278
16279   add_com ("commands", class_breakpoint, commands_command, _("\
16280 Set commands to be executed when a breakpoint is hit.\n\
16281 Give breakpoint number as argument after \"commands\".\n\
16282 With no argument, the targeted breakpoint is the last one set.\n\
16283 The commands themselves follow starting on the next line.\n\
16284 Type a line containing \"end\" to indicate the end of them.\n\
16285 Give \"silent\" as the first line to make the breakpoint silent;\n\
16286 then no output is printed when it is hit, except what the commands print."));
16287
16288   c = add_com ("condition", class_breakpoint, condition_command, _("\
16289 Specify breakpoint number N to break only if COND is true.\n\
16290 Usage is `condition N COND', where N is an integer and COND is an\n\
16291 expression to be evaluated whenever breakpoint N is reached."));
16292   set_cmd_completer (c, condition_completer);
16293
16294   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16295 Set a temporary breakpoint.\n\
16296 Like \"break\" except the breakpoint is only temporary,\n\
16297 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16298 by using \"enable delete\" on the breakpoint number.\n\
16299 \n"
16300 BREAK_ARGS_HELP ("tbreak")));
16301   set_cmd_completer (c, location_completer);
16302
16303   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16304 Set a hardware assisted breakpoint.\n\
16305 Like \"break\" except the breakpoint requires hardware support,\n\
16306 some target hardware may not have this support.\n\
16307 \n"
16308 BREAK_ARGS_HELP ("hbreak")));
16309   set_cmd_completer (c, location_completer);
16310
16311   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16312 Set a temporary hardware assisted breakpoint.\n\
16313 Like \"hbreak\" except the breakpoint is only temporary,\n\
16314 so it will be deleted when hit.\n\
16315 \n"
16316 BREAK_ARGS_HELP ("thbreak")));
16317   set_cmd_completer (c, location_completer);
16318
16319   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16320 Enable some breakpoints.\n\
16321 Give breakpoint numbers (separated by spaces) as arguments.\n\
16322 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16323 This is used to cancel the effect of the \"disable\" command.\n\
16324 With a subcommand you can enable temporarily."),
16325                   &enablelist, "enable ", 1, &cmdlist);
16326   if (xdb_commands)
16327     add_com ("ab", class_breakpoint, enable_command, _("\
16328 Enable some breakpoints.\n\
16329 Give breakpoint numbers (separated by spaces) as arguments.\n\
16330 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16331 This is used to cancel the effect of the \"disable\" command.\n\
16332 With a subcommand you can enable temporarily."));
16333
16334   add_com_alias ("en", "enable", class_breakpoint, 1);
16335
16336   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16337 Enable some breakpoints.\n\
16338 Give breakpoint numbers (separated by spaces) as arguments.\n\
16339 This is used to cancel the effect of the \"disable\" command.\n\
16340 May be abbreviated to simply \"enable\".\n"),
16341                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16342
16343   add_cmd ("once", no_class, enable_once_command, _("\
16344 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16345 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16346            &enablebreaklist);
16347
16348   add_cmd ("delete", no_class, enable_delete_command, _("\
16349 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16350 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16351            &enablebreaklist);
16352
16353   add_cmd ("count", no_class, enable_count_command, _("\
16354 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16355 If a breakpoint is hit while enabled in this fashion,\n\
16356 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16357            &enablebreaklist);
16358
16359   add_cmd ("delete", no_class, enable_delete_command, _("\
16360 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16361 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16362            &enablelist);
16363
16364   add_cmd ("once", no_class, enable_once_command, _("\
16365 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16366 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16367            &enablelist);
16368
16369   add_cmd ("count", no_class, enable_count_command, _("\
16370 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16371 If a breakpoint is hit while enabled in this fashion,\n\
16372 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16373            &enablelist);
16374
16375   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16376 Disable some breakpoints.\n\
16377 Arguments are breakpoint numbers with spaces in between.\n\
16378 To disable all breakpoints, give no argument.\n\
16379 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16380                   &disablelist, "disable ", 1, &cmdlist);
16381   add_com_alias ("dis", "disable", class_breakpoint, 1);
16382   add_com_alias ("disa", "disable", class_breakpoint, 1);
16383   if (xdb_commands)
16384     add_com ("sb", class_breakpoint, disable_command, _("\
16385 Disable some breakpoints.\n\
16386 Arguments are breakpoint numbers with spaces in between.\n\
16387 To disable all breakpoints, give no argument.\n\
16388 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16389
16390   add_cmd ("breakpoints", class_alias, disable_command, _("\
16391 Disable some breakpoints.\n\
16392 Arguments are breakpoint numbers with spaces in between.\n\
16393 To disable all breakpoints, give no argument.\n\
16394 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16395 This command may be abbreviated \"disable\"."),
16396            &disablelist);
16397
16398   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16399 Delete some breakpoints or auto-display expressions.\n\
16400 Arguments are breakpoint numbers with spaces in between.\n\
16401 To delete all breakpoints, give no argument.\n\
16402 \n\
16403 Also a prefix command for deletion of other GDB objects.\n\
16404 The \"unset\" command is also an alias for \"delete\"."),
16405                   &deletelist, "delete ", 1, &cmdlist);
16406   add_com_alias ("d", "delete", class_breakpoint, 1);
16407   add_com_alias ("del", "delete", class_breakpoint, 1);
16408   if (xdb_commands)
16409     add_com ("db", class_breakpoint, delete_command, _("\
16410 Delete some breakpoints.\n\
16411 Arguments are breakpoint numbers with spaces in between.\n\
16412 To delete all breakpoints, give no argument.\n"));
16413
16414   add_cmd ("breakpoints", class_alias, delete_command, _("\
16415 Delete some breakpoints or auto-display expressions.\n\
16416 Arguments are breakpoint numbers with spaces in between.\n\
16417 To delete all breakpoints, give no argument.\n\
16418 This command may be abbreviated \"delete\"."),
16419            &deletelist);
16420
16421   add_com ("clear", class_breakpoint, clear_command, _("\
16422 Clear breakpoint at specified line or function.\n\
16423 Argument may be line number, function name, or \"*\" and an address.\n\
16424 If line number is specified, all breakpoints in that line are cleared.\n\
16425 If function is specified, breakpoints at beginning of function are cleared.\n\
16426 If an address is specified, breakpoints at that address are cleared.\n\
16427 \n\
16428 With no argument, clears all breakpoints in the line that the selected frame\n\
16429 is executing in.\n\
16430 \n\
16431 See also the \"delete\" command which clears breakpoints by number."));
16432   add_com_alias ("cl", "clear", class_breakpoint, 1);
16433
16434   c = add_com ("break", class_breakpoint, break_command, _("\
16435 Set breakpoint at specified line or function.\n"
16436 BREAK_ARGS_HELP ("break")));
16437   set_cmd_completer (c, location_completer);
16438
16439   add_com_alias ("b", "break", class_run, 1);
16440   add_com_alias ("br", "break", class_run, 1);
16441   add_com_alias ("bre", "break", class_run, 1);
16442   add_com_alias ("brea", "break", class_run, 1);
16443
16444   if (xdb_commands)
16445    add_com_alias ("ba", "break", class_breakpoint, 1);
16446
16447   if (dbx_commands)
16448     {
16449       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16450 Break in function/address or break at a line in the current file."),
16451                              &stoplist, "stop ", 1, &cmdlist);
16452       add_cmd ("in", class_breakpoint, stopin_command,
16453                _("Break in function or address."), &stoplist);
16454       add_cmd ("at", class_breakpoint, stopat_command,
16455                _("Break at a line in the current file."), &stoplist);
16456       add_com ("status", class_info, breakpoints_info, _("\
16457 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16458 The \"Type\" column indicates one of:\n\
16459 \tbreakpoint     - normal breakpoint\n\
16460 \twatchpoint     - watchpoint\n\
16461 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16462 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16463 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16464 address and file/line number respectively.\n\
16465 \n\
16466 Convenience variable \"$_\" and default examine address for \"x\"\n\
16467 are set to the address of the last breakpoint listed unless the command\n\
16468 is prefixed with \"server \".\n\n\
16469 Convenience variable \"$bpnum\" contains the number of the last\n\
16470 breakpoint set."));
16471     }
16472
16473   add_info ("breakpoints", breakpoints_info, _("\
16474 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16475 The \"Type\" column indicates one of:\n\
16476 \tbreakpoint     - normal breakpoint\n\
16477 \twatchpoint     - watchpoint\n\
16478 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16479 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16480 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16481 address and file/line number respectively.\n\
16482 \n\
16483 Convenience variable \"$_\" and default examine address for \"x\"\n\
16484 are set to the address of the last breakpoint listed unless the command\n\
16485 is prefixed with \"server \".\n\n\
16486 Convenience variable \"$bpnum\" contains the number of the last\n\
16487 breakpoint set."));
16488
16489   add_info_alias ("b", "breakpoints", 1);
16490
16491   if (xdb_commands)
16492     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16493 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16494 The \"Type\" column indicates one of:\n\
16495 \tbreakpoint     - normal breakpoint\n\
16496 \twatchpoint     - watchpoint\n\
16497 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16498 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16499 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16500 address and file/line number respectively.\n\
16501 \n\
16502 Convenience variable \"$_\" and default examine address for \"x\"\n\
16503 are set to the address of the last breakpoint listed unless the command\n\
16504 is prefixed with \"server \".\n\n\
16505 Convenience variable \"$bpnum\" contains the number of the last\n\
16506 breakpoint set."));
16507
16508   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16509 Status of all breakpoints, or breakpoint number NUMBER.\n\
16510 The \"Type\" column indicates one of:\n\
16511 \tbreakpoint     - normal breakpoint\n\
16512 \twatchpoint     - watchpoint\n\
16513 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16514 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16515 \tuntil          - internal breakpoint used by the \"until\" command\n\
16516 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16517 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16518 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16519 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16520 address and file/line number respectively.\n\
16521 \n\
16522 Convenience variable \"$_\" and default examine address for \"x\"\n\
16523 are set to the address of the last breakpoint listed unless the command\n\
16524 is prefixed with \"server \".\n\n\
16525 Convenience variable \"$bpnum\" contains the number of the last\n\
16526 breakpoint set."),
16527            &maintenanceinfolist);
16528
16529   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16530 Set catchpoints to catch events."),
16531                   &catch_cmdlist, "catch ",
16532                   0/*allow-unknown*/, &cmdlist);
16533
16534   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16535 Set temporary catchpoints to catch events."),
16536                   &tcatch_cmdlist, "tcatch ",
16537                   0/*allow-unknown*/, &cmdlist);
16538
16539   add_catch_command ("fork", _("Catch calls to fork."),
16540                      catch_fork_command_1,
16541                      NULL,
16542                      (void *) (uintptr_t) catch_fork_permanent,
16543                      (void *) (uintptr_t) catch_fork_temporary);
16544   add_catch_command ("vfork", _("Catch calls to vfork."),
16545                      catch_fork_command_1,
16546                      NULL,
16547                      (void *) (uintptr_t) catch_vfork_permanent,
16548                      (void *) (uintptr_t) catch_vfork_temporary);
16549   add_catch_command ("exec", _("Catch calls to exec."),
16550                      catch_exec_command_1,
16551                      NULL,
16552                      CATCH_PERMANENT,
16553                      CATCH_TEMPORARY);
16554   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16555 Usage: catch load [REGEX]\n\
16556 If REGEX is given, only stop for libraries matching the regular expression."),
16557                      catch_load_command_1,
16558                      NULL,
16559                      CATCH_PERMANENT,
16560                      CATCH_TEMPORARY);
16561   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16562 Usage: catch unload [REGEX]\n\
16563 If REGEX is given, only stop for libraries matching the regular expression."),
16564                      catch_unload_command_1,
16565                      NULL,
16566                      CATCH_PERMANENT,
16567                      CATCH_TEMPORARY);
16568   add_catch_command ("syscall", _("\
16569 Catch system calls by their names and/or numbers.\n\
16570 Arguments say which system calls to catch.  If no arguments\n\
16571 are given, every system call will be caught.\n\
16572 Arguments, if given, should be one or more system call names\n\
16573 (if your system supports that), or system call numbers."),
16574                      catch_syscall_command_1,
16575                      catch_syscall_completer,
16576                      CATCH_PERMANENT,
16577                      CATCH_TEMPORARY);
16578
16579   c = add_com ("watch", class_breakpoint, watch_command, _("\
16580 Set a watchpoint for an expression.\n\
16581 Usage: watch [-l|-location] EXPRESSION\n\
16582 A watchpoint stops execution of your program whenever the value of\n\
16583 an expression changes.\n\
16584 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16585 the memory to which it refers."));
16586   set_cmd_completer (c, expression_completer);
16587
16588   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16589 Set a read watchpoint for an expression.\n\
16590 Usage: rwatch [-l|-location] EXPRESSION\n\
16591 A watchpoint stops execution of your program whenever the value of\n\
16592 an expression is read.\n\
16593 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16594 the memory to which it refers."));
16595   set_cmd_completer (c, expression_completer);
16596
16597   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16598 Set a watchpoint for an expression.\n\
16599 Usage: awatch [-l|-location] EXPRESSION\n\
16600 A watchpoint stops execution of your program whenever the value of\n\
16601 an expression is either read or written.\n\
16602 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16603 the memory to which it refers."));
16604   set_cmd_completer (c, expression_completer);
16605
16606   add_info ("watchpoints", watchpoints_info, _("\
16607 Status of specified watchpoints (all watchpoints if no argument)."));
16608
16609   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16610      respond to changes - contrary to the description.  */
16611   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16612                             &can_use_hw_watchpoints, _("\
16613 Set debugger's willingness to use watchpoint hardware."), _("\
16614 Show debugger's willingness to use watchpoint hardware."), _("\
16615 If zero, gdb will not use hardware for new watchpoints, even if\n\
16616 such is available.  (However, any hardware watchpoints that were\n\
16617 created before setting this to nonzero, will continue to use watchpoint\n\
16618 hardware.)"),
16619                             NULL,
16620                             show_can_use_hw_watchpoints,
16621                             &setlist, &showlist);
16622
16623   can_use_hw_watchpoints = 1;
16624
16625   /* Tracepoint manipulation commands.  */
16626
16627   c = add_com ("trace", class_breakpoint, trace_command, _("\
16628 Set a tracepoint at specified line or function.\n\
16629 \n"
16630 BREAK_ARGS_HELP ("trace") "\n\
16631 Do \"help tracepoints\" for info on other tracepoint commands."));
16632   set_cmd_completer (c, location_completer);
16633
16634   add_com_alias ("tp", "trace", class_alias, 0);
16635   add_com_alias ("tr", "trace", class_alias, 1);
16636   add_com_alias ("tra", "trace", class_alias, 1);
16637   add_com_alias ("trac", "trace", class_alias, 1);
16638
16639   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16640 Set a fast tracepoint at specified line or function.\n\
16641 \n"
16642 BREAK_ARGS_HELP ("ftrace") "\n\
16643 Do \"help tracepoints\" for info on other tracepoint commands."));
16644   set_cmd_completer (c, location_completer);
16645
16646   c = add_com ("strace", class_breakpoint, strace_command, _("\
16647 Set a static tracepoint at specified line, function or marker.\n\
16648 \n\
16649 strace [LOCATION] [if CONDITION]\n\
16650 LOCATION may be a line number, function name, \"*\" and an address,\n\
16651 or -m MARKER_ID.\n\
16652 If a line number is specified, probe the marker at start of code\n\
16653 for that line.  If a function is specified, probe the marker at start\n\
16654 of code for that function.  If an address is specified, probe the marker\n\
16655 at that exact address.  If a marker id is specified, probe the marker\n\
16656 with that name.  With no LOCATION, uses current execution address of\n\
16657 the selected stack frame.\n\
16658 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16659 This collects arbitrary user data passed in the probe point call to the\n\
16660 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16661 by printing the $_sdata variable like any other convenience variable.\n\
16662 \n\
16663 CONDITION is a boolean expression.\n\
16664 \n\
16665 Multiple tracepoints at one place are permitted, and useful if their\n\
16666 conditions are different.\n\
16667 \n\
16668 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16669 Do \"help tracepoints\" for info on other tracepoint commands."));
16670   set_cmd_completer (c, location_completer);
16671
16672   add_info ("tracepoints", tracepoints_info, _("\
16673 Status of specified tracepoints (all tracepoints if no argument).\n\
16674 Convenience variable \"$tpnum\" contains the number of the\n\
16675 last tracepoint set."));
16676
16677   add_info_alias ("tp", "tracepoints", 1);
16678
16679   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16680 Delete specified tracepoints.\n\
16681 Arguments are tracepoint numbers, separated by spaces.\n\
16682 No argument means delete all tracepoints."),
16683            &deletelist);
16684   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16685
16686   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16687 Disable specified tracepoints.\n\
16688 Arguments are tracepoint numbers, separated by spaces.\n\
16689 No argument means disable all tracepoints."),
16690            &disablelist);
16691   deprecate_cmd (c, "disable");
16692
16693   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16694 Enable specified tracepoints.\n\
16695 Arguments are tracepoint numbers, separated by spaces.\n\
16696 No argument means enable all tracepoints."),
16697            &enablelist);
16698   deprecate_cmd (c, "enable");
16699
16700   add_com ("passcount", class_trace, trace_pass_command, _("\
16701 Set the passcount for a tracepoint.\n\
16702 The trace will end when the tracepoint has been passed 'count' times.\n\
16703 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16704 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16705
16706   add_prefix_cmd ("save", class_breakpoint, save_command,
16707                   _("Save breakpoint definitions as a script."),
16708                   &save_cmdlist, "save ",
16709                   0/*allow-unknown*/, &cmdlist);
16710
16711   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16712 Save current breakpoint definitions as a script.\n\
16713 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16714 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16715 session to restore them."),
16716                &save_cmdlist);
16717   set_cmd_completer (c, filename_completer);
16718
16719   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16720 Save current tracepoint definitions as a script.\n\
16721 Use the 'source' command in another debug session to restore them."),
16722                &save_cmdlist);
16723   set_cmd_completer (c, filename_completer);
16724
16725   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16726   deprecate_cmd (c, "save tracepoints");
16727
16728   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16729 Breakpoint specific settings\n\
16730 Configure various breakpoint-specific variables such as\n\
16731 pending breakpoint behavior"),
16732                   &breakpoint_set_cmdlist, "set breakpoint ",
16733                   0/*allow-unknown*/, &setlist);
16734   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16735 Breakpoint specific settings\n\
16736 Configure various breakpoint-specific variables such as\n\
16737 pending breakpoint behavior"),
16738                   &breakpoint_show_cmdlist, "show breakpoint ",
16739                   0/*allow-unknown*/, &showlist);
16740
16741   add_setshow_auto_boolean_cmd ("pending", no_class,
16742                                 &pending_break_support, _("\
16743 Set debugger's behavior regarding pending breakpoints."), _("\
16744 Show debugger's behavior regarding pending breakpoints."), _("\
16745 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16746 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16747 an error.  If auto, an unrecognized breakpoint location results in a\n\
16748 user-query to see if a pending breakpoint should be created."),
16749                                 NULL,
16750                                 show_pending_break_support,
16751                                 &breakpoint_set_cmdlist,
16752                                 &breakpoint_show_cmdlist);
16753
16754   pending_break_support = AUTO_BOOLEAN_AUTO;
16755
16756   add_setshow_boolean_cmd ("auto-hw", no_class,
16757                            &automatic_hardware_breakpoints, _("\
16758 Set automatic usage of hardware breakpoints."), _("\
16759 Show automatic usage of hardware breakpoints."), _("\
16760 If set, the debugger will automatically use hardware breakpoints for\n\
16761 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16762 a warning will be emitted for such breakpoints."),
16763                            NULL,
16764                            show_automatic_hardware_breakpoints,
16765                            &breakpoint_set_cmdlist,
16766                            &breakpoint_show_cmdlist);
16767
16768   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16769                                 &always_inserted_mode, _("\
16770 Set mode for inserting breakpoints."), _("\
16771 Show mode for inserting breakpoints."), _("\
16772 When this mode is off, breakpoints are inserted in inferior when it is\n\
16773 resumed, and removed when execution stops.  When this mode is on,\n\
16774 breakpoints are inserted immediately and removed only when the user\n\
16775 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16776 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16777 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16778 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16779 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16780                                 NULL,
16781                                 &show_always_inserted_mode,
16782                                 &breakpoint_set_cmdlist,
16783                                 &breakpoint_show_cmdlist);
16784
16785   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16786                         condition_evaluation_enums,
16787                         &condition_evaluation_mode_1, _("\
16788 Set mode of breakpoint condition evaluation."), _("\
16789 Show mode of breakpoint condition evaluation."), _("\
16790 When this is set to \"host\", breakpoint conditions will be\n\
16791 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16792 breakpoint conditions will be downloaded to the target (if the target\n\
16793 supports such feature) and conditions will be evaluated on the target's side.\n\
16794 If this is set to \"auto\" (default), this will be automatically set to\n\
16795 \"target\" if it supports condition evaluation, otherwise it will\n\
16796 be set to \"gdb\""),
16797                            &set_condition_evaluation_mode,
16798                            &show_condition_evaluation_mode,
16799                            &breakpoint_set_cmdlist,
16800                            &breakpoint_show_cmdlist);
16801
16802   add_com ("break-range", class_breakpoint, break_range_command, _("\
16803 Set a breakpoint for an address range.\n\
16804 break-range START-LOCATION, END-LOCATION\n\
16805 where START-LOCATION and END-LOCATION can be one of the following:\n\
16806   LINENUM, for that line in the current file,\n\
16807   FILE:LINENUM, for that line in that file,\n\
16808   +OFFSET, for that number of lines after the current line\n\
16809            or the start of the range\n\
16810   FUNCTION, for the first line in that function,\n\
16811   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16812   *ADDRESS, for the instruction at that address.\n\
16813 \n\
16814 The breakpoint will stop execution of the inferior whenever it executes\n\
16815 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16816 range (including START-LOCATION and END-LOCATION)."));
16817
16818   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16819 Set a dynamic printf at specified line or function.\n\
16820 dprintf location,format string,arg1,arg2,...\n\
16821 location may be a line number, function name, or \"*\" and an address.\n\
16822 If a line number is specified, break at start of code for that line.\n\
16823 If a function is specified, break at start of code for that function."));
16824   set_cmd_completer (c, location_completer);
16825
16826   add_setshow_enum_cmd ("dprintf-style", class_support,
16827                         dprintf_style_enums, &dprintf_style, _("\
16828 Set the style of usage for dynamic printf."), _("\
16829 Show the style of usage for dynamic printf."), _("\
16830 This setting chooses how GDB will do a dynamic printf.\n\
16831 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16832 console, as with the \"printf\" command.\n\
16833 If the value is \"call\", the print is done by calling a function in your\n\
16834 program; by default printf(), but you can choose a different function or\n\
16835 output stream by setting dprintf-function and dprintf-channel."),
16836                         update_dprintf_commands, NULL,
16837                         &setlist, &showlist);
16838
16839   dprintf_function = xstrdup ("printf");
16840   add_setshow_string_cmd ("dprintf-function", class_support,
16841                           &dprintf_function, _("\
16842 Set the function to use for dynamic printf"), _("\
16843 Show the function to use for dynamic printf"), NULL,
16844                           update_dprintf_commands, NULL,
16845                           &setlist, &showlist);
16846
16847   dprintf_channel = xstrdup ("");
16848   add_setshow_string_cmd ("dprintf-channel", class_support,
16849                           &dprintf_channel, _("\
16850 Set the channel to use for dynamic printf"), _("\
16851 Show the channel to use for dynamic printf"), NULL,
16852                           update_dprintf_commands, NULL,
16853                           &setlist, &showlist);
16854
16855   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16856                            &disconnected_dprintf, _("\
16857 Set whether dprintf continues after GDB disconnects."), _("\
16858 Show whether dprintf continues after GDB disconnects."), _("\
16859 Use this to let dprintf commands continue to hit and produce output\n\
16860 even if GDB disconnects or detaches from the target."),
16861                            NULL,
16862                            NULL,
16863                            &setlist, &showlist);
16864
16865   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16866 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16867 (target agent only) This is useful for formatted output in user-defined commands."));
16868
16869   automatic_hardware_breakpoints = 1;
16870
16871   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16872   observer_attach_thread_exit (remove_threaded_breakpoints);
16873 }