Include gdb_assert.h in common-defs.h
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.h"
39 #include <string.h>
40 #include "gdb-demangle.h"
41 #include "filenames.h"
42 #include "annotate.h"
43 #include "symfile.h"
44 #include "objfiles.h"
45 #include "source.h"
46 #include "linespec.h"
47 #include "completer.h"
48 #include "gdb.h"
49 #include "ui-out.h"
50 #include "cli/cli-script.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "gdb_regex.h"
64 #include "probe.h"
65 #include "cli/cli-utils.h"
66 #include "continuations.h"
67 #include "stack.h"
68 #include "skip.h"
69 #include "ax-gdb.h"
70 #include "dummy-frame.h"
71
72 #include "format.h"
73
74 /* readline include files */
75 #include "readline/readline.h"
76 #include "readline/history.h"
77
78 /* readline defines this.  */
79 #undef savestring
80
81 #include "mi/mi-common.h"
82 #include "extension.h"
83
84 /* Enums for exception-handling support.  */
85 enum exception_event_kind
86 {
87   EX_EVENT_THROW,
88   EX_EVENT_RETHROW,
89   EX_EVENT_CATCH
90 };
91
92 /* Prototypes for local functions.  */
93
94 static void enable_delete_command (char *, int);
95
96 static void enable_once_command (char *, int);
97
98 static void enable_count_command (char *, int);
99
100 static void disable_command (char *, int);
101
102 static void enable_command (char *, int);
103
104 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
105                                                       void *),
106                                     void *);
107
108 static void ignore_command (char *, int);
109
110 static int breakpoint_re_set_one (void *);
111
112 static void breakpoint_re_set_default (struct breakpoint *);
113
114 static void create_sals_from_address_default (char **,
115                                               struct linespec_result *,
116                                               enum bptype, char *,
117                                               char **);
118
119 static void create_breakpoints_sal_default (struct gdbarch *,
120                                             struct linespec_result *,
121                                             char *, char *, enum bptype,
122                                             enum bpdisp, int, int,
123                                             int,
124                                             const struct breakpoint_ops *,
125                                             int, int, int, unsigned);
126
127 static void decode_linespec_default (struct breakpoint *, char **,
128                                      struct symtabs_and_lines *);
129
130 static void clear_command (char *, int);
131
132 static void catch_command (char *, int);
133
134 static int can_use_hardware_watchpoint (struct value *);
135
136 static void break_command_1 (char *, int, int);
137
138 static void mention (struct breakpoint *);
139
140 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
141                                                                enum bptype,
142                                                                const struct breakpoint_ops *);
143 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
144                                                        const struct symtab_and_line *);
145
146 /* This function is used in gdbtk sources and thus can not be made
147    static.  */
148 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
149                                        struct symtab_and_line,
150                                        enum bptype,
151                                        const struct breakpoint_ops *);
152
153 static struct breakpoint *
154   momentary_breakpoint_from_master (struct breakpoint *orig,
155                                     enum bptype type,
156                                     const struct breakpoint_ops *ops,
157                                     int loc_enabled);
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 int find_single_step_breakpoint (struct address_space *aspace,
233                                         CORE_ADDR pc);
234
235 static void free_bp_location (struct bp_location *loc);
236 static void incref_bp_location (struct bp_location *loc);
237 static void decref_bp_location (struct bp_location **loc);
238
239 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
240
241 static void update_global_location_list (int);
242
243 static void update_global_location_list_nothrow (int);
244
245 static int is_hardware_watchpoint (const struct breakpoint *bpt);
246
247 static void insert_breakpoint_locations (void);
248
249 static int syscall_catchpoint_p (struct breakpoint *b);
250
251 static void tracepoints_info (char *, int);
252
253 static void delete_trace_command (char *, int);
254
255 static void enable_trace_command (char *, int);
256
257 static void disable_trace_command (char *, int);
258
259 static void trace_pass_command (char *, int);
260
261 static void set_tracepoint_count (int num);
262
263 static int is_masked_watchpoint (const struct breakpoint *b);
264
265 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
266
267 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
268    otherwise.  */
269
270 static int strace_marker_p (struct breakpoint *b);
271
272 /* The abstract base class all breakpoint_ops structures inherit
273    from.  */
274 struct breakpoint_ops base_breakpoint_ops;
275
276 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
277    that are implemented on top of software or hardware breakpoints
278    (user breakpoints, internal and momentary breakpoints, etc.).  */
279 static struct breakpoint_ops bkpt_base_breakpoint_ops;
280
281 /* Internal breakpoints class type.  */
282 static struct breakpoint_ops internal_breakpoint_ops;
283
284 /* Momentary breakpoints class type.  */
285 static struct breakpoint_ops momentary_breakpoint_ops;
286
287 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
288 static struct breakpoint_ops longjmp_breakpoint_ops;
289
290 /* The breakpoint_ops structure to be used in regular user created
291    breakpoints.  */
292 struct breakpoint_ops bkpt_breakpoint_ops;
293
294 /* Breakpoints set on probes.  */
295 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
296
297 /* Dynamic printf class type.  */
298 struct breakpoint_ops dprintf_breakpoint_ops;
299
300 /* One (or perhaps two) breakpoints used for software single
301    stepping.  */
302
303 static void *single_step_breakpoints[2];
304 static struct gdbarch *single_step_gdbarch[2];
305
306 /* The style in which to perform a dynamic printf.  This is a user
307    option because different output options have different tradeoffs;
308    if GDB does the printing, there is better error handling if there
309    is a problem with any of the arguments, but using an inferior
310    function lets you have special-purpose printers and sending of
311    output to the same place as compiled-in print functions.  */
312
313 static const char dprintf_style_gdb[] = "gdb";
314 static const char dprintf_style_call[] = "call";
315 static const char dprintf_style_agent[] = "agent";
316 static const char *const dprintf_style_enums[] = {
317   dprintf_style_gdb,
318   dprintf_style_call,
319   dprintf_style_agent,
320   NULL
321 };
322 static const char *dprintf_style = dprintf_style_gdb;
323
324 /* The function to use for dynamic printf if the preferred style is to
325    call into the inferior.  The value is simply a string that is
326    copied into the command, so it can be anything that GDB can
327    evaluate to a callable address, not necessarily a function name.  */
328
329 static char *dprintf_function = "";
330
331 /* The channel to use for dynamic printf if the preferred style is to
332    call into the inferior; if a nonempty string, it will be passed to
333    the call as the first argument, with the format string as the
334    second.  As with the dprintf function, this can be anything that
335    GDB knows how to evaluate, so in addition to common choices like
336    "stderr", this could be an app-specific expression like
337    "mystreams[curlogger]".  */
338
339 static char *dprintf_channel = "";
340
341 /* True if dprintf commands should continue to operate even if GDB
342    has disconnected.  */
343 static int disconnected_dprintf = 1;
344
345 /* A reference-counted struct command_line.  This lets multiple
346    breakpoints share a single command list.  */
347 struct counted_command_line
348 {
349   /* The reference count.  */
350   int refc;
351
352   /* The command list.  */
353   struct command_line *commands;
354 };
355
356 struct command_line *
357 breakpoint_commands (struct breakpoint *b)
358 {
359   return b->commands ? b->commands->commands : NULL;
360 }
361
362 /* Flag indicating that a command has proceeded the inferior past the
363    current breakpoint.  */
364
365 static int breakpoint_proceeded;
366
367 const char *
368 bpdisp_text (enum bpdisp disp)
369 {
370   /* NOTE: the following values are a part of MI protocol and
371      represent values of 'disp' field returned when inferior stops at
372      a breakpoint.  */
373   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
374
375   return bpdisps[(int) disp];
376 }
377
378 /* Prototypes for exported functions.  */
379 /* If FALSE, gdb will not use hardware support for watchpoints, even
380    if such is available.  */
381 static int can_use_hw_watchpoints;
382
383 static void
384 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
385                              struct cmd_list_element *c,
386                              const char *value)
387 {
388   fprintf_filtered (file,
389                     _("Debugger's willingness to use "
390                       "watchpoint hardware is %s.\n"),
391                     value);
392 }
393
394 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
395    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
396    for unrecognized breakpoint locations.
397    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
398 static enum auto_boolean pending_break_support;
399 static void
400 show_pending_break_support (struct ui_file *file, int from_tty,
401                             struct cmd_list_element *c,
402                             const char *value)
403 {
404   fprintf_filtered (file,
405                     _("Debugger's behavior regarding "
406                       "pending breakpoints is %s.\n"),
407                     value);
408 }
409
410 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
411    set with "break" but falling in read-only memory.
412    If 0, gdb will warn about such breakpoints, but won't automatically
413    use hardware breakpoints.  */
414 static int automatic_hardware_breakpoints;
415 static void
416 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
417                                      struct cmd_list_element *c,
418                                      const char *value)
419 {
420   fprintf_filtered (file,
421                     _("Automatic usage of hardware breakpoints is %s.\n"),
422                     value);
423 }
424
425 /* If on, gdb will keep breakpoints inserted even as inferior is
426    stopped, and immediately insert any new breakpoints.  If off, gdb
427    will insert breakpoints into inferior only when resuming it, and
428    will remove breakpoints upon stop.  If auto, GDB will behave as ON
429    if in non-stop mode, and as OFF if all-stop mode.*/
430
431 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
432
433 static void
434 show_always_inserted_mode (struct ui_file *file, int from_tty,
435                      struct cmd_list_element *c, const char *value)
436 {
437   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
438     fprintf_filtered (file,
439                       _("Always inserted breakpoint "
440                         "mode is %s (currently %s).\n"),
441                       value,
442                       breakpoints_always_inserted_mode () ? "on" : "off");
443   else
444     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
445                       value);
446 }
447
448 int
449 breakpoints_always_inserted_mode (void)
450 {
451   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
452           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
453 }
454
455 static const char condition_evaluation_both[] = "host or target";
456
457 /* Modes for breakpoint condition evaluation.  */
458 static const char condition_evaluation_auto[] = "auto";
459 static const char condition_evaluation_host[] = "host";
460 static const char condition_evaluation_target[] = "target";
461 static const char *const condition_evaluation_enums[] = {
462   condition_evaluation_auto,
463   condition_evaluation_host,
464   condition_evaluation_target,
465   NULL
466 };
467
468 /* Global that holds the current mode for breakpoint condition evaluation.  */
469 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
470
471 /* Global that we use to display information to the user (gets its value from
472    condition_evaluation_mode_1.  */
473 static const char *condition_evaluation_mode = condition_evaluation_auto;
474
475 /* Translate a condition evaluation mode MODE into either "host"
476    or "target".  This is used mostly to translate from "auto" to the
477    real setting that is being used.  It returns the translated
478    evaluation mode.  */
479
480 static const char *
481 translate_condition_evaluation_mode (const char *mode)
482 {
483   if (mode == condition_evaluation_auto)
484     {
485       if (target_supports_evaluation_of_breakpoint_conditions ())
486         return condition_evaluation_target;
487       else
488         return condition_evaluation_host;
489     }
490   else
491     return mode;
492 }
493
494 /* Discovers what condition_evaluation_auto translates to.  */
495
496 static const char *
497 breakpoint_condition_evaluation_mode (void)
498 {
499   return translate_condition_evaluation_mode (condition_evaluation_mode);
500 }
501
502 /* Return true if GDB should evaluate breakpoint conditions or false
503    otherwise.  */
504
505 static int
506 gdb_evaluates_breakpoint_condition_p (void)
507 {
508   const char *mode = breakpoint_condition_evaluation_mode ();
509
510   return (mode == condition_evaluation_host);
511 }
512
513 void _initialize_breakpoint (void);
514
515 /* Are we executing breakpoint commands?  */
516 static int executing_breakpoint_commands;
517
518 /* Are overlay event breakpoints enabled? */
519 static int overlay_events_enabled;
520
521 /* See description in breakpoint.h. */
522 int target_exact_watchpoints = 0;
523
524 /* Walk the following statement or block through all breakpoints.
525    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
526    current breakpoint.  */
527
528 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
529
530 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
531         for (B = breakpoint_chain;      \
532              B ? (TMP=B->next, 1): 0;   \
533              B = TMP)
534
535 /* Similar iterator for the low-level breakpoints.  SAFE variant is
536    not provided so update_global_location_list must not be called
537    while executing the block of ALL_BP_LOCATIONS.  */
538
539 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
540         for (BP_TMP = bp_location;                                      \
541              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
542              BP_TMP++)
543
544 /* Iterates through locations with address ADDRESS for the currently selected
545    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
546    to where the loop should start from.
547    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
548    appropriate location to start with.  */
549
550 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
551         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
552              BP_LOCP_TMP = BP_LOCP_START;                               \
553              BP_LOCP_START                                              \
554              && (BP_LOCP_TMP < bp_location + bp_location_count          \
555              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
556              BP_LOCP_TMP++)
557
558 /* Iterator for tracepoints only.  */
559
560 #define ALL_TRACEPOINTS(B)  \
561   for (B = breakpoint_chain; B; B = B->next)  \
562     if (is_tracepoint (B))
563
564 /* Chains of all breakpoints defined.  */
565
566 struct breakpoint *breakpoint_chain;
567
568 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
569
570 static struct bp_location **bp_location;
571
572 /* Number of elements of BP_LOCATION.  */
573
574 static unsigned bp_location_count;
575
576 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
577    ADDRESS for the current elements of BP_LOCATION which get a valid
578    result from bp_location_has_shadow.  You can use it for roughly
579    limiting the subrange of BP_LOCATION to scan for shadow bytes for
580    an address you need to read.  */
581
582 static CORE_ADDR bp_location_placed_address_before_address_max;
583
584 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
585    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
586    BP_LOCATION which get a valid result from bp_location_has_shadow.
587    You can use it for roughly limiting the subrange of BP_LOCATION to
588    scan for shadow bytes for an address you need to read.  */
589
590 static CORE_ADDR bp_location_shadow_len_after_address_max;
591
592 /* The locations that no longer correspond to any breakpoint, unlinked
593    from bp_location array, but for which a hit may still be reported
594    by a target.  */
595 VEC(bp_location_p) *moribund_locations = NULL;
596
597 /* Number of last breakpoint made.  */
598
599 static int breakpoint_count;
600
601 /* The value of `breakpoint_count' before the last command that
602    created breakpoints.  If the last (break-like) command created more
603    than one breakpoint, then the difference between BREAKPOINT_COUNT
604    and PREV_BREAKPOINT_COUNT is more than one.  */
605 static int prev_breakpoint_count;
606
607 /* Number of last tracepoint made.  */
608
609 static int tracepoint_count;
610
611 static struct cmd_list_element *breakpoint_set_cmdlist;
612 static struct cmd_list_element *breakpoint_show_cmdlist;
613 struct cmd_list_element *save_cmdlist;
614
615 /* Return whether a breakpoint is an active enabled breakpoint.  */
616 static int
617 breakpoint_enabled (struct breakpoint *b)
618 {
619   return (b->enable_state == bp_enabled);
620 }
621
622 /* Set breakpoint count to NUM.  */
623
624 static void
625 set_breakpoint_count (int num)
626 {
627   prev_breakpoint_count = breakpoint_count;
628   breakpoint_count = num;
629   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
630 }
631
632 /* Used by `start_rbreak_breakpoints' below, to record the current
633    breakpoint count before "rbreak" creates any breakpoint.  */
634 static int rbreak_start_breakpoint_count;
635
636 /* Called at the start an "rbreak" command to record the first
637    breakpoint made.  */
638
639 void
640 start_rbreak_breakpoints (void)
641 {
642   rbreak_start_breakpoint_count = breakpoint_count;
643 }
644
645 /* Called at the end of an "rbreak" command to record the last
646    breakpoint made.  */
647
648 void
649 end_rbreak_breakpoints (void)
650 {
651   prev_breakpoint_count = rbreak_start_breakpoint_count;
652 }
653
654 /* Used in run_command to zero the hit count when a new run starts.  */
655
656 void
657 clear_breakpoint_hit_counts (void)
658 {
659   struct breakpoint *b;
660
661   ALL_BREAKPOINTS (b)
662     b->hit_count = 0;
663 }
664
665 /* Allocate a new counted_command_line with reference count of 1.
666    The new structure owns COMMANDS.  */
667
668 static struct counted_command_line *
669 alloc_counted_command_line (struct command_line *commands)
670 {
671   struct counted_command_line *result
672     = xmalloc (sizeof (struct counted_command_line));
673
674   result->refc = 1;
675   result->commands = commands;
676   return result;
677 }
678
679 /* Increment reference count.  This does nothing if CMD is NULL.  */
680
681 static void
682 incref_counted_command_line (struct counted_command_line *cmd)
683 {
684   if (cmd)
685     ++cmd->refc;
686 }
687
688 /* Decrement reference count.  If the reference count reaches 0,
689    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
690    nothing if *CMDP is NULL.  */
691
692 static void
693 decref_counted_command_line (struct counted_command_line **cmdp)
694 {
695   if (*cmdp)
696     {
697       if (--(*cmdp)->refc == 0)
698         {
699           free_command_lines (&(*cmdp)->commands);
700           xfree (*cmdp);
701         }
702       *cmdp = NULL;
703     }
704 }
705
706 /* A cleanup function that calls decref_counted_command_line.  */
707
708 static void
709 do_cleanup_counted_command_line (void *arg)
710 {
711   decref_counted_command_line (arg);
712 }
713
714 /* Create a cleanup that calls decref_counted_command_line on the
715    argument.  */
716
717 static struct cleanup *
718 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
719 {
720   return make_cleanup (do_cleanup_counted_command_line, cmdp);
721 }
722
723 \f
724 /* Return the breakpoint with the specified number, or NULL
725    if the number does not refer to an existing breakpoint.  */
726
727 struct breakpoint *
728 get_breakpoint (int num)
729 {
730   struct breakpoint *b;
731
732   ALL_BREAKPOINTS (b)
733     if (b->number == num)
734       return b;
735   
736   return NULL;
737 }
738
739 \f
740
741 /* Mark locations as "conditions have changed" in case the target supports
742    evaluating conditions on its side.  */
743
744 static void
745 mark_breakpoint_modified (struct breakpoint *b)
746 {
747   struct bp_location *loc;
748
749   /* This is only meaningful if the target is
750      evaluating conditions and if the user has
751      opted for condition evaluation on the target's
752      side.  */
753   if (gdb_evaluates_breakpoint_condition_p ()
754       || !target_supports_evaluation_of_breakpoint_conditions ())
755     return;
756
757   if (!is_breakpoint (b))
758     return;
759
760   for (loc = b->loc; loc; loc = loc->next)
761     loc->condition_changed = condition_modified;
762 }
763
764 /* Mark location as "conditions have changed" in case the target supports
765    evaluating conditions on its side.  */
766
767 static void
768 mark_breakpoint_location_modified (struct bp_location *loc)
769 {
770   /* This is only meaningful if the target is
771      evaluating conditions and if the user has
772      opted for condition evaluation on the target's
773      side.  */
774   if (gdb_evaluates_breakpoint_condition_p ()
775       || !target_supports_evaluation_of_breakpoint_conditions ())
776
777     return;
778
779   if (!is_breakpoint (loc->owner))
780     return;
781
782   loc->condition_changed = condition_modified;
783 }
784
785 /* Sets the condition-evaluation mode using the static global
786    condition_evaluation_mode.  */
787
788 static void
789 set_condition_evaluation_mode (char *args, int from_tty,
790                                struct cmd_list_element *c)
791 {
792   const char *old_mode, *new_mode;
793
794   if ((condition_evaluation_mode_1 == condition_evaluation_target)
795       && !target_supports_evaluation_of_breakpoint_conditions ())
796     {
797       condition_evaluation_mode_1 = condition_evaluation_mode;
798       warning (_("Target does not support breakpoint condition evaluation.\n"
799                  "Using host evaluation mode instead."));
800       return;
801     }
802
803   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
804   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
805
806   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
807      settings was "auto".  */
808   condition_evaluation_mode = condition_evaluation_mode_1;
809
810   /* Only update the mode if the user picked a different one.  */
811   if (new_mode != old_mode)
812     {
813       struct bp_location *loc, **loc_tmp;
814       /* If the user switched to a different evaluation mode, we
815          need to synch the changes with the target as follows:
816
817          "host" -> "target": Send all (valid) conditions to the target.
818          "target" -> "host": Remove all the conditions from the target.
819       */
820
821       if (new_mode == condition_evaluation_target)
822         {
823           /* Mark everything modified and synch conditions with the
824              target.  */
825           ALL_BP_LOCATIONS (loc, loc_tmp)
826             mark_breakpoint_location_modified (loc);
827         }
828       else
829         {
830           /* Manually mark non-duplicate locations to synch conditions
831              with the target.  We do this to remove all the conditions the
832              target knows about.  */
833           ALL_BP_LOCATIONS (loc, loc_tmp)
834             if (is_breakpoint (loc->owner) && loc->inserted)
835               loc->needs_update = 1;
836         }
837
838       /* Do the update.  */
839       update_global_location_list (1);
840     }
841
842   return;
843 }
844
845 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
846    what "auto" is translating to.  */
847
848 static void
849 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
850                                 struct cmd_list_element *c, const char *value)
851 {
852   if (condition_evaluation_mode == condition_evaluation_auto)
853     fprintf_filtered (file,
854                       _("Breakpoint condition evaluation "
855                         "mode is %s (currently %s).\n"),
856                       value,
857                       breakpoint_condition_evaluation_mode ());
858   else
859     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
860                       value);
861 }
862
863 /* A comparison function for bp_location AP and BP that is used by
864    bsearch.  This comparison function only cares about addresses, unlike
865    the more general bp_location_compare function.  */
866
867 static int
868 bp_location_compare_addrs (const void *ap, const void *bp)
869 {
870   struct bp_location *a = *(void **) ap;
871   struct bp_location *b = *(void **) bp;
872
873   if (a->address == b->address)
874     return 0;
875   else
876     return ((a->address > b->address) - (a->address < b->address));
877 }
878
879 /* Helper function to skip all bp_locations with addresses
880    less than ADDRESS.  It returns the first bp_location that
881    is greater than or equal to ADDRESS.  If none is found, just
882    return NULL.  */
883
884 static struct bp_location **
885 get_first_locp_gte_addr (CORE_ADDR address)
886 {
887   struct bp_location dummy_loc;
888   struct bp_location *dummy_locp = &dummy_loc;
889   struct bp_location **locp_found = NULL;
890
891   /* Initialize the dummy location's address field.  */
892   memset (&dummy_loc, 0, sizeof (struct bp_location));
893   dummy_loc.address = address;
894
895   /* Find a close match to the first location at ADDRESS.  */
896   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
897                         sizeof (struct bp_location **),
898                         bp_location_compare_addrs);
899
900   /* Nothing was found, nothing left to do.  */
901   if (locp_found == NULL)
902     return NULL;
903
904   /* We may have found a location that is at ADDRESS but is not the first in the
905      location's list.  Go backwards (if possible) and locate the first one.  */
906   while ((locp_found - 1) >= bp_location
907          && (*(locp_found - 1))->address == address)
908     locp_found--;
909
910   return locp_found;
911 }
912
913 void
914 set_breakpoint_condition (struct breakpoint *b, char *exp,
915                           int from_tty)
916 {
917   xfree (b->cond_string);
918   b->cond_string = NULL;
919
920   if (is_watchpoint (b))
921     {
922       struct watchpoint *w = (struct watchpoint *) b;
923
924       xfree (w->cond_exp);
925       w->cond_exp = NULL;
926     }
927   else
928     {
929       struct bp_location *loc;
930
931       for (loc = b->loc; loc; loc = loc->next)
932         {
933           xfree (loc->cond);
934           loc->cond = NULL;
935
936           /* No need to free the condition agent expression
937              bytecode (if we have one).  We will handle this
938              when we go through update_global_location_list.  */
939         }
940     }
941
942   if (*exp == 0)
943     {
944       if (from_tty)
945         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
946     }
947   else
948     {
949       const char *arg = exp;
950
951       /* I don't know if it matters whether this is the string the user
952          typed in or the decompiled expression.  */
953       b->cond_string = xstrdup (arg);
954       b->condition_not_parsed = 0;
955
956       if (is_watchpoint (b))
957         {
958           struct watchpoint *w = (struct watchpoint *) b;
959
960           innermost_block = NULL;
961           arg = exp;
962           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
963           if (*arg)
964             error (_("Junk at end of expression"));
965           w->cond_exp_valid_block = innermost_block;
966         }
967       else
968         {
969           struct bp_location *loc;
970
971           for (loc = b->loc; loc; loc = loc->next)
972             {
973               arg = exp;
974               loc->cond =
975                 parse_exp_1 (&arg, loc->address,
976                              block_for_pc (loc->address), 0);
977               if (*arg)
978                 error (_("Junk at end of expression"));
979             }
980         }
981     }
982   mark_breakpoint_modified (b);
983
984   observer_notify_breakpoint_modified (b);
985 }
986
987 /* Completion for the "condition" command.  */
988
989 static VEC (char_ptr) *
990 condition_completer (struct cmd_list_element *cmd,
991                      const char *text, const char *word)
992 {
993   const char *space;
994
995   text = skip_spaces_const (text);
996   space = skip_to_space_const (text);
997   if (*space == '\0')
998     {
999       int len;
1000       struct breakpoint *b;
1001       VEC (char_ptr) *result = NULL;
1002
1003       if (text[0] == '$')
1004         {
1005           /* We don't support completion of history indices.  */
1006           if (isdigit (text[1]))
1007             return NULL;
1008           return complete_internalvar (&text[1]);
1009         }
1010
1011       /* We're completing the breakpoint number.  */
1012       len = strlen (text);
1013
1014       ALL_BREAKPOINTS (b)
1015         {
1016           char number[50];
1017
1018           xsnprintf (number, sizeof (number), "%d", b->number);
1019
1020           if (strncmp (number, text, len) == 0)
1021             VEC_safe_push (char_ptr, result, xstrdup (number));
1022         }
1023
1024       return result;
1025     }
1026
1027   /* We're completing the expression part.  */
1028   text = skip_spaces_const (space);
1029   return expression_completer (cmd, text, word);
1030 }
1031
1032 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1033
1034 static void
1035 condition_command (char *arg, int from_tty)
1036 {
1037   struct breakpoint *b;
1038   char *p;
1039   int bnum;
1040
1041   if (arg == 0)
1042     error_no_arg (_("breakpoint number"));
1043
1044   p = arg;
1045   bnum = get_number (&p);
1046   if (bnum == 0)
1047     error (_("Bad breakpoint argument: '%s'"), arg);
1048
1049   ALL_BREAKPOINTS (b)
1050     if (b->number == bnum)
1051       {
1052         /* Check if this breakpoint has a "stop" method implemented in an
1053            extension language.  This method and conditions entered into GDB
1054            from the CLI are mutually exclusive.  */
1055         const struct extension_language_defn *extlang
1056           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1057
1058         if (extlang != NULL)
1059           {
1060             error (_("Only one stop condition allowed.  There is currently"
1061                      " a %s stop condition defined for this breakpoint."),
1062                    ext_lang_capitalized_name (extlang));
1063           }
1064         set_breakpoint_condition (b, p, from_tty);
1065
1066         if (is_breakpoint (b))
1067           update_global_location_list (1);
1068
1069         return;
1070       }
1071
1072   error (_("No breakpoint number %d."), bnum);
1073 }
1074
1075 /* Check that COMMAND do not contain commands that are suitable
1076    only for tracepoints and not suitable for ordinary breakpoints.
1077    Throw if any such commands is found.  */
1078
1079 static void
1080 check_no_tracepoint_commands (struct command_line *commands)
1081 {
1082   struct command_line *c;
1083
1084   for (c = commands; c; c = c->next)
1085     {
1086       int i;
1087
1088       if (c->control_type == while_stepping_control)
1089         error (_("The 'while-stepping' command can "
1090                  "only be used for tracepoints"));
1091
1092       for (i = 0; i < c->body_count; ++i)
1093         check_no_tracepoint_commands ((c->body_list)[i]);
1094
1095       /* Not that command parsing removes leading whitespace and comment
1096          lines and also empty lines.  So, we only need to check for
1097          command directly.  */
1098       if (strstr (c->line, "collect ") == c->line)
1099         error (_("The 'collect' command can only be used for tracepoints"));
1100
1101       if (strstr (c->line, "teval ") == c->line)
1102         error (_("The 'teval' command can only be used for tracepoints"));
1103     }
1104 }
1105
1106 /* Encapsulate tests for different types of tracepoints.  */
1107
1108 static int
1109 is_tracepoint_type (enum bptype type)
1110 {
1111   return (type == bp_tracepoint
1112           || type == bp_fast_tracepoint
1113           || type == bp_static_tracepoint);
1114 }
1115
1116 int
1117 is_tracepoint (const struct breakpoint *b)
1118 {
1119   return is_tracepoint_type (b->type);
1120 }
1121
1122 /* A helper function that validates that COMMANDS are valid for a
1123    breakpoint.  This function will throw an exception if a problem is
1124    found.  */
1125
1126 static void
1127 validate_commands_for_breakpoint (struct breakpoint *b,
1128                                   struct command_line *commands)
1129 {
1130   if (is_tracepoint (b))
1131     {
1132       struct tracepoint *t = (struct tracepoint *) b;
1133       struct command_line *c;
1134       struct command_line *while_stepping = 0;
1135
1136       /* Reset the while-stepping step count.  The previous commands
1137          might have included a while-stepping action, while the new
1138          ones might not.  */
1139       t->step_count = 0;
1140
1141       /* We need to verify that each top-level element of commands is
1142          valid for tracepoints, that there's at most one
1143          while-stepping element, and that the while-stepping's body
1144          has valid tracing commands excluding nested while-stepping.
1145          We also need to validate the tracepoint action line in the
1146          context of the tracepoint --- validate_actionline actually
1147          has side effects, like setting the tracepoint's
1148          while-stepping STEP_COUNT, in addition to checking if the
1149          collect/teval actions parse and make sense in the
1150          tracepoint's context.  */
1151       for (c = commands; c; c = c->next)
1152         {
1153           if (c->control_type == while_stepping_control)
1154             {
1155               if (b->type == bp_fast_tracepoint)
1156                 error (_("The 'while-stepping' command "
1157                          "cannot be used for fast tracepoint"));
1158               else if (b->type == bp_static_tracepoint)
1159                 error (_("The 'while-stepping' command "
1160                          "cannot be used for static tracepoint"));
1161
1162               if (while_stepping)
1163                 error (_("The 'while-stepping' command "
1164                          "can be used only once"));
1165               else
1166                 while_stepping = c;
1167             }
1168
1169           validate_actionline (c->line, b);
1170         }
1171       if (while_stepping)
1172         {
1173           struct command_line *c2;
1174
1175           gdb_assert (while_stepping->body_count == 1);
1176           c2 = while_stepping->body_list[0];
1177           for (; c2; c2 = c2->next)
1178             {
1179               if (c2->control_type == while_stepping_control)
1180                 error (_("The 'while-stepping' command cannot be nested"));
1181             }
1182         }
1183     }
1184   else
1185     {
1186       check_no_tracepoint_commands (commands);
1187     }
1188 }
1189
1190 /* Return a vector of all the static tracepoints set at ADDR.  The
1191    caller is responsible for releasing the vector.  */
1192
1193 VEC(breakpoint_p) *
1194 static_tracepoints_here (CORE_ADDR addr)
1195 {
1196   struct breakpoint *b;
1197   VEC(breakpoint_p) *found = 0;
1198   struct bp_location *loc;
1199
1200   ALL_BREAKPOINTS (b)
1201     if (b->type == bp_static_tracepoint)
1202       {
1203         for (loc = b->loc; loc; loc = loc->next)
1204           if (loc->address == addr)
1205             VEC_safe_push(breakpoint_p, found, b);
1206       }
1207
1208   return found;
1209 }
1210
1211 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1212    validate that only allowed commands are included.  */
1213
1214 void
1215 breakpoint_set_commands (struct breakpoint *b, 
1216                          struct command_line *commands)
1217 {
1218   validate_commands_for_breakpoint (b, commands);
1219
1220   decref_counted_command_line (&b->commands);
1221   b->commands = alloc_counted_command_line (commands);
1222   observer_notify_breakpoint_modified (b);
1223 }
1224
1225 /* Set the internal `silent' flag on the breakpoint.  Note that this
1226    is not the same as the "silent" that may appear in the breakpoint's
1227    commands.  */
1228
1229 void
1230 breakpoint_set_silent (struct breakpoint *b, int silent)
1231 {
1232   int old_silent = b->silent;
1233
1234   b->silent = silent;
1235   if (old_silent != silent)
1236     observer_notify_breakpoint_modified (b);
1237 }
1238
1239 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1240    breakpoint work for any thread.  */
1241
1242 void
1243 breakpoint_set_thread (struct breakpoint *b, int thread)
1244 {
1245   int old_thread = b->thread;
1246
1247   b->thread = thread;
1248   if (old_thread != thread)
1249     observer_notify_breakpoint_modified (b);
1250 }
1251
1252 /* Set the task for this breakpoint.  If TASK is 0, make the
1253    breakpoint work for any task.  */
1254
1255 void
1256 breakpoint_set_task (struct breakpoint *b, int task)
1257 {
1258   int old_task = b->task;
1259
1260   b->task = task;
1261   if (old_task != task)
1262     observer_notify_breakpoint_modified (b);
1263 }
1264
1265 void
1266 check_tracepoint_command (char *line, void *closure)
1267 {
1268   struct breakpoint *b = closure;
1269
1270   validate_actionline (line, b);
1271 }
1272
1273 /* A structure used to pass information through
1274    map_breakpoint_numbers.  */
1275
1276 struct commands_info
1277 {
1278   /* True if the command was typed at a tty.  */
1279   int from_tty;
1280
1281   /* The breakpoint range spec.  */
1282   char *arg;
1283
1284   /* Non-NULL if the body of the commands are being read from this
1285      already-parsed command.  */
1286   struct command_line *control;
1287
1288   /* The command lines read from the user, or NULL if they have not
1289      yet been read.  */
1290   struct counted_command_line *cmd;
1291 };
1292
1293 /* A callback for map_breakpoint_numbers that sets the commands for
1294    commands_command.  */
1295
1296 static void
1297 do_map_commands_command (struct breakpoint *b, void *data)
1298 {
1299   struct commands_info *info = data;
1300
1301   if (info->cmd == NULL)
1302     {
1303       struct command_line *l;
1304
1305       if (info->control != NULL)
1306         l = copy_command_lines (info->control->body_list[0]);
1307       else
1308         {
1309           struct cleanup *old_chain;
1310           char *str;
1311
1312           str = xstrprintf (_("Type commands for breakpoint(s) "
1313                               "%s, one per line."),
1314                             info->arg);
1315
1316           old_chain = make_cleanup (xfree, str);
1317
1318           l = read_command_lines (str,
1319                                   info->from_tty, 1,
1320                                   (is_tracepoint (b)
1321                                    ? check_tracepoint_command : 0),
1322                                   b);
1323
1324           do_cleanups (old_chain);
1325         }
1326
1327       info->cmd = alloc_counted_command_line (l);
1328     }
1329
1330   /* If a breakpoint was on the list more than once, we don't need to
1331      do anything.  */
1332   if (b->commands != info->cmd)
1333     {
1334       validate_commands_for_breakpoint (b, info->cmd->commands);
1335       incref_counted_command_line (info->cmd);
1336       decref_counted_command_line (&b->commands);
1337       b->commands = info->cmd;
1338       observer_notify_breakpoint_modified (b);
1339     }
1340 }
1341
1342 static void
1343 commands_command_1 (char *arg, int from_tty, 
1344                     struct command_line *control)
1345 {
1346   struct cleanup *cleanups;
1347   struct commands_info info;
1348
1349   info.from_tty = from_tty;
1350   info.control = control;
1351   info.cmd = NULL;
1352   /* If we read command lines from the user, then `info' will hold an
1353      extra reference to the commands that we must clean up.  */
1354   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1355
1356   if (arg == NULL || !*arg)
1357     {
1358       if (breakpoint_count - prev_breakpoint_count > 1)
1359         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1360                           breakpoint_count);
1361       else if (breakpoint_count > 0)
1362         arg = xstrprintf ("%d", breakpoint_count);
1363       else
1364         {
1365           /* So that we don't try to free the incoming non-NULL
1366              argument in the cleanup below.  Mapping breakpoint
1367              numbers will fail in this case.  */
1368           arg = NULL;
1369         }
1370     }
1371   else
1372     /* The command loop has some static state, so we need to preserve
1373        our argument.  */
1374     arg = xstrdup (arg);
1375
1376   if (arg != NULL)
1377     make_cleanup (xfree, arg);
1378
1379   info.arg = arg;
1380
1381   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1382
1383   if (info.cmd == NULL)
1384     error (_("No breakpoints specified."));
1385
1386   do_cleanups (cleanups);
1387 }
1388
1389 static void
1390 commands_command (char *arg, int from_tty)
1391 {
1392   commands_command_1 (arg, from_tty, NULL);
1393 }
1394
1395 /* Like commands_command, but instead of reading the commands from
1396    input stream, takes them from an already parsed command structure.
1397
1398    This is used by cli-script.c to DTRT with breakpoint commands
1399    that are part of if and while bodies.  */
1400 enum command_control_type
1401 commands_from_control_command (char *arg, struct command_line *cmd)
1402 {
1403   commands_command_1 (arg, 0, cmd);
1404   return simple_control;
1405 }
1406
1407 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1408
1409 static int
1410 bp_location_has_shadow (struct bp_location *bl)
1411 {
1412   if (bl->loc_type != bp_loc_software_breakpoint)
1413     return 0;
1414   if (!bl->inserted)
1415     return 0;
1416   if (bl->target_info.shadow_len == 0)
1417     /* BL isn't valid, or doesn't shadow memory.  */
1418     return 0;
1419   return 1;
1420 }
1421
1422 /* Update BUF, which is LEN bytes read from the target address
1423    MEMADDR, by replacing a memory breakpoint with its shadowed
1424    contents.
1425
1426    If READBUF is not NULL, this buffer must not overlap with the of
1427    the breakpoint location's shadow_contents buffer.  Otherwise, a
1428    failed assertion internal error will be raised.  */
1429
1430 static void
1431 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1432                             const gdb_byte *writebuf_org,
1433                             ULONGEST memaddr, LONGEST len,
1434                             struct bp_target_info *target_info,
1435                             struct gdbarch *gdbarch)
1436 {
1437   /* Now do full processing of the found relevant range of elements.  */
1438   CORE_ADDR bp_addr = 0;
1439   int bp_size = 0;
1440   int bptoffset = 0;
1441
1442   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1443                                  current_program_space->aspace, 0))
1444     {
1445       /* The breakpoint is inserted in a different address space.  */
1446       return;
1447     }
1448
1449   /* Addresses and length of the part of the breakpoint that
1450      we need to copy.  */
1451   bp_addr = target_info->placed_address;
1452   bp_size = target_info->shadow_len;
1453
1454   if (bp_addr + bp_size <= memaddr)
1455     {
1456       /* The breakpoint is entirely before the chunk of memory we are
1457          reading.  */
1458       return;
1459     }
1460
1461   if (bp_addr >= memaddr + len)
1462     {
1463       /* The breakpoint is entirely after the chunk of memory we are
1464          reading.  */
1465       return;
1466     }
1467
1468   /* Offset within shadow_contents.  */
1469   if (bp_addr < memaddr)
1470     {
1471       /* Only copy the second part of the breakpoint.  */
1472       bp_size -= memaddr - bp_addr;
1473       bptoffset = memaddr - bp_addr;
1474       bp_addr = memaddr;
1475     }
1476
1477   if (bp_addr + bp_size > memaddr + len)
1478     {
1479       /* Only copy the first part of the breakpoint.  */
1480       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1481     }
1482
1483   if (readbuf != NULL)
1484     {
1485       /* Verify that the readbuf buffer does not overlap with the
1486          shadow_contents buffer.  */
1487       gdb_assert (target_info->shadow_contents >= readbuf + len
1488                   || readbuf >= (target_info->shadow_contents
1489                                  + target_info->shadow_len));
1490
1491       /* Update the read buffer with this inserted breakpoint's
1492          shadow.  */
1493       memcpy (readbuf + bp_addr - memaddr,
1494               target_info->shadow_contents + bptoffset, bp_size);
1495     }
1496   else
1497     {
1498       const unsigned char *bp;
1499       CORE_ADDR placed_address = target_info->placed_address;
1500       int placed_size = target_info->placed_size;
1501
1502       /* Update the shadow with what we want to write to memory.  */
1503       memcpy (target_info->shadow_contents + bptoffset,
1504               writebuf_org + bp_addr - memaddr, bp_size);
1505
1506       /* Determine appropriate breakpoint contents and size for this
1507          address.  */
1508       bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1509
1510       /* Update the final write buffer with this inserted
1511          breakpoint's INSN.  */
1512       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1513     }
1514 }
1515
1516 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1517    by replacing any memory breakpoints with their shadowed contents.
1518
1519    If READBUF is not NULL, this buffer must not overlap with any of
1520    the breakpoint location's shadow_contents buffers.  Otherwise,
1521    a failed assertion internal error will be raised.
1522
1523    The range of shadowed area by each bp_location is:
1524      bl->address - bp_location_placed_address_before_address_max
1525      up to bl->address + bp_location_shadow_len_after_address_max
1526    The range we were requested to resolve shadows for is:
1527      memaddr ... memaddr + len
1528    Thus the safe cutoff boundaries for performance optimization are
1529      memaddr + len <= (bl->address
1530                        - bp_location_placed_address_before_address_max)
1531    and:
1532      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1533
1534 void
1535 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1536                         const gdb_byte *writebuf_org,
1537                         ULONGEST memaddr, LONGEST len)
1538 {
1539   /* Left boundary, right boundary and median element of our binary
1540      search.  */
1541   unsigned bc_l, bc_r, bc;
1542   size_t i;
1543
1544   /* Find BC_L which is a leftmost element which may affect BUF
1545      content.  It is safe to report lower value but a failure to
1546      report higher one.  */
1547
1548   bc_l = 0;
1549   bc_r = bp_location_count;
1550   while (bc_l + 1 < bc_r)
1551     {
1552       struct bp_location *bl;
1553
1554       bc = (bc_l + bc_r) / 2;
1555       bl = bp_location[bc];
1556
1557       /* Check first BL->ADDRESS will not overflow due to the added
1558          constant.  Then advance the left boundary only if we are sure
1559          the BC element can in no way affect the BUF content (MEMADDR
1560          to MEMADDR + LEN range).
1561
1562          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1563          offset so that we cannot miss a breakpoint with its shadow
1564          range tail still reaching MEMADDR.  */
1565
1566       if ((bl->address + bp_location_shadow_len_after_address_max
1567            >= bl->address)
1568           && (bl->address + bp_location_shadow_len_after_address_max
1569               <= memaddr))
1570         bc_l = bc;
1571       else
1572         bc_r = bc;
1573     }
1574
1575   /* Due to the binary search above, we need to make sure we pick the
1576      first location that's at BC_L's address.  E.g., if there are
1577      multiple locations at the same address, BC_L may end up pointing
1578      at a duplicate location, and miss the "master"/"inserted"
1579      location.  Say, given locations L1, L2 and L3 at addresses A and
1580      B:
1581
1582       L1@A, L2@A, L3@B, ...
1583
1584      BC_L could end up pointing at location L2, while the "master"
1585      location could be L1.  Since the `loc->inserted' flag is only set
1586      on "master" locations, we'd forget to restore the shadow of L1
1587      and L2.  */
1588   while (bc_l > 0
1589          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1590     bc_l--;
1591
1592   /* Now do full processing of the found relevant range of elements.  */
1593
1594   for (bc = bc_l; bc < bp_location_count; bc++)
1595   {
1596     struct bp_location *bl = bp_location[bc];
1597     CORE_ADDR bp_addr = 0;
1598     int bp_size = 0;
1599     int bptoffset = 0;
1600
1601     /* bp_location array has BL->OWNER always non-NULL.  */
1602     if (bl->owner->type == bp_none)
1603       warning (_("reading through apparently deleted breakpoint #%d?"),
1604                bl->owner->number);
1605
1606     /* Performance optimization: any further element can no longer affect BUF
1607        content.  */
1608
1609     if (bl->address >= bp_location_placed_address_before_address_max
1610         && memaddr + len <= (bl->address
1611                              - bp_location_placed_address_before_address_max))
1612       break;
1613
1614     if (!bp_location_has_shadow (bl))
1615       continue;
1616
1617     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1618                                 memaddr, len, &bl->target_info, bl->gdbarch);
1619   }
1620
1621   /* Now process single-step breakpoints.  These are not found in the
1622      bp_location array.  */
1623   for (i = 0; i < 2; i++)
1624     {
1625       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
1626
1627       if (bp_tgt != NULL)
1628         {
1629           struct gdbarch *gdbarch = single_step_gdbarch[i];
1630
1631           one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1632                                       memaddr, len, bp_tgt, gdbarch);
1633         }
1634     }
1635 }
1636
1637 \f
1638
1639 /* Return true if BPT is either a software breakpoint or a hardware
1640    breakpoint.  */
1641
1642 int
1643 is_breakpoint (const struct breakpoint *bpt)
1644 {
1645   return (bpt->type == bp_breakpoint
1646           || bpt->type == bp_hardware_breakpoint
1647           || bpt->type == bp_dprintf);
1648 }
1649
1650 /* Return true if BPT is of any hardware watchpoint kind.  */
1651
1652 static int
1653 is_hardware_watchpoint (const struct breakpoint *bpt)
1654 {
1655   return (bpt->type == bp_hardware_watchpoint
1656           || bpt->type == bp_read_watchpoint
1657           || bpt->type == bp_access_watchpoint);
1658 }
1659
1660 /* Return true if BPT is of any watchpoint kind, hardware or
1661    software.  */
1662
1663 int
1664 is_watchpoint (const struct breakpoint *bpt)
1665 {
1666   return (is_hardware_watchpoint (bpt)
1667           || bpt->type == bp_watchpoint);
1668 }
1669
1670 /* Returns true if the current thread and its running state are safe
1671    to evaluate or update watchpoint B.  Watchpoints on local
1672    expressions need to be evaluated in the context of the thread that
1673    was current when the watchpoint was created, and, that thread needs
1674    to be stopped to be able to select the correct frame context.
1675    Watchpoints on global expressions can be evaluated on any thread,
1676    and in any state.  It is presently left to the target allowing
1677    memory accesses when threads are running.  */
1678
1679 static int
1680 watchpoint_in_thread_scope (struct watchpoint *b)
1681 {
1682   return (b->base.pspace == current_program_space
1683           && (ptid_equal (b->watchpoint_thread, null_ptid)
1684               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1685                   && !is_executing (inferior_ptid))));
1686 }
1687
1688 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1689    associated bp_watchpoint_scope breakpoint.  */
1690
1691 static void
1692 watchpoint_del_at_next_stop (struct watchpoint *w)
1693 {
1694   struct breakpoint *b = &w->base;
1695
1696   if (b->related_breakpoint != b)
1697     {
1698       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1699       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1700       b->related_breakpoint->disposition = disp_del_at_next_stop;
1701       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1702       b->related_breakpoint = b;
1703     }
1704   b->disposition = disp_del_at_next_stop;
1705 }
1706
1707 /* Assuming that B is a watchpoint:
1708    - Reparse watchpoint expression, if REPARSE is non-zero
1709    - Evaluate expression and store the result in B->val
1710    - Evaluate the condition if there is one, and store the result
1711      in b->loc->cond.
1712    - Update the list of values that must be watched in B->loc.
1713
1714    If the watchpoint disposition is disp_del_at_next_stop, then do
1715    nothing.  If this is local watchpoint that is out of scope, delete
1716    it.
1717
1718    Even with `set breakpoint always-inserted on' the watchpoints are
1719    removed + inserted on each stop here.  Normal breakpoints must
1720    never be removed because they might be missed by a running thread
1721    when debugging in non-stop mode.  On the other hand, hardware
1722    watchpoints (is_hardware_watchpoint; processed here) are specific
1723    to each LWP since they are stored in each LWP's hardware debug
1724    registers.  Therefore, such LWP must be stopped first in order to
1725    be able to modify its hardware watchpoints.
1726
1727    Hardware watchpoints must be reset exactly once after being
1728    presented to the user.  It cannot be done sooner, because it would
1729    reset the data used to present the watchpoint hit to the user.  And
1730    it must not be done later because it could display the same single
1731    watchpoint hit during multiple GDB stops.  Note that the latter is
1732    relevant only to the hardware watchpoint types bp_read_watchpoint
1733    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1734    not user-visible - its hit is suppressed if the memory content has
1735    not changed.
1736
1737    The following constraints influence the location where we can reset
1738    hardware watchpoints:
1739
1740    * target_stopped_by_watchpoint and target_stopped_data_address are
1741      called several times when GDB stops.
1742
1743    [linux] 
1744    * Multiple hardware watchpoints can be hit at the same time,
1745      causing GDB to stop.  GDB only presents one hardware watchpoint
1746      hit at a time as the reason for stopping, and all the other hits
1747      are presented later, one after the other, each time the user
1748      requests the execution to be resumed.  Execution is not resumed
1749      for the threads still having pending hit event stored in
1750      LWP_INFO->STATUS.  While the watchpoint is already removed from
1751      the inferior on the first stop the thread hit event is kept being
1752      reported from its cached value by linux_nat_stopped_data_address
1753      until the real thread resume happens after the watchpoint gets
1754      presented and thus its LWP_INFO->STATUS gets reset.
1755
1756    Therefore the hardware watchpoint hit can get safely reset on the
1757    watchpoint removal from inferior.  */
1758
1759 static void
1760 update_watchpoint (struct watchpoint *b, int reparse)
1761 {
1762   int within_current_scope;
1763   struct frame_id saved_frame_id;
1764   int frame_saved;
1765
1766   /* If this is a local watchpoint, we only want to check if the
1767      watchpoint frame is in scope if the current thread is the thread
1768      that was used to create the watchpoint.  */
1769   if (!watchpoint_in_thread_scope (b))
1770     return;
1771
1772   if (b->base.disposition == disp_del_at_next_stop)
1773     return;
1774  
1775   frame_saved = 0;
1776
1777   /* Determine if the watchpoint is within scope.  */
1778   if (b->exp_valid_block == NULL)
1779     within_current_scope = 1;
1780   else
1781     {
1782       struct frame_info *fi = get_current_frame ();
1783       struct gdbarch *frame_arch = get_frame_arch (fi);
1784       CORE_ADDR frame_pc = get_frame_pc (fi);
1785
1786       /* If we're in a function epilogue, unwinding may not work
1787          properly, so do not attempt to recreate locations at this
1788          point.  See similar comments in watchpoint_check.  */
1789       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1790         return;
1791
1792       /* Save the current frame's ID so we can restore it after
1793          evaluating the watchpoint expression on its own frame.  */
1794       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1795          took a frame parameter, so that we didn't have to change the
1796          selected frame.  */
1797       frame_saved = 1;
1798       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1799
1800       fi = frame_find_by_id (b->watchpoint_frame);
1801       within_current_scope = (fi != NULL);
1802       if (within_current_scope)
1803         select_frame (fi);
1804     }
1805
1806   /* We don't free locations.  They are stored in the bp_location array
1807      and update_global_location_list will eventually delete them and
1808      remove breakpoints if needed.  */
1809   b->base.loc = NULL;
1810
1811   if (within_current_scope && reparse)
1812     {
1813       const char *s;
1814
1815       if (b->exp)
1816         {
1817           xfree (b->exp);
1818           b->exp = NULL;
1819         }
1820       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1821       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1822       /* If the meaning of expression itself changed, the old value is
1823          no longer relevant.  We don't want to report a watchpoint hit
1824          to the user when the old value and the new value may actually
1825          be completely different objects.  */
1826       value_free (b->val);
1827       b->val = NULL;
1828       b->val_valid = 0;
1829
1830       /* Note that unlike with breakpoints, the watchpoint's condition
1831          expression is stored in the breakpoint object, not in the
1832          locations (re)created below.  */
1833       if (b->base.cond_string != NULL)
1834         {
1835           if (b->cond_exp != NULL)
1836             {
1837               xfree (b->cond_exp);
1838               b->cond_exp = NULL;
1839             }
1840
1841           s = b->base.cond_string;
1842           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1843         }
1844     }
1845
1846   /* If we failed to parse the expression, for example because
1847      it refers to a global variable in a not-yet-loaded shared library,
1848      don't try to insert watchpoint.  We don't automatically delete
1849      such watchpoint, though, since failure to parse expression
1850      is different from out-of-scope watchpoint.  */
1851   if (!target_has_execution)
1852     {
1853       /* Without execution, memory can't change.  No use to try and
1854          set watchpoint locations.  The watchpoint will be reset when
1855          the target gains execution, through breakpoint_re_set.  */
1856       if (!can_use_hw_watchpoints)
1857         {
1858           if (b->base.ops->works_in_software_mode (&b->base))
1859             b->base.type = bp_watchpoint;
1860           else
1861             error (_("Can't set read/access watchpoint when "
1862                      "hardware watchpoints are disabled."));
1863         }
1864     }
1865   else if (within_current_scope && b->exp)
1866     {
1867       int pc = 0;
1868       struct value *val_chain, *v, *result, *next;
1869       struct program_space *frame_pspace;
1870
1871       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1872
1873       /* Avoid setting b->val if it's already set.  The meaning of
1874          b->val is 'the last value' user saw, and we should update
1875          it only if we reported that last value to user.  As it
1876          happens, the code that reports it updates b->val directly.
1877          We don't keep track of the memory value for masked
1878          watchpoints.  */
1879       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1880         {
1881           b->val = v;
1882           b->val_valid = 1;
1883         }
1884
1885       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1886
1887       /* Look at each value on the value chain.  */
1888       for (v = val_chain; v; v = value_next (v))
1889         {
1890           /* If it's a memory location, and GDB actually needed
1891              its contents to evaluate the expression, then we
1892              must watch it.  If the first value returned is
1893              still lazy, that means an error occurred reading it;
1894              watch it anyway in case it becomes readable.  */
1895           if (VALUE_LVAL (v) == lval_memory
1896               && (v == val_chain || ! value_lazy (v)))
1897             {
1898               struct type *vtype = check_typedef (value_type (v));
1899
1900               /* We only watch structs and arrays if user asked
1901                  for it explicitly, never if they just happen to
1902                  appear in the middle of some value chain.  */
1903               if (v == result
1904                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1905                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1906                 {
1907                   CORE_ADDR addr;
1908                   int type;
1909                   struct bp_location *loc, **tmp;
1910
1911                   addr = value_address (v);
1912                   type = hw_write;
1913                   if (b->base.type == bp_read_watchpoint)
1914                     type = hw_read;
1915                   else if (b->base.type == bp_access_watchpoint)
1916                     type = hw_access;
1917
1918                   loc = allocate_bp_location (&b->base);
1919                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1920                     ;
1921                   *tmp = loc;
1922                   loc->gdbarch = get_type_arch (value_type (v));
1923
1924                   loc->pspace = frame_pspace;
1925                   loc->address = addr;
1926                   loc->length = TYPE_LENGTH (value_type (v));
1927                   loc->watchpoint_type = type;
1928                 }
1929             }
1930         }
1931
1932       /* Change the type of breakpoint between hardware assisted or
1933          an ordinary watchpoint depending on the hardware support
1934          and free hardware slots.  REPARSE is set when the inferior
1935          is started.  */
1936       if (reparse)
1937         {
1938           int reg_cnt;
1939           enum bp_loc_type loc_type;
1940           struct bp_location *bl;
1941
1942           reg_cnt = can_use_hardware_watchpoint (val_chain);
1943
1944           if (reg_cnt)
1945             {
1946               int i, target_resources_ok, other_type_used;
1947               enum bptype type;
1948
1949               /* Use an exact watchpoint when there's only one memory region to be
1950                  watched, and only one debug register is needed to watch it.  */
1951               b->exact = target_exact_watchpoints && reg_cnt == 1;
1952
1953               /* We need to determine how many resources are already
1954                  used for all other hardware watchpoints plus this one
1955                  to see if we still have enough resources to also fit
1956                  this watchpoint in as well.  */
1957
1958               /* If this is a software watchpoint, we try to turn it
1959                  to a hardware one -- count resources as if B was of
1960                  hardware watchpoint type.  */
1961               type = b->base.type;
1962               if (type == bp_watchpoint)
1963                 type = bp_hardware_watchpoint;
1964
1965               /* This watchpoint may or may not have been placed on
1966                  the list yet at this point (it won't be in the list
1967                  if we're trying to create it for the first time,
1968                  through watch_command), so always account for it
1969                  manually.  */
1970
1971               /* Count resources used by all watchpoints except B.  */
1972               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1973
1974               /* Add in the resources needed for B.  */
1975               i += hw_watchpoint_use_count (&b->base);
1976
1977               target_resources_ok
1978                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1979               if (target_resources_ok <= 0)
1980                 {
1981                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1982
1983                   if (target_resources_ok == 0 && !sw_mode)
1984                     error (_("Target does not support this type of "
1985                              "hardware watchpoint."));
1986                   else if (target_resources_ok < 0 && !sw_mode)
1987                     error (_("There are not enough available hardware "
1988                              "resources for this watchpoint."));
1989
1990                   /* Downgrade to software watchpoint.  */
1991                   b->base.type = bp_watchpoint;
1992                 }
1993               else
1994                 {
1995                   /* If this was a software watchpoint, we've just
1996                      found we have enough resources to turn it to a
1997                      hardware watchpoint.  Otherwise, this is a
1998                      nop.  */
1999                   b->base.type = type;
2000                 }
2001             }
2002           else if (!b->base.ops->works_in_software_mode (&b->base))
2003             {
2004               if (!can_use_hw_watchpoints)
2005                 error (_("Can't set read/access watchpoint when "
2006                          "hardware watchpoints are disabled."));
2007               else
2008                 error (_("Expression cannot be implemented with "
2009                          "read/access watchpoint."));
2010             }
2011           else
2012             b->base.type = bp_watchpoint;
2013
2014           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2015                       : bp_loc_hardware_watchpoint);
2016           for (bl = b->base.loc; bl; bl = bl->next)
2017             bl->loc_type = loc_type;
2018         }
2019
2020       for (v = val_chain; v; v = next)
2021         {
2022           next = value_next (v);
2023           if (v != b->val)
2024             value_free (v);
2025         }
2026
2027       /* If a software watchpoint is not watching any memory, then the
2028          above left it without any location set up.  But,
2029          bpstat_stop_status requires a location to be able to report
2030          stops, so make sure there's at least a dummy one.  */
2031       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2032         {
2033           struct breakpoint *base = &b->base;
2034           base->loc = allocate_bp_location (base);
2035           base->loc->pspace = frame_pspace;
2036           base->loc->address = -1;
2037           base->loc->length = -1;
2038           base->loc->watchpoint_type = -1;
2039         }
2040     }
2041   else if (!within_current_scope)
2042     {
2043       printf_filtered (_("\
2044 Watchpoint %d deleted because the program has left the block\n\
2045 in which its expression is valid.\n"),
2046                        b->base.number);
2047       watchpoint_del_at_next_stop (b);
2048     }
2049
2050   /* Restore the selected frame.  */
2051   if (frame_saved)
2052     select_frame (frame_find_by_id (saved_frame_id));
2053 }
2054
2055
2056 /* Returns 1 iff breakpoint location should be
2057    inserted in the inferior.  We don't differentiate the type of BL's owner
2058    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2059    breakpoint_ops is not defined, because in insert_bp_location,
2060    tracepoint's insert_location will not be called.  */
2061 static int
2062 should_be_inserted (struct bp_location *bl)
2063 {
2064   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2065     return 0;
2066
2067   if (bl->owner->disposition == disp_del_at_next_stop)
2068     return 0;
2069
2070   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2071     return 0;
2072
2073   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2074     return 0;
2075
2076   /* This is set for example, when we're attached to the parent of a
2077      vfork, and have detached from the child.  The child is running
2078      free, and we expect it to do an exec or exit, at which point the
2079      OS makes the parent schedulable again (and the target reports
2080      that the vfork is done).  Until the child is done with the shared
2081      memory region, do not insert breakpoints in the parent, otherwise
2082      the child could still trip on the parent's breakpoints.  Since
2083      the parent is blocked anyway, it won't miss any breakpoint.  */
2084   if (bl->pspace->breakpoints_not_allowed)
2085     return 0;
2086
2087   /* Don't insert a breakpoint if we're trying to step past its
2088      location.  */
2089   if ((bl->loc_type == bp_loc_software_breakpoint
2090        || bl->loc_type == bp_loc_hardware_breakpoint)
2091       && stepping_past_instruction_at (bl->pspace->aspace,
2092                                        bl->address))
2093     return 0;
2094
2095   return 1;
2096 }
2097
2098 /* Same as should_be_inserted but does the check assuming
2099    that the location is not duplicated.  */
2100
2101 static int
2102 unduplicated_should_be_inserted (struct bp_location *bl)
2103 {
2104   int result;
2105   const int save_duplicate = bl->duplicate;
2106
2107   bl->duplicate = 0;
2108   result = should_be_inserted (bl);
2109   bl->duplicate = save_duplicate;
2110   return result;
2111 }
2112
2113 /* Parses a conditional described by an expression COND into an
2114    agent expression bytecode suitable for evaluation
2115    by the bytecode interpreter.  Return NULL if there was
2116    any error during parsing.  */
2117
2118 static struct agent_expr *
2119 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2120 {
2121   struct agent_expr *aexpr = NULL;
2122   volatile struct gdb_exception ex;
2123
2124   if (!cond)
2125     return NULL;
2126
2127   /* We don't want to stop processing, so catch any errors
2128      that may show up.  */
2129   TRY_CATCH (ex, RETURN_MASK_ERROR)
2130     {
2131       aexpr = gen_eval_for_expr (scope, cond);
2132     }
2133
2134   if (ex.reason < 0)
2135     {
2136       /* If we got here, it means the condition could not be parsed to a valid
2137          bytecode expression and thus can't be evaluated on the target's side.
2138          It's no use iterating through the conditions.  */
2139       return NULL;
2140     }
2141
2142   /* We have a valid agent expression.  */
2143   return aexpr;
2144 }
2145
2146 /* Based on location BL, create a list of breakpoint conditions to be
2147    passed on to the target.  If we have duplicated locations with different
2148    conditions, we will add such conditions to the list.  The idea is that the
2149    target will evaluate the list of conditions and will only notify GDB when
2150    one of them is true.  */
2151
2152 static void
2153 build_target_condition_list (struct bp_location *bl)
2154 {
2155   struct bp_location **locp = NULL, **loc2p;
2156   int null_condition_or_parse_error = 0;
2157   int modified = bl->needs_update;
2158   struct bp_location *loc;
2159
2160   /* Release conditions left over from a previous insert.  */
2161   VEC_free (agent_expr_p, bl->target_info.conditions);
2162
2163   /* This is only meaningful if the target is
2164      evaluating conditions and if the user has
2165      opted for condition evaluation on the target's
2166      side.  */
2167   if (gdb_evaluates_breakpoint_condition_p ()
2168       || !target_supports_evaluation_of_breakpoint_conditions ())
2169     return;
2170
2171   /* Do a first pass to check for locations with no assigned
2172      conditions or conditions that fail to parse to a valid agent expression
2173      bytecode.  If any of these happen, then it's no use to send conditions
2174      to the target since this location will always trigger and generate a
2175      response back to GDB.  */
2176   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2177     {
2178       loc = (*loc2p);
2179       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2180         {
2181           if (modified)
2182             {
2183               struct agent_expr *aexpr;
2184
2185               /* Re-parse the conditions since something changed.  In that
2186                  case we already freed the condition bytecodes (see
2187                  force_breakpoint_reinsertion).  We just
2188                  need to parse the condition to bytecodes again.  */
2189               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2190               loc->cond_bytecode = aexpr;
2191
2192               /* Check if we managed to parse the conditional expression
2193                  correctly.  If not, we will not send this condition
2194                  to the target.  */
2195               if (aexpr)
2196                 continue;
2197             }
2198
2199           /* If we have a NULL bytecode expression, it means something
2200              went wrong or we have a null condition expression.  */
2201           if (!loc->cond_bytecode)
2202             {
2203               null_condition_or_parse_error = 1;
2204               break;
2205             }
2206         }
2207     }
2208
2209   /* If any of these happened, it means we will have to evaluate the conditions
2210      for the location's address on gdb's side.  It is no use keeping bytecodes
2211      for all the other duplicate locations, thus we free all of them here.
2212
2213      This is so we have a finer control over which locations' conditions are
2214      being evaluated by GDB or the remote stub.  */
2215   if (null_condition_or_parse_error)
2216     {
2217       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2218         {
2219           loc = (*loc2p);
2220           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2221             {
2222               /* Only go as far as the first NULL bytecode is
2223                  located.  */
2224               if (!loc->cond_bytecode)
2225                 return;
2226
2227               free_agent_expr (loc->cond_bytecode);
2228               loc->cond_bytecode = NULL;
2229             }
2230         }
2231     }
2232
2233   /* No NULL conditions or failed bytecode generation.  Build a condition list
2234      for this location's address.  */
2235   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2236     {
2237       loc = (*loc2p);
2238       if (loc->cond
2239           && is_breakpoint (loc->owner)
2240           && loc->pspace->num == bl->pspace->num
2241           && loc->owner->enable_state == bp_enabled
2242           && loc->enabled)
2243         /* Add the condition to the vector.  This will be used later to send the
2244            conditions to the target.  */
2245         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2246                        loc->cond_bytecode);
2247     }
2248
2249   return;
2250 }
2251
2252 /* Parses a command described by string CMD into an agent expression
2253    bytecode suitable for evaluation by the bytecode interpreter.
2254    Return NULL if there was any error during parsing.  */
2255
2256 static struct agent_expr *
2257 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2258 {
2259   struct cleanup *old_cleanups = 0;
2260   struct expression *expr, **argvec;
2261   struct agent_expr *aexpr = NULL;
2262   volatile struct gdb_exception ex;
2263   const char *cmdrest;
2264   const char *format_start, *format_end;
2265   struct format_piece *fpieces;
2266   int nargs;
2267   struct gdbarch *gdbarch = get_current_arch ();
2268
2269   if (!cmd)
2270     return NULL;
2271
2272   cmdrest = cmd;
2273
2274   if (*cmdrest == ',')
2275     ++cmdrest;
2276   cmdrest = skip_spaces_const (cmdrest);
2277
2278   if (*cmdrest++ != '"')
2279     error (_("No format string following the location"));
2280
2281   format_start = cmdrest;
2282
2283   fpieces = parse_format_string (&cmdrest);
2284
2285   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2286
2287   format_end = cmdrest;
2288
2289   if (*cmdrest++ != '"')
2290     error (_("Bad format string, non-terminated '\"'."));
2291   
2292   cmdrest = skip_spaces_const (cmdrest);
2293
2294   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2295     error (_("Invalid argument syntax"));
2296
2297   if (*cmdrest == ',')
2298     cmdrest++;
2299   cmdrest = skip_spaces_const (cmdrest);
2300
2301   /* For each argument, make an expression.  */
2302
2303   argvec = (struct expression **) alloca (strlen (cmd)
2304                                          * sizeof (struct expression *));
2305
2306   nargs = 0;
2307   while (*cmdrest != '\0')
2308     {
2309       const char *cmd1;
2310
2311       cmd1 = cmdrest;
2312       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2313       argvec[nargs++] = expr;
2314       cmdrest = cmd1;
2315       if (*cmdrest == ',')
2316         ++cmdrest;
2317     }
2318
2319   /* We don't want to stop processing, so catch any errors
2320      that may show up.  */
2321   TRY_CATCH (ex, RETURN_MASK_ERROR)
2322     {
2323       aexpr = gen_printf (scope, gdbarch, 0, 0,
2324                           format_start, format_end - format_start,
2325                           fpieces, nargs, argvec);
2326     }
2327
2328   do_cleanups (old_cleanups);
2329
2330   if (ex.reason < 0)
2331     {
2332       /* If we got here, it means the command could not be parsed to a valid
2333          bytecode expression and thus can't be evaluated on the target's side.
2334          It's no use iterating through the other commands.  */
2335       return NULL;
2336     }
2337
2338   /* We have a valid agent expression, return it.  */
2339   return aexpr;
2340 }
2341
2342 /* Based on location BL, create a list of breakpoint commands to be
2343    passed on to the target.  If we have duplicated locations with
2344    different commands, we will add any such to the list.  */
2345
2346 static void
2347 build_target_command_list (struct bp_location *bl)
2348 {
2349   struct bp_location **locp = NULL, **loc2p;
2350   int null_command_or_parse_error = 0;
2351   int modified = bl->needs_update;
2352   struct bp_location *loc;
2353
2354   /* Release commands left over from a previous insert.  */
2355   VEC_free (agent_expr_p, bl->target_info.tcommands);
2356
2357   if (!target_can_run_breakpoint_commands ())
2358     return;
2359
2360   /* For now, limit to agent-style dprintf breakpoints.  */
2361   if (dprintf_style != dprintf_style_agent)
2362     return;
2363
2364   /* For now, if we have any duplicate location that isn't a dprintf,
2365      don't install the target-side commands, as that would make the
2366      breakpoint not be reported to the core, and we'd lose
2367      control.  */
2368   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2369     {
2370       loc = (*loc2p);
2371       if (is_breakpoint (loc->owner)
2372           && loc->pspace->num == bl->pspace->num
2373           && loc->owner->type != bp_dprintf)
2374         return;
2375     }
2376
2377   /* Do a first pass to check for locations with no assigned
2378      conditions or conditions that fail to parse to a valid agent expression
2379      bytecode.  If any of these happen, then it's no use to send conditions
2380      to the target since this location will always trigger and generate a
2381      response back to GDB.  */
2382   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2383     {
2384       loc = (*loc2p);
2385       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2386         {
2387           if (modified)
2388             {
2389               struct agent_expr *aexpr;
2390
2391               /* Re-parse the commands since something changed.  In that
2392                  case we already freed the command bytecodes (see
2393                  force_breakpoint_reinsertion).  We just
2394                  need to parse the command to bytecodes again.  */
2395               aexpr = parse_cmd_to_aexpr (bl->address,
2396                                           loc->owner->extra_string);
2397               loc->cmd_bytecode = aexpr;
2398
2399               if (!aexpr)
2400                 continue;
2401             }
2402
2403           /* If we have a NULL bytecode expression, it means something
2404              went wrong or we have a null command expression.  */
2405           if (!loc->cmd_bytecode)
2406             {
2407               null_command_or_parse_error = 1;
2408               break;
2409             }
2410         }
2411     }
2412
2413   /* If anything failed, then we're not doing target-side commands,
2414      and so clean up.  */
2415   if (null_command_or_parse_error)
2416     {
2417       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2418         {
2419           loc = (*loc2p);
2420           if (is_breakpoint (loc->owner)
2421               && loc->pspace->num == bl->pspace->num)
2422             {
2423               /* Only go as far as the first NULL bytecode is
2424                  located.  */
2425               if (loc->cmd_bytecode == NULL)
2426                 return;
2427
2428               free_agent_expr (loc->cmd_bytecode);
2429               loc->cmd_bytecode = NULL;
2430             }
2431         }
2432     }
2433
2434   /* No NULL commands or failed bytecode generation.  Build a command list
2435      for this location's address.  */
2436   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2437     {
2438       loc = (*loc2p);
2439       if (loc->owner->extra_string
2440           && is_breakpoint (loc->owner)
2441           && loc->pspace->num == bl->pspace->num
2442           && loc->owner->enable_state == bp_enabled
2443           && loc->enabled)
2444         /* Add the command to the vector.  This will be used later
2445            to send the commands to the target.  */
2446         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2447                        loc->cmd_bytecode);
2448     }
2449
2450   bl->target_info.persist = 0;
2451   /* Maybe flag this location as persistent.  */
2452   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2453     bl->target_info.persist = 1;
2454 }
2455
2456 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2457    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2458    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2459    Returns 0 for success, 1 if the bp_location type is not supported or
2460    -1 for failure.
2461
2462    NOTE drow/2003-09-09: This routine could be broken down to an
2463    object-style method for each breakpoint or catchpoint type.  */
2464 static int
2465 insert_bp_location (struct bp_location *bl,
2466                     struct ui_file *tmp_error_stream,
2467                     int *disabled_breaks,
2468                     int *hw_breakpoint_error,
2469                     int *hw_bp_error_explained_already)
2470 {
2471   enum errors bp_err = GDB_NO_ERROR;
2472   const char *bp_err_message = NULL;
2473   volatile struct gdb_exception e;
2474
2475   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2476     return 0;
2477
2478   /* Note we don't initialize bl->target_info, as that wipes out
2479      the breakpoint location's shadow_contents if the breakpoint
2480      is still inserted at that location.  This in turn breaks
2481      target_read_memory which depends on these buffers when
2482      a memory read is requested at the breakpoint location:
2483      Once the target_info has been wiped, we fail to see that
2484      we have a breakpoint inserted at that address and thus
2485      read the breakpoint instead of returning the data saved in
2486      the breakpoint location's shadow contents.  */
2487   bl->target_info.placed_address = bl->address;
2488   bl->target_info.placed_address_space = bl->pspace->aspace;
2489   bl->target_info.length = bl->length;
2490
2491   /* When working with target-side conditions, we must pass all the conditions
2492      for the same breakpoint address down to the target since GDB will not
2493      insert those locations.  With a list of breakpoint conditions, the target
2494      can decide when to stop and notify GDB.  */
2495
2496   if (is_breakpoint (bl->owner))
2497     {
2498       build_target_condition_list (bl);
2499       build_target_command_list (bl);
2500       /* Reset the modification marker.  */
2501       bl->needs_update = 0;
2502     }
2503
2504   if (bl->loc_type == bp_loc_software_breakpoint
2505       || bl->loc_type == bp_loc_hardware_breakpoint)
2506     {
2507       if (bl->owner->type != bp_hardware_breakpoint)
2508         {
2509           /* If the explicitly specified breakpoint type
2510              is not hardware breakpoint, check the memory map to see
2511              if the breakpoint address is in read only memory or not.
2512
2513              Two important cases are:
2514              - location type is not hardware breakpoint, memory
2515              is readonly.  We change the type of the location to
2516              hardware breakpoint.
2517              - location type is hardware breakpoint, memory is
2518              read-write.  This means we've previously made the
2519              location hardware one, but then the memory map changed,
2520              so we undo.
2521              
2522              When breakpoints are removed, remove_breakpoints will use
2523              location types we've just set here, the only possible
2524              problem is that memory map has changed during running
2525              program, but it's not going to work anyway with current
2526              gdb.  */
2527           struct mem_region *mr 
2528             = lookup_mem_region (bl->target_info.placed_address);
2529           
2530           if (mr)
2531             {
2532               if (automatic_hardware_breakpoints)
2533                 {
2534                   enum bp_loc_type new_type;
2535                   
2536                   if (mr->attrib.mode != MEM_RW)
2537                     new_type = bp_loc_hardware_breakpoint;
2538                   else 
2539                     new_type = bp_loc_software_breakpoint;
2540                   
2541                   if (new_type != bl->loc_type)
2542                     {
2543                       static int said = 0;
2544
2545                       bl->loc_type = new_type;
2546                       if (!said)
2547                         {
2548                           fprintf_filtered (gdb_stdout,
2549                                             _("Note: automatically using "
2550                                               "hardware breakpoints for "
2551                                               "read-only addresses.\n"));
2552                           said = 1;
2553                         }
2554                     }
2555                 }
2556               else if (bl->loc_type == bp_loc_software_breakpoint
2557                        && mr->attrib.mode != MEM_RW)        
2558                 warning (_("cannot set software breakpoint "
2559                            "at readonly address %s"),
2560                          paddress (bl->gdbarch, bl->address));
2561             }
2562         }
2563         
2564       /* First check to see if we have to handle an overlay.  */
2565       if (overlay_debugging == ovly_off
2566           || bl->section == NULL
2567           || !(section_is_overlay (bl->section)))
2568         {
2569           /* No overlay handling: just set the breakpoint.  */
2570           TRY_CATCH (e, RETURN_MASK_ALL)
2571             {
2572               int val;
2573
2574               val = bl->owner->ops->insert_location (bl);
2575               if (val)
2576                 bp_err = GENERIC_ERROR;
2577             }
2578           if (e.reason < 0)
2579             {
2580               bp_err = e.error;
2581               bp_err_message = e.message;
2582             }
2583         }
2584       else
2585         {
2586           /* This breakpoint is in an overlay section.
2587              Shall we set a breakpoint at the LMA?  */
2588           if (!overlay_events_enabled)
2589             {
2590               /* Yes -- overlay event support is not active, 
2591                  so we must try to set a breakpoint at the LMA.
2592                  This will not work for a hardware breakpoint.  */
2593               if (bl->loc_type == bp_loc_hardware_breakpoint)
2594                 warning (_("hardware breakpoint %d not supported in overlay!"),
2595                          bl->owner->number);
2596               else
2597                 {
2598                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2599                                                              bl->section);
2600                   /* Set a software (trap) breakpoint at the LMA.  */
2601                   bl->overlay_target_info = bl->target_info;
2602                   bl->overlay_target_info.placed_address = addr;
2603
2604                   /* No overlay handling: just set the breakpoint.  */
2605                   TRY_CATCH (e, RETURN_MASK_ALL)
2606                     {
2607                       int val;
2608
2609                       val = target_insert_breakpoint (bl->gdbarch,
2610                                                       &bl->overlay_target_info);
2611                       if (val)
2612                         bp_err = GENERIC_ERROR;
2613                     }
2614                   if (e.reason < 0)
2615                     {
2616                       bp_err = e.error;
2617                       bp_err_message = e.message;
2618                     }
2619
2620                   if (bp_err != GDB_NO_ERROR)
2621                     fprintf_unfiltered (tmp_error_stream,
2622                                         "Overlay breakpoint %d "
2623                                         "failed: in ROM?\n",
2624                                         bl->owner->number);
2625                 }
2626             }
2627           /* Shall we set a breakpoint at the VMA? */
2628           if (section_is_mapped (bl->section))
2629             {
2630               /* Yes.  This overlay section is mapped into memory.  */
2631               TRY_CATCH (e, RETURN_MASK_ALL)
2632                 {
2633                   int val;
2634
2635                   val = bl->owner->ops->insert_location (bl);
2636                   if (val)
2637                     bp_err = GENERIC_ERROR;
2638                 }
2639               if (e.reason < 0)
2640                 {
2641                   bp_err = e.error;
2642                   bp_err_message = e.message;
2643                 }
2644             }
2645           else
2646             {
2647               /* No.  This breakpoint will not be inserted.  
2648                  No error, but do not mark the bp as 'inserted'.  */
2649               return 0;
2650             }
2651         }
2652
2653       if (bp_err != GDB_NO_ERROR)
2654         {
2655           /* Can't set the breakpoint.  */
2656
2657           /* In some cases, we might not be able to insert a
2658              breakpoint in a shared library that has already been
2659              removed, but we have not yet processed the shlib unload
2660              event.  Unfortunately, some targets that implement
2661              breakpoint insertion themselves can't tell why the
2662              breakpoint insertion failed (e.g., the remote target
2663              doesn't define error codes), so we must treat generic
2664              errors as memory errors.  */
2665           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2666               && bl->loc_type == bp_loc_software_breakpoint
2667               && (solib_name_from_address (bl->pspace, bl->address)
2668                   || shared_objfile_contains_address_p (bl->pspace,
2669                                                         bl->address)))
2670             {
2671               /* See also: disable_breakpoints_in_shlibs.  */
2672               bl->shlib_disabled = 1;
2673               observer_notify_breakpoint_modified (bl->owner);
2674               if (!*disabled_breaks)
2675                 {
2676                   fprintf_unfiltered (tmp_error_stream, 
2677                                       "Cannot insert breakpoint %d.\n", 
2678                                       bl->owner->number);
2679                   fprintf_unfiltered (tmp_error_stream, 
2680                                       "Temporarily disabling shared "
2681                                       "library breakpoints:\n");
2682                 }
2683               *disabled_breaks = 1;
2684               fprintf_unfiltered (tmp_error_stream,
2685                                   "breakpoint #%d\n", bl->owner->number);
2686               return 0;
2687             }
2688           else
2689             {
2690               if (bl->loc_type == bp_loc_hardware_breakpoint)
2691                 {
2692                   *hw_breakpoint_error = 1;
2693                   *hw_bp_error_explained_already = bp_err_message != NULL;
2694                   fprintf_unfiltered (tmp_error_stream,
2695                                       "Cannot insert hardware breakpoint %d%s",
2696                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2697                   if (bp_err_message != NULL)
2698                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2699                 }
2700               else
2701                 {
2702                   if (bp_err_message == NULL)
2703                     {
2704                       char *message
2705                         = memory_error_message (TARGET_XFER_E_IO,
2706                                                 bl->gdbarch, bl->address);
2707                       struct cleanup *old_chain = make_cleanup (xfree, message);
2708
2709                       fprintf_unfiltered (tmp_error_stream,
2710                                           "Cannot insert breakpoint %d.\n"
2711                                           "%s\n",
2712                                           bl->owner->number, message);
2713                       do_cleanups (old_chain);
2714                     }
2715                   else
2716                     {
2717                       fprintf_unfiltered (tmp_error_stream,
2718                                           "Cannot insert breakpoint %d: %s\n",
2719                                           bl->owner->number,
2720                                           bp_err_message);
2721                     }
2722                 }
2723               return 1;
2724
2725             }
2726         }
2727       else
2728         bl->inserted = 1;
2729
2730       return 0;
2731     }
2732
2733   else if (bl->loc_type == bp_loc_hardware_watchpoint
2734            /* NOTE drow/2003-09-08: This state only exists for removing
2735               watchpoints.  It's not clear that it's necessary...  */
2736            && bl->owner->disposition != disp_del_at_next_stop)
2737     {
2738       int val;
2739
2740       gdb_assert (bl->owner->ops != NULL
2741                   && bl->owner->ops->insert_location != NULL);
2742
2743       val = bl->owner->ops->insert_location (bl);
2744
2745       /* If trying to set a read-watchpoint, and it turns out it's not
2746          supported, try emulating one with an access watchpoint.  */
2747       if (val == 1 && bl->watchpoint_type == hw_read)
2748         {
2749           struct bp_location *loc, **loc_temp;
2750
2751           /* But don't try to insert it, if there's already another
2752              hw_access location that would be considered a duplicate
2753              of this one.  */
2754           ALL_BP_LOCATIONS (loc, loc_temp)
2755             if (loc != bl
2756                 && loc->watchpoint_type == hw_access
2757                 && watchpoint_locations_match (bl, loc))
2758               {
2759                 bl->duplicate = 1;
2760                 bl->inserted = 1;
2761                 bl->target_info = loc->target_info;
2762                 bl->watchpoint_type = hw_access;
2763                 val = 0;
2764                 break;
2765               }
2766
2767           if (val == 1)
2768             {
2769               bl->watchpoint_type = hw_access;
2770               val = bl->owner->ops->insert_location (bl);
2771
2772               if (val)
2773                 /* Back to the original value.  */
2774                 bl->watchpoint_type = hw_read;
2775             }
2776         }
2777
2778       bl->inserted = (val == 0);
2779     }
2780
2781   else if (bl->owner->type == bp_catchpoint)
2782     {
2783       int val;
2784
2785       gdb_assert (bl->owner->ops != NULL
2786                   && bl->owner->ops->insert_location != NULL);
2787
2788       val = bl->owner->ops->insert_location (bl);
2789       if (val)
2790         {
2791           bl->owner->enable_state = bp_disabled;
2792
2793           if (val == 1)
2794             warning (_("\
2795 Error inserting catchpoint %d: Your system does not support this type\n\
2796 of catchpoint."), bl->owner->number);
2797           else
2798             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2799         }
2800
2801       bl->inserted = (val == 0);
2802
2803       /* We've already printed an error message if there was a problem
2804          inserting this catchpoint, and we've disabled the catchpoint,
2805          so just return success.  */
2806       return 0;
2807     }
2808
2809   return 0;
2810 }
2811
2812 /* This function is called when program space PSPACE is about to be
2813    deleted.  It takes care of updating breakpoints to not reference
2814    PSPACE anymore.  */
2815
2816 void
2817 breakpoint_program_space_exit (struct program_space *pspace)
2818 {
2819   struct breakpoint *b, *b_temp;
2820   struct bp_location *loc, **loc_temp;
2821
2822   /* Remove any breakpoint that was set through this program space.  */
2823   ALL_BREAKPOINTS_SAFE (b, b_temp)
2824     {
2825       if (b->pspace == pspace)
2826         delete_breakpoint (b);
2827     }
2828
2829   /* Breakpoints set through other program spaces could have locations
2830      bound to PSPACE as well.  Remove those.  */
2831   ALL_BP_LOCATIONS (loc, loc_temp)
2832     {
2833       struct bp_location *tmp;
2834
2835       if (loc->pspace == pspace)
2836         {
2837           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2838           if (loc->owner->loc == loc)
2839             loc->owner->loc = loc->next;
2840           else
2841             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2842               if (tmp->next == loc)
2843                 {
2844                   tmp->next = loc->next;
2845                   break;
2846                 }
2847         }
2848     }
2849
2850   /* Now update the global location list to permanently delete the
2851      removed locations above.  */
2852   update_global_location_list (0);
2853 }
2854
2855 /* Make sure all breakpoints are inserted in inferior.
2856    Throws exception on any error.
2857    A breakpoint that is already inserted won't be inserted
2858    again, so calling this function twice is safe.  */
2859 void
2860 insert_breakpoints (void)
2861 {
2862   struct breakpoint *bpt;
2863
2864   ALL_BREAKPOINTS (bpt)
2865     if (is_hardware_watchpoint (bpt))
2866       {
2867         struct watchpoint *w = (struct watchpoint *) bpt;
2868
2869         update_watchpoint (w, 0 /* don't reparse.  */);
2870       }
2871
2872   update_global_location_list (1);
2873
2874   /* update_global_location_list does not insert breakpoints when
2875      always_inserted_mode is not enabled.  Explicitly insert them
2876      now.  */
2877   if (!breakpoints_always_inserted_mode ())
2878     insert_breakpoint_locations ();
2879 }
2880
2881 /* Invoke CALLBACK for each of bp_location.  */
2882
2883 void
2884 iterate_over_bp_locations (walk_bp_location_callback callback)
2885 {
2886   struct bp_location *loc, **loc_tmp;
2887
2888   ALL_BP_LOCATIONS (loc, loc_tmp)
2889     {
2890       callback (loc, NULL);
2891     }
2892 }
2893
2894 /* This is used when we need to synch breakpoint conditions between GDB and the
2895    target.  It is the case with deleting and disabling of breakpoints when using
2896    always-inserted mode.  */
2897
2898 static void
2899 update_inserted_breakpoint_locations (void)
2900 {
2901   struct bp_location *bl, **blp_tmp;
2902   int error_flag = 0;
2903   int val = 0;
2904   int disabled_breaks = 0;
2905   int hw_breakpoint_error = 0;
2906   int hw_bp_details_reported = 0;
2907
2908   struct ui_file *tmp_error_stream = mem_fileopen ();
2909   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2910
2911   /* Explicitly mark the warning -- this will only be printed if
2912      there was an error.  */
2913   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2914
2915   save_current_space_and_thread ();
2916
2917   ALL_BP_LOCATIONS (bl, blp_tmp)
2918     {
2919       /* We only want to update software breakpoints and hardware
2920          breakpoints.  */
2921       if (!is_breakpoint (bl->owner))
2922         continue;
2923
2924       /* We only want to update locations that are already inserted
2925          and need updating.  This is to avoid unwanted insertion during
2926          deletion of breakpoints.  */
2927       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2928         continue;
2929
2930       switch_to_program_space_and_thread (bl->pspace);
2931
2932       /* For targets that support global breakpoints, there's no need
2933          to select an inferior to insert breakpoint to.  In fact, even
2934          if we aren't attached to any process yet, we should still
2935          insert breakpoints.  */
2936       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2937           && ptid_equal (inferior_ptid, null_ptid))
2938         continue;
2939
2940       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2941                                     &hw_breakpoint_error, &hw_bp_details_reported);
2942       if (val)
2943         error_flag = val;
2944     }
2945
2946   if (error_flag)
2947     {
2948       target_terminal_ours_for_output ();
2949       error_stream (tmp_error_stream);
2950     }
2951
2952   do_cleanups (cleanups);
2953 }
2954
2955 /* Used when starting or continuing the program.  */
2956
2957 static void
2958 insert_breakpoint_locations (void)
2959 {
2960   struct breakpoint *bpt;
2961   struct bp_location *bl, **blp_tmp;
2962   int error_flag = 0;
2963   int val = 0;
2964   int disabled_breaks = 0;
2965   int hw_breakpoint_error = 0;
2966   int hw_bp_error_explained_already = 0;
2967
2968   struct ui_file *tmp_error_stream = mem_fileopen ();
2969   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2970   
2971   /* Explicitly mark the warning -- this will only be printed if
2972      there was an error.  */
2973   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2974
2975   save_current_space_and_thread ();
2976
2977   ALL_BP_LOCATIONS (bl, blp_tmp)
2978     {
2979       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2980         continue;
2981
2982       /* There is no point inserting thread-specific breakpoints if
2983          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2984          has BL->OWNER always non-NULL.  */
2985       if (bl->owner->thread != -1
2986           && !valid_thread_id (bl->owner->thread))
2987         continue;
2988
2989       switch_to_program_space_and_thread (bl->pspace);
2990
2991       /* For targets that support global breakpoints, there's no need
2992          to select an inferior to insert breakpoint to.  In fact, even
2993          if we aren't attached to any process yet, we should still
2994          insert breakpoints.  */
2995       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2996           && ptid_equal (inferior_ptid, null_ptid))
2997         continue;
2998
2999       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3000                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3001       if (val)
3002         error_flag = val;
3003     }
3004
3005   /* If we failed to insert all locations of a watchpoint, remove
3006      them, as half-inserted watchpoint is of limited use.  */
3007   ALL_BREAKPOINTS (bpt)  
3008     {
3009       int some_failed = 0;
3010       struct bp_location *loc;
3011
3012       if (!is_hardware_watchpoint (bpt))
3013         continue;
3014
3015       if (!breakpoint_enabled (bpt))
3016         continue;
3017
3018       if (bpt->disposition == disp_del_at_next_stop)
3019         continue;
3020       
3021       for (loc = bpt->loc; loc; loc = loc->next)
3022         if (!loc->inserted && should_be_inserted (loc))
3023           {
3024             some_failed = 1;
3025             break;
3026           }
3027       if (some_failed)
3028         {
3029           for (loc = bpt->loc; loc; loc = loc->next)
3030             if (loc->inserted)
3031               remove_breakpoint (loc, mark_uninserted);
3032
3033           hw_breakpoint_error = 1;
3034           fprintf_unfiltered (tmp_error_stream,
3035                               "Could not insert hardware watchpoint %d.\n", 
3036                               bpt->number);
3037           error_flag = -1;
3038         }
3039     }
3040
3041   if (error_flag)
3042     {
3043       /* If a hardware breakpoint or watchpoint was inserted, add a
3044          message about possibly exhausted resources.  */
3045       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3046         {
3047           fprintf_unfiltered (tmp_error_stream, 
3048                               "Could not insert hardware breakpoints:\n\
3049 You may have requested too many hardware breakpoints/watchpoints.\n");
3050         }
3051       target_terminal_ours_for_output ();
3052       error_stream (tmp_error_stream);
3053     }
3054
3055   do_cleanups (cleanups);
3056 }
3057
3058 /* Used when the program stops.
3059    Returns zero if successful, or non-zero if there was a problem
3060    removing a breakpoint location.  */
3061
3062 int
3063 remove_breakpoints (void)
3064 {
3065   struct bp_location *bl, **blp_tmp;
3066   int val = 0;
3067
3068   ALL_BP_LOCATIONS (bl, blp_tmp)
3069   {
3070     if (bl->inserted && !is_tracepoint (bl->owner))
3071       val |= remove_breakpoint (bl, mark_uninserted);
3072   }
3073   return val;
3074 }
3075
3076 /* When a thread exits, remove breakpoints that are related to
3077    that thread.  */
3078
3079 static void
3080 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3081 {
3082   struct breakpoint *b, *b_tmp;
3083
3084   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3085     {
3086       if (b->thread == tp->num && user_breakpoint_p (b))
3087         {
3088           b->disposition = disp_del_at_next_stop;
3089
3090           printf_filtered (_("\
3091 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3092                           b->number, tp->num);
3093
3094           /* Hide it from the user.  */
3095           b->number = 0;
3096        }
3097     }
3098 }
3099
3100 /* Remove breakpoints of process PID.  */
3101
3102 int
3103 remove_breakpoints_pid (int pid)
3104 {
3105   struct bp_location *bl, **blp_tmp;
3106   int val;
3107   struct inferior *inf = find_inferior_pid (pid);
3108
3109   ALL_BP_LOCATIONS (bl, blp_tmp)
3110   {
3111     if (bl->pspace != inf->pspace)
3112       continue;
3113
3114     if (bl->owner->type == bp_dprintf)
3115       continue;
3116
3117     if (bl->inserted)
3118       {
3119         val = remove_breakpoint (bl, mark_uninserted);
3120         if (val != 0)
3121           return val;
3122       }
3123   }
3124   return 0;
3125 }
3126
3127 int
3128 reattach_breakpoints (int pid)
3129 {
3130   struct cleanup *old_chain;
3131   struct bp_location *bl, **blp_tmp;
3132   int val;
3133   struct ui_file *tmp_error_stream;
3134   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3135   struct inferior *inf;
3136   struct thread_info *tp;
3137
3138   tp = any_live_thread_of_process (pid);
3139   if (tp == NULL)
3140     return 1;
3141
3142   inf = find_inferior_pid (pid);
3143   old_chain = save_inferior_ptid ();
3144
3145   inferior_ptid = tp->ptid;
3146
3147   tmp_error_stream = mem_fileopen ();
3148   make_cleanup_ui_file_delete (tmp_error_stream);
3149
3150   ALL_BP_LOCATIONS (bl, blp_tmp)
3151   {
3152     if (bl->pspace != inf->pspace)
3153       continue;
3154
3155     if (bl->inserted)
3156       {
3157         bl->inserted = 0;
3158         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3159         if (val != 0)
3160           {
3161             do_cleanups (old_chain);
3162             return val;
3163           }
3164       }
3165   }
3166   do_cleanups (old_chain);
3167   return 0;
3168 }
3169
3170 static int internal_breakpoint_number = -1;
3171
3172 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3173    If INTERNAL is non-zero, the breakpoint number will be populated
3174    from internal_breakpoint_number and that variable decremented.
3175    Otherwise the breakpoint number will be populated from
3176    breakpoint_count and that value incremented.  Internal breakpoints
3177    do not set the internal var bpnum.  */
3178 static void
3179 set_breakpoint_number (int internal, struct breakpoint *b)
3180 {
3181   if (internal)
3182     b->number = internal_breakpoint_number--;
3183   else
3184     {
3185       set_breakpoint_count (breakpoint_count + 1);
3186       b->number = breakpoint_count;
3187     }
3188 }
3189
3190 static struct breakpoint *
3191 create_internal_breakpoint (struct gdbarch *gdbarch,
3192                             CORE_ADDR address, enum bptype type,
3193                             const struct breakpoint_ops *ops)
3194 {
3195   struct symtab_and_line sal;
3196   struct breakpoint *b;
3197
3198   init_sal (&sal);              /* Initialize to zeroes.  */
3199
3200   sal.pc = address;
3201   sal.section = find_pc_overlay (sal.pc);
3202   sal.pspace = current_program_space;
3203
3204   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3205   b->number = internal_breakpoint_number--;
3206   b->disposition = disp_donttouch;
3207
3208   return b;
3209 }
3210
3211 static const char *const longjmp_names[] =
3212   {
3213     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3214   };
3215 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3216
3217 /* Per-objfile data private to breakpoint.c.  */
3218 struct breakpoint_objfile_data
3219 {
3220   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3221   struct bound_minimal_symbol overlay_msym;
3222
3223   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3224   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3225
3226   /* True if we have looked for longjmp probes.  */
3227   int longjmp_searched;
3228
3229   /* SystemTap probe points for longjmp (if any).  */
3230   VEC (probe_p) *longjmp_probes;
3231
3232   /* Minimal symbol for "std::terminate()" (if any).  */
3233   struct bound_minimal_symbol terminate_msym;
3234
3235   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3236   struct bound_minimal_symbol exception_msym;
3237
3238   /* True if we have looked for exception probes.  */
3239   int exception_searched;
3240
3241   /* SystemTap probe points for unwinding (if any).  */
3242   VEC (probe_p) *exception_probes;
3243 };
3244
3245 static const struct objfile_data *breakpoint_objfile_key;
3246
3247 /* Minimal symbol not found sentinel.  */
3248 static struct minimal_symbol msym_not_found;
3249
3250 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3251
3252 static int
3253 msym_not_found_p (const struct minimal_symbol *msym)
3254 {
3255   return msym == &msym_not_found;
3256 }
3257
3258 /* Return per-objfile data needed by breakpoint.c.
3259    Allocate the data if necessary.  */
3260
3261 static struct breakpoint_objfile_data *
3262 get_breakpoint_objfile_data (struct objfile *objfile)
3263 {
3264   struct breakpoint_objfile_data *bp_objfile_data;
3265
3266   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3267   if (bp_objfile_data == NULL)
3268     {
3269       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3270                                        sizeof (*bp_objfile_data));
3271
3272       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3273       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3274     }
3275   return bp_objfile_data;
3276 }
3277
3278 static void
3279 free_breakpoint_probes (struct objfile *obj, void *data)
3280 {
3281   struct breakpoint_objfile_data *bp_objfile_data = data;
3282
3283   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3284   VEC_free (probe_p, bp_objfile_data->exception_probes);
3285 }
3286
3287 static void
3288 create_overlay_event_breakpoint (void)
3289 {
3290   struct objfile *objfile;
3291   const char *const func_name = "_ovly_debug_event";
3292
3293   ALL_OBJFILES (objfile)
3294     {
3295       struct breakpoint *b;
3296       struct breakpoint_objfile_data *bp_objfile_data;
3297       CORE_ADDR addr;
3298
3299       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3300
3301       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3302         continue;
3303
3304       if (bp_objfile_data->overlay_msym.minsym == NULL)
3305         {
3306           struct bound_minimal_symbol m;
3307
3308           m = lookup_minimal_symbol_text (func_name, objfile);
3309           if (m.minsym == NULL)
3310             {
3311               /* Avoid future lookups in this objfile.  */
3312               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3313               continue;
3314             }
3315           bp_objfile_data->overlay_msym = m;
3316         }
3317
3318       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3319       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3320                                       bp_overlay_event,
3321                                       &internal_breakpoint_ops);
3322       b->addr_string = xstrdup (func_name);
3323
3324       if (overlay_debugging == ovly_auto)
3325         {
3326           b->enable_state = bp_enabled;
3327           overlay_events_enabled = 1;
3328         }
3329       else
3330        {
3331          b->enable_state = bp_disabled;
3332          overlay_events_enabled = 0;
3333        }
3334     }
3335   update_global_location_list (1);
3336 }
3337
3338 static void
3339 create_longjmp_master_breakpoint (void)
3340 {
3341   struct program_space *pspace;
3342   struct cleanup *old_chain;
3343
3344   old_chain = save_current_program_space ();
3345
3346   ALL_PSPACES (pspace)
3347   {
3348     struct objfile *objfile;
3349
3350     set_current_program_space (pspace);
3351
3352     ALL_OBJFILES (objfile)
3353     {
3354       int i;
3355       struct gdbarch *gdbarch;
3356       struct breakpoint_objfile_data *bp_objfile_data;
3357
3358       gdbarch = get_objfile_arch (objfile);
3359
3360       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3361
3362       if (!bp_objfile_data->longjmp_searched)
3363         {
3364           VEC (probe_p) *ret;
3365
3366           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3367           if (ret != NULL)
3368             {
3369               /* We are only interested in checking one element.  */
3370               struct probe *p = VEC_index (probe_p, ret, 0);
3371
3372               if (!can_evaluate_probe_arguments (p))
3373                 {
3374                   /* We cannot use the probe interface here, because it does
3375                      not know how to evaluate arguments.  */
3376                   VEC_free (probe_p, ret);
3377                   ret = NULL;
3378                 }
3379             }
3380           bp_objfile_data->longjmp_probes = ret;
3381           bp_objfile_data->longjmp_searched = 1;
3382         }
3383
3384       if (bp_objfile_data->longjmp_probes != NULL)
3385         {
3386           int i;
3387           struct probe *probe;
3388           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3389
3390           for (i = 0;
3391                VEC_iterate (probe_p,
3392                             bp_objfile_data->longjmp_probes,
3393                             i, probe);
3394                ++i)
3395             {
3396               struct breakpoint *b;
3397
3398               b = create_internal_breakpoint (gdbarch,
3399                                               get_probe_address (probe,
3400                                                                  objfile),
3401                                               bp_longjmp_master,
3402                                               &internal_breakpoint_ops);
3403               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3404               b->enable_state = bp_disabled;
3405             }
3406
3407           continue;
3408         }
3409
3410       if (!gdbarch_get_longjmp_target_p (gdbarch))
3411         continue;
3412
3413       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3414         {
3415           struct breakpoint *b;
3416           const char *func_name;
3417           CORE_ADDR addr;
3418
3419           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3420             continue;
3421
3422           func_name = longjmp_names[i];
3423           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3424             {
3425               struct bound_minimal_symbol m;
3426
3427               m = lookup_minimal_symbol_text (func_name, objfile);
3428               if (m.minsym == NULL)
3429                 {
3430                   /* Prevent future lookups in this objfile.  */
3431                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3432                   continue;
3433                 }
3434               bp_objfile_data->longjmp_msym[i] = m;
3435             }
3436
3437           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3438           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3439                                           &internal_breakpoint_ops);
3440           b->addr_string = xstrdup (func_name);
3441           b->enable_state = bp_disabled;
3442         }
3443     }
3444   }
3445   update_global_location_list (1);
3446
3447   do_cleanups (old_chain);
3448 }
3449
3450 /* Create a master std::terminate breakpoint.  */
3451 static void
3452 create_std_terminate_master_breakpoint (void)
3453 {
3454   struct program_space *pspace;
3455   struct cleanup *old_chain;
3456   const char *const func_name = "std::terminate()";
3457
3458   old_chain = save_current_program_space ();
3459
3460   ALL_PSPACES (pspace)
3461   {
3462     struct objfile *objfile;
3463     CORE_ADDR addr;
3464
3465     set_current_program_space (pspace);
3466
3467     ALL_OBJFILES (objfile)
3468     {
3469       struct breakpoint *b;
3470       struct breakpoint_objfile_data *bp_objfile_data;
3471
3472       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3473
3474       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3475         continue;
3476
3477       if (bp_objfile_data->terminate_msym.minsym == NULL)
3478         {
3479           struct bound_minimal_symbol m;
3480
3481           m = lookup_minimal_symbol (func_name, NULL, objfile);
3482           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3483                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3484             {
3485               /* Prevent future lookups in this objfile.  */
3486               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3487               continue;
3488             }
3489           bp_objfile_data->terminate_msym = m;
3490         }
3491
3492       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3493       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3494                                       bp_std_terminate_master,
3495                                       &internal_breakpoint_ops);
3496       b->addr_string = xstrdup (func_name);
3497       b->enable_state = bp_disabled;
3498     }
3499   }
3500
3501   update_global_location_list (1);
3502
3503   do_cleanups (old_chain);
3504 }
3505
3506 /* Install a master breakpoint on the unwinder's debug hook.  */
3507
3508 static void
3509 create_exception_master_breakpoint (void)
3510 {
3511   struct objfile *objfile;
3512   const char *const func_name = "_Unwind_DebugHook";
3513
3514   ALL_OBJFILES (objfile)
3515     {
3516       struct breakpoint *b;
3517       struct gdbarch *gdbarch;
3518       struct breakpoint_objfile_data *bp_objfile_data;
3519       CORE_ADDR addr;
3520
3521       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3522
3523       /* We prefer the SystemTap probe point if it exists.  */
3524       if (!bp_objfile_data->exception_searched)
3525         {
3526           VEC (probe_p) *ret;
3527
3528           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3529
3530           if (ret != NULL)
3531             {
3532               /* We are only interested in checking one element.  */
3533               struct probe *p = VEC_index (probe_p, ret, 0);
3534
3535               if (!can_evaluate_probe_arguments (p))
3536                 {
3537                   /* We cannot use the probe interface here, because it does
3538                      not know how to evaluate arguments.  */
3539                   VEC_free (probe_p, ret);
3540                   ret = NULL;
3541                 }
3542             }
3543           bp_objfile_data->exception_probes = ret;
3544           bp_objfile_data->exception_searched = 1;
3545         }
3546
3547       if (bp_objfile_data->exception_probes != NULL)
3548         {
3549           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3550           int i;
3551           struct probe *probe;
3552
3553           for (i = 0;
3554                VEC_iterate (probe_p,
3555                             bp_objfile_data->exception_probes,
3556                             i, probe);
3557                ++i)
3558             {
3559               struct breakpoint *b;
3560
3561               b = create_internal_breakpoint (gdbarch,
3562                                               get_probe_address (probe,
3563                                                                  objfile),
3564                                               bp_exception_master,
3565                                               &internal_breakpoint_ops);
3566               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3567               b->enable_state = bp_disabled;
3568             }
3569
3570           continue;
3571         }
3572
3573       /* Otherwise, try the hook function.  */
3574
3575       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3576         continue;
3577
3578       gdbarch = get_objfile_arch (objfile);
3579
3580       if (bp_objfile_data->exception_msym.minsym == NULL)
3581         {
3582           struct bound_minimal_symbol debug_hook;
3583
3584           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3585           if (debug_hook.minsym == NULL)
3586             {
3587               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3588               continue;
3589             }
3590
3591           bp_objfile_data->exception_msym = debug_hook;
3592         }
3593
3594       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3595       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3596                                                  &current_target);
3597       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3598                                       &internal_breakpoint_ops);
3599       b->addr_string = xstrdup (func_name);
3600       b->enable_state = bp_disabled;
3601     }
3602
3603   update_global_location_list (1);
3604 }
3605
3606 void
3607 update_breakpoints_after_exec (void)
3608 {
3609   struct breakpoint *b, *b_tmp;
3610   struct bp_location *bploc, **bplocp_tmp;
3611
3612   /* We're about to delete breakpoints from GDB's lists.  If the
3613      INSERTED flag is true, GDB will try to lift the breakpoints by
3614      writing the breakpoints' "shadow contents" back into memory.  The
3615      "shadow contents" are NOT valid after an exec, so GDB should not
3616      do that.  Instead, the target is responsible from marking
3617      breakpoints out as soon as it detects an exec.  We don't do that
3618      here instead, because there may be other attempts to delete
3619      breakpoints after detecting an exec and before reaching here.  */
3620   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3621     if (bploc->pspace == current_program_space)
3622       gdb_assert (!bploc->inserted);
3623
3624   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3625   {
3626     if (b->pspace != current_program_space)
3627       continue;
3628
3629     /* Solib breakpoints must be explicitly reset after an exec().  */
3630     if (b->type == bp_shlib_event)
3631       {
3632         delete_breakpoint (b);
3633         continue;
3634       }
3635
3636     /* JIT breakpoints must be explicitly reset after an exec().  */
3637     if (b->type == bp_jit_event)
3638       {
3639         delete_breakpoint (b);
3640         continue;
3641       }
3642
3643     /* Thread event breakpoints must be set anew after an exec(),
3644        as must overlay event and longjmp master breakpoints.  */
3645     if (b->type == bp_thread_event || b->type == bp_overlay_event
3646         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3647         || b->type == bp_exception_master)
3648       {
3649         delete_breakpoint (b);
3650         continue;
3651       }
3652
3653     /* Step-resume breakpoints are meaningless after an exec().  */
3654     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3655       {
3656         delete_breakpoint (b);
3657         continue;
3658       }
3659
3660     /* Longjmp and longjmp-resume breakpoints are also meaningless
3661        after an exec.  */
3662     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3663         || b->type == bp_longjmp_call_dummy
3664         || b->type == bp_exception || b->type == bp_exception_resume)
3665       {
3666         delete_breakpoint (b);
3667         continue;
3668       }
3669
3670     if (b->type == bp_catchpoint)
3671       {
3672         /* For now, none of the bp_catchpoint breakpoints need to
3673            do anything at this point.  In the future, if some of
3674            the catchpoints need to something, we will need to add
3675            a new method, and call this method from here.  */
3676         continue;
3677       }
3678
3679     /* bp_finish is a special case.  The only way we ought to be able
3680        to see one of these when an exec() has happened, is if the user
3681        caught a vfork, and then said "finish".  Ordinarily a finish just
3682        carries them to the call-site of the current callee, by setting
3683        a temporary bp there and resuming.  But in this case, the finish
3684        will carry them entirely through the vfork & exec.
3685
3686        We don't want to allow a bp_finish to remain inserted now.  But
3687        we can't safely delete it, 'cause finish_command has a handle to
3688        the bp on a bpstat, and will later want to delete it.  There's a
3689        chance (and I've seen it happen) that if we delete the bp_finish
3690        here, that its storage will get reused by the time finish_command
3691        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3692        We really must allow finish_command to delete a bp_finish.
3693
3694        In the absence of a general solution for the "how do we know
3695        it's safe to delete something others may have handles to?"
3696        problem, what we'll do here is just uninsert the bp_finish, and
3697        let finish_command delete it.
3698
3699        (We know the bp_finish is "doomed" in the sense that it's
3700        momentary, and will be deleted as soon as finish_command sees
3701        the inferior stopped.  So it doesn't matter that the bp's
3702        address is probably bogus in the new a.out, unlike e.g., the
3703        solib breakpoints.)  */
3704
3705     if (b->type == bp_finish)
3706       {
3707         continue;
3708       }
3709
3710     /* Without a symbolic address, we have little hope of the
3711        pre-exec() address meaning the same thing in the post-exec()
3712        a.out.  */
3713     if (b->addr_string == NULL)
3714       {
3715         delete_breakpoint (b);
3716         continue;
3717       }
3718   }
3719   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3720   create_overlay_event_breakpoint ();
3721   create_longjmp_master_breakpoint ();
3722   create_std_terminate_master_breakpoint ();
3723   create_exception_master_breakpoint ();
3724 }
3725
3726 int
3727 detach_breakpoints (ptid_t ptid)
3728 {
3729   struct bp_location *bl, **blp_tmp;
3730   int val = 0;
3731   struct cleanup *old_chain = save_inferior_ptid ();
3732   struct inferior *inf = current_inferior ();
3733
3734   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3735     error (_("Cannot detach breakpoints of inferior_ptid"));
3736
3737   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3738   inferior_ptid = ptid;
3739   ALL_BP_LOCATIONS (bl, blp_tmp)
3740   {
3741     if (bl->pspace != inf->pspace)
3742       continue;
3743
3744     /* This function must physically remove breakpoints locations
3745        from the specified ptid, without modifying the breakpoint
3746        package's state.  Locations of type bp_loc_other are only
3747        maintained at GDB side.  So, there is no need to remove
3748        these bp_loc_other locations.  Moreover, removing these
3749        would modify the breakpoint package's state.  */
3750     if (bl->loc_type == bp_loc_other)
3751       continue;
3752
3753     if (bl->inserted)
3754       val |= remove_breakpoint_1 (bl, mark_inserted);
3755   }
3756
3757   /* Detach single-step breakpoints as well.  */
3758   detach_single_step_breakpoints ();
3759
3760   do_cleanups (old_chain);
3761   return val;
3762 }
3763
3764 /* Remove the breakpoint location BL from the current address space.
3765    Note that this is used to detach breakpoints from a child fork.
3766    When we get here, the child isn't in the inferior list, and neither
3767    do we have objects to represent its address space --- we should
3768    *not* look at bl->pspace->aspace here.  */
3769
3770 static int
3771 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3772 {
3773   int val;
3774
3775   /* BL is never in moribund_locations by our callers.  */
3776   gdb_assert (bl->owner != NULL);
3777
3778   if (bl->owner->enable_state == bp_permanent)
3779     /* Permanent breakpoints cannot be inserted or removed.  */
3780     return 0;
3781
3782   /* The type of none suggests that owner is actually deleted.
3783      This should not ever happen.  */
3784   gdb_assert (bl->owner->type != bp_none);
3785
3786   if (bl->loc_type == bp_loc_software_breakpoint
3787       || bl->loc_type == bp_loc_hardware_breakpoint)
3788     {
3789       /* "Normal" instruction breakpoint: either the standard
3790          trap-instruction bp (bp_breakpoint), or a
3791          bp_hardware_breakpoint.  */
3792
3793       /* First check to see if we have to handle an overlay.  */
3794       if (overlay_debugging == ovly_off
3795           || bl->section == NULL
3796           || !(section_is_overlay (bl->section)))
3797         {
3798           /* No overlay handling: just remove the breakpoint.  */
3799
3800           /* If we're trying to uninsert a memory breakpoint that we
3801              know is set in a dynamic object that is marked
3802              shlib_disabled, then either the dynamic object was
3803              removed with "remove-symbol-file" or with
3804              "nosharedlibrary".  In the former case, we don't know
3805              whether another dynamic object might have loaded over the
3806              breakpoint's address -- the user might well let us know
3807              about it next with add-symbol-file (the whole point of
3808              add-symbol-file is letting the user manually maintain a
3809              list of dynamically loaded objects).  If we have the
3810              breakpoint's shadow memory, that is, this is a software
3811              breakpoint managed by GDB, check whether the breakpoint
3812              is still inserted in memory, to avoid overwriting wrong
3813              code with stale saved shadow contents.  Note that HW
3814              breakpoints don't have shadow memory, as they're
3815              implemented using a mechanism that is not dependent on
3816              being able to modify the target's memory, and as such
3817              they should always be removed.  */
3818           if (bl->shlib_disabled
3819               && bl->target_info.shadow_len != 0
3820               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3821             val = 0;
3822           else
3823             val = bl->owner->ops->remove_location (bl);
3824         }
3825       else
3826         {
3827           /* This breakpoint is in an overlay section.
3828              Did we set a breakpoint at the LMA?  */
3829           if (!overlay_events_enabled)
3830               {
3831                 /* Yes -- overlay event support is not active, so we
3832                    should have set a breakpoint at the LMA.  Remove it.  
3833                 */
3834                 /* Ignore any failures: if the LMA is in ROM, we will
3835                    have already warned when we failed to insert it.  */
3836                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3837                   target_remove_hw_breakpoint (bl->gdbarch,
3838                                                &bl->overlay_target_info);
3839                 else
3840                   target_remove_breakpoint (bl->gdbarch,
3841                                             &bl->overlay_target_info);
3842               }
3843           /* Did we set a breakpoint at the VMA? 
3844              If so, we will have marked the breakpoint 'inserted'.  */
3845           if (bl->inserted)
3846             {
3847               /* Yes -- remove it.  Previously we did not bother to
3848                  remove the breakpoint if the section had been
3849                  unmapped, but let's not rely on that being safe.  We
3850                  don't know what the overlay manager might do.  */
3851
3852               /* However, we should remove *software* breakpoints only
3853                  if the section is still mapped, or else we overwrite
3854                  wrong code with the saved shadow contents.  */
3855               if (bl->loc_type == bp_loc_hardware_breakpoint
3856                   || section_is_mapped (bl->section))
3857                 val = bl->owner->ops->remove_location (bl);
3858               else
3859                 val = 0;
3860             }
3861           else
3862             {
3863               /* No -- not inserted, so no need to remove.  No error.  */
3864               val = 0;
3865             }
3866         }
3867
3868       /* In some cases, we might not be able to remove a breakpoint in
3869          a shared library that has already been removed, but we have
3870          not yet processed the shlib unload event.  Similarly for an
3871          unloaded add-symbol-file object - the user might not yet have
3872          had the chance to remove-symbol-file it.  shlib_disabled will
3873          be set if the library/object has already been removed, but
3874          the breakpoint hasn't been uninserted yet, e.g., after
3875          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3876          always-inserted mode.  */
3877       if (val
3878           && (bl->loc_type == bp_loc_software_breakpoint
3879               && (bl->shlib_disabled
3880                   || solib_name_from_address (bl->pspace, bl->address)
3881                   || shared_objfile_contains_address_p (bl->pspace,
3882                                                         bl->address))))
3883         val = 0;
3884
3885       if (val)
3886         return val;
3887       bl->inserted = (is == mark_inserted);
3888     }
3889   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3890     {
3891       gdb_assert (bl->owner->ops != NULL
3892                   && bl->owner->ops->remove_location != NULL);
3893
3894       bl->inserted = (is == mark_inserted);
3895       bl->owner->ops->remove_location (bl);
3896
3897       /* Failure to remove any of the hardware watchpoints comes here.  */
3898       if ((is == mark_uninserted) && (bl->inserted))
3899         warning (_("Could not remove hardware watchpoint %d."),
3900                  bl->owner->number);
3901     }
3902   else if (bl->owner->type == bp_catchpoint
3903            && breakpoint_enabled (bl->owner)
3904            && !bl->duplicate)
3905     {
3906       gdb_assert (bl->owner->ops != NULL
3907                   && bl->owner->ops->remove_location != NULL);
3908
3909       val = bl->owner->ops->remove_location (bl);
3910       if (val)
3911         return val;
3912
3913       bl->inserted = (is == mark_inserted);
3914     }
3915
3916   return 0;
3917 }
3918
3919 static int
3920 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3921 {
3922   int ret;
3923   struct cleanup *old_chain;
3924
3925   /* BL is never in moribund_locations by our callers.  */
3926   gdb_assert (bl->owner != NULL);
3927
3928   if (bl->owner->enable_state == bp_permanent)
3929     /* Permanent breakpoints cannot be inserted or removed.  */
3930     return 0;
3931
3932   /* The type of none suggests that owner is actually deleted.
3933      This should not ever happen.  */
3934   gdb_assert (bl->owner->type != bp_none);
3935
3936   old_chain = save_current_space_and_thread ();
3937
3938   switch_to_program_space_and_thread (bl->pspace);
3939
3940   ret = remove_breakpoint_1 (bl, is);
3941
3942   do_cleanups (old_chain);
3943   return ret;
3944 }
3945
3946 /* Clear the "inserted" flag in all breakpoints.  */
3947
3948 void
3949 mark_breakpoints_out (void)
3950 {
3951   struct bp_location *bl, **blp_tmp;
3952
3953   ALL_BP_LOCATIONS (bl, blp_tmp)
3954     if (bl->pspace == current_program_space)
3955       bl->inserted = 0;
3956 }
3957
3958 /* Clear the "inserted" flag in all breakpoints and delete any
3959    breakpoints which should go away between runs of the program.
3960
3961    Plus other such housekeeping that has to be done for breakpoints
3962    between runs.
3963
3964    Note: this function gets called at the end of a run (by
3965    generic_mourn_inferior) and when a run begins (by
3966    init_wait_for_inferior).  */
3967
3968
3969
3970 void
3971 breakpoint_init_inferior (enum inf_context context)
3972 {
3973   struct breakpoint *b, *b_tmp;
3974   struct bp_location *bl, **blp_tmp;
3975   int ix;
3976   struct program_space *pspace = current_program_space;
3977
3978   /* If breakpoint locations are shared across processes, then there's
3979      nothing to do.  */
3980   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3981     return;
3982
3983   ALL_BP_LOCATIONS (bl, blp_tmp)
3984   {
3985     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3986     if (bl->pspace == pspace
3987         && bl->owner->enable_state != bp_permanent)
3988       bl->inserted = 0;
3989   }
3990
3991   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3992   {
3993     if (b->loc && b->loc->pspace != pspace)
3994       continue;
3995
3996     switch (b->type)
3997       {
3998       case bp_call_dummy:
3999       case bp_longjmp_call_dummy:
4000
4001         /* If the call dummy breakpoint is at the entry point it will
4002            cause problems when the inferior is rerun, so we better get
4003            rid of it.  */
4004
4005       case bp_watchpoint_scope:
4006
4007         /* Also get rid of scope breakpoints.  */
4008
4009       case bp_shlib_event:
4010
4011         /* Also remove solib event breakpoints.  Their addresses may
4012            have changed since the last time we ran the program.
4013            Actually we may now be debugging against different target;
4014            and so the solib backend that installed this breakpoint may
4015            not be used in by the target.  E.g.,
4016
4017            (gdb) file prog-linux
4018            (gdb) run               # native linux target
4019            ...
4020            (gdb) kill
4021            (gdb) file prog-win.exe
4022            (gdb) tar rem :9999     # remote Windows gdbserver.
4023         */
4024
4025       case bp_step_resume:
4026
4027         /* Also remove step-resume breakpoints.  */
4028
4029         delete_breakpoint (b);
4030         break;
4031
4032       case bp_watchpoint:
4033       case bp_hardware_watchpoint:
4034       case bp_read_watchpoint:
4035       case bp_access_watchpoint:
4036         {
4037           struct watchpoint *w = (struct watchpoint *) b;
4038
4039           /* Likewise for watchpoints on local expressions.  */
4040           if (w->exp_valid_block != NULL)
4041             delete_breakpoint (b);
4042           else if (context == inf_starting)
4043             {
4044               /* Reset val field to force reread of starting value in
4045                  insert_breakpoints.  */
4046               if (w->val)
4047                 value_free (w->val);
4048               w->val = NULL;
4049               w->val_valid = 0;
4050           }
4051         }
4052         break;
4053       default:
4054         break;
4055       }
4056   }
4057
4058   /* Get rid of the moribund locations.  */
4059   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4060     decref_bp_location (&bl);
4061   VEC_free (bp_location_p, moribund_locations);
4062 }
4063
4064 /* These functions concern about actual breakpoints inserted in the
4065    target --- to e.g. check if we need to do decr_pc adjustment or if
4066    we need to hop over the bkpt --- so we check for address space
4067    match, not program space.  */
4068
4069 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4070    exists at PC.  It returns ordinary_breakpoint_here if it's an
4071    ordinary breakpoint, or permanent_breakpoint_here if it's a
4072    permanent breakpoint.
4073    - When continuing from a location with an ordinary breakpoint, we
4074      actually single step once before calling insert_breakpoints.
4075    - When continuing from a location with a permanent breakpoint, we
4076      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4077      the target, to advance the PC past the breakpoint.  */
4078
4079 enum breakpoint_here
4080 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4081 {
4082   struct bp_location *bl, **blp_tmp;
4083   int any_breakpoint_here = 0;
4084
4085   ALL_BP_LOCATIONS (bl, blp_tmp)
4086     {
4087       if (bl->loc_type != bp_loc_software_breakpoint
4088           && bl->loc_type != bp_loc_hardware_breakpoint)
4089         continue;
4090
4091       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4092       if ((breakpoint_enabled (bl->owner)
4093            || bl->owner->enable_state == bp_permanent)
4094           && breakpoint_location_address_match (bl, aspace, pc))
4095         {
4096           if (overlay_debugging 
4097               && section_is_overlay (bl->section)
4098               && !section_is_mapped (bl->section))
4099             continue;           /* unmapped overlay -- can't be a match */
4100           else if (bl->owner->enable_state == bp_permanent)
4101             return permanent_breakpoint_here;
4102           else
4103             any_breakpoint_here = 1;
4104         }
4105     }
4106
4107   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4108 }
4109
4110 /* Return true if there's a moribund breakpoint at PC.  */
4111
4112 int
4113 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4114 {
4115   struct bp_location *loc;
4116   int ix;
4117
4118   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4119     if (breakpoint_location_address_match (loc, aspace, pc))
4120       return 1;
4121
4122   return 0;
4123 }
4124
4125 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4126    inserted using regular breakpoint_chain / bp_location array
4127    mechanism.  This does not check for single-step breakpoints, which
4128    are inserted and removed using direct target manipulation.  */
4129
4130 int
4131 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4132                                     CORE_ADDR pc)
4133 {
4134   struct bp_location *bl, **blp_tmp;
4135
4136   ALL_BP_LOCATIONS (bl, blp_tmp)
4137     {
4138       if (bl->loc_type != bp_loc_software_breakpoint
4139           && bl->loc_type != bp_loc_hardware_breakpoint)
4140         continue;
4141
4142       if (bl->inserted
4143           && breakpoint_location_address_match (bl, aspace, pc))
4144         {
4145           if (overlay_debugging 
4146               && section_is_overlay (bl->section)
4147               && !section_is_mapped (bl->section))
4148             continue;           /* unmapped overlay -- can't be a match */
4149           else
4150             return 1;
4151         }
4152     }
4153   return 0;
4154 }
4155
4156 /* Returns non-zero iff there's either regular breakpoint
4157    or a single step breakpoint inserted at PC.  */
4158
4159 int
4160 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4161 {
4162   if (regular_breakpoint_inserted_here_p (aspace, pc))
4163     return 1;
4164
4165   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4166     return 1;
4167
4168   return 0;
4169 }
4170
4171 /* Ignoring deprecated raw breakpoints, return non-zero iff there is a
4172    software breakpoint inserted at PC.  */
4173
4174 static struct bp_location *
4175 find_non_raw_software_breakpoint_inserted_here (struct address_space *aspace,
4176                                                 CORE_ADDR pc)
4177 {
4178   struct bp_location *bl, **blp_tmp;
4179
4180   ALL_BP_LOCATIONS (bl, blp_tmp)
4181     {
4182       if (bl->loc_type != bp_loc_software_breakpoint)
4183         continue;
4184
4185       if (bl->inserted
4186           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4187                                        aspace, pc))
4188         {
4189           if (overlay_debugging 
4190               && section_is_overlay (bl->section)
4191               && !section_is_mapped (bl->section))
4192             continue;           /* unmapped overlay -- can't be a match */
4193           else
4194             return bl;
4195         }
4196     }
4197
4198   return NULL;
4199 }
4200
4201 /* This function returns non-zero iff there is a software breakpoint
4202    inserted at PC.  */
4203
4204 int
4205 software_breakpoint_inserted_here_p (struct address_space *aspace,
4206                                      CORE_ADDR pc)
4207 {
4208   if (find_non_raw_software_breakpoint_inserted_here (aspace, pc) != NULL)
4209     return 1;
4210
4211   /* Also check for software single-step breakpoints.  */
4212   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4213     return 1;
4214
4215   return 0;
4216 }
4217
4218 int
4219 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4220                                        CORE_ADDR addr, ULONGEST len)
4221 {
4222   struct breakpoint *bpt;
4223
4224   ALL_BREAKPOINTS (bpt)
4225     {
4226       struct bp_location *loc;
4227
4228       if (bpt->type != bp_hardware_watchpoint
4229           && bpt->type != bp_access_watchpoint)
4230         continue;
4231
4232       if (!breakpoint_enabled (bpt))
4233         continue;
4234
4235       for (loc = bpt->loc; loc; loc = loc->next)
4236         if (loc->pspace->aspace == aspace && loc->inserted)
4237           {
4238             CORE_ADDR l, h;
4239
4240             /* Check for intersection.  */
4241             l = max (loc->address, addr);
4242             h = min (loc->address + loc->length, addr + len);
4243             if (l < h)
4244               return 1;
4245           }
4246     }
4247   return 0;
4248 }
4249
4250 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4251    PC is valid for process/thread PTID.  */
4252
4253 int
4254 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4255                          ptid_t ptid)
4256 {
4257   struct bp_location *bl, **blp_tmp;
4258   /* The thread and task IDs associated to PTID, computed lazily.  */
4259   int thread = -1;
4260   int task = 0;
4261   
4262   ALL_BP_LOCATIONS (bl, blp_tmp)
4263     {
4264       if (bl->loc_type != bp_loc_software_breakpoint
4265           && bl->loc_type != bp_loc_hardware_breakpoint)
4266         continue;
4267
4268       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4269       if (!breakpoint_enabled (bl->owner)
4270           && bl->owner->enable_state != bp_permanent)
4271         continue;
4272
4273       if (!breakpoint_location_address_match (bl, aspace, pc))
4274         continue;
4275
4276       if (bl->owner->thread != -1)
4277         {
4278           /* This is a thread-specific breakpoint.  Check that ptid
4279              matches that thread.  If thread hasn't been computed yet,
4280              it is now time to do so.  */
4281           if (thread == -1)
4282             thread = pid_to_thread_id (ptid);
4283           if (bl->owner->thread != thread)
4284             continue;
4285         }
4286
4287       if (bl->owner->task != 0)
4288         {
4289           /* This is a task-specific breakpoint.  Check that ptid
4290              matches that task.  If task hasn't been computed yet,
4291              it is now time to do so.  */
4292           if (task == 0)
4293             task = ada_get_task_number (ptid);
4294           if (bl->owner->task != task)
4295             continue;
4296         }
4297
4298       if (overlay_debugging 
4299           && section_is_overlay (bl->section)
4300           && !section_is_mapped (bl->section))
4301         continue;           /* unmapped overlay -- can't be a match */
4302
4303       return 1;
4304     }
4305
4306   return 0;
4307 }
4308 \f
4309
4310 /* bpstat stuff.  External routines' interfaces are documented
4311    in breakpoint.h.  */
4312
4313 int
4314 is_catchpoint (struct breakpoint *ep)
4315 {
4316   return (ep->type == bp_catchpoint);
4317 }
4318
4319 /* Frees any storage that is part of a bpstat.  Does not walk the
4320    'next' chain.  */
4321
4322 static void
4323 bpstat_free (bpstat bs)
4324 {
4325   if (bs->old_val != NULL)
4326     value_free (bs->old_val);
4327   decref_counted_command_line (&bs->commands);
4328   decref_bp_location (&bs->bp_location_at);
4329   xfree (bs);
4330 }
4331
4332 /* Clear a bpstat so that it says we are not at any breakpoint.
4333    Also free any storage that is part of a bpstat.  */
4334
4335 void
4336 bpstat_clear (bpstat *bsp)
4337 {
4338   bpstat p;
4339   bpstat q;
4340
4341   if (bsp == 0)
4342     return;
4343   p = *bsp;
4344   while (p != NULL)
4345     {
4346       q = p->next;
4347       bpstat_free (p);
4348       p = q;
4349     }
4350   *bsp = NULL;
4351 }
4352
4353 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4354    is part of the bpstat is copied as well.  */
4355
4356 bpstat
4357 bpstat_copy (bpstat bs)
4358 {
4359   bpstat p = NULL;
4360   bpstat tmp;
4361   bpstat retval = NULL;
4362
4363   if (bs == NULL)
4364     return bs;
4365
4366   for (; bs != NULL; bs = bs->next)
4367     {
4368       tmp = (bpstat) xmalloc (sizeof (*tmp));
4369       memcpy (tmp, bs, sizeof (*tmp));
4370       incref_counted_command_line (tmp->commands);
4371       incref_bp_location (tmp->bp_location_at);
4372       if (bs->old_val != NULL)
4373         {
4374           tmp->old_val = value_copy (bs->old_val);
4375           release_value (tmp->old_val);
4376         }
4377
4378       if (p == NULL)
4379         /* This is the first thing in the chain.  */
4380         retval = tmp;
4381       else
4382         p->next = tmp;
4383       p = tmp;
4384     }
4385   p->next = NULL;
4386   return retval;
4387 }
4388
4389 /* Find the bpstat associated with this breakpoint.  */
4390
4391 bpstat
4392 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4393 {
4394   if (bsp == NULL)
4395     return NULL;
4396
4397   for (; bsp != NULL; bsp = bsp->next)
4398     {
4399       if (bsp->breakpoint_at == breakpoint)
4400         return bsp;
4401     }
4402   return NULL;
4403 }
4404
4405 /* See breakpoint.h.  */
4406
4407 int
4408 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4409 {
4410   for (; bsp != NULL; bsp = bsp->next)
4411     {
4412       if (bsp->breakpoint_at == NULL)
4413         {
4414           /* A moribund location can never explain a signal other than
4415              GDB_SIGNAL_TRAP.  */
4416           if (sig == GDB_SIGNAL_TRAP)
4417             return 1;
4418         }
4419       else
4420         {
4421           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4422                                                         sig))
4423             return 1;
4424         }
4425     }
4426
4427   return 0;
4428 }
4429
4430 /* Put in *NUM the breakpoint number of the first breakpoint we are
4431    stopped at.  *BSP upon return is a bpstat which points to the
4432    remaining breakpoints stopped at (but which is not guaranteed to be
4433    good for anything but further calls to bpstat_num).
4434
4435    Return 0 if passed a bpstat which does not indicate any breakpoints.
4436    Return -1 if stopped at a breakpoint that has been deleted since
4437    we set it.
4438    Return 1 otherwise.  */
4439
4440 int
4441 bpstat_num (bpstat *bsp, int *num)
4442 {
4443   struct breakpoint *b;
4444
4445   if ((*bsp) == NULL)
4446     return 0;                   /* No more breakpoint values */
4447
4448   /* We assume we'll never have several bpstats that correspond to a
4449      single breakpoint -- otherwise, this function might return the
4450      same number more than once and this will look ugly.  */
4451   b = (*bsp)->breakpoint_at;
4452   *bsp = (*bsp)->next;
4453   if (b == NULL)
4454     return -1;                  /* breakpoint that's been deleted since */
4455
4456   *num = b->number;             /* We have its number */
4457   return 1;
4458 }
4459
4460 /* See breakpoint.h.  */
4461
4462 void
4463 bpstat_clear_actions (void)
4464 {
4465   struct thread_info *tp;
4466   bpstat bs;
4467
4468   if (ptid_equal (inferior_ptid, null_ptid))
4469     return;
4470
4471   tp = find_thread_ptid (inferior_ptid);
4472   if (tp == NULL)
4473     return;
4474
4475   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4476     {
4477       decref_counted_command_line (&bs->commands);
4478
4479       if (bs->old_val != NULL)
4480         {
4481           value_free (bs->old_val);
4482           bs->old_val = NULL;
4483         }
4484     }
4485 }
4486
4487 /* Called when a command is about to proceed the inferior.  */
4488
4489 static void
4490 breakpoint_about_to_proceed (void)
4491 {
4492   if (!ptid_equal (inferior_ptid, null_ptid))
4493     {
4494       struct thread_info *tp = inferior_thread ();
4495
4496       /* Allow inferior function calls in breakpoint commands to not
4497          interrupt the command list.  When the call finishes
4498          successfully, the inferior will be standing at the same
4499          breakpoint as if nothing happened.  */
4500       if (tp->control.in_infcall)
4501         return;
4502     }
4503
4504   breakpoint_proceeded = 1;
4505 }
4506
4507 /* Stub for cleaning up our state if we error-out of a breakpoint
4508    command.  */
4509 static void
4510 cleanup_executing_breakpoints (void *ignore)
4511 {
4512   executing_breakpoint_commands = 0;
4513 }
4514
4515 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4516    or its equivalent.  */
4517
4518 static int
4519 command_line_is_silent (struct command_line *cmd)
4520 {
4521   return cmd && (strcmp ("silent", cmd->line) == 0
4522                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4523 }
4524
4525 /* Execute all the commands associated with all the breakpoints at
4526    this location.  Any of these commands could cause the process to
4527    proceed beyond this point, etc.  We look out for such changes by
4528    checking the global "breakpoint_proceeded" after each command.
4529
4530    Returns true if a breakpoint command resumed the inferior.  In that
4531    case, it is the caller's responsibility to recall it again with the
4532    bpstat of the current thread.  */
4533
4534 static int
4535 bpstat_do_actions_1 (bpstat *bsp)
4536 {
4537   bpstat bs;
4538   struct cleanup *old_chain;
4539   int again = 0;
4540
4541   /* Avoid endless recursion if a `source' command is contained
4542      in bs->commands.  */
4543   if (executing_breakpoint_commands)
4544     return 0;
4545
4546   executing_breakpoint_commands = 1;
4547   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4548
4549   prevent_dont_repeat ();
4550
4551   /* This pointer will iterate over the list of bpstat's.  */
4552   bs = *bsp;
4553
4554   breakpoint_proceeded = 0;
4555   for (; bs != NULL; bs = bs->next)
4556     {
4557       struct counted_command_line *ccmd;
4558       struct command_line *cmd;
4559       struct cleanup *this_cmd_tree_chain;
4560
4561       /* Take ownership of the BSP's command tree, if it has one.
4562
4563          The command tree could legitimately contain commands like
4564          'step' and 'next', which call clear_proceed_status, which
4565          frees stop_bpstat's command tree.  To make sure this doesn't
4566          free the tree we're executing out from under us, we need to
4567          take ownership of the tree ourselves.  Since a given bpstat's
4568          commands are only executed once, we don't need to copy it; we
4569          can clear the pointer in the bpstat, and make sure we free
4570          the tree when we're done.  */
4571       ccmd = bs->commands;
4572       bs->commands = NULL;
4573       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4574       cmd = ccmd ? ccmd->commands : NULL;
4575       if (command_line_is_silent (cmd))
4576         {
4577           /* The action has been already done by bpstat_stop_status.  */
4578           cmd = cmd->next;
4579         }
4580
4581       while (cmd != NULL)
4582         {
4583           execute_control_command (cmd);
4584
4585           if (breakpoint_proceeded)
4586             break;
4587           else
4588             cmd = cmd->next;
4589         }
4590
4591       /* We can free this command tree now.  */
4592       do_cleanups (this_cmd_tree_chain);
4593
4594       if (breakpoint_proceeded)
4595         {
4596           if (target_can_async_p ())
4597             /* If we are in async mode, then the target might be still
4598                running, not stopped at any breakpoint, so nothing for
4599                us to do here -- just return to the event loop.  */
4600             ;
4601           else
4602             /* In sync mode, when execute_control_command returns
4603                we're already standing on the next breakpoint.
4604                Breakpoint commands for that stop were not run, since
4605                execute_command does not run breakpoint commands --
4606                only command_line_handler does, but that one is not
4607                involved in execution of breakpoint commands.  So, we
4608                can now execute breakpoint commands.  It should be
4609                noted that making execute_command do bpstat actions is
4610                not an option -- in this case we'll have recursive
4611                invocation of bpstat for each breakpoint with a
4612                command, and can easily blow up GDB stack.  Instead, we
4613                return true, which will trigger the caller to recall us
4614                with the new stop_bpstat.  */
4615             again = 1;
4616           break;
4617         }
4618     }
4619   do_cleanups (old_chain);
4620   return again;
4621 }
4622
4623 void
4624 bpstat_do_actions (void)
4625 {
4626   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4627
4628   /* Do any commands attached to breakpoint we are stopped at.  */
4629   while (!ptid_equal (inferior_ptid, null_ptid)
4630          && target_has_execution
4631          && !is_exited (inferior_ptid)
4632          && !is_executing (inferior_ptid))
4633     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4634        and only return when it is stopped at the next breakpoint, we
4635        keep doing breakpoint actions until it returns false to
4636        indicate the inferior was not resumed.  */
4637     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4638       break;
4639
4640   discard_cleanups (cleanup_if_error);
4641 }
4642
4643 /* Print out the (old or new) value associated with a watchpoint.  */
4644
4645 static void
4646 watchpoint_value_print (struct value *val, struct ui_file *stream)
4647 {
4648   if (val == NULL)
4649     fprintf_unfiltered (stream, _("<unreadable>"));
4650   else
4651     {
4652       struct value_print_options opts;
4653       get_user_print_options (&opts);
4654       value_print (val, stream, &opts);
4655     }
4656 }
4657
4658 /* Generic routine for printing messages indicating why we
4659    stopped.  The behavior of this function depends on the value
4660    'print_it' in the bpstat structure.  Under some circumstances we
4661    may decide not to print anything here and delegate the task to
4662    normal_stop().  */
4663
4664 static enum print_stop_action
4665 print_bp_stop_message (bpstat bs)
4666 {
4667   switch (bs->print_it)
4668     {
4669     case print_it_noop:
4670       /* Nothing should be printed for this bpstat entry.  */
4671       return PRINT_UNKNOWN;
4672       break;
4673
4674     case print_it_done:
4675       /* We still want to print the frame, but we already printed the
4676          relevant messages.  */
4677       return PRINT_SRC_AND_LOC;
4678       break;
4679
4680     case print_it_normal:
4681       {
4682         struct breakpoint *b = bs->breakpoint_at;
4683
4684         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4685            which has since been deleted.  */
4686         if (b == NULL)
4687           return PRINT_UNKNOWN;
4688
4689         /* Normal case.  Call the breakpoint's print_it method.  */
4690         return b->ops->print_it (bs);
4691       }
4692       break;
4693
4694     default:
4695       internal_error (__FILE__, __LINE__,
4696                       _("print_bp_stop_message: unrecognized enum value"));
4697       break;
4698     }
4699 }
4700
4701 /* A helper function that prints a shared library stopped event.  */
4702
4703 static void
4704 print_solib_event (int is_catchpoint)
4705 {
4706   int any_deleted
4707     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4708   int any_added
4709     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4710
4711   if (!is_catchpoint)
4712     {
4713       if (any_added || any_deleted)
4714         ui_out_text (current_uiout,
4715                      _("Stopped due to shared library event:\n"));
4716       else
4717         ui_out_text (current_uiout,
4718                      _("Stopped due to shared library event (no "
4719                        "libraries added or removed)\n"));
4720     }
4721
4722   if (ui_out_is_mi_like_p (current_uiout))
4723     ui_out_field_string (current_uiout, "reason",
4724                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4725
4726   if (any_deleted)
4727     {
4728       struct cleanup *cleanup;
4729       char *name;
4730       int ix;
4731
4732       ui_out_text (current_uiout, _("  Inferior unloaded "));
4733       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4734                                                     "removed");
4735       for (ix = 0;
4736            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4737                         ix, name);
4738            ++ix)
4739         {
4740           if (ix > 0)
4741             ui_out_text (current_uiout, "    ");
4742           ui_out_field_string (current_uiout, "library", name);
4743           ui_out_text (current_uiout, "\n");
4744         }
4745
4746       do_cleanups (cleanup);
4747     }
4748
4749   if (any_added)
4750     {
4751       struct so_list *iter;
4752       int ix;
4753       struct cleanup *cleanup;
4754
4755       ui_out_text (current_uiout, _("  Inferior loaded "));
4756       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4757                                                     "added");
4758       for (ix = 0;
4759            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4760                         ix, iter);
4761            ++ix)
4762         {
4763           if (ix > 0)
4764             ui_out_text (current_uiout, "    ");
4765           ui_out_field_string (current_uiout, "library", iter->so_name);
4766           ui_out_text (current_uiout, "\n");
4767         }
4768
4769       do_cleanups (cleanup);
4770     }
4771 }
4772
4773 /* Print a message indicating what happened.  This is called from
4774    normal_stop().  The input to this routine is the head of the bpstat
4775    list - a list of the eventpoints that caused this stop.  KIND is
4776    the target_waitkind for the stopping event.  This
4777    routine calls the generic print routine for printing a message
4778    about reasons for stopping.  This will print (for example) the
4779    "Breakpoint n," part of the output.  The return value of this
4780    routine is one of:
4781
4782    PRINT_UNKNOWN: Means we printed nothing.
4783    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4784    code to print the location.  An example is 
4785    "Breakpoint 1, " which should be followed by
4786    the location.
4787    PRINT_SRC_ONLY: Means we printed something, but there is no need
4788    to also print the location part of the message.
4789    An example is the catch/throw messages, which
4790    don't require a location appended to the end.
4791    PRINT_NOTHING: We have done some printing and we don't need any 
4792    further info to be printed.  */
4793
4794 enum print_stop_action
4795 bpstat_print (bpstat bs, int kind)
4796 {
4797   int val;
4798
4799   /* Maybe another breakpoint in the chain caused us to stop.
4800      (Currently all watchpoints go on the bpstat whether hit or not.
4801      That probably could (should) be changed, provided care is taken
4802      with respect to bpstat_explains_signal).  */
4803   for (; bs; bs = bs->next)
4804     {
4805       val = print_bp_stop_message (bs);
4806       if (val == PRINT_SRC_ONLY 
4807           || val == PRINT_SRC_AND_LOC 
4808           || val == PRINT_NOTHING)
4809         return val;
4810     }
4811
4812   /* If we had hit a shared library event breakpoint,
4813      print_bp_stop_message would print out this message.  If we hit an
4814      OS-level shared library event, do the same thing.  */
4815   if (kind == TARGET_WAITKIND_LOADED)
4816     {
4817       print_solib_event (0);
4818       return PRINT_NOTHING;
4819     }
4820
4821   /* We reached the end of the chain, or we got a null BS to start
4822      with and nothing was printed.  */
4823   return PRINT_UNKNOWN;
4824 }
4825
4826 /* Evaluate the expression EXP and return 1 if value is zero.
4827    This returns the inverse of the condition because it is called
4828    from catch_errors which returns 0 if an exception happened, and if an
4829    exception happens we want execution to stop.
4830    The argument is a "struct expression *" that has been cast to a
4831    "void *" to make it pass through catch_errors.  */
4832
4833 static int
4834 breakpoint_cond_eval (void *exp)
4835 {
4836   struct value *mark = value_mark ();
4837   int i = !value_true (evaluate_expression ((struct expression *) exp));
4838
4839   value_free_to_mark (mark);
4840   return i;
4841 }
4842
4843 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4844
4845 static bpstat
4846 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4847 {
4848   bpstat bs;
4849
4850   bs = (bpstat) xmalloc (sizeof (*bs));
4851   bs->next = NULL;
4852   **bs_link_pointer = bs;
4853   *bs_link_pointer = &bs->next;
4854   bs->breakpoint_at = bl->owner;
4855   bs->bp_location_at = bl;
4856   incref_bp_location (bl);
4857   /* If the condition is false, etc., don't do the commands.  */
4858   bs->commands = NULL;
4859   bs->old_val = NULL;
4860   bs->print_it = print_it_normal;
4861   return bs;
4862 }
4863 \f
4864 /* The target has stopped with waitstatus WS.  Check if any hardware
4865    watchpoints have triggered, according to the target.  */
4866
4867 int
4868 watchpoints_triggered (struct target_waitstatus *ws)
4869 {
4870   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4871   CORE_ADDR addr;
4872   struct breakpoint *b;
4873
4874   if (!stopped_by_watchpoint)
4875     {
4876       /* We were not stopped by a watchpoint.  Mark all watchpoints
4877          as not triggered.  */
4878       ALL_BREAKPOINTS (b)
4879         if (is_hardware_watchpoint (b))
4880           {
4881             struct watchpoint *w = (struct watchpoint *) b;
4882
4883             w->watchpoint_triggered = watch_triggered_no;
4884           }
4885
4886       return 0;
4887     }
4888
4889   if (!target_stopped_data_address (&current_target, &addr))
4890     {
4891       /* We were stopped by a watchpoint, but we don't know where.
4892          Mark all watchpoints as unknown.  */
4893       ALL_BREAKPOINTS (b)
4894         if (is_hardware_watchpoint (b))
4895           {
4896             struct watchpoint *w = (struct watchpoint *) b;
4897
4898             w->watchpoint_triggered = watch_triggered_unknown;
4899           }
4900
4901       return 1;
4902     }
4903
4904   /* The target could report the data address.  Mark watchpoints
4905      affected by this data address as triggered, and all others as not
4906      triggered.  */
4907
4908   ALL_BREAKPOINTS (b)
4909     if (is_hardware_watchpoint (b))
4910       {
4911         struct watchpoint *w = (struct watchpoint *) b;
4912         struct bp_location *loc;
4913
4914         w->watchpoint_triggered = watch_triggered_no;
4915         for (loc = b->loc; loc; loc = loc->next)
4916           {
4917             if (is_masked_watchpoint (b))
4918               {
4919                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4920                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4921
4922                 if (newaddr == start)
4923                   {
4924                     w->watchpoint_triggered = watch_triggered_yes;
4925                     break;
4926                   }
4927               }
4928             /* Exact match not required.  Within range is sufficient.  */
4929             else if (target_watchpoint_addr_within_range (&current_target,
4930                                                          addr, loc->address,
4931                                                          loc->length))
4932               {
4933                 w->watchpoint_triggered = watch_triggered_yes;
4934                 break;
4935               }
4936           }
4937       }
4938
4939   return 1;
4940 }
4941
4942 /* Possible return values for watchpoint_check (this can't be an enum
4943    because of check_errors).  */
4944 /* The watchpoint has been deleted.  */
4945 #define WP_DELETED 1
4946 /* The value has changed.  */
4947 #define WP_VALUE_CHANGED 2
4948 /* The value has not changed.  */
4949 #define WP_VALUE_NOT_CHANGED 3
4950 /* Ignore this watchpoint, no matter if the value changed or not.  */
4951 #define WP_IGNORE 4
4952
4953 #define BP_TEMPFLAG 1
4954 #define BP_HARDWAREFLAG 2
4955
4956 /* Evaluate watchpoint condition expression and check if its value
4957    changed.
4958
4959    P should be a pointer to struct bpstat, but is defined as a void *
4960    in order for this function to be usable with catch_errors.  */
4961
4962 static int
4963 watchpoint_check (void *p)
4964 {
4965   bpstat bs = (bpstat) p;
4966   struct watchpoint *b;
4967   struct frame_info *fr;
4968   int within_current_scope;
4969
4970   /* BS is built from an existing struct breakpoint.  */
4971   gdb_assert (bs->breakpoint_at != NULL);
4972   b = (struct watchpoint *) bs->breakpoint_at;
4973
4974   /* If this is a local watchpoint, we only want to check if the
4975      watchpoint frame is in scope if the current thread is the thread
4976      that was used to create the watchpoint.  */
4977   if (!watchpoint_in_thread_scope (b))
4978     return WP_IGNORE;
4979
4980   if (b->exp_valid_block == NULL)
4981     within_current_scope = 1;
4982   else
4983     {
4984       struct frame_info *frame = get_current_frame ();
4985       struct gdbarch *frame_arch = get_frame_arch (frame);
4986       CORE_ADDR frame_pc = get_frame_pc (frame);
4987
4988       /* in_function_epilogue_p() returns a non-zero value if we're
4989          still in the function but the stack frame has already been
4990          invalidated.  Since we can't rely on the values of local
4991          variables after the stack has been destroyed, we are treating
4992          the watchpoint in that state as `not changed' without further
4993          checking.  Don't mark watchpoints as changed if the current
4994          frame is in an epilogue - even if they are in some other
4995          frame, our view of the stack is likely to be wrong and
4996          frame_find_by_id could error out.  */
4997       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4998         return WP_IGNORE;
4999
5000       fr = frame_find_by_id (b->watchpoint_frame);
5001       within_current_scope = (fr != NULL);
5002
5003       /* If we've gotten confused in the unwinder, we might have
5004          returned a frame that can't describe this variable.  */
5005       if (within_current_scope)
5006         {
5007           struct symbol *function;
5008
5009           function = get_frame_function (fr);
5010           if (function == NULL
5011               || !contained_in (b->exp_valid_block,
5012                                 SYMBOL_BLOCK_VALUE (function)))
5013             within_current_scope = 0;
5014         }
5015
5016       if (within_current_scope)
5017         /* If we end up stopping, the current frame will get selected
5018            in normal_stop.  So this call to select_frame won't affect
5019            the user.  */
5020         select_frame (fr);
5021     }
5022
5023   if (within_current_scope)
5024     {
5025       /* We use value_{,free_to_}mark because it could be a *long*
5026          time before we return to the command level and call
5027          free_all_values.  We can't call free_all_values because we
5028          might be in the middle of evaluating a function call.  */
5029
5030       int pc = 0;
5031       struct value *mark;
5032       struct value *new_val;
5033
5034       if (is_masked_watchpoint (&b->base))
5035         /* Since we don't know the exact trigger address (from
5036            stopped_data_address), just tell the user we've triggered
5037            a mask watchpoint.  */
5038         return WP_VALUE_CHANGED;
5039
5040       mark = value_mark ();
5041       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5042
5043       /* We use value_equal_contents instead of value_equal because
5044          the latter coerces an array to a pointer, thus comparing just
5045          the address of the array instead of its contents.  This is
5046          not what we want.  */
5047       if ((b->val != NULL) != (new_val != NULL)
5048           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5049         {
5050           if (new_val != NULL)
5051             {
5052               release_value (new_val);
5053               value_free_to_mark (mark);
5054             }
5055           bs->old_val = b->val;
5056           b->val = new_val;
5057           b->val_valid = 1;
5058           return WP_VALUE_CHANGED;
5059         }
5060       else
5061         {
5062           /* Nothing changed.  */
5063           value_free_to_mark (mark);
5064           return WP_VALUE_NOT_CHANGED;
5065         }
5066     }
5067   else
5068     {
5069       struct ui_out *uiout = current_uiout;
5070
5071       /* This seems like the only logical thing to do because
5072          if we temporarily ignored the watchpoint, then when
5073          we reenter the block in which it is valid it contains
5074          garbage (in the case of a function, it may have two
5075          garbage values, one before and one after the prologue).
5076          So we can't even detect the first assignment to it and
5077          watch after that (since the garbage may or may not equal
5078          the first value assigned).  */
5079       /* We print all the stop information in
5080          breakpoint_ops->print_it, but in this case, by the time we
5081          call breakpoint_ops->print_it this bp will be deleted
5082          already.  So we have no choice but print the information
5083          here.  */
5084       if (ui_out_is_mi_like_p (uiout))
5085         ui_out_field_string
5086           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5087       ui_out_text (uiout, "\nWatchpoint ");
5088       ui_out_field_int (uiout, "wpnum", b->base.number);
5089       ui_out_text (uiout,
5090                    " deleted because the program has left the block in\n\
5091 which its expression is valid.\n");     
5092
5093       /* Make sure the watchpoint's commands aren't executed.  */
5094       decref_counted_command_line (&b->base.commands);
5095       watchpoint_del_at_next_stop (b);
5096
5097       return WP_DELETED;
5098     }
5099 }
5100
5101 /* Return true if it looks like target has stopped due to hitting
5102    breakpoint location BL.  This function does not check if we should
5103    stop, only if BL explains the stop.  */
5104
5105 static int
5106 bpstat_check_location (const struct bp_location *bl,
5107                        struct address_space *aspace, CORE_ADDR bp_addr,
5108                        const struct target_waitstatus *ws)
5109 {
5110   struct breakpoint *b = bl->owner;
5111
5112   /* BL is from an existing breakpoint.  */
5113   gdb_assert (b != NULL);
5114
5115   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5116 }
5117
5118 /* Determine if the watched values have actually changed, and we
5119    should stop.  If not, set BS->stop to 0.  */
5120
5121 static void
5122 bpstat_check_watchpoint (bpstat bs)
5123 {
5124   const struct bp_location *bl;
5125   struct watchpoint *b;
5126
5127   /* BS is built for existing struct breakpoint.  */
5128   bl = bs->bp_location_at;
5129   gdb_assert (bl != NULL);
5130   b = (struct watchpoint *) bs->breakpoint_at;
5131   gdb_assert (b != NULL);
5132
5133     {
5134       int must_check_value = 0;
5135       
5136       if (b->base.type == bp_watchpoint)
5137         /* For a software watchpoint, we must always check the
5138            watched value.  */
5139         must_check_value = 1;
5140       else if (b->watchpoint_triggered == watch_triggered_yes)
5141         /* We have a hardware watchpoint (read, write, or access)
5142            and the target earlier reported an address watched by
5143            this watchpoint.  */
5144         must_check_value = 1;
5145       else if (b->watchpoint_triggered == watch_triggered_unknown
5146                && b->base.type == bp_hardware_watchpoint)
5147         /* We were stopped by a hardware watchpoint, but the target could
5148            not report the data address.  We must check the watchpoint's
5149            value.  Access and read watchpoints are out of luck; without
5150            a data address, we can't figure it out.  */
5151         must_check_value = 1;
5152
5153       if (must_check_value)
5154         {
5155           char *message
5156             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5157                           b->base.number);
5158           struct cleanup *cleanups = make_cleanup (xfree, message);
5159           int e = catch_errors (watchpoint_check, bs, message,
5160                                 RETURN_MASK_ALL);
5161           do_cleanups (cleanups);
5162           switch (e)
5163             {
5164             case WP_DELETED:
5165               /* We've already printed what needs to be printed.  */
5166               bs->print_it = print_it_done;
5167               /* Stop.  */
5168               break;
5169             case WP_IGNORE:
5170               bs->print_it = print_it_noop;
5171               bs->stop = 0;
5172               break;
5173             case WP_VALUE_CHANGED:
5174               if (b->base.type == bp_read_watchpoint)
5175                 {
5176                   /* There are two cases to consider here:
5177
5178                      1. We're watching the triggered memory for reads.
5179                      In that case, trust the target, and always report
5180                      the watchpoint hit to the user.  Even though
5181                      reads don't cause value changes, the value may
5182                      have changed since the last time it was read, and
5183                      since we're not trapping writes, we will not see
5184                      those, and as such we should ignore our notion of
5185                      old value.
5186
5187                      2. We're watching the triggered memory for both
5188                      reads and writes.  There are two ways this may
5189                      happen:
5190
5191                      2.1. This is a target that can't break on data
5192                      reads only, but can break on accesses (reads or
5193                      writes), such as e.g., x86.  We detect this case
5194                      at the time we try to insert read watchpoints.
5195
5196                      2.2. Otherwise, the target supports read
5197                      watchpoints, but, the user set an access or write
5198                      watchpoint watching the same memory as this read
5199                      watchpoint.
5200
5201                      If we're watching memory writes as well as reads,
5202                      ignore watchpoint hits when we find that the
5203                      value hasn't changed, as reads don't cause
5204                      changes.  This still gives false positives when
5205                      the program writes the same value to memory as
5206                      what there was already in memory (we will confuse
5207                      it for a read), but it's much better than
5208                      nothing.  */
5209
5210                   int other_write_watchpoint = 0;
5211
5212                   if (bl->watchpoint_type == hw_read)
5213                     {
5214                       struct breakpoint *other_b;
5215
5216                       ALL_BREAKPOINTS (other_b)
5217                         if (other_b->type == bp_hardware_watchpoint
5218                             || other_b->type == bp_access_watchpoint)
5219                           {
5220                             struct watchpoint *other_w =
5221                               (struct watchpoint *) other_b;
5222
5223                             if (other_w->watchpoint_triggered
5224                                 == watch_triggered_yes)
5225                               {
5226                                 other_write_watchpoint = 1;
5227                                 break;
5228                               }
5229                           }
5230                     }
5231
5232                   if (other_write_watchpoint
5233                       || bl->watchpoint_type == hw_access)
5234                     {
5235                       /* We're watching the same memory for writes,
5236                          and the value changed since the last time we
5237                          updated it, so this trap must be for a write.
5238                          Ignore it.  */
5239                       bs->print_it = print_it_noop;
5240                       bs->stop = 0;
5241                     }
5242                 }
5243               break;
5244             case WP_VALUE_NOT_CHANGED:
5245               if (b->base.type == bp_hardware_watchpoint
5246                   || b->base.type == bp_watchpoint)
5247                 {
5248                   /* Don't stop: write watchpoints shouldn't fire if
5249                      the value hasn't changed.  */
5250                   bs->print_it = print_it_noop;
5251                   bs->stop = 0;
5252                 }
5253               /* Stop.  */
5254               break;
5255             default:
5256               /* Can't happen.  */
5257             case 0:
5258               /* Error from catch_errors.  */
5259               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5260               watchpoint_del_at_next_stop (b);
5261               /* We've already printed what needs to be printed.  */
5262               bs->print_it = print_it_done;
5263               break;
5264             }
5265         }
5266       else      /* must_check_value == 0 */
5267         {
5268           /* This is a case where some watchpoint(s) triggered, but
5269              not at the address of this watchpoint, or else no
5270              watchpoint triggered after all.  So don't print
5271              anything for this watchpoint.  */
5272           bs->print_it = print_it_noop;
5273           bs->stop = 0;
5274         }
5275     }
5276 }
5277
5278 /* For breakpoints that are currently marked as telling gdb to stop,
5279    check conditions (condition proper, frame, thread and ignore count)
5280    of breakpoint referred to by BS.  If we should not stop for this
5281    breakpoint, set BS->stop to 0.  */
5282
5283 static void
5284 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5285 {
5286   const struct bp_location *bl;
5287   struct breakpoint *b;
5288   int value_is_zero = 0;
5289   struct expression *cond;
5290
5291   gdb_assert (bs->stop);
5292
5293   /* BS is built for existing struct breakpoint.  */
5294   bl = bs->bp_location_at;
5295   gdb_assert (bl != NULL);
5296   b = bs->breakpoint_at;
5297   gdb_assert (b != NULL);
5298
5299   /* Even if the target evaluated the condition on its end and notified GDB, we
5300      need to do so again since GDB does not know if we stopped due to a
5301      breakpoint or a single step breakpoint.  */
5302
5303   if (frame_id_p (b->frame_id)
5304       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5305     {
5306       bs->stop = 0;
5307       return;
5308     }
5309
5310   /* If this is a thread/task-specific breakpoint, don't waste cpu
5311      evaluating the condition if this isn't the specified
5312      thread/task.  */
5313   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5314       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5315
5316     {
5317       bs->stop = 0;
5318       return;
5319     }
5320
5321   /* Evaluate extension language breakpoints that have a "stop" method
5322      implemented.  */
5323   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5324
5325   if (is_watchpoint (b))
5326     {
5327       struct watchpoint *w = (struct watchpoint *) b;
5328
5329       cond = w->cond_exp;
5330     }
5331   else
5332     cond = bl->cond;
5333
5334   if (cond && b->disposition != disp_del_at_next_stop)
5335     {
5336       int within_current_scope = 1;
5337       struct watchpoint * w;
5338
5339       /* We use value_mark and value_free_to_mark because it could
5340          be a long time before we return to the command level and
5341          call free_all_values.  We can't call free_all_values
5342          because we might be in the middle of evaluating a
5343          function call.  */
5344       struct value *mark = value_mark ();
5345
5346       if (is_watchpoint (b))
5347         w = (struct watchpoint *) b;
5348       else
5349         w = NULL;
5350
5351       /* Need to select the frame, with all that implies so that
5352          the conditions will have the right context.  Because we
5353          use the frame, we will not see an inlined function's
5354          variables when we arrive at a breakpoint at the start
5355          of the inlined function; the current frame will be the
5356          call site.  */
5357       if (w == NULL || w->cond_exp_valid_block == NULL)
5358         select_frame (get_current_frame ());
5359       else
5360         {
5361           struct frame_info *frame;
5362
5363           /* For local watchpoint expressions, which particular
5364              instance of a local is being watched matters, so we
5365              keep track of the frame to evaluate the expression
5366              in.  To evaluate the condition however, it doesn't
5367              really matter which instantiation of the function
5368              where the condition makes sense triggers the
5369              watchpoint.  This allows an expression like "watch
5370              global if q > 10" set in `func', catch writes to
5371              global on all threads that call `func', or catch
5372              writes on all recursive calls of `func' by a single
5373              thread.  We simply always evaluate the condition in
5374              the innermost frame that's executing where it makes
5375              sense to evaluate the condition.  It seems
5376              intuitive.  */
5377           frame = block_innermost_frame (w->cond_exp_valid_block);
5378           if (frame != NULL)
5379             select_frame (frame);
5380           else
5381             within_current_scope = 0;
5382         }
5383       if (within_current_scope)
5384         value_is_zero
5385           = catch_errors (breakpoint_cond_eval, cond,
5386                           "Error in testing breakpoint condition:\n",
5387                           RETURN_MASK_ALL);
5388       else
5389         {
5390           warning (_("Watchpoint condition cannot be tested "
5391                      "in the current scope"));
5392           /* If we failed to set the right context for this
5393              watchpoint, unconditionally report it.  */
5394           value_is_zero = 0;
5395         }
5396       /* FIXME-someday, should give breakpoint #.  */
5397       value_free_to_mark (mark);
5398     }
5399
5400   if (cond && value_is_zero)
5401     {
5402       bs->stop = 0;
5403     }
5404   else if (b->ignore_count > 0)
5405     {
5406       b->ignore_count--;
5407       bs->stop = 0;
5408       /* Increase the hit count even though we don't stop.  */
5409       ++(b->hit_count);
5410       observer_notify_breakpoint_modified (b);
5411     }   
5412 }
5413
5414
5415 /* Get a bpstat associated with having just stopped at address
5416    BP_ADDR in thread PTID.
5417
5418    Determine whether we stopped at a breakpoint, etc, or whether we
5419    don't understand this stop.  Result is a chain of bpstat's such
5420    that:
5421
5422    if we don't understand the stop, the result is a null pointer.
5423
5424    if we understand why we stopped, the result is not null.
5425
5426    Each element of the chain refers to a particular breakpoint or
5427    watchpoint at which we have stopped.  (We may have stopped for
5428    several reasons concurrently.)
5429
5430    Each element of the chain has valid next, breakpoint_at,
5431    commands, FIXME??? fields.  */
5432
5433 bpstat
5434 bpstat_stop_status (struct address_space *aspace,
5435                     CORE_ADDR bp_addr, ptid_t ptid,
5436                     const struct target_waitstatus *ws)
5437 {
5438   struct breakpoint *b = NULL;
5439   struct bp_location *bl;
5440   struct bp_location *loc;
5441   /* First item of allocated bpstat's.  */
5442   bpstat bs_head = NULL, *bs_link = &bs_head;
5443   /* Pointer to the last thing in the chain currently.  */
5444   bpstat bs;
5445   int ix;
5446   int need_remove_insert;
5447   int removed_any;
5448
5449   /* First, build the bpstat chain with locations that explain a
5450      target stop, while being careful to not set the target running,
5451      as that may invalidate locations (in particular watchpoint
5452      locations are recreated).  Resuming will happen here with
5453      breakpoint conditions or watchpoint expressions that include
5454      inferior function calls.  */
5455
5456   ALL_BREAKPOINTS (b)
5457     {
5458       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5459         continue;
5460
5461       for (bl = b->loc; bl != NULL; bl = bl->next)
5462         {
5463           /* For hardware watchpoints, we look only at the first
5464              location.  The watchpoint_check function will work on the
5465              entire expression, not the individual locations.  For
5466              read watchpoints, the watchpoints_triggered function has
5467              checked all locations already.  */
5468           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5469             break;
5470
5471           if (!bl->enabled || bl->shlib_disabled)
5472             continue;
5473
5474           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5475             continue;
5476
5477           /* Come here if it's a watchpoint, or if the break address
5478              matches.  */
5479
5480           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5481                                                    explain stop.  */
5482
5483           /* Assume we stop.  Should we find a watchpoint that is not
5484              actually triggered, or if the condition of the breakpoint
5485              evaluates as false, we'll reset 'stop' to 0.  */
5486           bs->stop = 1;
5487           bs->print = 1;
5488
5489           /* If this is a scope breakpoint, mark the associated
5490              watchpoint as triggered so that we will handle the
5491              out-of-scope event.  We'll get to the watchpoint next
5492              iteration.  */
5493           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5494             {
5495               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5496
5497               w->watchpoint_triggered = watch_triggered_yes;
5498             }
5499         }
5500     }
5501
5502   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5503     {
5504       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5505         {
5506           bs = bpstat_alloc (loc, &bs_link);
5507           /* For hits of moribund locations, we should just proceed.  */
5508           bs->stop = 0;
5509           bs->print = 0;
5510           bs->print_it = print_it_noop;
5511         }
5512     }
5513
5514   /* A bit of special processing for shlib breakpoints.  We need to
5515      process solib loading here, so that the lists of loaded and
5516      unloaded libraries are correct before we handle "catch load" and
5517      "catch unload".  */
5518   for (bs = bs_head; bs != NULL; bs = bs->next)
5519     {
5520       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5521         {
5522           handle_solib_event ();
5523           break;
5524         }
5525     }
5526
5527   /* Now go through the locations that caused the target to stop, and
5528      check whether we're interested in reporting this stop to higher
5529      layers, or whether we should resume the target transparently.  */
5530
5531   removed_any = 0;
5532
5533   for (bs = bs_head; bs != NULL; bs = bs->next)
5534     {
5535       if (!bs->stop)
5536         continue;
5537
5538       b = bs->breakpoint_at;
5539       b->ops->check_status (bs);
5540       if (bs->stop)
5541         {
5542           bpstat_check_breakpoint_conditions (bs, ptid);
5543
5544           if (bs->stop)
5545             {
5546               ++(b->hit_count);
5547               observer_notify_breakpoint_modified (b);
5548
5549               /* We will stop here.  */
5550               if (b->disposition == disp_disable)
5551                 {
5552                   --(b->enable_count);
5553                   if (b->enable_count <= 0
5554                       && b->enable_state != bp_permanent)
5555                     b->enable_state = bp_disabled;
5556                   removed_any = 1;
5557                 }
5558               if (b->silent)
5559                 bs->print = 0;
5560               bs->commands = b->commands;
5561               incref_counted_command_line (bs->commands);
5562               if (command_line_is_silent (bs->commands
5563                                           ? bs->commands->commands : NULL))
5564                 bs->print = 0;
5565
5566               b->ops->after_condition_true (bs);
5567             }
5568
5569         }
5570
5571       /* Print nothing for this entry if we don't stop or don't
5572          print.  */
5573       if (!bs->stop || !bs->print)
5574         bs->print_it = print_it_noop;
5575     }
5576
5577   /* If we aren't stopping, the value of some hardware watchpoint may
5578      not have changed, but the intermediate memory locations we are
5579      watching may have.  Don't bother if we're stopping; this will get
5580      done later.  */
5581   need_remove_insert = 0;
5582   if (! bpstat_causes_stop (bs_head))
5583     for (bs = bs_head; bs != NULL; bs = bs->next)
5584       if (!bs->stop
5585           && bs->breakpoint_at
5586           && is_hardware_watchpoint (bs->breakpoint_at))
5587         {
5588           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5589
5590           update_watchpoint (w, 0 /* don't reparse.  */);
5591           need_remove_insert = 1;
5592         }
5593
5594   if (need_remove_insert)
5595     update_global_location_list (1);
5596   else if (removed_any)
5597     update_global_location_list (0);
5598
5599   return bs_head;
5600 }
5601
5602 static void
5603 handle_jit_event (void)
5604 {
5605   struct frame_info *frame;
5606   struct gdbarch *gdbarch;
5607
5608   /* Switch terminal for any messages produced by
5609      breakpoint_re_set.  */
5610   target_terminal_ours_for_output ();
5611
5612   frame = get_current_frame ();
5613   gdbarch = get_frame_arch (frame);
5614
5615   jit_event_handler (gdbarch);
5616
5617   target_terminal_inferior ();
5618 }
5619
5620 /* Prepare WHAT final decision for infrun.  */
5621
5622 /* Decide what infrun needs to do with this bpstat.  */
5623
5624 struct bpstat_what
5625 bpstat_what (bpstat bs_head)
5626 {
5627   struct bpstat_what retval;
5628   int jit_event = 0;
5629   bpstat bs;
5630
5631   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5632   retval.call_dummy = STOP_NONE;
5633   retval.is_longjmp = 0;
5634
5635   for (bs = bs_head; bs != NULL; bs = bs->next)
5636     {
5637       /* Extract this BS's action.  After processing each BS, we check
5638          if its action overrides all we've seem so far.  */
5639       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5640       enum bptype bptype;
5641
5642       if (bs->breakpoint_at == NULL)
5643         {
5644           /* I suspect this can happen if it was a momentary
5645              breakpoint which has since been deleted.  */
5646           bptype = bp_none;
5647         }
5648       else
5649         bptype = bs->breakpoint_at->type;
5650
5651       switch (bptype)
5652         {
5653         case bp_none:
5654           break;
5655         case bp_breakpoint:
5656         case bp_hardware_breakpoint:
5657         case bp_until:
5658         case bp_finish:
5659         case bp_shlib_event:
5660           if (bs->stop)
5661             {
5662               if (bs->print)
5663                 this_action = BPSTAT_WHAT_STOP_NOISY;
5664               else
5665                 this_action = BPSTAT_WHAT_STOP_SILENT;
5666             }
5667           else
5668             this_action = BPSTAT_WHAT_SINGLE;
5669           break;
5670         case bp_watchpoint:
5671         case bp_hardware_watchpoint:
5672         case bp_read_watchpoint:
5673         case bp_access_watchpoint:
5674           if (bs->stop)
5675             {
5676               if (bs->print)
5677                 this_action = BPSTAT_WHAT_STOP_NOISY;
5678               else
5679                 this_action = BPSTAT_WHAT_STOP_SILENT;
5680             }
5681           else
5682             {
5683               /* There was a watchpoint, but we're not stopping.
5684                  This requires no further action.  */
5685             }
5686           break;
5687         case bp_longjmp:
5688         case bp_longjmp_call_dummy:
5689         case bp_exception:
5690           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5691           retval.is_longjmp = bptype != bp_exception;
5692           break;
5693         case bp_longjmp_resume:
5694         case bp_exception_resume:
5695           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5696           retval.is_longjmp = bptype == bp_longjmp_resume;
5697           break;
5698         case bp_step_resume:
5699           if (bs->stop)
5700             this_action = BPSTAT_WHAT_STEP_RESUME;
5701           else
5702             {
5703               /* It is for the wrong frame.  */
5704               this_action = BPSTAT_WHAT_SINGLE;
5705             }
5706           break;
5707         case bp_hp_step_resume:
5708           if (bs->stop)
5709             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5710           else
5711             {
5712               /* It is for the wrong frame.  */
5713               this_action = BPSTAT_WHAT_SINGLE;
5714             }
5715           break;
5716         case bp_watchpoint_scope:
5717         case bp_thread_event:
5718         case bp_overlay_event:
5719         case bp_longjmp_master:
5720         case bp_std_terminate_master:
5721         case bp_exception_master:
5722           this_action = BPSTAT_WHAT_SINGLE;
5723           break;
5724         case bp_catchpoint:
5725           if (bs->stop)
5726             {
5727               if (bs->print)
5728                 this_action = BPSTAT_WHAT_STOP_NOISY;
5729               else
5730                 this_action = BPSTAT_WHAT_STOP_SILENT;
5731             }
5732           else
5733             {
5734               /* There was a catchpoint, but we're not stopping.
5735                  This requires no further action.  */
5736             }
5737           break;
5738         case bp_jit_event:
5739           jit_event = 1;
5740           this_action = BPSTAT_WHAT_SINGLE;
5741           break;
5742         case bp_call_dummy:
5743           /* Make sure the action is stop (silent or noisy),
5744              so infrun.c pops the dummy frame.  */
5745           retval.call_dummy = STOP_STACK_DUMMY;
5746           this_action = BPSTAT_WHAT_STOP_SILENT;
5747           break;
5748         case bp_std_terminate:
5749           /* Make sure the action is stop (silent or noisy),
5750              so infrun.c pops the dummy frame.  */
5751           retval.call_dummy = STOP_STD_TERMINATE;
5752           this_action = BPSTAT_WHAT_STOP_SILENT;
5753           break;
5754         case bp_tracepoint:
5755         case bp_fast_tracepoint:
5756         case bp_static_tracepoint:
5757           /* Tracepoint hits should not be reported back to GDB, and
5758              if one got through somehow, it should have been filtered
5759              out already.  */
5760           internal_error (__FILE__, __LINE__,
5761                           _("bpstat_what: tracepoint encountered"));
5762           break;
5763         case bp_gnu_ifunc_resolver:
5764           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5765           this_action = BPSTAT_WHAT_SINGLE;
5766           break;
5767         case bp_gnu_ifunc_resolver_return:
5768           /* The breakpoint will be removed, execution will restart from the
5769              PC of the former breakpoint.  */
5770           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5771           break;
5772
5773         case bp_dprintf:
5774           if (bs->stop)
5775             this_action = BPSTAT_WHAT_STOP_SILENT;
5776           else
5777             this_action = BPSTAT_WHAT_SINGLE;
5778           break;
5779
5780         default:
5781           internal_error (__FILE__, __LINE__,
5782                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5783         }
5784
5785       retval.main_action = max (retval.main_action, this_action);
5786     }
5787
5788   /* These operations may affect the bs->breakpoint_at state so they are
5789      delayed after MAIN_ACTION is decided above.  */
5790
5791   if (jit_event)
5792     {
5793       if (debug_infrun)
5794         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5795
5796       handle_jit_event ();
5797     }
5798
5799   for (bs = bs_head; bs != NULL; bs = bs->next)
5800     {
5801       struct breakpoint *b = bs->breakpoint_at;
5802
5803       if (b == NULL)
5804         continue;
5805       switch (b->type)
5806         {
5807         case bp_gnu_ifunc_resolver:
5808           gnu_ifunc_resolver_stop (b);
5809           break;
5810         case bp_gnu_ifunc_resolver_return:
5811           gnu_ifunc_resolver_return_stop (b);
5812           break;
5813         }
5814     }
5815
5816   return retval;
5817 }
5818
5819 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5820    without hardware support).  This isn't related to a specific bpstat,
5821    just to things like whether watchpoints are set.  */
5822
5823 int
5824 bpstat_should_step (void)
5825 {
5826   struct breakpoint *b;
5827
5828   ALL_BREAKPOINTS (b)
5829     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5830       return 1;
5831   return 0;
5832 }
5833
5834 int
5835 bpstat_causes_stop (bpstat bs)
5836 {
5837   for (; bs != NULL; bs = bs->next)
5838     if (bs->stop)
5839       return 1;
5840
5841   return 0;
5842 }
5843
5844 \f
5845
5846 /* Compute a string of spaces suitable to indent the next line
5847    so it starts at the position corresponding to the table column
5848    named COL_NAME in the currently active table of UIOUT.  */
5849
5850 static char *
5851 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5852 {
5853   static char wrap_indent[80];
5854   int i, total_width, width, align;
5855   char *text;
5856
5857   total_width = 0;
5858   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5859     {
5860       if (strcmp (text, col_name) == 0)
5861         {
5862           gdb_assert (total_width < sizeof wrap_indent);
5863           memset (wrap_indent, ' ', total_width);
5864           wrap_indent[total_width] = 0;
5865
5866           return wrap_indent;
5867         }
5868
5869       total_width += width + 1;
5870     }
5871
5872   return NULL;
5873 }
5874
5875 /* Determine if the locations of this breakpoint will have their conditions
5876    evaluated by the target, host or a mix of both.  Returns the following:
5877
5878     "host": Host evals condition.
5879     "host or target": Host or Target evals condition.
5880     "target": Target evals condition.
5881 */
5882
5883 static const char *
5884 bp_condition_evaluator (struct breakpoint *b)
5885 {
5886   struct bp_location *bl;
5887   char host_evals = 0;
5888   char target_evals = 0;
5889
5890   if (!b)
5891     return NULL;
5892
5893   if (!is_breakpoint (b))
5894     return NULL;
5895
5896   if (gdb_evaluates_breakpoint_condition_p ()
5897       || !target_supports_evaluation_of_breakpoint_conditions ())
5898     return condition_evaluation_host;
5899
5900   for (bl = b->loc; bl; bl = bl->next)
5901     {
5902       if (bl->cond_bytecode)
5903         target_evals++;
5904       else
5905         host_evals++;
5906     }
5907
5908   if (host_evals && target_evals)
5909     return condition_evaluation_both;
5910   else if (target_evals)
5911     return condition_evaluation_target;
5912   else
5913     return condition_evaluation_host;
5914 }
5915
5916 /* Determine the breakpoint location's condition evaluator.  This is
5917    similar to bp_condition_evaluator, but for locations.  */
5918
5919 static const char *
5920 bp_location_condition_evaluator (struct bp_location *bl)
5921 {
5922   if (bl && !is_breakpoint (bl->owner))
5923     return NULL;
5924
5925   if (gdb_evaluates_breakpoint_condition_p ()
5926       || !target_supports_evaluation_of_breakpoint_conditions ())
5927     return condition_evaluation_host;
5928
5929   if (bl && bl->cond_bytecode)
5930     return condition_evaluation_target;
5931   else
5932     return condition_evaluation_host;
5933 }
5934
5935 /* Print the LOC location out of the list of B->LOC locations.  */
5936
5937 static void
5938 print_breakpoint_location (struct breakpoint *b,
5939                            struct bp_location *loc)
5940 {
5941   struct ui_out *uiout = current_uiout;
5942   struct cleanup *old_chain = save_current_program_space ();
5943
5944   if (loc != NULL && loc->shlib_disabled)
5945     loc = NULL;
5946
5947   if (loc != NULL)
5948     set_current_program_space (loc->pspace);
5949
5950   if (b->display_canonical)
5951     ui_out_field_string (uiout, "what", b->addr_string);
5952   else if (loc && loc->symtab)
5953     {
5954       struct symbol *sym 
5955         = find_pc_sect_function (loc->address, loc->section);
5956       if (sym)
5957         {
5958           ui_out_text (uiout, "in ");
5959           ui_out_field_string (uiout, "func",
5960                                SYMBOL_PRINT_NAME (sym));
5961           ui_out_text (uiout, " ");
5962           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5963           ui_out_text (uiout, "at ");
5964         }
5965       ui_out_field_string (uiout, "file",
5966                            symtab_to_filename_for_display (loc->symtab));
5967       ui_out_text (uiout, ":");
5968
5969       if (ui_out_is_mi_like_p (uiout))
5970         ui_out_field_string (uiout, "fullname",
5971                              symtab_to_fullname (loc->symtab));
5972       
5973       ui_out_field_int (uiout, "line", loc->line_number);
5974     }
5975   else if (loc)
5976     {
5977       struct ui_file *stb = mem_fileopen ();
5978       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5979
5980       print_address_symbolic (loc->gdbarch, loc->address, stb,
5981                               demangle, "");
5982       ui_out_field_stream (uiout, "at", stb);
5983
5984       do_cleanups (stb_chain);
5985     }
5986   else
5987     ui_out_field_string (uiout, "pending", b->addr_string);
5988
5989   if (loc && is_breakpoint (b)
5990       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5991       && bp_condition_evaluator (b) == condition_evaluation_both)
5992     {
5993       ui_out_text (uiout, " (");
5994       ui_out_field_string (uiout, "evaluated-by",
5995                            bp_location_condition_evaluator (loc));
5996       ui_out_text (uiout, ")");
5997     }
5998
5999   do_cleanups (old_chain);
6000 }
6001
6002 static const char *
6003 bptype_string (enum bptype type)
6004 {
6005   struct ep_type_description
6006     {
6007       enum bptype type;
6008       char *description;
6009     };
6010   static struct ep_type_description bptypes[] =
6011   {
6012     {bp_none, "?deleted?"},
6013     {bp_breakpoint, "breakpoint"},
6014     {bp_hardware_breakpoint, "hw breakpoint"},
6015     {bp_until, "until"},
6016     {bp_finish, "finish"},
6017     {bp_watchpoint, "watchpoint"},
6018     {bp_hardware_watchpoint, "hw watchpoint"},
6019     {bp_read_watchpoint, "read watchpoint"},
6020     {bp_access_watchpoint, "acc watchpoint"},
6021     {bp_longjmp, "longjmp"},
6022     {bp_longjmp_resume, "longjmp resume"},
6023     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6024     {bp_exception, "exception"},
6025     {bp_exception_resume, "exception resume"},
6026     {bp_step_resume, "step resume"},
6027     {bp_hp_step_resume, "high-priority step resume"},
6028     {bp_watchpoint_scope, "watchpoint scope"},
6029     {bp_call_dummy, "call dummy"},
6030     {bp_std_terminate, "std::terminate"},
6031     {bp_shlib_event, "shlib events"},
6032     {bp_thread_event, "thread events"},
6033     {bp_overlay_event, "overlay events"},
6034     {bp_longjmp_master, "longjmp master"},
6035     {bp_std_terminate_master, "std::terminate master"},
6036     {bp_exception_master, "exception master"},
6037     {bp_catchpoint, "catchpoint"},
6038     {bp_tracepoint, "tracepoint"},
6039     {bp_fast_tracepoint, "fast tracepoint"},
6040     {bp_static_tracepoint, "static tracepoint"},
6041     {bp_dprintf, "dprintf"},
6042     {bp_jit_event, "jit events"},
6043     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6044     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6045   };
6046
6047   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6048       || ((int) type != bptypes[(int) type].type))
6049     internal_error (__FILE__, __LINE__,
6050                     _("bptypes table does not describe type #%d."),
6051                     (int) type);
6052
6053   return bptypes[(int) type].description;
6054 }
6055
6056 /* For MI, output a field named 'thread-groups' with a list as the value.
6057    For CLI, prefix the list with the string 'inf'. */
6058
6059 static void
6060 output_thread_groups (struct ui_out *uiout,
6061                       const char *field_name,
6062                       VEC(int) *inf_num,
6063                       int mi_only)
6064 {
6065   struct cleanup *back_to;
6066   int is_mi = ui_out_is_mi_like_p (uiout);
6067   int inf;
6068   int i;
6069
6070   /* For backward compatibility, don't display inferiors in CLI unless
6071      there are several.  Always display them for MI. */
6072   if (!is_mi && mi_only)
6073     return;
6074
6075   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6076
6077   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6078     {
6079       if (is_mi)
6080         {
6081           char mi_group[10];
6082
6083           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6084           ui_out_field_string (uiout, NULL, mi_group);
6085         }
6086       else
6087         {
6088           if (i == 0)
6089             ui_out_text (uiout, " inf ");
6090           else
6091             ui_out_text (uiout, ", ");
6092         
6093           ui_out_text (uiout, plongest (inf));
6094         }
6095     }
6096
6097   do_cleanups (back_to);
6098 }
6099
6100 /* Print B to gdb_stdout.  */
6101
6102 static void
6103 print_one_breakpoint_location (struct breakpoint *b,
6104                                struct bp_location *loc,
6105                                int loc_number,
6106                                struct bp_location **last_loc,
6107                                int allflag)
6108 {
6109   struct command_line *l;
6110   static char bpenables[] = "nynny";
6111
6112   struct ui_out *uiout = current_uiout;
6113   int header_of_multiple = 0;
6114   int part_of_multiple = (loc != NULL);
6115   struct value_print_options opts;
6116
6117   get_user_print_options (&opts);
6118
6119   gdb_assert (!loc || loc_number != 0);
6120   /* See comment in print_one_breakpoint concerning treatment of
6121      breakpoints with single disabled location.  */
6122   if (loc == NULL 
6123       && (b->loc != NULL 
6124           && (b->loc->next != NULL || !b->loc->enabled)))
6125     header_of_multiple = 1;
6126   if (loc == NULL)
6127     loc = b->loc;
6128
6129   annotate_record ();
6130
6131   /* 1 */
6132   annotate_field (0);
6133   if (part_of_multiple)
6134     {
6135       char *formatted;
6136       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6137       ui_out_field_string (uiout, "number", formatted);
6138       xfree (formatted);
6139     }
6140   else
6141     {
6142       ui_out_field_int (uiout, "number", b->number);
6143     }
6144
6145   /* 2 */
6146   annotate_field (1);
6147   if (part_of_multiple)
6148     ui_out_field_skip (uiout, "type");
6149   else
6150     ui_out_field_string (uiout, "type", bptype_string (b->type));
6151
6152   /* 3 */
6153   annotate_field (2);
6154   if (part_of_multiple)
6155     ui_out_field_skip (uiout, "disp");
6156   else
6157     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6158
6159
6160   /* 4 */
6161   annotate_field (3);
6162   if (part_of_multiple)
6163     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6164   else
6165     ui_out_field_fmt (uiout, "enabled", "%c", 
6166                       bpenables[(int) b->enable_state]);
6167   ui_out_spaces (uiout, 2);
6168
6169   
6170   /* 5 and 6 */
6171   if (b->ops != NULL && b->ops->print_one != NULL)
6172     {
6173       /* Although the print_one can possibly print all locations,
6174          calling it here is not likely to get any nice result.  So,
6175          make sure there's just one location.  */
6176       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6177       b->ops->print_one (b, last_loc);
6178     }
6179   else
6180     switch (b->type)
6181       {
6182       case bp_none:
6183         internal_error (__FILE__, __LINE__,
6184                         _("print_one_breakpoint: bp_none encountered\n"));
6185         break;
6186
6187       case bp_watchpoint:
6188       case bp_hardware_watchpoint:
6189       case bp_read_watchpoint:
6190       case bp_access_watchpoint:
6191         {
6192           struct watchpoint *w = (struct watchpoint *) b;
6193
6194           /* Field 4, the address, is omitted (which makes the columns
6195              not line up too nicely with the headers, but the effect
6196              is relatively readable).  */
6197           if (opts.addressprint)
6198             ui_out_field_skip (uiout, "addr");
6199           annotate_field (5);
6200           ui_out_field_string (uiout, "what", w->exp_string);
6201         }
6202         break;
6203
6204       case bp_breakpoint:
6205       case bp_hardware_breakpoint:
6206       case bp_until:
6207       case bp_finish:
6208       case bp_longjmp:
6209       case bp_longjmp_resume:
6210       case bp_longjmp_call_dummy:
6211       case bp_exception:
6212       case bp_exception_resume:
6213       case bp_step_resume:
6214       case bp_hp_step_resume:
6215       case bp_watchpoint_scope:
6216       case bp_call_dummy:
6217       case bp_std_terminate:
6218       case bp_shlib_event:
6219       case bp_thread_event:
6220       case bp_overlay_event:
6221       case bp_longjmp_master:
6222       case bp_std_terminate_master:
6223       case bp_exception_master:
6224       case bp_tracepoint:
6225       case bp_fast_tracepoint:
6226       case bp_static_tracepoint:
6227       case bp_dprintf:
6228       case bp_jit_event:
6229       case bp_gnu_ifunc_resolver:
6230       case bp_gnu_ifunc_resolver_return:
6231         if (opts.addressprint)
6232           {
6233             annotate_field (4);
6234             if (header_of_multiple)
6235               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6236             else if (b->loc == NULL || loc->shlib_disabled)
6237               ui_out_field_string (uiout, "addr", "<PENDING>");
6238             else
6239               ui_out_field_core_addr (uiout, "addr",
6240                                       loc->gdbarch, loc->address);
6241           }
6242         annotate_field (5);
6243         if (!header_of_multiple)
6244           print_breakpoint_location (b, loc);
6245         if (b->loc)
6246           *last_loc = b->loc;
6247         break;
6248       }
6249
6250
6251   if (loc != NULL && !header_of_multiple)
6252     {
6253       struct inferior *inf;
6254       VEC(int) *inf_num = NULL;
6255       int mi_only = 1;
6256
6257       ALL_INFERIORS (inf)
6258         {
6259           if (inf->pspace == loc->pspace)
6260             VEC_safe_push (int, inf_num, inf->num);
6261         }
6262
6263         /* For backward compatibility, don't display inferiors in CLI unless
6264            there are several.  Always display for MI. */
6265         if (allflag
6266             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6267                 && (number_of_program_spaces () > 1
6268                     || number_of_inferiors () > 1)
6269                 /* LOC is for existing B, it cannot be in
6270                    moribund_locations and thus having NULL OWNER.  */
6271                 && loc->owner->type != bp_catchpoint))
6272         mi_only = 0;
6273       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6274       VEC_free (int, inf_num);
6275     }
6276
6277   if (!part_of_multiple)
6278     {
6279       if (b->thread != -1)
6280         {
6281           /* FIXME: This seems to be redundant and lost here; see the
6282              "stop only in" line a little further down.  */
6283           ui_out_text (uiout, " thread ");
6284           ui_out_field_int (uiout, "thread", b->thread);
6285         }
6286       else if (b->task != 0)
6287         {
6288           ui_out_text (uiout, " task ");
6289           ui_out_field_int (uiout, "task", b->task);
6290         }
6291     }
6292
6293   ui_out_text (uiout, "\n");
6294
6295   if (!part_of_multiple)
6296     b->ops->print_one_detail (b, uiout);
6297
6298   if (part_of_multiple && frame_id_p (b->frame_id))
6299     {
6300       annotate_field (6);
6301       ui_out_text (uiout, "\tstop only in stack frame at ");
6302       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6303          the frame ID.  */
6304       ui_out_field_core_addr (uiout, "frame",
6305                               b->gdbarch, b->frame_id.stack_addr);
6306       ui_out_text (uiout, "\n");
6307     }
6308   
6309   if (!part_of_multiple && b->cond_string)
6310     {
6311       annotate_field (7);
6312       if (is_tracepoint (b))
6313         ui_out_text (uiout, "\ttrace only if ");
6314       else
6315         ui_out_text (uiout, "\tstop only if ");
6316       ui_out_field_string (uiout, "cond", b->cond_string);
6317
6318       /* Print whether the target is doing the breakpoint's condition
6319          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6320       if (is_breakpoint (b)
6321           && breakpoint_condition_evaluation_mode ()
6322           == condition_evaluation_target)
6323         {
6324           ui_out_text (uiout, " (");
6325           ui_out_field_string (uiout, "evaluated-by",
6326                                bp_condition_evaluator (b));
6327           ui_out_text (uiout, " evals)");
6328         }
6329       ui_out_text (uiout, "\n");
6330     }
6331
6332   if (!part_of_multiple && b->thread != -1)
6333     {
6334       /* FIXME should make an annotation for this.  */
6335       ui_out_text (uiout, "\tstop only in thread ");
6336       ui_out_field_int (uiout, "thread", b->thread);
6337       ui_out_text (uiout, "\n");
6338     }
6339   
6340   if (!part_of_multiple)
6341     {
6342       if (b->hit_count)
6343         {
6344           /* FIXME should make an annotation for this.  */
6345           if (is_catchpoint (b))
6346             ui_out_text (uiout, "\tcatchpoint");
6347           else if (is_tracepoint (b))
6348             ui_out_text (uiout, "\ttracepoint");
6349           else
6350             ui_out_text (uiout, "\tbreakpoint");
6351           ui_out_text (uiout, " already hit ");
6352           ui_out_field_int (uiout, "times", b->hit_count);
6353           if (b->hit_count == 1)
6354             ui_out_text (uiout, " time\n");
6355           else
6356             ui_out_text (uiout, " times\n");
6357         }
6358       else
6359         {
6360           /* Output the count also if it is zero, but only if this is mi.  */
6361           if (ui_out_is_mi_like_p (uiout))
6362             ui_out_field_int (uiout, "times", b->hit_count);
6363         }
6364     }
6365
6366   if (!part_of_multiple && b->ignore_count)
6367     {
6368       annotate_field (8);
6369       ui_out_text (uiout, "\tignore next ");
6370       ui_out_field_int (uiout, "ignore", b->ignore_count);
6371       ui_out_text (uiout, " hits\n");
6372     }
6373
6374   /* Note that an enable count of 1 corresponds to "enable once"
6375      behavior, which is reported by the combination of enablement and
6376      disposition, so we don't need to mention it here.  */
6377   if (!part_of_multiple && b->enable_count > 1)
6378     {
6379       annotate_field (8);
6380       ui_out_text (uiout, "\tdisable after ");
6381       /* Tweak the wording to clarify that ignore and enable counts
6382          are distinct, and have additive effect.  */
6383       if (b->ignore_count)
6384         ui_out_text (uiout, "additional ");
6385       else
6386         ui_out_text (uiout, "next ");
6387       ui_out_field_int (uiout, "enable", b->enable_count);
6388       ui_out_text (uiout, " hits\n");
6389     }
6390
6391   if (!part_of_multiple && is_tracepoint (b))
6392     {
6393       struct tracepoint *tp = (struct tracepoint *) b;
6394
6395       if (tp->traceframe_usage)
6396         {
6397           ui_out_text (uiout, "\ttrace buffer usage ");
6398           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6399           ui_out_text (uiout, " bytes\n");
6400         }
6401     }
6402
6403   l = b->commands ? b->commands->commands : NULL;
6404   if (!part_of_multiple && l)
6405     {
6406       struct cleanup *script_chain;
6407
6408       annotate_field (9);
6409       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6410       print_command_lines (uiout, l, 4);
6411       do_cleanups (script_chain);
6412     }
6413
6414   if (is_tracepoint (b))
6415     {
6416       struct tracepoint *t = (struct tracepoint *) b;
6417
6418       if (!part_of_multiple && t->pass_count)
6419         {
6420           annotate_field (10);
6421           ui_out_text (uiout, "\tpass count ");
6422           ui_out_field_int (uiout, "pass", t->pass_count);
6423           ui_out_text (uiout, " \n");
6424         }
6425
6426       /* Don't display it when tracepoint or tracepoint location is
6427          pending.   */
6428       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6429         {
6430           annotate_field (11);
6431
6432           if (ui_out_is_mi_like_p (uiout))
6433             ui_out_field_string (uiout, "installed",
6434                                  loc->inserted ? "y" : "n");
6435           else
6436             {
6437               if (loc->inserted)
6438                 ui_out_text (uiout, "\t");
6439               else
6440                 ui_out_text (uiout, "\tnot ");
6441               ui_out_text (uiout, "installed on target\n");
6442             }
6443         }
6444     }
6445
6446   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6447     {
6448       if (is_watchpoint (b))
6449         {
6450           struct watchpoint *w = (struct watchpoint *) b;
6451
6452           ui_out_field_string (uiout, "original-location", w->exp_string);
6453         }
6454       else if (b->addr_string)
6455         ui_out_field_string (uiout, "original-location", b->addr_string);
6456     }
6457 }
6458
6459 static void
6460 print_one_breakpoint (struct breakpoint *b,
6461                       struct bp_location **last_loc, 
6462                       int allflag)
6463 {
6464   struct cleanup *bkpt_chain;
6465   struct ui_out *uiout = current_uiout;
6466
6467   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6468
6469   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6470   do_cleanups (bkpt_chain);
6471
6472   /* If this breakpoint has custom print function,
6473      it's already printed.  Otherwise, print individual
6474      locations, if any.  */
6475   if (b->ops == NULL || b->ops->print_one == NULL)
6476     {
6477       /* If breakpoint has a single location that is disabled, we
6478          print it as if it had several locations, since otherwise it's
6479          hard to represent "breakpoint enabled, location disabled"
6480          situation.
6481
6482          Note that while hardware watchpoints have several locations
6483          internally, that's not a property exposed to user.  */
6484       if (b->loc 
6485           && !is_hardware_watchpoint (b)
6486           && (b->loc->next || !b->loc->enabled))
6487         {
6488           struct bp_location *loc;
6489           int n = 1;
6490
6491           for (loc = b->loc; loc; loc = loc->next, ++n)
6492             {
6493               struct cleanup *inner2 =
6494                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6495               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6496               do_cleanups (inner2);
6497             }
6498         }
6499     }
6500 }
6501
6502 static int
6503 breakpoint_address_bits (struct breakpoint *b)
6504 {
6505   int print_address_bits = 0;
6506   struct bp_location *loc;
6507
6508   for (loc = b->loc; loc; loc = loc->next)
6509     {
6510       int addr_bit;
6511
6512       /* Software watchpoints that aren't watching memory don't have
6513          an address to print.  */
6514       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6515         continue;
6516
6517       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6518       if (addr_bit > print_address_bits)
6519         print_address_bits = addr_bit;
6520     }
6521
6522   return print_address_bits;
6523 }
6524
6525 struct captured_breakpoint_query_args
6526   {
6527     int bnum;
6528   };
6529
6530 static int
6531 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6532 {
6533   struct captured_breakpoint_query_args *args = data;
6534   struct breakpoint *b;
6535   struct bp_location *dummy_loc = NULL;
6536
6537   ALL_BREAKPOINTS (b)
6538     {
6539       if (args->bnum == b->number)
6540         {
6541           print_one_breakpoint (b, &dummy_loc, 0);
6542           return GDB_RC_OK;
6543         }
6544     }
6545   return GDB_RC_NONE;
6546 }
6547
6548 enum gdb_rc
6549 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6550                       char **error_message)
6551 {
6552   struct captured_breakpoint_query_args args;
6553
6554   args.bnum = bnum;
6555   /* For the moment we don't trust print_one_breakpoint() to not throw
6556      an error.  */
6557   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6558                                  error_message, RETURN_MASK_ALL) < 0)
6559     return GDB_RC_FAIL;
6560   else
6561     return GDB_RC_OK;
6562 }
6563
6564 /* Return true if this breakpoint was set by the user, false if it is
6565    internal or momentary.  */
6566
6567 int
6568 user_breakpoint_p (struct breakpoint *b)
6569 {
6570   return b->number > 0;
6571 }
6572
6573 /* Print information on user settable breakpoint (watchpoint, etc)
6574    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6575    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6576    FILTER is non-NULL, call it on each breakpoint and only include the
6577    ones for which it returns non-zero.  Return the total number of
6578    breakpoints listed.  */
6579
6580 static int
6581 breakpoint_1 (char *args, int allflag, 
6582               int (*filter) (const struct breakpoint *))
6583 {
6584   struct breakpoint *b;
6585   struct bp_location *last_loc = NULL;
6586   int nr_printable_breakpoints;
6587   struct cleanup *bkpttbl_chain;
6588   struct value_print_options opts;
6589   int print_address_bits = 0;
6590   int print_type_col_width = 14;
6591   struct ui_out *uiout = current_uiout;
6592
6593   get_user_print_options (&opts);
6594
6595   /* Compute the number of rows in the table, as well as the size
6596      required for address fields.  */
6597   nr_printable_breakpoints = 0;
6598   ALL_BREAKPOINTS (b)
6599     {
6600       /* If we have a filter, only list the breakpoints it accepts.  */
6601       if (filter && !filter (b))
6602         continue;
6603
6604       /* If we have an "args" string, it is a list of breakpoints to 
6605          accept.  Skip the others.  */
6606       if (args != NULL && *args != '\0')
6607         {
6608           if (allflag && parse_and_eval_long (args) != b->number)
6609             continue;
6610           if (!allflag && !number_is_in_list (args, b->number))
6611             continue;
6612         }
6613
6614       if (allflag || user_breakpoint_p (b))
6615         {
6616           int addr_bit, type_len;
6617
6618           addr_bit = breakpoint_address_bits (b);
6619           if (addr_bit > print_address_bits)
6620             print_address_bits = addr_bit;
6621
6622           type_len = strlen (bptype_string (b->type));
6623           if (type_len > print_type_col_width)
6624             print_type_col_width = type_len;
6625
6626           nr_printable_breakpoints++;
6627         }
6628     }
6629
6630   if (opts.addressprint)
6631     bkpttbl_chain 
6632       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6633                                              nr_printable_breakpoints,
6634                                              "BreakpointTable");
6635   else
6636     bkpttbl_chain 
6637       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6638                                              nr_printable_breakpoints,
6639                                              "BreakpointTable");
6640
6641   if (nr_printable_breakpoints > 0)
6642     annotate_breakpoints_headers ();
6643   if (nr_printable_breakpoints > 0)
6644     annotate_field (0);
6645   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6646   if (nr_printable_breakpoints > 0)
6647     annotate_field (1);
6648   ui_out_table_header (uiout, print_type_col_width, ui_left,
6649                        "type", "Type");                         /* 2 */
6650   if (nr_printable_breakpoints > 0)
6651     annotate_field (2);
6652   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6653   if (nr_printable_breakpoints > 0)
6654     annotate_field (3);
6655   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6656   if (opts.addressprint)
6657     {
6658       if (nr_printable_breakpoints > 0)
6659         annotate_field (4);
6660       if (print_address_bits <= 32)
6661         ui_out_table_header (uiout, 10, ui_left, 
6662                              "addr", "Address");                /* 5 */
6663       else
6664         ui_out_table_header (uiout, 18, ui_left, 
6665                              "addr", "Address");                /* 5 */
6666     }
6667   if (nr_printable_breakpoints > 0)
6668     annotate_field (5);
6669   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6670   ui_out_table_body (uiout);
6671   if (nr_printable_breakpoints > 0)
6672     annotate_breakpoints_table ();
6673
6674   ALL_BREAKPOINTS (b)
6675     {
6676       QUIT;
6677       /* If we have a filter, only list the breakpoints it accepts.  */
6678       if (filter && !filter (b))
6679         continue;
6680
6681       /* If we have an "args" string, it is a list of breakpoints to 
6682          accept.  Skip the others.  */
6683
6684       if (args != NULL && *args != '\0')
6685         {
6686           if (allflag)  /* maintenance info breakpoint */
6687             {
6688               if (parse_and_eval_long (args) != b->number)
6689                 continue;
6690             }
6691           else          /* all others */
6692             {
6693               if (!number_is_in_list (args, b->number))
6694                 continue;
6695             }
6696         }
6697       /* We only print out user settable breakpoints unless the
6698          allflag is set.  */
6699       if (allflag || user_breakpoint_p (b))
6700         print_one_breakpoint (b, &last_loc, allflag);
6701     }
6702
6703   do_cleanups (bkpttbl_chain);
6704
6705   if (nr_printable_breakpoints == 0)
6706     {
6707       /* If there's a filter, let the caller decide how to report
6708          empty list.  */
6709       if (!filter)
6710         {
6711           if (args == NULL || *args == '\0')
6712             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6713           else
6714             ui_out_message (uiout, 0, 
6715                             "No breakpoint or watchpoint matching '%s'.\n",
6716                             args);
6717         }
6718     }
6719   else
6720     {
6721       if (last_loc && !server_command)
6722         set_next_address (last_loc->gdbarch, last_loc->address);
6723     }
6724
6725   /* FIXME?  Should this be moved up so that it is only called when
6726      there have been breakpoints? */
6727   annotate_breakpoints_table_end ();
6728
6729   return nr_printable_breakpoints;
6730 }
6731
6732 /* Display the value of default-collect in a way that is generally
6733    compatible with the breakpoint list.  */
6734
6735 static void
6736 default_collect_info (void)
6737 {
6738   struct ui_out *uiout = current_uiout;
6739
6740   /* If it has no value (which is frequently the case), say nothing; a
6741      message like "No default-collect." gets in user's face when it's
6742      not wanted.  */
6743   if (!*default_collect)
6744     return;
6745
6746   /* The following phrase lines up nicely with per-tracepoint collect
6747      actions.  */
6748   ui_out_text (uiout, "default collect ");
6749   ui_out_field_string (uiout, "default-collect", default_collect);
6750   ui_out_text (uiout, " \n");
6751 }
6752   
6753 static void
6754 breakpoints_info (char *args, int from_tty)
6755 {
6756   breakpoint_1 (args, 0, NULL);
6757
6758   default_collect_info ();
6759 }
6760
6761 static void
6762 watchpoints_info (char *args, int from_tty)
6763 {
6764   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6765   struct ui_out *uiout = current_uiout;
6766
6767   if (num_printed == 0)
6768     {
6769       if (args == NULL || *args == '\0')
6770         ui_out_message (uiout, 0, "No watchpoints.\n");
6771       else
6772         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6773     }
6774 }
6775
6776 static void
6777 maintenance_info_breakpoints (char *args, int from_tty)
6778 {
6779   breakpoint_1 (args, 1, NULL);
6780
6781   default_collect_info ();
6782 }
6783
6784 static int
6785 breakpoint_has_pc (struct breakpoint *b,
6786                    struct program_space *pspace,
6787                    CORE_ADDR pc, struct obj_section *section)
6788 {
6789   struct bp_location *bl = b->loc;
6790
6791   for (; bl; bl = bl->next)
6792     {
6793       if (bl->pspace == pspace
6794           && bl->address == pc
6795           && (!overlay_debugging || bl->section == section))
6796         return 1;         
6797     }
6798   return 0;
6799 }
6800
6801 /* Print a message describing any user-breakpoints set at PC.  This
6802    concerns with logical breakpoints, so we match program spaces, not
6803    address spaces.  */
6804
6805 static void
6806 describe_other_breakpoints (struct gdbarch *gdbarch,
6807                             struct program_space *pspace, CORE_ADDR pc,
6808                             struct obj_section *section, int thread)
6809 {
6810   int others = 0;
6811   struct breakpoint *b;
6812
6813   ALL_BREAKPOINTS (b)
6814     others += (user_breakpoint_p (b)
6815                && breakpoint_has_pc (b, pspace, pc, section));
6816   if (others > 0)
6817     {
6818       if (others == 1)
6819         printf_filtered (_("Note: breakpoint "));
6820       else /* if (others == ???) */
6821         printf_filtered (_("Note: breakpoints "));
6822       ALL_BREAKPOINTS (b)
6823         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6824           {
6825             others--;
6826             printf_filtered ("%d", b->number);
6827             if (b->thread == -1 && thread != -1)
6828               printf_filtered (" (all threads)");
6829             else if (b->thread != -1)
6830               printf_filtered (" (thread %d)", b->thread);
6831             printf_filtered ("%s%s ",
6832                              ((b->enable_state == bp_disabled
6833                                || b->enable_state == bp_call_disabled)
6834                               ? " (disabled)"
6835                               : b->enable_state == bp_permanent 
6836                               ? " (permanent)"
6837                               : ""),
6838                              (others > 1) ? "," 
6839                              : ((others == 1) ? " and" : ""));
6840           }
6841       printf_filtered (_("also set at pc "));
6842       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6843       printf_filtered (".\n");
6844     }
6845 }
6846 \f
6847
6848 /* Return true iff it is meaningful to use the address member of
6849    BPT.  For some breakpoint types, the address member is irrelevant
6850    and it makes no sense to attempt to compare it to other addresses
6851    (or use it for any other purpose either).
6852
6853    More specifically, each of the following breakpoint types will
6854    always have a zero valued address and we don't want to mark
6855    breakpoints of any of these types to be a duplicate of an actual
6856    breakpoint at address zero:
6857
6858       bp_watchpoint
6859       bp_catchpoint
6860
6861 */
6862
6863 static int
6864 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6865 {
6866   enum bptype type = bpt->type;
6867
6868   return (type != bp_watchpoint && type != bp_catchpoint);
6869 }
6870
6871 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6872    true if LOC1 and LOC2 represent the same watchpoint location.  */
6873
6874 static int
6875 watchpoint_locations_match (struct bp_location *loc1, 
6876                             struct bp_location *loc2)
6877 {
6878   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6879   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6880
6881   /* Both of them must exist.  */
6882   gdb_assert (w1 != NULL);
6883   gdb_assert (w2 != NULL);
6884
6885   /* If the target can evaluate the condition expression in hardware,
6886      then we we need to insert both watchpoints even if they are at
6887      the same place.  Otherwise the watchpoint will only trigger when
6888      the condition of whichever watchpoint was inserted evaluates to
6889      true, not giving a chance for GDB to check the condition of the
6890      other watchpoint.  */
6891   if ((w1->cond_exp
6892        && target_can_accel_watchpoint_condition (loc1->address, 
6893                                                  loc1->length,
6894                                                  loc1->watchpoint_type,
6895                                                  w1->cond_exp))
6896       || (w2->cond_exp
6897           && target_can_accel_watchpoint_condition (loc2->address, 
6898                                                     loc2->length,
6899                                                     loc2->watchpoint_type,
6900                                                     w2->cond_exp)))
6901     return 0;
6902
6903   /* Note that this checks the owner's type, not the location's.  In
6904      case the target does not support read watchpoints, but does
6905      support access watchpoints, we'll have bp_read_watchpoint
6906      watchpoints with hw_access locations.  Those should be considered
6907      duplicates of hw_read locations.  The hw_read locations will
6908      become hw_access locations later.  */
6909   return (loc1->owner->type == loc2->owner->type
6910           && loc1->pspace->aspace == loc2->pspace->aspace
6911           && loc1->address == loc2->address
6912           && loc1->length == loc2->length);
6913 }
6914
6915 /* See breakpoint.h.  */
6916
6917 int
6918 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6919                           struct address_space *aspace2, CORE_ADDR addr2)
6920 {
6921   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6922            || aspace1 == aspace2)
6923           && addr1 == addr2);
6924 }
6925
6926 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6927    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6928    matches ASPACE2.  On targets that have global breakpoints, the address
6929    space doesn't really matter.  */
6930
6931 static int
6932 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6933                                 int len1, struct address_space *aspace2,
6934                                 CORE_ADDR addr2)
6935 {
6936   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6937            || aspace1 == aspace2)
6938           && addr2 >= addr1 && addr2 < addr1 + len1);
6939 }
6940
6941 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6942    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6943    matches the breakpoint's address space.  On targets that have global
6944    breakpoints, the address space doesn't really matter.  */
6945
6946 static int
6947 breakpoint_location_address_match (struct bp_location *bl,
6948                                    struct address_space *aspace,
6949                                    CORE_ADDR addr)
6950 {
6951   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6952                                     aspace, addr)
6953           || (bl->length
6954               && breakpoint_address_match_range (bl->pspace->aspace,
6955                                                  bl->address, bl->length,
6956                                                  aspace, addr)));
6957 }
6958
6959 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6960    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6961    true, otherwise returns false.  */
6962
6963 static int
6964 tracepoint_locations_match (struct bp_location *loc1,
6965                             struct bp_location *loc2)
6966 {
6967   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6968     /* Since tracepoint locations are never duplicated with others', tracepoint
6969        locations at the same address of different tracepoints are regarded as
6970        different locations.  */
6971     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6972   else
6973     return 0;
6974 }
6975
6976 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6977    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6978    represent the same location.  */
6979
6980 static int
6981 breakpoint_locations_match (struct bp_location *loc1, 
6982                             struct bp_location *loc2)
6983 {
6984   int hw_point1, hw_point2;
6985
6986   /* Both of them must not be in moribund_locations.  */
6987   gdb_assert (loc1->owner != NULL);
6988   gdb_assert (loc2->owner != NULL);
6989
6990   hw_point1 = is_hardware_watchpoint (loc1->owner);
6991   hw_point2 = is_hardware_watchpoint (loc2->owner);
6992
6993   if (hw_point1 != hw_point2)
6994     return 0;
6995   else if (hw_point1)
6996     return watchpoint_locations_match (loc1, loc2);
6997   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6998     return tracepoint_locations_match (loc1, loc2);
6999   else
7000     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7001     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7002                                      loc2->pspace->aspace, loc2->address)
7003             && loc1->length == loc2->length);
7004 }
7005
7006 static void
7007 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7008                                int bnum, int have_bnum)
7009 {
7010   /* The longest string possibly returned by hex_string_custom
7011      is 50 chars.  These must be at least that big for safety.  */
7012   char astr1[64];
7013   char astr2[64];
7014
7015   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7016   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7017   if (have_bnum)
7018     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7019              bnum, astr1, astr2);
7020   else
7021     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7022 }
7023
7024 /* Adjust a breakpoint's address to account for architectural
7025    constraints on breakpoint placement.  Return the adjusted address.
7026    Note: Very few targets require this kind of adjustment.  For most
7027    targets, this function is simply the identity function.  */
7028
7029 static CORE_ADDR
7030 adjust_breakpoint_address (struct gdbarch *gdbarch,
7031                            CORE_ADDR bpaddr, enum bptype bptype)
7032 {
7033   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7034     {
7035       /* Very few targets need any kind of breakpoint adjustment.  */
7036       return bpaddr;
7037     }
7038   else if (bptype == bp_watchpoint
7039            || bptype == bp_hardware_watchpoint
7040            || bptype == bp_read_watchpoint
7041            || bptype == bp_access_watchpoint
7042            || bptype == bp_catchpoint)
7043     {
7044       /* Watchpoints and the various bp_catch_* eventpoints should not
7045          have their addresses modified.  */
7046       return bpaddr;
7047     }
7048   else
7049     {
7050       CORE_ADDR adjusted_bpaddr;
7051
7052       /* Some targets have architectural constraints on the placement
7053          of breakpoint instructions.  Obtain the adjusted address.  */
7054       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7055
7056       /* An adjusted breakpoint address can significantly alter
7057          a user's expectations.  Print a warning if an adjustment
7058          is required.  */
7059       if (adjusted_bpaddr != bpaddr)
7060         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7061
7062       return adjusted_bpaddr;
7063     }
7064 }
7065
7066 void
7067 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7068                   struct breakpoint *owner)
7069 {
7070   memset (loc, 0, sizeof (*loc));
7071
7072   gdb_assert (ops != NULL);
7073
7074   loc->ops = ops;
7075   loc->owner = owner;
7076   loc->cond = NULL;
7077   loc->cond_bytecode = NULL;
7078   loc->shlib_disabled = 0;
7079   loc->enabled = 1;
7080
7081   switch (owner->type)
7082     {
7083     case bp_breakpoint:
7084     case bp_until:
7085     case bp_finish:
7086     case bp_longjmp:
7087     case bp_longjmp_resume:
7088     case bp_longjmp_call_dummy:
7089     case bp_exception:
7090     case bp_exception_resume:
7091     case bp_step_resume:
7092     case bp_hp_step_resume:
7093     case bp_watchpoint_scope:
7094     case bp_call_dummy:
7095     case bp_std_terminate:
7096     case bp_shlib_event:
7097     case bp_thread_event:
7098     case bp_overlay_event:
7099     case bp_jit_event:
7100     case bp_longjmp_master:
7101     case bp_std_terminate_master:
7102     case bp_exception_master:
7103     case bp_gnu_ifunc_resolver:
7104     case bp_gnu_ifunc_resolver_return:
7105     case bp_dprintf:
7106       loc->loc_type = bp_loc_software_breakpoint;
7107       mark_breakpoint_location_modified (loc);
7108       break;
7109     case bp_hardware_breakpoint:
7110       loc->loc_type = bp_loc_hardware_breakpoint;
7111       mark_breakpoint_location_modified (loc);
7112       break;
7113     case bp_hardware_watchpoint:
7114     case bp_read_watchpoint:
7115     case bp_access_watchpoint:
7116       loc->loc_type = bp_loc_hardware_watchpoint;
7117       break;
7118     case bp_watchpoint:
7119     case bp_catchpoint:
7120     case bp_tracepoint:
7121     case bp_fast_tracepoint:
7122     case bp_static_tracepoint:
7123       loc->loc_type = bp_loc_other;
7124       break;
7125     default:
7126       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7127     }
7128
7129   loc->refc = 1;
7130 }
7131
7132 /* Allocate a struct bp_location.  */
7133
7134 static struct bp_location *
7135 allocate_bp_location (struct breakpoint *bpt)
7136 {
7137   return bpt->ops->allocate_location (bpt);
7138 }
7139
7140 static void
7141 free_bp_location (struct bp_location *loc)
7142 {
7143   loc->ops->dtor (loc);
7144   xfree (loc);
7145 }
7146
7147 /* Increment reference count.  */
7148
7149 static void
7150 incref_bp_location (struct bp_location *bl)
7151 {
7152   ++bl->refc;
7153 }
7154
7155 /* Decrement reference count.  If the reference count reaches 0,
7156    destroy the bp_location.  Sets *BLP to NULL.  */
7157
7158 static void
7159 decref_bp_location (struct bp_location **blp)
7160 {
7161   gdb_assert ((*blp)->refc > 0);
7162
7163   if (--(*blp)->refc == 0)
7164     free_bp_location (*blp);
7165   *blp = NULL;
7166 }
7167
7168 /* Add breakpoint B at the end of the global breakpoint chain.  */
7169
7170 static void
7171 add_to_breakpoint_chain (struct breakpoint *b)
7172 {
7173   struct breakpoint *b1;
7174
7175   /* Add this breakpoint to the end of the chain so that a list of
7176      breakpoints will come out in order of increasing numbers.  */
7177
7178   b1 = breakpoint_chain;
7179   if (b1 == 0)
7180     breakpoint_chain = b;
7181   else
7182     {
7183       while (b1->next)
7184         b1 = b1->next;
7185       b1->next = b;
7186     }
7187 }
7188
7189 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7190
7191 static void
7192 init_raw_breakpoint_without_location (struct breakpoint *b,
7193                                       struct gdbarch *gdbarch,
7194                                       enum bptype bptype,
7195                                       const struct breakpoint_ops *ops)
7196 {
7197   memset (b, 0, sizeof (*b));
7198
7199   gdb_assert (ops != NULL);
7200
7201   b->ops = ops;
7202   b->type = bptype;
7203   b->gdbarch = gdbarch;
7204   b->language = current_language->la_language;
7205   b->input_radix = input_radix;
7206   b->thread = -1;
7207   b->enable_state = bp_enabled;
7208   b->next = 0;
7209   b->silent = 0;
7210   b->ignore_count = 0;
7211   b->commands = NULL;
7212   b->frame_id = null_frame_id;
7213   b->condition_not_parsed = 0;
7214   b->py_bp_object = NULL;
7215   b->related_breakpoint = b;
7216 }
7217
7218 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7219    that has type BPTYPE and has no locations as yet.  */
7220
7221 static struct breakpoint *
7222 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7223                                      enum bptype bptype,
7224                                      const struct breakpoint_ops *ops)
7225 {
7226   struct breakpoint *b = XNEW (struct breakpoint);
7227
7228   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7229   add_to_breakpoint_chain (b);
7230   return b;
7231 }
7232
7233 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7234    resolutions should be made as the user specified the location explicitly
7235    enough.  */
7236
7237 static void
7238 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7239 {
7240   gdb_assert (loc->owner != NULL);
7241
7242   if (loc->owner->type == bp_breakpoint
7243       || loc->owner->type == bp_hardware_breakpoint
7244       || is_tracepoint (loc->owner))
7245     {
7246       int is_gnu_ifunc;
7247       const char *function_name;
7248       CORE_ADDR func_addr;
7249
7250       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7251                                           &func_addr, NULL, &is_gnu_ifunc);
7252
7253       if (is_gnu_ifunc && !explicit_loc)
7254         {
7255           struct breakpoint *b = loc->owner;
7256
7257           gdb_assert (loc->pspace == current_program_space);
7258           if (gnu_ifunc_resolve_name (function_name,
7259                                       &loc->requested_address))
7260             {
7261               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7262               loc->address = adjust_breakpoint_address (loc->gdbarch,
7263                                                         loc->requested_address,
7264                                                         b->type);
7265             }
7266           else if (b->type == bp_breakpoint && b->loc == loc
7267                    && loc->next == NULL && b->related_breakpoint == b)
7268             {
7269               /* Create only the whole new breakpoint of this type but do not
7270                  mess more complicated breakpoints with multiple locations.  */
7271               b->type = bp_gnu_ifunc_resolver;
7272               /* Remember the resolver's address for use by the return
7273                  breakpoint.  */
7274               loc->related_address = func_addr;
7275             }
7276         }
7277
7278       if (function_name)
7279         loc->function_name = xstrdup (function_name);
7280     }
7281 }
7282
7283 /* Attempt to determine architecture of location identified by SAL.  */
7284 struct gdbarch *
7285 get_sal_arch (struct symtab_and_line sal)
7286 {
7287   if (sal.section)
7288     return get_objfile_arch (sal.section->objfile);
7289   if (sal.symtab)
7290     return get_objfile_arch (sal.symtab->objfile);
7291
7292   return NULL;
7293 }
7294
7295 /* Low level routine for partially initializing a breakpoint of type
7296    BPTYPE.  The newly created breakpoint's address, section, source
7297    file name, and line number are provided by SAL.
7298
7299    It is expected that the caller will complete the initialization of
7300    the newly created breakpoint struct as well as output any status
7301    information regarding the creation of a new breakpoint.  */
7302
7303 static void
7304 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7305                      struct symtab_and_line sal, enum bptype bptype,
7306                      const struct breakpoint_ops *ops)
7307 {
7308   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7309
7310   add_location_to_breakpoint (b, &sal);
7311
7312   if (bptype != bp_catchpoint)
7313     gdb_assert (sal.pspace != NULL);
7314
7315   /* Store the program space that was used to set the breakpoint,
7316      except for ordinary breakpoints, which are independent of the
7317      program space.  */
7318   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7319     b->pspace = sal.pspace;
7320 }
7321
7322 /* set_raw_breakpoint is a low level routine for allocating and
7323    partially initializing a breakpoint of type BPTYPE.  The newly
7324    created breakpoint's address, section, source file name, and line
7325    number are provided by SAL.  The newly created and partially
7326    initialized breakpoint is added to the breakpoint chain and
7327    is also returned as the value of this function.
7328
7329    It is expected that the caller will complete the initialization of
7330    the newly created breakpoint struct as well as output any status
7331    information regarding the creation of a new breakpoint.  In
7332    particular, set_raw_breakpoint does NOT set the breakpoint
7333    number!  Care should be taken to not allow an error to occur
7334    prior to completing the initialization of the breakpoint.  If this
7335    should happen, a bogus breakpoint will be left on the chain.  */
7336
7337 struct breakpoint *
7338 set_raw_breakpoint (struct gdbarch *gdbarch,
7339                     struct symtab_and_line sal, enum bptype bptype,
7340                     const struct breakpoint_ops *ops)
7341 {
7342   struct breakpoint *b = XNEW (struct breakpoint);
7343
7344   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7345   add_to_breakpoint_chain (b);
7346   return b;
7347 }
7348
7349
7350 /* Note that the breakpoint object B describes a permanent breakpoint
7351    instruction, hard-wired into the inferior's code.  */
7352 void
7353 make_breakpoint_permanent (struct breakpoint *b)
7354 {
7355   struct bp_location *bl;
7356
7357   b->enable_state = bp_permanent;
7358
7359   /* By definition, permanent breakpoints are already present in the
7360      code.  Mark all locations as inserted.  For now,
7361      make_breakpoint_permanent is called in just one place, so it's
7362      hard to say if it's reasonable to have permanent breakpoint with
7363      multiple locations or not, but it's easy to implement.  */
7364   for (bl = b->loc; bl; bl = bl->next)
7365     bl->inserted = 1;
7366 }
7367
7368 /* Call this routine when stepping and nexting to enable a breakpoint
7369    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7370    initiated the operation.  */
7371
7372 void
7373 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7374 {
7375   struct breakpoint *b, *b_tmp;
7376   int thread = tp->num;
7377
7378   /* To avoid having to rescan all objfile symbols at every step,
7379      we maintain a list of continually-inserted but always disabled
7380      longjmp "master" breakpoints.  Here, we simply create momentary
7381      clones of those and enable them for the requested thread.  */
7382   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7383     if (b->pspace == current_program_space
7384         && (b->type == bp_longjmp_master
7385             || b->type == bp_exception_master))
7386       {
7387         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7388         struct breakpoint *clone;
7389
7390         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7391            after their removal.  */
7392         clone = momentary_breakpoint_from_master (b, type,
7393                                                   &longjmp_breakpoint_ops, 1);
7394         clone->thread = thread;
7395       }
7396
7397   tp->initiating_frame = frame;
7398 }
7399
7400 /* Delete all longjmp breakpoints from THREAD.  */
7401 void
7402 delete_longjmp_breakpoint (int thread)
7403 {
7404   struct breakpoint *b, *b_tmp;
7405
7406   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7407     if (b->type == bp_longjmp || b->type == bp_exception)
7408       {
7409         if (b->thread == thread)
7410           delete_breakpoint (b);
7411       }
7412 }
7413
7414 void
7415 delete_longjmp_breakpoint_at_next_stop (int thread)
7416 {
7417   struct breakpoint *b, *b_tmp;
7418
7419   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7420     if (b->type == bp_longjmp || b->type == bp_exception)
7421       {
7422         if (b->thread == thread)
7423           b->disposition = disp_del_at_next_stop;
7424       }
7425 }
7426
7427 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7428    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7429    pointer to any of them.  Return NULL if this system cannot place longjmp
7430    breakpoints.  */
7431
7432 struct breakpoint *
7433 set_longjmp_breakpoint_for_call_dummy (void)
7434 {
7435   struct breakpoint *b, *retval = NULL;
7436
7437   ALL_BREAKPOINTS (b)
7438     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7439       {
7440         struct breakpoint *new_b;
7441
7442         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7443                                                   &momentary_breakpoint_ops,
7444                                                   1);
7445         new_b->thread = pid_to_thread_id (inferior_ptid);
7446
7447         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7448
7449         gdb_assert (new_b->related_breakpoint == new_b);
7450         if (retval == NULL)
7451           retval = new_b;
7452         new_b->related_breakpoint = retval;
7453         while (retval->related_breakpoint != new_b->related_breakpoint)
7454           retval = retval->related_breakpoint;
7455         retval->related_breakpoint = new_b;
7456       }
7457
7458   return retval;
7459 }
7460
7461 /* Verify all existing dummy frames and their associated breakpoints for
7462    TP.  Remove those which can no longer be found in the current frame
7463    stack.
7464
7465    You should call this function only at places where it is safe to currently
7466    unwind the whole stack.  Failed stack unwind would discard live dummy
7467    frames.  */
7468
7469 void
7470 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7471 {
7472   struct breakpoint *b, *b_tmp;
7473
7474   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7475     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7476       {
7477         struct breakpoint *dummy_b = b->related_breakpoint;
7478
7479         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7480           dummy_b = dummy_b->related_breakpoint;
7481         if (dummy_b->type != bp_call_dummy
7482             || frame_find_by_id (dummy_b->frame_id) != NULL)
7483           continue;
7484         
7485         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7486
7487         while (b->related_breakpoint != b)
7488           {
7489             if (b_tmp == b->related_breakpoint)
7490               b_tmp = b->related_breakpoint->next;
7491             delete_breakpoint (b->related_breakpoint);
7492           }
7493         delete_breakpoint (b);
7494       }
7495 }
7496
7497 void
7498 enable_overlay_breakpoints (void)
7499 {
7500   struct breakpoint *b;
7501
7502   ALL_BREAKPOINTS (b)
7503     if (b->type == bp_overlay_event)
7504     {
7505       b->enable_state = bp_enabled;
7506       update_global_location_list (1);
7507       overlay_events_enabled = 1;
7508     }
7509 }
7510
7511 void
7512 disable_overlay_breakpoints (void)
7513 {
7514   struct breakpoint *b;
7515
7516   ALL_BREAKPOINTS (b)
7517     if (b->type == bp_overlay_event)
7518     {
7519       b->enable_state = bp_disabled;
7520       update_global_location_list (0);
7521       overlay_events_enabled = 0;
7522     }
7523 }
7524
7525 /* Set an active std::terminate breakpoint for each std::terminate
7526    master breakpoint.  */
7527 void
7528 set_std_terminate_breakpoint (void)
7529 {
7530   struct breakpoint *b, *b_tmp;
7531
7532   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7533     if (b->pspace == current_program_space
7534         && b->type == bp_std_terminate_master)
7535       {
7536         momentary_breakpoint_from_master (b, bp_std_terminate,
7537                                           &momentary_breakpoint_ops, 1);
7538       }
7539 }
7540
7541 /* Delete all the std::terminate breakpoints.  */
7542 void
7543 delete_std_terminate_breakpoint (void)
7544 {
7545   struct breakpoint *b, *b_tmp;
7546
7547   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7548     if (b->type == bp_std_terminate)
7549       delete_breakpoint (b);
7550 }
7551
7552 struct breakpoint *
7553 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7554 {
7555   struct breakpoint *b;
7556
7557   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7558                                   &internal_breakpoint_ops);
7559
7560   b->enable_state = bp_enabled;
7561   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7562   b->addr_string
7563     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7564
7565   update_global_location_list_nothrow (1);
7566
7567   return b;
7568 }
7569
7570 void
7571 remove_thread_event_breakpoints (void)
7572 {
7573   struct breakpoint *b, *b_tmp;
7574
7575   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7576     if (b->type == bp_thread_event
7577         && b->loc->pspace == current_program_space)
7578       delete_breakpoint (b);
7579 }
7580
7581 struct lang_and_radix
7582   {
7583     enum language lang;
7584     int radix;
7585   };
7586
7587 /* Create a breakpoint for JIT code registration and unregistration.  */
7588
7589 struct breakpoint *
7590 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7591 {
7592   struct breakpoint *b;
7593
7594   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7595                                   &internal_breakpoint_ops);
7596   update_global_location_list_nothrow (1);
7597   return b;
7598 }
7599
7600 /* Remove JIT code registration and unregistration breakpoint(s).  */
7601
7602 void
7603 remove_jit_event_breakpoints (void)
7604 {
7605   struct breakpoint *b, *b_tmp;
7606
7607   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7608     if (b->type == bp_jit_event
7609         && b->loc->pspace == current_program_space)
7610       delete_breakpoint (b);
7611 }
7612
7613 void
7614 remove_solib_event_breakpoints (void)
7615 {
7616   struct breakpoint *b, *b_tmp;
7617
7618   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7619     if (b->type == bp_shlib_event
7620         && b->loc->pspace == current_program_space)
7621       delete_breakpoint (b);
7622 }
7623
7624 struct breakpoint *
7625 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7626 {
7627   struct breakpoint *b;
7628
7629   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7630                                   &internal_breakpoint_ops);
7631   update_global_location_list_nothrow (1);
7632   return b;
7633 }
7634
7635 /* Disable any breakpoints that are on code in shared libraries.  Only
7636    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7637
7638 void
7639 disable_breakpoints_in_shlibs (void)
7640 {
7641   struct bp_location *loc, **locp_tmp;
7642
7643   ALL_BP_LOCATIONS (loc, locp_tmp)
7644   {
7645     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7646     struct breakpoint *b = loc->owner;
7647
7648     /* We apply the check to all breakpoints, including disabled for
7649        those with loc->duplicate set.  This is so that when breakpoint
7650        becomes enabled, or the duplicate is removed, gdb will try to
7651        insert all breakpoints.  If we don't set shlib_disabled here,
7652        we'll try to insert those breakpoints and fail.  */
7653     if (((b->type == bp_breakpoint)
7654          || (b->type == bp_jit_event)
7655          || (b->type == bp_hardware_breakpoint)
7656          || (is_tracepoint (b)))
7657         && loc->pspace == current_program_space
7658         && !loc->shlib_disabled
7659         && solib_name_from_address (loc->pspace, loc->address)
7660         )
7661       {
7662         loc->shlib_disabled = 1;
7663       }
7664   }
7665 }
7666
7667 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7668    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7669    disabled ones can just stay disabled.  */
7670
7671 static void
7672 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7673 {
7674   struct bp_location *loc, **locp_tmp;
7675   int disabled_shlib_breaks = 0;
7676
7677   /* SunOS a.out shared libraries are always mapped, so do not
7678      disable breakpoints; they will only be reported as unloaded
7679      through clear_solib when GDB discards its shared library
7680      list.  See clear_solib for more information.  */
7681   if (exec_bfd != NULL
7682       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7683     return;
7684
7685   ALL_BP_LOCATIONS (loc, locp_tmp)
7686   {
7687     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7688     struct breakpoint *b = loc->owner;
7689
7690     if (solib->pspace == loc->pspace
7691         && !loc->shlib_disabled
7692         && (((b->type == bp_breakpoint
7693               || b->type == bp_jit_event
7694               || b->type == bp_hardware_breakpoint)
7695              && (loc->loc_type == bp_loc_hardware_breakpoint
7696                  || loc->loc_type == bp_loc_software_breakpoint))
7697             || is_tracepoint (b))
7698         && solib_contains_address_p (solib, loc->address))
7699       {
7700         loc->shlib_disabled = 1;
7701         /* At this point, we cannot rely on remove_breakpoint
7702            succeeding so we must mark the breakpoint as not inserted
7703            to prevent future errors occurring in remove_breakpoints.  */
7704         loc->inserted = 0;
7705
7706         /* This may cause duplicate notifications for the same breakpoint.  */
7707         observer_notify_breakpoint_modified (b);
7708
7709         if (!disabled_shlib_breaks)
7710           {
7711             target_terminal_ours_for_output ();
7712             warning (_("Temporarily disabling breakpoints "
7713                        "for unloaded shared library \"%s\""),
7714                      solib->so_name);
7715           }
7716         disabled_shlib_breaks = 1;
7717       }
7718   }
7719 }
7720
7721 /* Disable any breakpoints and tracepoints in OBJFILE upon
7722    notification of free_objfile.  Only apply to enabled breakpoints,
7723    disabled ones can just stay disabled.  */
7724
7725 static void
7726 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7727 {
7728   struct breakpoint *b;
7729
7730   if (objfile == NULL)
7731     return;
7732
7733   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7734      managed by the user with add-symbol-file/remove-symbol-file.
7735      Similarly to how breakpoints in shared libraries are handled in
7736      response to "nosharedlibrary", mark breakpoints in such modules
7737      shlib_disabled so they end up uninserted on the next global
7738      location list update.  Shared libraries not loaded by the user
7739      aren't handled here -- they're already handled in
7740      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7741      solib_unloaded observer.  We skip objfiles that are not
7742      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7743      main objfile).  */
7744   if ((objfile->flags & OBJF_SHARED) == 0
7745       || (objfile->flags & OBJF_USERLOADED) == 0)
7746     return;
7747
7748   ALL_BREAKPOINTS (b)
7749     {
7750       struct bp_location *loc;
7751       int bp_modified = 0;
7752
7753       if (!is_breakpoint (b) && !is_tracepoint (b))
7754         continue;
7755
7756       for (loc = b->loc; loc != NULL; loc = loc->next)
7757         {
7758           CORE_ADDR loc_addr = loc->address;
7759
7760           if (loc->loc_type != bp_loc_hardware_breakpoint
7761               && loc->loc_type != bp_loc_software_breakpoint)
7762             continue;
7763
7764           if (loc->shlib_disabled != 0)
7765             continue;
7766
7767           if (objfile->pspace != loc->pspace)
7768             continue;
7769
7770           if (loc->loc_type != bp_loc_hardware_breakpoint
7771               && loc->loc_type != bp_loc_software_breakpoint)
7772             continue;
7773
7774           if (is_addr_in_objfile (loc_addr, objfile))
7775             {
7776               loc->shlib_disabled = 1;
7777               /* At this point, we don't know whether the object was
7778                  unmapped from the inferior or not, so leave the
7779                  inserted flag alone.  We'll handle failure to
7780                  uninsert quietly, in case the object was indeed
7781                  unmapped.  */
7782
7783               mark_breakpoint_location_modified (loc);
7784
7785               bp_modified = 1;
7786             }
7787         }
7788
7789       if (bp_modified)
7790         observer_notify_breakpoint_modified (b);
7791     }
7792 }
7793
7794 /* FORK & VFORK catchpoints.  */
7795
7796 /* An instance of this type is used to represent a fork or vfork
7797    catchpoint.  It includes a "struct breakpoint" as a kind of base
7798    class; users downcast to "struct breakpoint *" when needed.  A
7799    breakpoint is really of this type iff its ops pointer points to
7800    CATCH_FORK_BREAKPOINT_OPS.  */
7801
7802 struct fork_catchpoint
7803 {
7804   /* The base class.  */
7805   struct breakpoint base;
7806
7807   /* Process id of a child process whose forking triggered this
7808      catchpoint.  This field is only valid immediately after this
7809      catchpoint has triggered.  */
7810   ptid_t forked_inferior_pid;
7811 };
7812
7813 /* Implement the "insert" breakpoint_ops method for fork
7814    catchpoints.  */
7815
7816 static int
7817 insert_catch_fork (struct bp_location *bl)
7818 {
7819   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7820 }
7821
7822 /* Implement the "remove" breakpoint_ops method for fork
7823    catchpoints.  */
7824
7825 static int
7826 remove_catch_fork (struct bp_location *bl)
7827 {
7828   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7829 }
7830
7831 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7832    catchpoints.  */
7833
7834 static int
7835 breakpoint_hit_catch_fork (const struct bp_location *bl,
7836                            struct address_space *aspace, CORE_ADDR bp_addr,
7837                            const struct target_waitstatus *ws)
7838 {
7839   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7840
7841   if (ws->kind != TARGET_WAITKIND_FORKED)
7842     return 0;
7843
7844   c->forked_inferior_pid = ws->value.related_pid;
7845   return 1;
7846 }
7847
7848 /* Implement the "print_it" breakpoint_ops method for fork
7849    catchpoints.  */
7850
7851 static enum print_stop_action
7852 print_it_catch_fork (bpstat bs)
7853 {
7854   struct ui_out *uiout = current_uiout;
7855   struct breakpoint *b = bs->breakpoint_at;
7856   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7857
7858   annotate_catchpoint (b->number);
7859   if (b->disposition == disp_del)
7860     ui_out_text (uiout, "\nTemporary catchpoint ");
7861   else
7862     ui_out_text (uiout, "\nCatchpoint ");
7863   if (ui_out_is_mi_like_p (uiout))
7864     {
7865       ui_out_field_string (uiout, "reason",
7866                            async_reason_lookup (EXEC_ASYNC_FORK));
7867       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7868     }
7869   ui_out_field_int (uiout, "bkptno", b->number);
7870   ui_out_text (uiout, " (forked process ");
7871   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7872   ui_out_text (uiout, "), ");
7873   return PRINT_SRC_AND_LOC;
7874 }
7875
7876 /* Implement the "print_one" breakpoint_ops method for fork
7877    catchpoints.  */
7878
7879 static void
7880 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7881 {
7882   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7883   struct value_print_options opts;
7884   struct ui_out *uiout = current_uiout;
7885
7886   get_user_print_options (&opts);
7887
7888   /* Field 4, the address, is omitted (which makes the columns not
7889      line up too nicely with the headers, but the effect is relatively
7890      readable).  */
7891   if (opts.addressprint)
7892     ui_out_field_skip (uiout, "addr");
7893   annotate_field (5);
7894   ui_out_text (uiout, "fork");
7895   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7896     {
7897       ui_out_text (uiout, ", process ");
7898       ui_out_field_int (uiout, "what",
7899                         ptid_get_pid (c->forked_inferior_pid));
7900       ui_out_spaces (uiout, 1);
7901     }
7902
7903   if (ui_out_is_mi_like_p (uiout))
7904     ui_out_field_string (uiout, "catch-type", "fork");
7905 }
7906
7907 /* Implement the "print_mention" breakpoint_ops method for fork
7908    catchpoints.  */
7909
7910 static void
7911 print_mention_catch_fork (struct breakpoint *b)
7912 {
7913   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7914 }
7915
7916 /* Implement the "print_recreate" breakpoint_ops method for fork
7917    catchpoints.  */
7918
7919 static void
7920 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7921 {
7922   fprintf_unfiltered (fp, "catch fork");
7923   print_recreate_thread (b, fp);
7924 }
7925
7926 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7927
7928 static struct breakpoint_ops catch_fork_breakpoint_ops;
7929
7930 /* Implement the "insert" breakpoint_ops method for vfork
7931    catchpoints.  */
7932
7933 static int
7934 insert_catch_vfork (struct bp_location *bl)
7935 {
7936   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7937 }
7938
7939 /* Implement the "remove" breakpoint_ops method for vfork
7940    catchpoints.  */
7941
7942 static int
7943 remove_catch_vfork (struct bp_location *bl)
7944 {
7945   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7946 }
7947
7948 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7949    catchpoints.  */
7950
7951 static int
7952 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7953                             struct address_space *aspace, CORE_ADDR bp_addr,
7954                             const struct target_waitstatus *ws)
7955 {
7956   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7957
7958   if (ws->kind != TARGET_WAITKIND_VFORKED)
7959     return 0;
7960
7961   c->forked_inferior_pid = ws->value.related_pid;
7962   return 1;
7963 }
7964
7965 /* Implement the "print_it" breakpoint_ops method for vfork
7966    catchpoints.  */
7967
7968 static enum print_stop_action
7969 print_it_catch_vfork (bpstat bs)
7970 {
7971   struct ui_out *uiout = current_uiout;
7972   struct breakpoint *b = bs->breakpoint_at;
7973   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7974
7975   annotate_catchpoint (b->number);
7976   if (b->disposition == disp_del)
7977     ui_out_text (uiout, "\nTemporary catchpoint ");
7978   else
7979     ui_out_text (uiout, "\nCatchpoint ");
7980   if (ui_out_is_mi_like_p (uiout))
7981     {
7982       ui_out_field_string (uiout, "reason",
7983                            async_reason_lookup (EXEC_ASYNC_VFORK));
7984       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7985     }
7986   ui_out_field_int (uiout, "bkptno", b->number);
7987   ui_out_text (uiout, " (vforked process ");
7988   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7989   ui_out_text (uiout, "), ");
7990   return PRINT_SRC_AND_LOC;
7991 }
7992
7993 /* Implement the "print_one" breakpoint_ops method for vfork
7994    catchpoints.  */
7995
7996 static void
7997 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7998 {
7999   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8000   struct value_print_options opts;
8001   struct ui_out *uiout = current_uiout;
8002
8003   get_user_print_options (&opts);
8004   /* Field 4, the address, is omitted (which makes the columns not
8005      line up too nicely with the headers, but the effect is relatively
8006      readable).  */
8007   if (opts.addressprint)
8008     ui_out_field_skip (uiout, "addr");
8009   annotate_field (5);
8010   ui_out_text (uiout, "vfork");
8011   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8012     {
8013       ui_out_text (uiout, ", process ");
8014       ui_out_field_int (uiout, "what",
8015                         ptid_get_pid (c->forked_inferior_pid));
8016       ui_out_spaces (uiout, 1);
8017     }
8018
8019   if (ui_out_is_mi_like_p (uiout))
8020     ui_out_field_string (uiout, "catch-type", "vfork");
8021 }
8022
8023 /* Implement the "print_mention" breakpoint_ops method for vfork
8024    catchpoints.  */
8025
8026 static void
8027 print_mention_catch_vfork (struct breakpoint *b)
8028 {
8029   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8030 }
8031
8032 /* Implement the "print_recreate" breakpoint_ops method for vfork
8033    catchpoints.  */
8034
8035 static void
8036 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8037 {
8038   fprintf_unfiltered (fp, "catch vfork");
8039   print_recreate_thread (b, fp);
8040 }
8041
8042 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8043
8044 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8045
8046 /* An instance of this type is used to represent an solib catchpoint.
8047    It includes a "struct breakpoint" as a kind of base class; users
8048    downcast to "struct breakpoint *" when needed.  A breakpoint is
8049    really of this type iff its ops pointer points to
8050    CATCH_SOLIB_BREAKPOINT_OPS.  */
8051
8052 struct solib_catchpoint
8053 {
8054   /* The base class.  */
8055   struct breakpoint base;
8056
8057   /* True for "catch load", false for "catch unload".  */
8058   unsigned char is_load;
8059
8060   /* Regular expression to match, if any.  COMPILED is only valid when
8061      REGEX is non-NULL.  */
8062   char *regex;
8063   regex_t compiled;
8064 };
8065
8066 static void
8067 dtor_catch_solib (struct breakpoint *b)
8068 {
8069   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8070
8071   if (self->regex)
8072     regfree (&self->compiled);
8073   xfree (self->regex);
8074
8075   base_breakpoint_ops.dtor (b);
8076 }
8077
8078 static int
8079 insert_catch_solib (struct bp_location *ignore)
8080 {
8081   return 0;
8082 }
8083
8084 static int
8085 remove_catch_solib (struct bp_location *ignore)
8086 {
8087   return 0;
8088 }
8089
8090 static int
8091 breakpoint_hit_catch_solib (const struct bp_location *bl,
8092                             struct address_space *aspace,
8093                             CORE_ADDR bp_addr,
8094                             const struct target_waitstatus *ws)
8095 {
8096   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8097   struct breakpoint *other;
8098
8099   if (ws->kind == TARGET_WAITKIND_LOADED)
8100     return 1;
8101
8102   ALL_BREAKPOINTS (other)
8103   {
8104     struct bp_location *other_bl;
8105
8106     if (other == bl->owner)
8107       continue;
8108
8109     if (other->type != bp_shlib_event)
8110       continue;
8111
8112     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8113       continue;
8114
8115     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8116       {
8117         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8118           return 1;
8119       }
8120   }
8121
8122   return 0;
8123 }
8124
8125 static void
8126 check_status_catch_solib (struct bpstats *bs)
8127 {
8128   struct solib_catchpoint *self
8129     = (struct solib_catchpoint *) bs->breakpoint_at;
8130   int ix;
8131
8132   if (self->is_load)
8133     {
8134       struct so_list *iter;
8135
8136       for (ix = 0;
8137            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8138                         ix, iter);
8139            ++ix)
8140         {
8141           if (!self->regex
8142               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8143             return;
8144         }
8145     }
8146   else
8147     {
8148       char *iter;
8149
8150       for (ix = 0;
8151            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8152                         ix, iter);
8153            ++ix)
8154         {
8155           if (!self->regex
8156               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8157             return;
8158         }
8159     }
8160
8161   bs->stop = 0;
8162   bs->print_it = print_it_noop;
8163 }
8164
8165 static enum print_stop_action
8166 print_it_catch_solib (bpstat bs)
8167 {
8168   struct breakpoint *b = bs->breakpoint_at;
8169   struct ui_out *uiout = current_uiout;
8170
8171   annotate_catchpoint (b->number);
8172   if (b->disposition == disp_del)
8173     ui_out_text (uiout, "\nTemporary catchpoint ");
8174   else
8175     ui_out_text (uiout, "\nCatchpoint ");
8176   ui_out_field_int (uiout, "bkptno", b->number);
8177   ui_out_text (uiout, "\n");
8178   if (ui_out_is_mi_like_p (uiout))
8179     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8180   print_solib_event (1);
8181   return PRINT_SRC_AND_LOC;
8182 }
8183
8184 static void
8185 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8186 {
8187   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8188   struct value_print_options opts;
8189   struct ui_out *uiout = current_uiout;
8190   char *msg;
8191
8192   get_user_print_options (&opts);
8193   /* Field 4, the address, is omitted (which makes the columns not
8194      line up too nicely with the headers, but the effect is relatively
8195      readable).  */
8196   if (opts.addressprint)
8197     {
8198       annotate_field (4);
8199       ui_out_field_skip (uiout, "addr");
8200     }
8201
8202   annotate_field (5);
8203   if (self->is_load)
8204     {
8205       if (self->regex)
8206         msg = xstrprintf (_("load of library matching %s"), self->regex);
8207       else
8208         msg = xstrdup (_("load of library"));
8209     }
8210   else
8211     {
8212       if (self->regex)
8213         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8214       else
8215         msg = xstrdup (_("unload of library"));
8216     }
8217   ui_out_field_string (uiout, "what", msg);
8218   xfree (msg);
8219
8220   if (ui_out_is_mi_like_p (uiout))
8221     ui_out_field_string (uiout, "catch-type",
8222                          self->is_load ? "load" : "unload");
8223 }
8224
8225 static void
8226 print_mention_catch_solib (struct breakpoint *b)
8227 {
8228   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8229
8230   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8231                    self->is_load ? "load" : "unload");
8232 }
8233
8234 static void
8235 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8236 {
8237   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8238
8239   fprintf_unfiltered (fp, "%s %s",
8240                       b->disposition == disp_del ? "tcatch" : "catch",
8241                       self->is_load ? "load" : "unload");
8242   if (self->regex)
8243     fprintf_unfiltered (fp, " %s", self->regex);
8244   fprintf_unfiltered (fp, "\n");
8245 }
8246
8247 static struct breakpoint_ops catch_solib_breakpoint_ops;
8248
8249 /* Shared helper function (MI and CLI) for creating and installing
8250    a shared object event catchpoint.  If IS_LOAD is non-zero then
8251    the events to be caught are load events, otherwise they are
8252    unload events.  If IS_TEMP is non-zero the catchpoint is a
8253    temporary one.  If ENABLED is non-zero the catchpoint is
8254    created in an enabled state.  */
8255
8256 void
8257 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8258 {
8259   struct solib_catchpoint *c;
8260   struct gdbarch *gdbarch = get_current_arch ();
8261   struct cleanup *cleanup;
8262
8263   if (!arg)
8264     arg = "";
8265   arg = skip_spaces (arg);
8266
8267   c = XCNEW (struct solib_catchpoint);
8268   cleanup = make_cleanup (xfree, c);
8269
8270   if (*arg != '\0')
8271     {
8272       int errcode;
8273
8274       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8275       if (errcode != 0)
8276         {
8277           char *err = get_regcomp_error (errcode, &c->compiled);
8278
8279           make_cleanup (xfree, err);
8280           error (_("Invalid regexp (%s): %s"), err, arg);
8281         }
8282       c->regex = xstrdup (arg);
8283     }
8284
8285   c->is_load = is_load;
8286   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8287                    &catch_solib_breakpoint_ops);
8288
8289   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8290
8291   discard_cleanups (cleanup);
8292   install_breakpoint (0, &c->base, 1);
8293 }
8294
8295 /* A helper function that does all the work for "catch load" and
8296    "catch unload".  */
8297
8298 static void
8299 catch_load_or_unload (char *arg, int from_tty, int is_load,
8300                       struct cmd_list_element *command)
8301 {
8302   int tempflag;
8303   const int enabled = 1;
8304
8305   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8306
8307   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8308 }
8309
8310 static void
8311 catch_load_command_1 (char *arg, int from_tty,
8312                       struct cmd_list_element *command)
8313 {
8314   catch_load_or_unload (arg, from_tty, 1, command);
8315 }
8316
8317 static void
8318 catch_unload_command_1 (char *arg, int from_tty,
8319                         struct cmd_list_element *command)
8320 {
8321   catch_load_or_unload (arg, from_tty, 0, command);
8322 }
8323
8324 /* An instance of this type is used to represent a syscall catchpoint.
8325    It includes a "struct breakpoint" as a kind of base class; users
8326    downcast to "struct breakpoint *" when needed.  A breakpoint is
8327    really of this type iff its ops pointer points to
8328    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8329
8330 struct syscall_catchpoint
8331 {
8332   /* The base class.  */
8333   struct breakpoint base;
8334
8335   /* Syscall numbers used for the 'catch syscall' feature.  If no
8336      syscall has been specified for filtering, its value is NULL.
8337      Otherwise, it holds a list of all syscalls to be caught.  The
8338      list elements are allocated with xmalloc.  */
8339   VEC(int) *syscalls_to_be_caught;
8340 };
8341
8342 /* Implement the "dtor" breakpoint_ops method for syscall
8343    catchpoints.  */
8344
8345 static void
8346 dtor_catch_syscall (struct breakpoint *b)
8347 {
8348   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8349
8350   VEC_free (int, c->syscalls_to_be_caught);
8351
8352   base_breakpoint_ops.dtor (b);
8353 }
8354
8355 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8356
8357 struct catch_syscall_inferior_data
8358 {
8359   /* We keep a count of the number of times the user has requested a
8360      particular syscall to be tracked, and pass this information to the
8361      target.  This lets capable targets implement filtering directly.  */
8362
8363   /* Number of times that "any" syscall is requested.  */
8364   int any_syscall_count;
8365
8366   /* Count of each system call.  */
8367   VEC(int) *syscalls_counts;
8368
8369   /* This counts all syscall catch requests, so we can readily determine
8370      if any catching is necessary.  */
8371   int total_syscalls_count;
8372 };
8373
8374 static struct catch_syscall_inferior_data*
8375 get_catch_syscall_inferior_data (struct inferior *inf)
8376 {
8377   struct catch_syscall_inferior_data *inf_data;
8378
8379   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8380   if (inf_data == NULL)
8381     {
8382       inf_data = XCNEW (struct catch_syscall_inferior_data);
8383       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8384     }
8385
8386   return inf_data;
8387 }
8388
8389 static void
8390 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8391 {
8392   xfree (arg);
8393 }
8394
8395
8396 /* Implement the "insert" breakpoint_ops method for syscall
8397    catchpoints.  */
8398
8399 static int
8400 insert_catch_syscall (struct bp_location *bl)
8401 {
8402   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8403   struct inferior *inf = current_inferior ();
8404   struct catch_syscall_inferior_data *inf_data
8405     = get_catch_syscall_inferior_data (inf);
8406
8407   ++inf_data->total_syscalls_count;
8408   if (!c->syscalls_to_be_caught)
8409     ++inf_data->any_syscall_count;
8410   else
8411     {
8412       int i, iter;
8413
8414       for (i = 0;
8415            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8416            i++)
8417         {
8418           int elem;
8419
8420           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8421             {
8422               int old_size = VEC_length (int, inf_data->syscalls_counts);
8423               uintptr_t vec_addr_offset
8424                 = old_size * ((uintptr_t) sizeof (int));
8425               uintptr_t vec_addr;
8426               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8427               vec_addr = ((uintptr_t) VEC_address (int,
8428                                                   inf_data->syscalls_counts)
8429                           + vec_addr_offset);
8430               memset ((void *) vec_addr, 0,
8431                       (iter + 1 - old_size) * sizeof (int));
8432             }
8433           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8434           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8435         }
8436     }
8437
8438   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8439                                         inf_data->total_syscalls_count != 0,
8440                                         inf_data->any_syscall_count,
8441                                         VEC_length (int,
8442                                                     inf_data->syscalls_counts),
8443                                         VEC_address (int,
8444                                                      inf_data->syscalls_counts));
8445 }
8446
8447 /* Implement the "remove" breakpoint_ops method for syscall
8448    catchpoints.  */
8449
8450 static int
8451 remove_catch_syscall (struct bp_location *bl)
8452 {
8453   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8454   struct inferior *inf = current_inferior ();
8455   struct catch_syscall_inferior_data *inf_data
8456     = get_catch_syscall_inferior_data (inf);
8457
8458   --inf_data->total_syscalls_count;
8459   if (!c->syscalls_to_be_caught)
8460     --inf_data->any_syscall_count;
8461   else
8462     {
8463       int i, iter;
8464
8465       for (i = 0;
8466            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8467            i++)
8468         {
8469           int elem;
8470           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8471             /* Shouldn't happen.  */
8472             continue;
8473           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8474           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8475         }
8476     }
8477
8478   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8479                                         inf_data->total_syscalls_count != 0,
8480                                         inf_data->any_syscall_count,
8481                                         VEC_length (int,
8482                                                     inf_data->syscalls_counts),
8483                                         VEC_address (int,
8484                                                      inf_data->syscalls_counts));
8485 }
8486
8487 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8488    catchpoints.  */
8489
8490 static int
8491 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8492                               struct address_space *aspace, CORE_ADDR bp_addr,
8493                               const struct target_waitstatus *ws)
8494 {
8495   /* We must check if we are catching specific syscalls in this
8496      breakpoint.  If we are, then we must guarantee that the called
8497      syscall is the same syscall we are catching.  */
8498   int syscall_number = 0;
8499   const struct syscall_catchpoint *c
8500     = (const struct syscall_catchpoint *) bl->owner;
8501
8502   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8503       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8504     return 0;
8505
8506   syscall_number = ws->value.syscall_number;
8507
8508   /* Now, checking if the syscall is the same.  */
8509   if (c->syscalls_to_be_caught)
8510     {
8511       int i, iter;
8512
8513       for (i = 0;
8514            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8515            i++)
8516         if (syscall_number == iter)
8517           return 1;
8518
8519       return 0;
8520     }
8521
8522   return 1;
8523 }
8524
8525 /* Implement the "print_it" breakpoint_ops method for syscall
8526    catchpoints.  */
8527
8528 static enum print_stop_action
8529 print_it_catch_syscall (bpstat bs)
8530 {
8531   struct ui_out *uiout = current_uiout;
8532   struct breakpoint *b = bs->breakpoint_at;
8533   /* These are needed because we want to know in which state a
8534      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8535      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8536      must print "called syscall" or "returned from syscall".  */
8537   ptid_t ptid;
8538   struct target_waitstatus last;
8539   struct syscall s;
8540
8541   get_last_target_status (&ptid, &last);
8542
8543   get_syscall_by_number (last.value.syscall_number, &s);
8544
8545   annotate_catchpoint (b->number);
8546
8547   if (b->disposition == disp_del)
8548     ui_out_text (uiout, "\nTemporary catchpoint ");
8549   else
8550     ui_out_text (uiout, "\nCatchpoint ");
8551   if (ui_out_is_mi_like_p (uiout))
8552     {
8553       ui_out_field_string (uiout, "reason",
8554                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8555                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8556                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8557       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8558     }
8559   ui_out_field_int (uiout, "bkptno", b->number);
8560
8561   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8562     ui_out_text (uiout, " (call to syscall ");
8563   else
8564     ui_out_text (uiout, " (returned from syscall ");
8565
8566   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8567     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8568   if (s.name != NULL)
8569     ui_out_field_string (uiout, "syscall-name", s.name);
8570
8571   ui_out_text (uiout, "), ");
8572
8573   return PRINT_SRC_AND_LOC;
8574 }
8575
8576 /* Implement the "print_one" breakpoint_ops method for syscall
8577    catchpoints.  */
8578
8579 static void
8580 print_one_catch_syscall (struct breakpoint *b,
8581                          struct bp_location **last_loc)
8582 {
8583   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8584   struct value_print_options opts;
8585   struct ui_out *uiout = current_uiout;
8586
8587   get_user_print_options (&opts);
8588   /* Field 4, the address, is omitted (which makes the columns not
8589      line up too nicely with the headers, but the effect is relatively
8590      readable).  */
8591   if (opts.addressprint)
8592     ui_out_field_skip (uiout, "addr");
8593   annotate_field (5);
8594
8595   if (c->syscalls_to_be_caught
8596       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8597     ui_out_text (uiout, "syscalls \"");
8598   else
8599     ui_out_text (uiout, "syscall \"");
8600
8601   if (c->syscalls_to_be_caught)
8602     {
8603       int i, iter;
8604       char *text = xstrprintf ("%s", "");
8605
8606       for (i = 0;
8607            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8608            i++)
8609         {
8610           char *x = text;
8611           struct syscall s;
8612           get_syscall_by_number (iter, &s);
8613
8614           if (s.name != NULL)
8615             text = xstrprintf ("%s%s, ", text, s.name);
8616           else
8617             text = xstrprintf ("%s%d, ", text, iter);
8618
8619           /* We have to xfree the last 'text' (now stored at 'x')
8620              because xstrprintf dynamically allocates new space for it
8621              on every call.  */
8622           xfree (x);
8623         }
8624       /* Remove the last comma.  */
8625       text[strlen (text) - 2] = '\0';
8626       ui_out_field_string (uiout, "what", text);
8627     }
8628   else
8629     ui_out_field_string (uiout, "what", "<any syscall>");
8630   ui_out_text (uiout, "\" ");
8631
8632   if (ui_out_is_mi_like_p (uiout))
8633     ui_out_field_string (uiout, "catch-type", "syscall");
8634 }
8635
8636 /* Implement the "print_mention" breakpoint_ops method for syscall
8637    catchpoints.  */
8638
8639 static void
8640 print_mention_catch_syscall (struct breakpoint *b)
8641 {
8642   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8643
8644   if (c->syscalls_to_be_caught)
8645     {
8646       int i, iter;
8647
8648       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8649         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8650       else
8651         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8652
8653       for (i = 0;
8654            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8655            i++)
8656         {
8657           struct syscall s;
8658           get_syscall_by_number (iter, &s);
8659
8660           if (s.name)
8661             printf_filtered (" '%s' [%d]", s.name, s.number);
8662           else
8663             printf_filtered (" %d", s.number);
8664         }
8665       printf_filtered (")");
8666     }
8667   else
8668     printf_filtered (_("Catchpoint %d (any syscall)"),
8669                      b->number);
8670 }
8671
8672 /* Implement the "print_recreate" breakpoint_ops method for syscall
8673    catchpoints.  */
8674
8675 static void
8676 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8677 {
8678   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8679
8680   fprintf_unfiltered (fp, "catch syscall");
8681
8682   if (c->syscalls_to_be_caught)
8683     {
8684       int i, iter;
8685
8686       for (i = 0;
8687            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8688            i++)
8689         {
8690           struct syscall s;
8691
8692           get_syscall_by_number (iter, &s);
8693           if (s.name)
8694             fprintf_unfiltered (fp, " %s", s.name);
8695           else
8696             fprintf_unfiltered (fp, " %d", s.number);
8697         }
8698     }
8699   print_recreate_thread (b, fp);
8700 }
8701
8702 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8703
8704 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8705
8706 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8707
8708 static int
8709 syscall_catchpoint_p (struct breakpoint *b)
8710 {
8711   return (b->ops == &catch_syscall_breakpoint_ops);
8712 }
8713
8714 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8715    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8716    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8717    the breakpoint_ops structure associated to the catchpoint.  */
8718
8719 void
8720 init_catchpoint (struct breakpoint *b,
8721                  struct gdbarch *gdbarch, int tempflag,
8722                  char *cond_string,
8723                  const struct breakpoint_ops *ops)
8724 {
8725   struct symtab_and_line sal;
8726
8727   init_sal (&sal);
8728   sal.pspace = current_program_space;
8729
8730   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8731
8732   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8733   b->disposition = tempflag ? disp_del : disp_donttouch;
8734 }
8735
8736 void
8737 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8738 {
8739   add_to_breakpoint_chain (b);
8740   set_breakpoint_number (internal, b);
8741   if (is_tracepoint (b))
8742     set_tracepoint_count (breakpoint_count);
8743   if (!internal)
8744     mention (b);
8745   observer_notify_breakpoint_created (b);
8746
8747   if (update_gll)
8748     update_global_location_list (1);
8749 }
8750
8751 static void
8752 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8753                                     int tempflag, char *cond_string,
8754                                     const struct breakpoint_ops *ops)
8755 {
8756   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8757
8758   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8759
8760   c->forked_inferior_pid = null_ptid;
8761
8762   install_breakpoint (0, &c->base, 1);
8763 }
8764
8765 /* Exec catchpoints.  */
8766
8767 /* An instance of this type is used to represent an exec catchpoint.
8768    It includes a "struct breakpoint" as a kind of base class; users
8769    downcast to "struct breakpoint *" when needed.  A breakpoint is
8770    really of this type iff its ops pointer points to
8771    CATCH_EXEC_BREAKPOINT_OPS.  */
8772
8773 struct exec_catchpoint
8774 {
8775   /* The base class.  */
8776   struct breakpoint base;
8777
8778   /* Filename of a program whose exec triggered this catchpoint.
8779      This field is only valid immediately after this catchpoint has
8780      triggered.  */
8781   char *exec_pathname;
8782 };
8783
8784 /* Implement the "dtor" breakpoint_ops method for exec
8785    catchpoints.  */
8786
8787 static void
8788 dtor_catch_exec (struct breakpoint *b)
8789 {
8790   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8791
8792   xfree (c->exec_pathname);
8793
8794   base_breakpoint_ops.dtor (b);
8795 }
8796
8797 static int
8798 insert_catch_exec (struct bp_location *bl)
8799 {
8800   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8801 }
8802
8803 static int
8804 remove_catch_exec (struct bp_location *bl)
8805 {
8806   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8807 }
8808
8809 static int
8810 breakpoint_hit_catch_exec (const struct bp_location *bl,
8811                            struct address_space *aspace, CORE_ADDR bp_addr,
8812                            const struct target_waitstatus *ws)
8813 {
8814   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8815
8816   if (ws->kind != TARGET_WAITKIND_EXECD)
8817     return 0;
8818
8819   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8820   return 1;
8821 }
8822
8823 static enum print_stop_action
8824 print_it_catch_exec (bpstat bs)
8825 {
8826   struct ui_out *uiout = current_uiout;
8827   struct breakpoint *b = bs->breakpoint_at;
8828   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8829
8830   annotate_catchpoint (b->number);
8831   if (b->disposition == disp_del)
8832     ui_out_text (uiout, "\nTemporary catchpoint ");
8833   else
8834     ui_out_text (uiout, "\nCatchpoint ");
8835   if (ui_out_is_mi_like_p (uiout))
8836     {
8837       ui_out_field_string (uiout, "reason",
8838                            async_reason_lookup (EXEC_ASYNC_EXEC));
8839       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8840     }
8841   ui_out_field_int (uiout, "bkptno", b->number);
8842   ui_out_text (uiout, " (exec'd ");
8843   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8844   ui_out_text (uiout, "), ");
8845
8846   return PRINT_SRC_AND_LOC;
8847 }
8848
8849 static void
8850 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8851 {
8852   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8853   struct value_print_options opts;
8854   struct ui_out *uiout = current_uiout;
8855
8856   get_user_print_options (&opts);
8857
8858   /* Field 4, the address, is omitted (which makes the columns
8859      not line up too nicely with the headers, but the effect
8860      is relatively readable).  */
8861   if (opts.addressprint)
8862     ui_out_field_skip (uiout, "addr");
8863   annotate_field (5);
8864   ui_out_text (uiout, "exec");
8865   if (c->exec_pathname != NULL)
8866     {
8867       ui_out_text (uiout, ", program \"");
8868       ui_out_field_string (uiout, "what", c->exec_pathname);
8869       ui_out_text (uiout, "\" ");
8870     }
8871
8872   if (ui_out_is_mi_like_p (uiout))
8873     ui_out_field_string (uiout, "catch-type", "exec");
8874 }
8875
8876 static void
8877 print_mention_catch_exec (struct breakpoint *b)
8878 {
8879   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8880 }
8881
8882 /* Implement the "print_recreate" breakpoint_ops method for exec
8883    catchpoints.  */
8884
8885 static void
8886 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8887 {
8888   fprintf_unfiltered (fp, "catch exec");
8889   print_recreate_thread (b, fp);
8890 }
8891
8892 static struct breakpoint_ops catch_exec_breakpoint_ops;
8893
8894 static void
8895 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8896                                  const struct breakpoint_ops *ops)
8897 {
8898   struct syscall_catchpoint *c;
8899   struct gdbarch *gdbarch = get_current_arch ();
8900
8901   c = XNEW (struct syscall_catchpoint);
8902   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8903   c->syscalls_to_be_caught = filter;
8904
8905   install_breakpoint (0, &c->base, 1);
8906 }
8907
8908 static int
8909 hw_breakpoint_used_count (void)
8910 {
8911   int i = 0;
8912   struct breakpoint *b;
8913   struct bp_location *bl;
8914
8915   ALL_BREAKPOINTS (b)
8916   {
8917     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8918       for (bl = b->loc; bl; bl = bl->next)
8919         {
8920           /* Special types of hardware breakpoints may use more than
8921              one register.  */
8922           i += b->ops->resources_needed (bl);
8923         }
8924   }
8925
8926   return i;
8927 }
8928
8929 /* Returns the resources B would use if it were a hardware
8930    watchpoint.  */
8931
8932 static int
8933 hw_watchpoint_use_count (struct breakpoint *b)
8934 {
8935   int i = 0;
8936   struct bp_location *bl;
8937
8938   if (!breakpoint_enabled (b))
8939     return 0;
8940
8941   for (bl = b->loc; bl; bl = bl->next)
8942     {
8943       /* Special types of hardware watchpoints may use more than
8944          one register.  */
8945       i += b->ops->resources_needed (bl);
8946     }
8947
8948   return i;
8949 }
8950
8951 /* Returns the sum the used resources of all hardware watchpoints of
8952    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8953    the sum of the used resources of all hardware watchpoints of other
8954    types _not_ TYPE.  */
8955
8956 static int
8957 hw_watchpoint_used_count_others (struct breakpoint *except,
8958                                  enum bptype type, int *other_type_used)
8959 {
8960   int i = 0;
8961   struct breakpoint *b;
8962
8963   *other_type_used = 0;
8964   ALL_BREAKPOINTS (b)
8965     {
8966       if (b == except)
8967         continue;
8968       if (!breakpoint_enabled (b))
8969         continue;
8970
8971       if (b->type == type)
8972         i += hw_watchpoint_use_count (b);
8973       else if (is_hardware_watchpoint (b))
8974         *other_type_used = 1;
8975     }
8976
8977   return i;
8978 }
8979
8980 void
8981 disable_watchpoints_before_interactive_call_start (void)
8982 {
8983   struct breakpoint *b;
8984
8985   ALL_BREAKPOINTS (b)
8986   {
8987     if (is_watchpoint (b) && breakpoint_enabled (b))
8988       {
8989         b->enable_state = bp_call_disabled;
8990         update_global_location_list (0);
8991       }
8992   }
8993 }
8994
8995 void
8996 enable_watchpoints_after_interactive_call_stop (void)
8997 {
8998   struct breakpoint *b;
8999
9000   ALL_BREAKPOINTS (b)
9001   {
9002     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9003       {
9004         b->enable_state = bp_enabled;
9005         update_global_location_list (1);
9006       }
9007   }
9008 }
9009
9010 void
9011 disable_breakpoints_before_startup (void)
9012 {
9013   current_program_space->executing_startup = 1;
9014   update_global_location_list (0);
9015 }
9016
9017 void
9018 enable_breakpoints_after_startup (void)
9019 {
9020   current_program_space->executing_startup = 0;
9021   breakpoint_re_set ();
9022 }
9023
9024
9025 /* Set a breakpoint that will evaporate an end of command
9026    at address specified by SAL.
9027    Restrict it to frame FRAME if FRAME is nonzero.  */
9028
9029 struct breakpoint *
9030 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9031                           struct frame_id frame_id, enum bptype type)
9032 {
9033   struct breakpoint *b;
9034
9035   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9036      tail-called one.  */
9037   gdb_assert (!frame_id_artificial_p (frame_id));
9038
9039   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9040   b->enable_state = bp_enabled;
9041   b->disposition = disp_donttouch;
9042   b->frame_id = frame_id;
9043
9044   /* If we're debugging a multi-threaded program, then we want
9045      momentary breakpoints to be active in only a single thread of
9046      control.  */
9047   if (in_thread_list (inferior_ptid))
9048     b->thread = pid_to_thread_id (inferior_ptid);
9049
9050   update_global_location_list_nothrow (1);
9051
9052   return b;
9053 }
9054
9055 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9056    The new breakpoint will have type TYPE, use OPS as its
9057    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9058
9059 static struct breakpoint *
9060 momentary_breakpoint_from_master (struct breakpoint *orig,
9061                                   enum bptype type,
9062                                   const struct breakpoint_ops *ops,
9063                                   int loc_enabled)
9064 {
9065   struct breakpoint *copy;
9066
9067   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9068   copy->loc = allocate_bp_location (copy);
9069   set_breakpoint_location_function (copy->loc, 1);
9070
9071   copy->loc->gdbarch = orig->loc->gdbarch;
9072   copy->loc->requested_address = orig->loc->requested_address;
9073   copy->loc->address = orig->loc->address;
9074   copy->loc->section = orig->loc->section;
9075   copy->loc->pspace = orig->loc->pspace;
9076   copy->loc->probe = orig->loc->probe;
9077   copy->loc->line_number = orig->loc->line_number;
9078   copy->loc->symtab = orig->loc->symtab;
9079   copy->loc->enabled = loc_enabled;
9080   copy->frame_id = orig->frame_id;
9081   copy->thread = orig->thread;
9082   copy->pspace = orig->pspace;
9083
9084   copy->enable_state = bp_enabled;
9085   copy->disposition = disp_donttouch;
9086   copy->number = internal_breakpoint_number--;
9087
9088   update_global_location_list_nothrow (0);
9089   return copy;
9090 }
9091
9092 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9093    ORIG is NULL.  */
9094
9095 struct breakpoint *
9096 clone_momentary_breakpoint (struct breakpoint *orig)
9097 {
9098   /* If there's nothing to clone, then return nothing.  */
9099   if (orig == NULL)
9100     return NULL;
9101
9102   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9103 }
9104
9105 struct breakpoint *
9106 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9107                                 enum bptype type)
9108 {
9109   struct symtab_and_line sal;
9110
9111   sal = find_pc_line (pc, 0);
9112   sal.pc = pc;
9113   sal.section = find_pc_overlay (pc);
9114   sal.explicit_pc = 1;
9115
9116   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9117 }
9118 \f
9119
9120 /* Tell the user we have just set a breakpoint B.  */
9121
9122 static void
9123 mention (struct breakpoint *b)
9124 {
9125   b->ops->print_mention (b);
9126   if (ui_out_is_mi_like_p (current_uiout))
9127     return;
9128   printf_filtered ("\n");
9129 }
9130 \f
9131
9132 static struct bp_location *
9133 add_location_to_breakpoint (struct breakpoint *b,
9134                             const struct symtab_and_line *sal)
9135 {
9136   struct bp_location *loc, **tmp;
9137   CORE_ADDR adjusted_address;
9138   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9139
9140   if (loc_gdbarch == NULL)
9141     loc_gdbarch = b->gdbarch;
9142
9143   /* Adjust the breakpoint's address prior to allocating a location.
9144      Once we call allocate_bp_location(), that mostly uninitialized
9145      location will be placed on the location chain.  Adjustment of the
9146      breakpoint may cause target_read_memory() to be called and we do
9147      not want its scan of the location chain to find a breakpoint and
9148      location that's only been partially initialized.  */
9149   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9150                                                 sal->pc, b->type);
9151
9152   /* Sort the locations by their ADDRESS.  */
9153   loc = allocate_bp_location (b);
9154   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9155        tmp = &((*tmp)->next))
9156     ;
9157   loc->next = *tmp;
9158   *tmp = loc;
9159
9160   loc->requested_address = sal->pc;
9161   loc->address = adjusted_address;
9162   loc->pspace = sal->pspace;
9163   loc->probe.probe = sal->probe;
9164   loc->probe.objfile = sal->objfile;
9165   gdb_assert (loc->pspace != NULL);
9166   loc->section = sal->section;
9167   loc->gdbarch = loc_gdbarch;
9168   loc->line_number = sal->line;
9169   loc->symtab = sal->symtab;
9170
9171   set_breakpoint_location_function (loc,
9172                                     sal->explicit_pc || sal->explicit_line);
9173   return loc;
9174 }
9175 \f
9176
9177 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9178    return 0 otherwise.  */
9179
9180 static int
9181 bp_loc_is_permanent (struct bp_location *loc)
9182 {
9183   int len;
9184   CORE_ADDR addr;
9185   const gdb_byte *bpoint;
9186   gdb_byte *target_mem;
9187   struct cleanup *cleanup;
9188   int retval = 0;
9189
9190   gdb_assert (loc != NULL);
9191
9192   addr = loc->address;
9193   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9194
9195   /* Software breakpoints unsupported?  */
9196   if (bpoint == NULL)
9197     return 0;
9198
9199   target_mem = alloca (len);
9200
9201   /* Enable the automatic memory restoration from breakpoints while
9202      we read the memory.  Otherwise we could say about our temporary
9203      breakpoints they are permanent.  */
9204   cleanup = save_current_space_and_thread ();
9205
9206   switch_to_program_space_and_thread (loc->pspace);
9207   make_show_memory_breakpoints_cleanup (0);
9208
9209   if (target_read_memory (loc->address, target_mem, len) == 0
9210       && memcmp (target_mem, bpoint, len) == 0)
9211     retval = 1;
9212
9213   do_cleanups (cleanup);
9214
9215   return retval;
9216 }
9217
9218 /* Build a command list for the dprintf corresponding to the current
9219    settings of the dprintf style options.  */
9220
9221 static void
9222 update_dprintf_command_list (struct breakpoint *b)
9223 {
9224   char *dprintf_args = b->extra_string;
9225   char *printf_line = NULL;
9226
9227   if (!dprintf_args)
9228     return;
9229
9230   dprintf_args = skip_spaces (dprintf_args);
9231
9232   /* Allow a comma, as it may have terminated a location, but don't
9233      insist on it.  */
9234   if (*dprintf_args == ',')
9235     ++dprintf_args;
9236   dprintf_args = skip_spaces (dprintf_args);
9237
9238   if (*dprintf_args != '"')
9239     error (_("Bad format string, missing '\"'."));
9240
9241   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9242     printf_line = xstrprintf ("printf %s", dprintf_args);
9243   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9244     {
9245       if (!dprintf_function)
9246         error (_("No function supplied for dprintf call"));
9247
9248       if (dprintf_channel && strlen (dprintf_channel) > 0)
9249         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9250                                   dprintf_function,
9251                                   dprintf_channel,
9252                                   dprintf_args);
9253       else
9254         printf_line = xstrprintf ("call (void) %s (%s)",
9255                                   dprintf_function,
9256                                   dprintf_args);
9257     }
9258   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9259     {
9260       if (target_can_run_breakpoint_commands ())
9261         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9262       else
9263         {
9264           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9265           printf_line = xstrprintf ("printf %s", dprintf_args);
9266         }
9267     }
9268   else
9269     internal_error (__FILE__, __LINE__,
9270                     _("Invalid dprintf style."));
9271
9272   gdb_assert (printf_line != NULL);
9273   /* Manufacture a printf sequence.  */
9274   {
9275     struct command_line *printf_cmd_line
9276       = xmalloc (sizeof (struct command_line));
9277
9278     printf_cmd_line = xmalloc (sizeof (struct command_line));
9279     printf_cmd_line->control_type = simple_control;
9280     printf_cmd_line->body_count = 0;
9281     printf_cmd_line->body_list = NULL;
9282     printf_cmd_line->next = NULL;
9283     printf_cmd_line->line = printf_line;
9284
9285     breakpoint_set_commands (b, printf_cmd_line);
9286   }
9287 }
9288
9289 /* Update all dprintf commands, making their command lists reflect
9290    current style settings.  */
9291
9292 static void
9293 update_dprintf_commands (char *args, int from_tty,
9294                          struct cmd_list_element *c)
9295 {
9296   struct breakpoint *b;
9297
9298   ALL_BREAKPOINTS (b)
9299     {
9300       if (b->type == bp_dprintf)
9301         update_dprintf_command_list (b);
9302     }
9303 }
9304
9305 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9306    as textual description of the location, and COND_STRING
9307    as condition expression.  */
9308
9309 static void
9310 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9311                      struct symtabs_and_lines sals, char *addr_string,
9312                      char *filter, char *cond_string,
9313                      char *extra_string,
9314                      enum bptype type, enum bpdisp disposition,
9315                      int thread, int task, int ignore_count,
9316                      const struct breakpoint_ops *ops, int from_tty,
9317                      int enabled, int internal, unsigned flags,
9318                      int display_canonical)
9319 {
9320   int i;
9321
9322   if (type == bp_hardware_breakpoint)
9323     {
9324       int target_resources_ok;
9325
9326       i = hw_breakpoint_used_count ();
9327       target_resources_ok =
9328         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9329                                             i + 1, 0);
9330       if (target_resources_ok == 0)
9331         error (_("No hardware breakpoint support in the target."));
9332       else if (target_resources_ok < 0)
9333         error (_("Hardware breakpoints used exceeds limit."));
9334     }
9335
9336   gdb_assert (sals.nelts > 0);
9337
9338   for (i = 0; i < sals.nelts; ++i)
9339     {
9340       struct symtab_and_line sal = sals.sals[i];
9341       struct bp_location *loc;
9342
9343       if (from_tty)
9344         {
9345           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9346           if (!loc_gdbarch)
9347             loc_gdbarch = gdbarch;
9348
9349           describe_other_breakpoints (loc_gdbarch,
9350                                       sal.pspace, sal.pc, sal.section, thread);
9351         }
9352
9353       if (i == 0)
9354         {
9355           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9356           b->thread = thread;
9357           b->task = task;
9358
9359           b->cond_string = cond_string;
9360           b->extra_string = extra_string;
9361           b->ignore_count = ignore_count;
9362           b->enable_state = enabled ? bp_enabled : bp_disabled;
9363           b->disposition = disposition;
9364
9365           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9366             b->loc->inserted = 1;
9367
9368           if (type == bp_static_tracepoint)
9369             {
9370               struct tracepoint *t = (struct tracepoint *) b;
9371               struct static_tracepoint_marker marker;
9372
9373               if (strace_marker_p (b))
9374                 {
9375                   /* We already know the marker exists, otherwise, we
9376                      wouldn't see a sal for it.  */
9377                   char *p = &addr_string[3];
9378                   char *endp;
9379                   char *marker_str;
9380
9381                   p = skip_spaces (p);
9382
9383                   endp = skip_to_space (p);
9384
9385                   marker_str = savestring (p, endp - p);
9386                   t->static_trace_marker_id = marker_str;
9387
9388                   printf_filtered (_("Probed static tracepoint "
9389                                      "marker \"%s\"\n"),
9390                                    t->static_trace_marker_id);
9391                 }
9392               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9393                 {
9394                   t->static_trace_marker_id = xstrdup (marker.str_id);
9395                   release_static_tracepoint_marker (&marker);
9396
9397                   printf_filtered (_("Probed static tracepoint "
9398                                      "marker \"%s\"\n"),
9399                                    t->static_trace_marker_id);
9400                 }
9401               else
9402                 warning (_("Couldn't determine the static "
9403                            "tracepoint marker to probe"));
9404             }
9405
9406           loc = b->loc;
9407         }
9408       else
9409         {
9410           loc = add_location_to_breakpoint (b, &sal);
9411           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9412             loc->inserted = 1;
9413         }
9414
9415       if (bp_loc_is_permanent (loc))
9416         make_breakpoint_permanent (b);
9417
9418       if (b->cond_string)
9419         {
9420           const char *arg = b->cond_string;
9421
9422           loc->cond = parse_exp_1 (&arg, loc->address,
9423                                    block_for_pc (loc->address), 0);
9424           if (*arg)
9425               error (_("Garbage '%s' follows condition"), arg);
9426         }
9427
9428       /* Dynamic printf requires and uses additional arguments on the
9429          command line, otherwise it's an error.  */
9430       if (type == bp_dprintf)
9431         {
9432           if (b->extra_string)
9433             update_dprintf_command_list (b);
9434           else
9435             error (_("Format string required"));
9436         }
9437       else if (b->extra_string)
9438         error (_("Garbage '%s' at end of command"), b->extra_string);
9439     }
9440
9441   b->display_canonical = display_canonical;
9442   if (addr_string)
9443     b->addr_string = addr_string;
9444   else
9445     /* addr_string has to be used or breakpoint_re_set will delete
9446        me.  */
9447     b->addr_string
9448       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9449   b->filter = filter;
9450 }
9451
9452 static void
9453 create_breakpoint_sal (struct gdbarch *gdbarch,
9454                        struct symtabs_and_lines sals, char *addr_string,
9455                        char *filter, char *cond_string,
9456                        char *extra_string,
9457                        enum bptype type, enum bpdisp disposition,
9458                        int thread, int task, int ignore_count,
9459                        const struct breakpoint_ops *ops, int from_tty,
9460                        int enabled, int internal, unsigned flags,
9461                        int display_canonical)
9462 {
9463   struct breakpoint *b;
9464   struct cleanup *old_chain;
9465
9466   if (is_tracepoint_type (type))
9467     {
9468       struct tracepoint *t;
9469
9470       t = XCNEW (struct tracepoint);
9471       b = &t->base;
9472     }
9473   else
9474     b = XNEW (struct breakpoint);
9475
9476   old_chain = make_cleanup (xfree, b);
9477
9478   init_breakpoint_sal (b, gdbarch,
9479                        sals, addr_string,
9480                        filter, cond_string, extra_string,
9481                        type, disposition,
9482                        thread, task, ignore_count,
9483                        ops, from_tty,
9484                        enabled, internal, flags,
9485                        display_canonical);
9486   discard_cleanups (old_chain);
9487
9488   install_breakpoint (internal, b, 0);
9489 }
9490
9491 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9492    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9493    value.  COND_STRING, if not NULL, specified the condition to be
9494    used for all breakpoints.  Essentially the only case where
9495    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9496    function.  In that case, it's still not possible to specify
9497    separate conditions for different overloaded functions, so
9498    we take just a single condition string.
9499    
9500    NOTE: If the function succeeds, the caller is expected to cleanup
9501    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9502    array contents).  If the function fails (error() is called), the
9503    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9504    COND and SALS arrays and each of those arrays contents.  */
9505
9506 static void
9507 create_breakpoints_sal (struct gdbarch *gdbarch,
9508                         struct linespec_result *canonical,
9509                         char *cond_string, char *extra_string,
9510                         enum bptype type, enum bpdisp disposition,
9511                         int thread, int task, int ignore_count,
9512                         const struct breakpoint_ops *ops, int from_tty,
9513                         int enabled, int internal, unsigned flags)
9514 {
9515   int i;
9516   struct linespec_sals *lsal;
9517
9518   if (canonical->pre_expanded)
9519     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9520
9521   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9522     {
9523       /* Note that 'addr_string' can be NULL in the case of a plain
9524          'break', without arguments.  */
9525       char *addr_string = (canonical->addr_string
9526                            ? xstrdup (canonical->addr_string)
9527                            : NULL);
9528       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9529       struct cleanup *inner = make_cleanup (xfree, addr_string);
9530
9531       make_cleanup (xfree, filter_string);
9532       create_breakpoint_sal (gdbarch, lsal->sals,
9533                              addr_string,
9534                              filter_string,
9535                              cond_string, extra_string,
9536                              type, disposition,
9537                              thread, task, ignore_count, ops,
9538                              from_tty, enabled, internal, flags,
9539                              canonical->special_display);
9540       discard_cleanups (inner);
9541     }
9542 }
9543
9544 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9545    followed by conditionals.  On return, SALS contains an array of SAL
9546    addresses found.  ADDR_STRING contains a vector of (canonical)
9547    address strings.  ADDRESS points to the end of the SAL.
9548
9549    The array and the line spec strings are allocated on the heap, it is
9550    the caller's responsibility to free them.  */
9551
9552 static void
9553 parse_breakpoint_sals (char **address,
9554                        struct linespec_result *canonical)
9555 {
9556   /* If no arg given, or if first arg is 'if ', use the default
9557      breakpoint.  */
9558   if ((*address) == NULL
9559       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9560     {
9561       /* The last displayed codepoint, if it's valid, is our default breakpoint
9562          address.  */
9563       if (last_displayed_sal_is_valid ())
9564         {
9565           struct linespec_sals lsal;
9566           struct symtab_and_line sal;
9567           CORE_ADDR pc;
9568
9569           init_sal (&sal);              /* Initialize to zeroes.  */
9570           lsal.sals.sals = (struct symtab_and_line *)
9571             xmalloc (sizeof (struct symtab_and_line));
9572
9573           /* Set sal's pspace, pc, symtab, and line to the values
9574              corresponding to the last call to print_frame_info.
9575              Be sure to reinitialize LINE with NOTCURRENT == 0
9576              as the breakpoint line number is inappropriate otherwise.
9577              find_pc_line would adjust PC, re-set it back.  */
9578           get_last_displayed_sal (&sal);
9579           pc = sal.pc;
9580           sal = find_pc_line (pc, 0);
9581
9582           /* "break" without arguments is equivalent to "break *PC"
9583              where PC is the last displayed codepoint's address.  So
9584              make sure to set sal.explicit_pc to prevent GDB from
9585              trying to expand the list of sals to include all other
9586              instances with the same symtab and line.  */
9587           sal.pc = pc;
9588           sal.explicit_pc = 1;
9589
9590           lsal.sals.sals[0] = sal;
9591           lsal.sals.nelts = 1;
9592           lsal.canonical = NULL;
9593
9594           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9595         }
9596       else
9597         error (_("No default breakpoint address now."));
9598     }
9599   else
9600     {
9601       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9602
9603       /* Force almost all breakpoints to be in terms of the
9604          current_source_symtab (which is decode_line_1's default).
9605          This should produce the results we want almost all of the
9606          time while leaving default_breakpoint_* alone.
9607
9608          ObjC: However, don't match an Objective-C method name which
9609          may have a '+' or '-' succeeded by a '['.  */
9610       if (last_displayed_sal_is_valid ()
9611           && (!cursal.symtab
9612               || ((strchr ("+-", (*address)[0]) != NULL)
9613                   && ((*address)[1] != '['))))
9614         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9615                           get_last_displayed_symtab (),
9616                           get_last_displayed_line (),
9617                           canonical, NULL, NULL);
9618       else
9619         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9620                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9621     }
9622 }
9623
9624
9625 /* Convert each SAL into a real PC.  Verify that the PC can be
9626    inserted as a breakpoint.  If it can't throw an error.  */
9627
9628 static void
9629 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9630 {    
9631   int i;
9632
9633   for (i = 0; i < sals->nelts; i++)
9634     resolve_sal_pc (&sals->sals[i]);
9635 }
9636
9637 /* Fast tracepoints may have restrictions on valid locations.  For
9638    instance, a fast tracepoint using a jump instead of a trap will
9639    likely have to overwrite more bytes than a trap would, and so can
9640    only be placed where the instruction is longer than the jump, or a
9641    multi-instruction sequence does not have a jump into the middle of
9642    it, etc.  */
9643
9644 static void
9645 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9646                             struct symtabs_and_lines *sals)
9647 {
9648   int i, rslt;
9649   struct symtab_and_line *sal;
9650   char *msg;
9651   struct cleanup *old_chain;
9652
9653   for (i = 0; i < sals->nelts; i++)
9654     {
9655       struct gdbarch *sarch;
9656
9657       sal = &sals->sals[i];
9658
9659       sarch = get_sal_arch (*sal);
9660       /* We fall back to GDBARCH if there is no architecture
9661          associated with SAL.  */
9662       if (sarch == NULL)
9663         sarch = gdbarch;
9664       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9665                                                NULL, &msg);
9666       old_chain = make_cleanup (xfree, msg);
9667
9668       if (!rslt)
9669         error (_("May not have a fast tracepoint at 0x%s%s"),
9670                paddress (sarch, sal->pc), (msg ? msg : ""));
9671
9672       do_cleanups (old_chain);
9673     }
9674 }
9675
9676 /* Issue an invalid thread ID error.  */
9677
9678 static void ATTRIBUTE_NORETURN
9679 invalid_thread_id_error (int id)
9680 {
9681   error (_("Unknown thread %d."), id);
9682 }
9683
9684 /* Given TOK, a string specification of condition and thread, as
9685    accepted by the 'break' command, extract the condition
9686    string and thread number and set *COND_STRING and *THREAD.
9687    PC identifies the context at which the condition should be parsed.
9688    If no condition is found, *COND_STRING is set to NULL.
9689    If no thread is found, *THREAD is set to -1.  */
9690
9691 static void
9692 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9693                            char **cond_string, int *thread, int *task,
9694                            char **rest)
9695 {
9696   *cond_string = NULL;
9697   *thread = -1;
9698   *task = 0;
9699   *rest = NULL;
9700
9701   while (tok && *tok)
9702     {
9703       const char *end_tok;
9704       int toklen;
9705       const char *cond_start = NULL;
9706       const char *cond_end = NULL;
9707
9708       tok = skip_spaces_const (tok);
9709
9710       if ((*tok == '"' || *tok == ',') && rest)
9711         {
9712           *rest = savestring (tok, strlen (tok));
9713           return;
9714         }
9715
9716       end_tok = skip_to_space_const (tok);
9717
9718       toklen = end_tok - tok;
9719
9720       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9721         {
9722           struct expression *expr;
9723
9724           tok = cond_start = end_tok + 1;
9725           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9726           xfree (expr);
9727           cond_end = tok;
9728           *cond_string = savestring (cond_start, cond_end - cond_start);
9729         }
9730       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9731         {
9732           char *tmptok;
9733
9734           tok = end_tok + 1;
9735           *thread = strtol (tok, &tmptok, 0);
9736           if (tok == tmptok)
9737             error (_("Junk after thread keyword."));
9738           if (!valid_thread_id (*thread))
9739             invalid_thread_id_error (*thread);
9740           tok = tmptok;
9741         }
9742       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9743         {
9744           char *tmptok;
9745
9746           tok = end_tok + 1;
9747           *task = strtol (tok, &tmptok, 0);
9748           if (tok == tmptok)
9749             error (_("Junk after task keyword."));
9750           if (!valid_task_id (*task))
9751             error (_("Unknown task %d."), *task);
9752           tok = tmptok;
9753         }
9754       else if (rest)
9755         {
9756           *rest = savestring (tok, strlen (tok));
9757           return;
9758         }
9759       else
9760         error (_("Junk at end of arguments."));
9761     }
9762 }
9763
9764 /* Decode a static tracepoint marker spec.  */
9765
9766 static struct symtabs_and_lines
9767 decode_static_tracepoint_spec (char **arg_p)
9768 {
9769   VEC(static_tracepoint_marker_p) *markers = NULL;
9770   struct symtabs_and_lines sals;
9771   struct cleanup *old_chain;
9772   char *p = &(*arg_p)[3];
9773   char *endp;
9774   char *marker_str;
9775   int i;
9776
9777   p = skip_spaces (p);
9778
9779   endp = skip_to_space (p);
9780
9781   marker_str = savestring (p, endp - p);
9782   old_chain = make_cleanup (xfree, marker_str);
9783
9784   markers = target_static_tracepoint_markers_by_strid (marker_str);
9785   if (VEC_empty(static_tracepoint_marker_p, markers))
9786     error (_("No known static tracepoint marker named %s"), marker_str);
9787
9788   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9789   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9790
9791   for (i = 0; i < sals.nelts; i++)
9792     {
9793       struct static_tracepoint_marker *marker;
9794
9795       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9796
9797       init_sal (&sals.sals[i]);
9798
9799       sals.sals[i] = find_pc_line (marker->address, 0);
9800       sals.sals[i].pc = marker->address;
9801
9802       release_static_tracepoint_marker (marker);
9803     }
9804
9805   do_cleanups (old_chain);
9806
9807   *arg_p = endp;
9808   return sals;
9809 }
9810
9811 /* Set a breakpoint.  This function is shared between CLI and MI
9812    functions for setting a breakpoint.  This function has two major
9813    modes of operations, selected by the PARSE_ARG parameter.  If
9814    non-zero, the function will parse ARG, extracting location,
9815    condition, thread and extra string.  Otherwise, ARG is just the
9816    breakpoint's location, with condition, thread, and extra string
9817    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9818    If INTERNAL is non-zero, the breakpoint number will be allocated
9819    from the internal breakpoint count.  Returns true if any breakpoint
9820    was created; false otherwise.  */
9821
9822 int
9823 create_breakpoint (struct gdbarch *gdbarch,
9824                    char *arg, char *cond_string,
9825                    int thread, char *extra_string,
9826                    int parse_arg,
9827                    int tempflag, enum bptype type_wanted,
9828                    int ignore_count,
9829                    enum auto_boolean pending_break_support,
9830                    const struct breakpoint_ops *ops,
9831                    int from_tty, int enabled, int internal,
9832                    unsigned flags)
9833 {
9834   volatile struct gdb_exception e;
9835   char *copy_arg = NULL;
9836   char *addr_start = arg;
9837   struct linespec_result canonical;
9838   struct cleanup *old_chain;
9839   struct cleanup *bkpt_chain = NULL;
9840   int pending = 0;
9841   int task = 0;
9842   int prev_bkpt_count = breakpoint_count;
9843
9844   gdb_assert (ops != NULL);
9845
9846   init_linespec_result (&canonical);
9847
9848   TRY_CATCH (e, RETURN_MASK_ALL)
9849     {
9850       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9851                                      addr_start, &copy_arg);
9852     }
9853
9854   /* If caller is interested in rc value from parse, set value.  */
9855   switch (e.reason)
9856     {
9857     case GDB_NO_ERROR:
9858       if (VEC_empty (linespec_sals, canonical.sals))
9859         return 0;
9860       break;
9861     case RETURN_ERROR:
9862       switch (e.error)
9863         {
9864         case NOT_FOUND_ERROR:
9865
9866           /* If pending breakpoint support is turned off, throw
9867              error.  */
9868
9869           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9870             throw_exception (e);
9871
9872           exception_print (gdb_stderr, e);
9873
9874           /* If pending breakpoint support is auto query and the user
9875              selects no, then simply return the error code.  */
9876           if (pending_break_support == AUTO_BOOLEAN_AUTO
9877               && !nquery (_("Make %s pending on future shared library load? "),
9878                           bptype_string (type_wanted)))
9879             return 0;
9880
9881           /* At this point, either the user was queried about setting
9882              a pending breakpoint and selected yes, or pending
9883              breakpoint behavior is on and thus a pending breakpoint
9884              is defaulted on behalf of the user.  */
9885           {
9886             struct linespec_sals lsal;
9887
9888             copy_arg = xstrdup (addr_start);
9889             lsal.canonical = xstrdup (copy_arg);
9890             lsal.sals.nelts = 1;
9891             lsal.sals.sals = XNEW (struct symtab_and_line);
9892             init_sal (&lsal.sals.sals[0]);
9893             pending = 1;
9894             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9895           }
9896           break;
9897         default:
9898           throw_exception (e);
9899         }
9900       break;
9901     default:
9902       throw_exception (e);
9903     }
9904
9905   /* Create a chain of things that always need to be cleaned up.  */
9906   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9907
9908   /* ----------------------------- SNIP -----------------------------
9909      Anything added to the cleanup chain beyond this point is assumed
9910      to be part of a breakpoint.  If the breakpoint create succeeds
9911      then the memory is not reclaimed.  */
9912   bkpt_chain = make_cleanup (null_cleanup, 0);
9913
9914   /* Resolve all line numbers to PC's and verify that the addresses
9915      are ok for the target.  */
9916   if (!pending)
9917     {
9918       int ix;
9919       struct linespec_sals *iter;
9920
9921       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9922         breakpoint_sals_to_pc (&iter->sals);
9923     }
9924
9925   /* Fast tracepoints may have additional restrictions on location.  */
9926   if (!pending && type_wanted == bp_fast_tracepoint)
9927     {
9928       int ix;
9929       struct linespec_sals *iter;
9930
9931       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9932         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9933     }
9934
9935   /* Verify that condition can be parsed, before setting any
9936      breakpoints.  Allocate a separate condition expression for each
9937      breakpoint.  */
9938   if (!pending)
9939     {
9940       if (parse_arg)
9941         {
9942           char *rest;
9943           struct linespec_sals *lsal;
9944
9945           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9946
9947           /* Here we only parse 'arg' to separate condition
9948              from thread number, so parsing in context of first
9949              sal is OK.  When setting the breakpoint we'll
9950              re-parse it in context of each sal.  */
9951
9952           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9953                                      &thread, &task, &rest);
9954           if (cond_string)
9955             make_cleanup (xfree, cond_string);
9956           if (rest)
9957             make_cleanup (xfree, rest);
9958           if (rest)
9959             extra_string = rest;
9960         }
9961       else
9962         {
9963           if (*arg != '\0')
9964             error (_("Garbage '%s' at end of location"), arg);
9965
9966           /* Create a private copy of condition string.  */
9967           if (cond_string)
9968             {
9969               cond_string = xstrdup (cond_string);
9970               make_cleanup (xfree, cond_string);
9971             }
9972           /* Create a private copy of any extra string.  */
9973           if (extra_string)
9974             {
9975               extra_string = xstrdup (extra_string);
9976               make_cleanup (xfree, extra_string);
9977             }
9978         }
9979
9980       ops->create_breakpoints_sal (gdbarch, &canonical,
9981                                    cond_string, extra_string, type_wanted,
9982                                    tempflag ? disp_del : disp_donttouch,
9983                                    thread, task, ignore_count, ops,
9984                                    from_tty, enabled, internal, flags);
9985     }
9986   else
9987     {
9988       struct breakpoint *b;
9989
9990       make_cleanup (xfree, copy_arg);
9991
9992       if (is_tracepoint_type (type_wanted))
9993         {
9994           struct tracepoint *t;
9995
9996           t = XCNEW (struct tracepoint);
9997           b = &t->base;
9998         }
9999       else
10000         b = XNEW (struct breakpoint);
10001
10002       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10003
10004       b->addr_string = copy_arg;
10005       if (parse_arg)
10006         b->cond_string = NULL;
10007       else
10008         {
10009           /* Create a private copy of condition string.  */
10010           if (cond_string)
10011             {
10012               cond_string = xstrdup (cond_string);
10013               make_cleanup (xfree, cond_string);
10014             }
10015           b->cond_string = cond_string;
10016         }
10017       b->extra_string = NULL;
10018       b->ignore_count = ignore_count;
10019       b->disposition = tempflag ? disp_del : disp_donttouch;
10020       b->condition_not_parsed = 1;
10021       b->enable_state = enabled ? bp_enabled : bp_disabled;
10022       if ((type_wanted != bp_breakpoint
10023            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10024         b->pspace = current_program_space;
10025
10026       install_breakpoint (internal, b, 0);
10027     }
10028   
10029   if (VEC_length (linespec_sals, canonical.sals) > 1)
10030     {
10031       warning (_("Multiple breakpoints were set.\nUse the "
10032                  "\"delete\" command to delete unwanted breakpoints."));
10033       prev_breakpoint_count = prev_bkpt_count;
10034     }
10035
10036   /* That's it.  Discard the cleanups for data inserted into the
10037      breakpoint.  */
10038   discard_cleanups (bkpt_chain);
10039   /* But cleanup everything else.  */
10040   do_cleanups (old_chain);
10041
10042   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10043   update_global_location_list (1);
10044
10045   return 1;
10046 }
10047
10048 /* Set a breakpoint.
10049    ARG is a string describing breakpoint address,
10050    condition, and thread.
10051    FLAG specifies if a breakpoint is hardware on,
10052    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10053    and BP_TEMPFLAG.  */
10054
10055 static void
10056 break_command_1 (char *arg, int flag, int from_tty)
10057 {
10058   int tempflag = flag & BP_TEMPFLAG;
10059   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10060                              ? bp_hardware_breakpoint
10061                              : bp_breakpoint);
10062   struct breakpoint_ops *ops;
10063   const char *arg_cp = arg;
10064
10065   /* Matching breakpoints on probes.  */
10066   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10067     ops = &bkpt_probe_breakpoint_ops;
10068   else
10069     ops = &bkpt_breakpoint_ops;
10070
10071   create_breakpoint (get_current_arch (),
10072                      arg,
10073                      NULL, 0, NULL, 1 /* parse arg */,
10074                      tempflag, type_wanted,
10075                      0 /* Ignore count */,
10076                      pending_break_support,
10077                      ops,
10078                      from_tty,
10079                      1 /* enabled */,
10080                      0 /* internal */,
10081                      0);
10082 }
10083
10084 /* Helper function for break_command_1 and disassemble_command.  */
10085
10086 void
10087 resolve_sal_pc (struct symtab_and_line *sal)
10088 {
10089   CORE_ADDR pc;
10090
10091   if (sal->pc == 0 && sal->symtab != NULL)
10092     {
10093       if (!find_line_pc (sal->symtab, sal->line, &pc))
10094         error (_("No line %d in file \"%s\"."),
10095                sal->line, symtab_to_filename_for_display (sal->symtab));
10096       sal->pc = pc;
10097
10098       /* If this SAL corresponds to a breakpoint inserted using a line
10099          number, then skip the function prologue if necessary.  */
10100       if (sal->explicit_line)
10101         skip_prologue_sal (sal);
10102     }
10103
10104   if (sal->section == 0 && sal->symtab != NULL)
10105     {
10106       const struct blockvector *bv;
10107       const struct block *b;
10108       struct symbol *sym;
10109
10110       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10111       if (bv != NULL)
10112         {
10113           sym = block_linkage_function (b);
10114           if (sym != NULL)
10115             {
10116               fixup_symbol_section (sym, sal->symtab->objfile);
10117               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10118             }
10119           else
10120             {
10121               /* It really is worthwhile to have the section, so we'll
10122                  just have to look harder. This case can be executed
10123                  if we have line numbers but no functions (as can
10124                  happen in assembly source).  */
10125
10126               struct bound_minimal_symbol msym;
10127               struct cleanup *old_chain = save_current_space_and_thread ();
10128
10129               switch_to_program_space_and_thread (sal->pspace);
10130
10131               msym = lookup_minimal_symbol_by_pc (sal->pc);
10132               if (msym.minsym)
10133                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10134
10135               do_cleanups (old_chain);
10136             }
10137         }
10138     }
10139 }
10140
10141 void
10142 break_command (char *arg, int from_tty)
10143 {
10144   break_command_1 (arg, 0, from_tty);
10145 }
10146
10147 void
10148 tbreak_command (char *arg, int from_tty)
10149 {
10150   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10151 }
10152
10153 static void
10154 hbreak_command (char *arg, int from_tty)
10155 {
10156   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10157 }
10158
10159 static void
10160 thbreak_command (char *arg, int from_tty)
10161 {
10162   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10163 }
10164
10165 static void
10166 stop_command (char *arg, int from_tty)
10167 {
10168   printf_filtered (_("Specify the type of breakpoint to set.\n\
10169 Usage: stop in <function | address>\n\
10170        stop at <line>\n"));
10171 }
10172
10173 static void
10174 stopin_command (char *arg, int from_tty)
10175 {
10176   int badInput = 0;
10177
10178   if (arg == (char *) NULL)
10179     badInput = 1;
10180   else if (*arg != '*')
10181     {
10182       char *argptr = arg;
10183       int hasColon = 0;
10184
10185       /* Look for a ':'.  If this is a line number specification, then
10186          say it is bad, otherwise, it should be an address or
10187          function/method name.  */
10188       while (*argptr && !hasColon)
10189         {
10190           hasColon = (*argptr == ':');
10191           argptr++;
10192         }
10193
10194       if (hasColon)
10195         badInput = (*argptr != ':');    /* Not a class::method */
10196       else
10197         badInput = isdigit (*arg);      /* a simple line number */
10198     }
10199
10200   if (badInput)
10201     printf_filtered (_("Usage: stop in <function | address>\n"));
10202   else
10203     break_command_1 (arg, 0, from_tty);
10204 }
10205
10206 static void
10207 stopat_command (char *arg, int from_tty)
10208 {
10209   int badInput = 0;
10210
10211   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10212     badInput = 1;
10213   else
10214     {
10215       char *argptr = arg;
10216       int hasColon = 0;
10217
10218       /* Look for a ':'.  If there is a '::' then get out, otherwise
10219          it is probably a line number.  */
10220       while (*argptr && !hasColon)
10221         {
10222           hasColon = (*argptr == ':');
10223           argptr++;
10224         }
10225
10226       if (hasColon)
10227         badInput = (*argptr == ':');    /* we have class::method */
10228       else
10229         badInput = !isdigit (*arg);     /* not a line number */
10230     }
10231
10232   if (badInput)
10233     printf_filtered (_("Usage: stop at <line>\n"));
10234   else
10235     break_command_1 (arg, 0, from_tty);
10236 }
10237
10238 /* The dynamic printf command is mostly like a regular breakpoint, but
10239    with a prewired command list consisting of a single output command,
10240    built from extra arguments supplied on the dprintf command
10241    line.  */
10242
10243 static void
10244 dprintf_command (char *arg, int from_tty)
10245 {
10246   create_breakpoint (get_current_arch (),
10247                      arg,
10248                      NULL, 0, NULL, 1 /* parse arg */,
10249                      0, bp_dprintf,
10250                      0 /* Ignore count */,
10251                      pending_break_support,
10252                      &dprintf_breakpoint_ops,
10253                      from_tty,
10254                      1 /* enabled */,
10255                      0 /* internal */,
10256                      0);
10257 }
10258
10259 static void
10260 agent_printf_command (char *arg, int from_tty)
10261 {
10262   error (_("May only run agent-printf on the target"));
10263 }
10264
10265 /* Implement the "breakpoint_hit" breakpoint_ops method for
10266    ranged breakpoints.  */
10267
10268 static int
10269 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10270                                   struct address_space *aspace,
10271                                   CORE_ADDR bp_addr,
10272                                   const struct target_waitstatus *ws)
10273 {
10274   if (ws->kind != TARGET_WAITKIND_STOPPED
10275       || ws->value.sig != GDB_SIGNAL_TRAP)
10276     return 0;
10277
10278   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10279                                          bl->length, aspace, bp_addr);
10280 }
10281
10282 /* Implement the "resources_needed" breakpoint_ops method for
10283    ranged breakpoints.  */
10284
10285 static int
10286 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10287 {
10288   return target_ranged_break_num_registers ();
10289 }
10290
10291 /* Implement the "print_it" breakpoint_ops method for
10292    ranged breakpoints.  */
10293
10294 static enum print_stop_action
10295 print_it_ranged_breakpoint (bpstat bs)
10296 {
10297   struct breakpoint *b = bs->breakpoint_at;
10298   struct bp_location *bl = b->loc;
10299   struct ui_out *uiout = current_uiout;
10300
10301   gdb_assert (b->type == bp_hardware_breakpoint);
10302
10303   /* Ranged breakpoints have only one location.  */
10304   gdb_assert (bl && bl->next == NULL);
10305
10306   annotate_breakpoint (b->number);
10307   if (b->disposition == disp_del)
10308     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10309   else
10310     ui_out_text (uiout, "\nRanged breakpoint ");
10311   if (ui_out_is_mi_like_p (uiout))
10312     {
10313       ui_out_field_string (uiout, "reason",
10314                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10315       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10316     }
10317   ui_out_field_int (uiout, "bkptno", b->number);
10318   ui_out_text (uiout, ", ");
10319
10320   return PRINT_SRC_AND_LOC;
10321 }
10322
10323 /* Implement the "print_one" breakpoint_ops method for
10324    ranged breakpoints.  */
10325
10326 static void
10327 print_one_ranged_breakpoint (struct breakpoint *b,
10328                              struct bp_location **last_loc)
10329 {
10330   struct bp_location *bl = b->loc;
10331   struct value_print_options opts;
10332   struct ui_out *uiout = current_uiout;
10333
10334   /* Ranged breakpoints have only one location.  */
10335   gdb_assert (bl && bl->next == NULL);
10336
10337   get_user_print_options (&opts);
10338
10339   if (opts.addressprint)
10340     /* We don't print the address range here, it will be printed later
10341        by print_one_detail_ranged_breakpoint.  */
10342     ui_out_field_skip (uiout, "addr");
10343   annotate_field (5);
10344   print_breakpoint_location (b, bl);
10345   *last_loc = bl;
10346 }
10347
10348 /* Implement the "print_one_detail" breakpoint_ops method for
10349    ranged breakpoints.  */
10350
10351 static void
10352 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10353                                     struct ui_out *uiout)
10354 {
10355   CORE_ADDR address_start, address_end;
10356   struct bp_location *bl = b->loc;
10357   struct ui_file *stb = mem_fileopen ();
10358   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10359
10360   gdb_assert (bl);
10361
10362   address_start = bl->address;
10363   address_end = address_start + bl->length - 1;
10364
10365   ui_out_text (uiout, "\taddress range: ");
10366   fprintf_unfiltered (stb, "[%s, %s]",
10367                       print_core_address (bl->gdbarch, address_start),
10368                       print_core_address (bl->gdbarch, address_end));
10369   ui_out_field_stream (uiout, "addr", stb);
10370   ui_out_text (uiout, "\n");
10371
10372   do_cleanups (cleanup);
10373 }
10374
10375 /* Implement the "print_mention" breakpoint_ops method for
10376    ranged breakpoints.  */
10377
10378 static void
10379 print_mention_ranged_breakpoint (struct breakpoint *b)
10380 {
10381   struct bp_location *bl = b->loc;
10382   struct ui_out *uiout = current_uiout;
10383
10384   gdb_assert (bl);
10385   gdb_assert (b->type == bp_hardware_breakpoint);
10386
10387   if (ui_out_is_mi_like_p (uiout))
10388     return;
10389
10390   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10391                    b->number, paddress (bl->gdbarch, bl->address),
10392                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10393 }
10394
10395 /* Implement the "print_recreate" breakpoint_ops method for
10396    ranged breakpoints.  */
10397
10398 static void
10399 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10400 {
10401   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10402                       b->addr_string_range_end);
10403   print_recreate_thread (b, fp);
10404 }
10405
10406 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10407
10408 static struct breakpoint_ops ranged_breakpoint_ops;
10409
10410 /* Find the address where the end of the breakpoint range should be
10411    placed, given the SAL of the end of the range.  This is so that if
10412    the user provides a line number, the end of the range is set to the
10413    last instruction of the given line.  */
10414
10415 static CORE_ADDR
10416 find_breakpoint_range_end (struct symtab_and_line sal)
10417 {
10418   CORE_ADDR end;
10419
10420   /* If the user provided a PC value, use it.  Otherwise,
10421      find the address of the end of the given location.  */
10422   if (sal.explicit_pc)
10423     end = sal.pc;
10424   else
10425     {
10426       int ret;
10427       CORE_ADDR start;
10428
10429       ret = find_line_pc_range (sal, &start, &end);
10430       if (!ret)
10431         error (_("Could not find location of the end of the range."));
10432
10433       /* find_line_pc_range returns the start of the next line.  */
10434       end--;
10435     }
10436
10437   return end;
10438 }
10439
10440 /* Implement the "break-range" CLI command.  */
10441
10442 static void
10443 break_range_command (char *arg, int from_tty)
10444 {
10445   char *arg_start, *addr_string_start, *addr_string_end;
10446   struct linespec_result canonical_start, canonical_end;
10447   int bp_count, can_use_bp, length;
10448   CORE_ADDR end;
10449   struct breakpoint *b;
10450   struct symtab_and_line sal_start, sal_end;
10451   struct cleanup *cleanup_bkpt;
10452   struct linespec_sals *lsal_start, *lsal_end;
10453
10454   /* We don't support software ranged breakpoints.  */
10455   if (target_ranged_break_num_registers () < 0)
10456     error (_("This target does not support hardware ranged breakpoints."));
10457
10458   bp_count = hw_breakpoint_used_count ();
10459   bp_count += target_ranged_break_num_registers ();
10460   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10461                                                    bp_count, 0);
10462   if (can_use_bp < 0)
10463     error (_("Hardware breakpoints used exceeds limit."));
10464
10465   arg = skip_spaces (arg);
10466   if (arg == NULL || arg[0] == '\0')
10467     error(_("No address range specified."));
10468
10469   init_linespec_result (&canonical_start);
10470
10471   arg_start = arg;
10472   parse_breakpoint_sals (&arg, &canonical_start);
10473
10474   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10475
10476   if (arg[0] != ',')
10477     error (_("Too few arguments."));
10478   else if (VEC_empty (linespec_sals, canonical_start.sals))
10479     error (_("Could not find location of the beginning of the range."));
10480
10481   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10482
10483   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10484       || lsal_start->sals.nelts != 1)
10485     error (_("Cannot create a ranged breakpoint with multiple locations."));
10486
10487   sal_start = lsal_start->sals.sals[0];
10488   addr_string_start = savestring (arg_start, arg - arg_start);
10489   make_cleanup (xfree, addr_string_start);
10490
10491   arg++;        /* Skip the comma.  */
10492   arg = skip_spaces (arg);
10493
10494   /* Parse the end location.  */
10495
10496   init_linespec_result (&canonical_end);
10497   arg_start = arg;
10498
10499   /* We call decode_line_full directly here instead of using
10500      parse_breakpoint_sals because we need to specify the start location's
10501      symtab and line as the default symtab and line for the end of the
10502      range.  This makes it possible to have ranges like "foo.c:27, +14",
10503      where +14 means 14 lines from the start location.  */
10504   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10505                     sal_start.symtab, sal_start.line,
10506                     &canonical_end, NULL, NULL);
10507
10508   make_cleanup_destroy_linespec_result (&canonical_end);
10509
10510   if (VEC_empty (linespec_sals, canonical_end.sals))
10511     error (_("Could not find location of the end of the range."));
10512
10513   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10514   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10515       || lsal_end->sals.nelts != 1)
10516     error (_("Cannot create a ranged breakpoint with multiple locations."));
10517
10518   sal_end = lsal_end->sals.sals[0];
10519   addr_string_end = savestring (arg_start, arg - arg_start);
10520   make_cleanup (xfree, addr_string_end);
10521
10522   end = find_breakpoint_range_end (sal_end);
10523   if (sal_start.pc > end)
10524     error (_("Invalid address range, end precedes start."));
10525
10526   length = end - sal_start.pc + 1;
10527   if (length < 0)
10528     /* Length overflowed.  */
10529     error (_("Address range too large."));
10530   else if (length == 1)
10531     {
10532       /* This range is simple enough to be handled by
10533          the `hbreak' command.  */
10534       hbreak_command (addr_string_start, 1);
10535
10536       do_cleanups (cleanup_bkpt);
10537
10538       return;
10539     }
10540
10541   /* Now set up the breakpoint.  */
10542   b = set_raw_breakpoint (get_current_arch (), sal_start,
10543                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10544   set_breakpoint_count (breakpoint_count + 1);
10545   b->number = breakpoint_count;
10546   b->disposition = disp_donttouch;
10547   b->addr_string = xstrdup (addr_string_start);
10548   b->addr_string_range_end = xstrdup (addr_string_end);
10549   b->loc->length = length;
10550
10551   do_cleanups (cleanup_bkpt);
10552
10553   mention (b);
10554   observer_notify_breakpoint_created (b);
10555   update_global_location_list (1);
10556 }
10557
10558 /*  Return non-zero if EXP is verified as constant.  Returned zero
10559     means EXP is variable.  Also the constant detection may fail for
10560     some constant expressions and in such case still falsely return
10561     zero.  */
10562
10563 static int
10564 watchpoint_exp_is_const (const struct expression *exp)
10565 {
10566   int i = exp->nelts;
10567
10568   while (i > 0)
10569     {
10570       int oplenp, argsp;
10571
10572       /* We are only interested in the descriptor of each element.  */
10573       operator_length (exp, i, &oplenp, &argsp);
10574       i -= oplenp;
10575
10576       switch (exp->elts[i].opcode)
10577         {
10578         case BINOP_ADD:
10579         case BINOP_SUB:
10580         case BINOP_MUL:
10581         case BINOP_DIV:
10582         case BINOP_REM:
10583         case BINOP_MOD:
10584         case BINOP_LSH:
10585         case BINOP_RSH:
10586         case BINOP_LOGICAL_AND:
10587         case BINOP_LOGICAL_OR:
10588         case BINOP_BITWISE_AND:
10589         case BINOP_BITWISE_IOR:
10590         case BINOP_BITWISE_XOR:
10591         case BINOP_EQUAL:
10592         case BINOP_NOTEQUAL:
10593         case BINOP_LESS:
10594         case BINOP_GTR:
10595         case BINOP_LEQ:
10596         case BINOP_GEQ:
10597         case BINOP_REPEAT:
10598         case BINOP_COMMA:
10599         case BINOP_EXP:
10600         case BINOP_MIN:
10601         case BINOP_MAX:
10602         case BINOP_INTDIV:
10603         case BINOP_CONCAT:
10604         case TERNOP_COND:
10605         case TERNOP_SLICE:
10606
10607         case OP_LONG:
10608         case OP_DOUBLE:
10609         case OP_DECFLOAT:
10610         case OP_LAST:
10611         case OP_COMPLEX:
10612         case OP_STRING:
10613         case OP_ARRAY:
10614         case OP_TYPE:
10615         case OP_TYPEOF:
10616         case OP_DECLTYPE:
10617         case OP_TYPEID:
10618         case OP_NAME:
10619         case OP_OBJC_NSSTRING:
10620
10621         case UNOP_NEG:
10622         case UNOP_LOGICAL_NOT:
10623         case UNOP_COMPLEMENT:
10624         case UNOP_ADDR:
10625         case UNOP_HIGH:
10626         case UNOP_CAST:
10627
10628         case UNOP_CAST_TYPE:
10629         case UNOP_REINTERPRET_CAST:
10630         case UNOP_DYNAMIC_CAST:
10631           /* Unary, binary and ternary operators: We have to check
10632              their operands.  If they are constant, then so is the
10633              result of that operation.  For instance, if A and B are
10634              determined to be constants, then so is "A + B".
10635
10636              UNOP_IND is one exception to the rule above, because the
10637              value of *ADDR is not necessarily a constant, even when
10638              ADDR is.  */
10639           break;
10640
10641         case OP_VAR_VALUE:
10642           /* Check whether the associated symbol is a constant.
10643
10644              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10645              possible that a buggy compiler could mark a variable as
10646              constant even when it is not, and TYPE_CONST would return
10647              true in this case, while SYMBOL_CLASS wouldn't.
10648
10649              We also have to check for function symbols because they
10650              are always constant.  */
10651           {
10652             struct symbol *s = exp->elts[i + 2].symbol;
10653
10654             if (SYMBOL_CLASS (s) != LOC_BLOCK
10655                 && SYMBOL_CLASS (s) != LOC_CONST
10656                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10657               return 0;
10658             break;
10659           }
10660
10661         /* The default action is to return 0 because we are using
10662            the optimistic approach here: If we don't know something,
10663            then it is not a constant.  */
10664         default:
10665           return 0;
10666         }
10667     }
10668
10669   return 1;
10670 }
10671
10672 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10673
10674 static void
10675 dtor_watchpoint (struct breakpoint *self)
10676 {
10677   struct watchpoint *w = (struct watchpoint *) self;
10678
10679   xfree (w->cond_exp);
10680   xfree (w->exp);
10681   xfree (w->exp_string);
10682   xfree (w->exp_string_reparse);
10683   value_free (w->val);
10684
10685   base_breakpoint_ops.dtor (self);
10686 }
10687
10688 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10689
10690 static void
10691 re_set_watchpoint (struct breakpoint *b)
10692 {
10693   struct watchpoint *w = (struct watchpoint *) b;
10694
10695   /* Watchpoint can be either on expression using entirely global
10696      variables, or it can be on local variables.
10697
10698      Watchpoints of the first kind are never auto-deleted, and even
10699      persist across program restarts.  Since they can use variables
10700      from shared libraries, we need to reparse expression as libraries
10701      are loaded and unloaded.
10702
10703      Watchpoints on local variables can also change meaning as result
10704      of solib event.  For example, if a watchpoint uses both a local
10705      and a global variables in expression, it's a local watchpoint,
10706      but unloading of a shared library will make the expression
10707      invalid.  This is not a very common use case, but we still
10708      re-evaluate expression, to avoid surprises to the user.
10709
10710      Note that for local watchpoints, we re-evaluate it only if
10711      watchpoints frame id is still valid.  If it's not, it means the
10712      watchpoint is out of scope and will be deleted soon.  In fact,
10713      I'm not sure we'll ever be called in this case.
10714
10715      If a local watchpoint's frame id is still valid, then
10716      w->exp_valid_block is likewise valid, and we can safely use it.
10717
10718      Don't do anything about disabled watchpoints, since they will be
10719      reevaluated again when enabled.  */
10720   update_watchpoint (w, 1 /* reparse */);
10721 }
10722
10723 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10724
10725 static int
10726 insert_watchpoint (struct bp_location *bl)
10727 {
10728   struct watchpoint *w = (struct watchpoint *) bl->owner;
10729   int length = w->exact ? 1 : bl->length;
10730
10731   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10732                                    w->cond_exp);
10733 }
10734
10735 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10736
10737 static int
10738 remove_watchpoint (struct bp_location *bl)
10739 {
10740   struct watchpoint *w = (struct watchpoint *) bl->owner;
10741   int length = w->exact ? 1 : bl->length;
10742
10743   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10744                                    w->cond_exp);
10745 }
10746
10747 static int
10748 breakpoint_hit_watchpoint (const struct bp_location *bl,
10749                            struct address_space *aspace, CORE_ADDR bp_addr,
10750                            const struct target_waitstatus *ws)
10751 {
10752   struct breakpoint *b = bl->owner;
10753   struct watchpoint *w = (struct watchpoint *) b;
10754
10755   /* Continuable hardware watchpoints are treated as non-existent if the
10756      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10757      some data address).  Otherwise gdb won't stop on a break instruction
10758      in the code (not from a breakpoint) when a hardware watchpoint has
10759      been defined.  Also skip watchpoints which we know did not trigger
10760      (did not match the data address).  */
10761   if (is_hardware_watchpoint (b)
10762       && w->watchpoint_triggered == watch_triggered_no)
10763     return 0;
10764
10765   return 1;
10766 }
10767
10768 static void
10769 check_status_watchpoint (bpstat bs)
10770 {
10771   gdb_assert (is_watchpoint (bs->breakpoint_at));
10772
10773   bpstat_check_watchpoint (bs);
10774 }
10775
10776 /* Implement the "resources_needed" breakpoint_ops method for
10777    hardware watchpoints.  */
10778
10779 static int
10780 resources_needed_watchpoint (const struct bp_location *bl)
10781 {
10782   struct watchpoint *w = (struct watchpoint *) bl->owner;
10783   int length = w->exact? 1 : bl->length;
10784
10785   return target_region_ok_for_hw_watchpoint (bl->address, length);
10786 }
10787
10788 /* Implement the "works_in_software_mode" breakpoint_ops method for
10789    hardware watchpoints.  */
10790
10791 static int
10792 works_in_software_mode_watchpoint (const struct breakpoint *b)
10793 {
10794   /* Read and access watchpoints only work with hardware support.  */
10795   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10796 }
10797
10798 static enum print_stop_action
10799 print_it_watchpoint (bpstat bs)
10800 {
10801   struct cleanup *old_chain;
10802   struct breakpoint *b;
10803   struct ui_file *stb;
10804   enum print_stop_action result;
10805   struct watchpoint *w;
10806   struct ui_out *uiout = current_uiout;
10807
10808   gdb_assert (bs->bp_location_at != NULL);
10809
10810   b = bs->breakpoint_at;
10811   w = (struct watchpoint *) b;
10812
10813   stb = mem_fileopen ();
10814   old_chain = make_cleanup_ui_file_delete (stb);
10815
10816   switch (b->type)
10817     {
10818     case bp_watchpoint:
10819     case bp_hardware_watchpoint:
10820       annotate_watchpoint (b->number);
10821       if (ui_out_is_mi_like_p (uiout))
10822         ui_out_field_string
10823           (uiout, "reason",
10824            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10825       mention (b);
10826       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10827       ui_out_text (uiout, "\nOld value = ");
10828       watchpoint_value_print (bs->old_val, stb);
10829       ui_out_field_stream (uiout, "old", stb);
10830       ui_out_text (uiout, "\nNew value = ");
10831       watchpoint_value_print (w->val, stb);
10832       ui_out_field_stream (uiout, "new", stb);
10833       ui_out_text (uiout, "\n");
10834       /* More than one watchpoint may have been triggered.  */
10835       result = PRINT_UNKNOWN;
10836       break;
10837
10838     case bp_read_watchpoint:
10839       if (ui_out_is_mi_like_p (uiout))
10840         ui_out_field_string
10841           (uiout, "reason",
10842            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10843       mention (b);
10844       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10845       ui_out_text (uiout, "\nValue = ");
10846       watchpoint_value_print (w->val, stb);
10847       ui_out_field_stream (uiout, "value", stb);
10848       ui_out_text (uiout, "\n");
10849       result = PRINT_UNKNOWN;
10850       break;
10851
10852     case bp_access_watchpoint:
10853       if (bs->old_val != NULL)
10854         {
10855           annotate_watchpoint (b->number);
10856           if (ui_out_is_mi_like_p (uiout))
10857             ui_out_field_string
10858               (uiout, "reason",
10859                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10860           mention (b);
10861           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10862           ui_out_text (uiout, "\nOld value = ");
10863           watchpoint_value_print (bs->old_val, stb);
10864           ui_out_field_stream (uiout, "old", stb);
10865           ui_out_text (uiout, "\nNew value = ");
10866         }
10867       else
10868         {
10869           mention (b);
10870           if (ui_out_is_mi_like_p (uiout))
10871             ui_out_field_string
10872               (uiout, "reason",
10873                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10874           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10875           ui_out_text (uiout, "\nValue = ");
10876         }
10877       watchpoint_value_print (w->val, stb);
10878       ui_out_field_stream (uiout, "new", stb);
10879       ui_out_text (uiout, "\n");
10880       result = PRINT_UNKNOWN;
10881       break;
10882     default:
10883       result = PRINT_UNKNOWN;
10884     }
10885
10886   do_cleanups (old_chain);
10887   return result;
10888 }
10889
10890 /* Implement the "print_mention" breakpoint_ops method for hardware
10891    watchpoints.  */
10892
10893 static void
10894 print_mention_watchpoint (struct breakpoint *b)
10895 {
10896   struct cleanup *ui_out_chain;
10897   struct watchpoint *w = (struct watchpoint *) b;
10898   struct ui_out *uiout = current_uiout;
10899
10900   switch (b->type)
10901     {
10902     case bp_watchpoint:
10903       ui_out_text (uiout, "Watchpoint ");
10904       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10905       break;
10906     case bp_hardware_watchpoint:
10907       ui_out_text (uiout, "Hardware watchpoint ");
10908       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10909       break;
10910     case bp_read_watchpoint:
10911       ui_out_text (uiout, "Hardware read watchpoint ");
10912       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10913       break;
10914     case bp_access_watchpoint:
10915       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10916       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10917       break;
10918     default:
10919       internal_error (__FILE__, __LINE__,
10920                       _("Invalid hardware watchpoint type."));
10921     }
10922
10923   ui_out_field_int (uiout, "number", b->number);
10924   ui_out_text (uiout, ": ");
10925   ui_out_field_string (uiout, "exp", w->exp_string);
10926   do_cleanups (ui_out_chain);
10927 }
10928
10929 /* Implement the "print_recreate" breakpoint_ops method for
10930    watchpoints.  */
10931
10932 static void
10933 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10934 {
10935   struct watchpoint *w = (struct watchpoint *) b;
10936
10937   switch (b->type)
10938     {
10939     case bp_watchpoint:
10940     case bp_hardware_watchpoint:
10941       fprintf_unfiltered (fp, "watch");
10942       break;
10943     case bp_read_watchpoint:
10944       fprintf_unfiltered (fp, "rwatch");
10945       break;
10946     case bp_access_watchpoint:
10947       fprintf_unfiltered (fp, "awatch");
10948       break;
10949     default:
10950       internal_error (__FILE__, __LINE__,
10951                       _("Invalid watchpoint type."));
10952     }
10953
10954   fprintf_unfiltered (fp, " %s", w->exp_string);
10955   print_recreate_thread (b, fp);
10956 }
10957
10958 /* Implement the "explains_signal" breakpoint_ops method for
10959    watchpoints.  */
10960
10961 static int
10962 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10963 {
10964   /* A software watchpoint cannot cause a signal other than
10965      GDB_SIGNAL_TRAP.  */
10966   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10967     return 0;
10968
10969   return 1;
10970 }
10971
10972 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10973
10974 static struct breakpoint_ops watchpoint_breakpoint_ops;
10975
10976 /* Implement the "insert" breakpoint_ops method for
10977    masked hardware watchpoints.  */
10978
10979 static int
10980 insert_masked_watchpoint (struct bp_location *bl)
10981 {
10982   struct watchpoint *w = (struct watchpoint *) bl->owner;
10983
10984   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10985                                         bl->watchpoint_type);
10986 }
10987
10988 /* Implement the "remove" breakpoint_ops method for
10989    masked hardware watchpoints.  */
10990
10991 static int
10992 remove_masked_watchpoint (struct bp_location *bl)
10993 {
10994   struct watchpoint *w = (struct watchpoint *) bl->owner;
10995
10996   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10997                                         bl->watchpoint_type);
10998 }
10999
11000 /* Implement the "resources_needed" breakpoint_ops method for
11001    masked hardware watchpoints.  */
11002
11003 static int
11004 resources_needed_masked_watchpoint (const struct bp_location *bl)
11005 {
11006   struct watchpoint *w = (struct watchpoint *) bl->owner;
11007
11008   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11009 }
11010
11011 /* Implement the "works_in_software_mode" breakpoint_ops method for
11012    masked hardware watchpoints.  */
11013
11014 static int
11015 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11016 {
11017   return 0;
11018 }
11019
11020 /* Implement the "print_it" breakpoint_ops method for
11021    masked hardware watchpoints.  */
11022
11023 static enum print_stop_action
11024 print_it_masked_watchpoint (bpstat bs)
11025 {
11026   struct breakpoint *b = bs->breakpoint_at;
11027   struct ui_out *uiout = current_uiout;
11028
11029   /* Masked watchpoints have only one location.  */
11030   gdb_assert (b->loc && b->loc->next == NULL);
11031
11032   switch (b->type)
11033     {
11034     case bp_hardware_watchpoint:
11035       annotate_watchpoint (b->number);
11036       if (ui_out_is_mi_like_p (uiout))
11037         ui_out_field_string
11038           (uiout, "reason",
11039            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11040       break;
11041
11042     case bp_read_watchpoint:
11043       if (ui_out_is_mi_like_p (uiout))
11044         ui_out_field_string
11045           (uiout, "reason",
11046            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11047       break;
11048
11049     case bp_access_watchpoint:
11050       if (ui_out_is_mi_like_p (uiout))
11051         ui_out_field_string
11052           (uiout, "reason",
11053            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11054       break;
11055     default:
11056       internal_error (__FILE__, __LINE__,
11057                       _("Invalid hardware watchpoint type."));
11058     }
11059
11060   mention (b);
11061   ui_out_text (uiout, _("\n\
11062 Check the underlying instruction at PC for the memory\n\
11063 address and value which triggered this watchpoint.\n"));
11064   ui_out_text (uiout, "\n");
11065
11066   /* More than one watchpoint may have been triggered.  */
11067   return PRINT_UNKNOWN;
11068 }
11069
11070 /* Implement the "print_one_detail" breakpoint_ops method for
11071    masked hardware watchpoints.  */
11072
11073 static void
11074 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11075                                     struct ui_out *uiout)
11076 {
11077   struct watchpoint *w = (struct watchpoint *) b;
11078
11079   /* Masked watchpoints have only one location.  */
11080   gdb_assert (b->loc && b->loc->next == NULL);
11081
11082   ui_out_text (uiout, "\tmask ");
11083   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11084   ui_out_text (uiout, "\n");
11085 }
11086
11087 /* Implement the "print_mention" breakpoint_ops method for
11088    masked hardware watchpoints.  */
11089
11090 static void
11091 print_mention_masked_watchpoint (struct breakpoint *b)
11092 {
11093   struct watchpoint *w = (struct watchpoint *) b;
11094   struct ui_out *uiout = current_uiout;
11095   struct cleanup *ui_out_chain;
11096
11097   switch (b->type)
11098     {
11099     case bp_hardware_watchpoint:
11100       ui_out_text (uiout, "Masked hardware watchpoint ");
11101       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11102       break;
11103     case bp_read_watchpoint:
11104       ui_out_text (uiout, "Masked hardware read watchpoint ");
11105       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11106       break;
11107     case bp_access_watchpoint:
11108       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11109       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11110       break;
11111     default:
11112       internal_error (__FILE__, __LINE__,
11113                       _("Invalid hardware watchpoint type."));
11114     }
11115
11116   ui_out_field_int (uiout, "number", b->number);
11117   ui_out_text (uiout, ": ");
11118   ui_out_field_string (uiout, "exp", w->exp_string);
11119   do_cleanups (ui_out_chain);
11120 }
11121
11122 /* Implement the "print_recreate" breakpoint_ops method for
11123    masked hardware watchpoints.  */
11124
11125 static void
11126 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11127 {
11128   struct watchpoint *w = (struct watchpoint *) b;
11129   char tmp[40];
11130
11131   switch (b->type)
11132     {
11133     case bp_hardware_watchpoint:
11134       fprintf_unfiltered (fp, "watch");
11135       break;
11136     case bp_read_watchpoint:
11137       fprintf_unfiltered (fp, "rwatch");
11138       break;
11139     case bp_access_watchpoint:
11140       fprintf_unfiltered (fp, "awatch");
11141       break;
11142     default:
11143       internal_error (__FILE__, __LINE__,
11144                       _("Invalid hardware watchpoint type."));
11145     }
11146
11147   sprintf_vma (tmp, w->hw_wp_mask);
11148   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11149   print_recreate_thread (b, fp);
11150 }
11151
11152 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11153
11154 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11155
11156 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11157
11158 static int
11159 is_masked_watchpoint (const struct breakpoint *b)
11160 {
11161   return b->ops == &masked_watchpoint_breakpoint_ops;
11162 }
11163
11164 /* accessflag:  hw_write:  watch write, 
11165                 hw_read:   watch read, 
11166                 hw_access: watch access (read or write) */
11167 static void
11168 watch_command_1 (const char *arg, int accessflag, int from_tty,
11169                  int just_location, int internal)
11170 {
11171   volatile struct gdb_exception e;
11172   struct breakpoint *b, *scope_breakpoint = NULL;
11173   struct expression *exp;
11174   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11175   struct value *val, *mark, *result;
11176   struct frame_info *frame;
11177   const char *exp_start = NULL;
11178   const char *exp_end = NULL;
11179   const char *tok, *end_tok;
11180   int toklen = -1;
11181   const char *cond_start = NULL;
11182   const char *cond_end = NULL;
11183   enum bptype bp_type;
11184   int thread = -1;
11185   int pc = 0;
11186   /* Flag to indicate whether we are going to use masks for
11187      the hardware watchpoint.  */
11188   int use_mask = 0;
11189   CORE_ADDR mask = 0;
11190   struct watchpoint *w;
11191   char *expression;
11192   struct cleanup *back_to;
11193
11194   /* Make sure that we actually have parameters to parse.  */
11195   if (arg != NULL && arg[0] != '\0')
11196     {
11197       const char *value_start;
11198
11199       exp_end = arg + strlen (arg);
11200
11201       /* Look for "parameter value" pairs at the end
11202          of the arguments string.  */
11203       for (tok = exp_end - 1; tok > arg; tok--)
11204         {
11205           /* Skip whitespace at the end of the argument list.  */
11206           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11207             tok--;
11208
11209           /* Find the beginning of the last token.
11210              This is the value of the parameter.  */
11211           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11212             tok--;
11213           value_start = tok + 1;
11214
11215           /* Skip whitespace.  */
11216           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11217             tok--;
11218
11219           end_tok = tok;
11220
11221           /* Find the beginning of the second to last token.
11222              This is the parameter itself.  */
11223           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11224             tok--;
11225           tok++;
11226           toklen = end_tok - tok + 1;
11227
11228           if (toklen == 6 && !strncmp (tok, "thread", 6))
11229             {
11230               /* At this point we've found a "thread" token, which means
11231                  the user is trying to set a watchpoint that triggers
11232                  only in a specific thread.  */
11233               char *endp;
11234
11235               if (thread != -1)
11236                 error(_("You can specify only one thread."));
11237
11238               /* Extract the thread ID from the next token.  */
11239               thread = strtol (value_start, &endp, 0);
11240
11241               /* Check if the user provided a valid numeric value for the
11242                  thread ID.  */
11243               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11244                 error (_("Invalid thread ID specification %s."), value_start);
11245
11246               /* Check if the thread actually exists.  */
11247               if (!valid_thread_id (thread))
11248                 invalid_thread_id_error (thread);
11249             }
11250           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11251             {
11252               /* We've found a "mask" token, which means the user wants to
11253                  create a hardware watchpoint that is going to have the mask
11254                  facility.  */
11255               struct value *mask_value, *mark;
11256
11257               if (use_mask)
11258                 error(_("You can specify only one mask."));
11259
11260               use_mask = just_location = 1;
11261
11262               mark = value_mark ();
11263               mask_value = parse_to_comma_and_eval (&value_start);
11264               mask = value_as_address (mask_value);
11265               value_free_to_mark (mark);
11266             }
11267           else
11268             /* We didn't recognize what we found.  We should stop here.  */
11269             break;
11270
11271           /* Truncate the string and get rid of the "parameter value" pair before
11272              the arguments string is parsed by the parse_exp_1 function.  */
11273           exp_end = tok;
11274         }
11275     }
11276   else
11277     exp_end = arg;
11278
11279   /* Parse the rest of the arguments.  From here on out, everything
11280      is in terms of a newly allocated string instead of the original
11281      ARG.  */
11282   innermost_block = NULL;
11283   expression = savestring (arg, exp_end - arg);
11284   back_to = make_cleanup (xfree, expression);
11285   exp_start = arg = expression;
11286   exp = parse_exp_1 (&arg, 0, 0, 0);
11287   exp_end = arg;
11288   /* Remove trailing whitespace from the expression before saving it.
11289      This makes the eventual display of the expression string a bit
11290      prettier.  */
11291   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11292     --exp_end;
11293
11294   /* Checking if the expression is not constant.  */
11295   if (watchpoint_exp_is_const (exp))
11296     {
11297       int len;
11298
11299       len = exp_end - exp_start;
11300       while (len > 0 && isspace (exp_start[len - 1]))
11301         len--;
11302       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11303     }
11304
11305   exp_valid_block = innermost_block;
11306   mark = value_mark ();
11307   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11308
11309   if (just_location)
11310     {
11311       int ret;
11312
11313       exp_valid_block = NULL;
11314       val = value_addr (result);
11315       release_value (val);
11316       value_free_to_mark (mark);
11317
11318       if (use_mask)
11319         {
11320           ret = target_masked_watch_num_registers (value_as_address (val),
11321                                                    mask);
11322           if (ret == -1)
11323             error (_("This target does not support masked watchpoints."));
11324           else if (ret == -2)
11325             error (_("Invalid mask or memory region."));
11326         }
11327     }
11328   else if (val != NULL)
11329     release_value (val);
11330
11331   tok = skip_spaces_const (arg);
11332   end_tok = skip_to_space_const (tok);
11333
11334   toklen = end_tok - tok;
11335   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11336     {
11337       struct expression *cond;
11338
11339       innermost_block = NULL;
11340       tok = cond_start = end_tok + 1;
11341       cond = parse_exp_1 (&tok, 0, 0, 0);
11342
11343       /* The watchpoint expression may not be local, but the condition
11344          may still be.  E.g.: `watch global if local > 0'.  */
11345       cond_exp_valid_block = innermost_block;
11346
11347       xfree (cond);
11348       cond_end = tok;
11349     }
11350   if (*tok)
11351     error (_("Junk at end of command."));
11352
11353   frame = block_innermost_frame (exp_valid_block);
11354
11355   /* If the expression is "local", then set up a "watchpoint scope"
11356      breakpoint at the point where we've left the scope of the watchpoint
11357      expression.  Create the scope breakpoint before the watchpoint, so
11358      that we will encounter it first in bpstat_stop_status.  */
11359   if (exp_valid_block && frame)
11360     {
11361       if (frame_id_p (frame_unwind_caller_id (frame)))
11362         {
11363           scope_breakpoint
11364             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11365                                           frame_unwind_caller_pc (frame),
11366                                           bp_watchpoint_scope,
11367                                           &momentary_breakpoint_ops);
11368
11369           scope_breakpoint->enable_state = bp_enabled;
11370
11371           /* Automatically delete the breakpoint when it hits.  */
11372           scope_breakpoint->disposition = disp_del;
11373
11374           /* Only break in the proper frame (help with recursion).  */
11375           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11376
11377           /* Set the address at which we will stop.  */
11378           scope_breakpoint->loc->gdbarch
11379             = frame_unwind_caller_arch (frame);
11380           scope_breakpoint->loc->requested_address
11381             = frame_unwind_caller_pc (frame);
11382           scope_breakpoint->loc->address
11383             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11384                                          scope_breakpoint->loc->requested_address,
11385                                          scope_breakpoint->type);
11386         }
11387     }
11388
11389   /* Now set up the breakpoint.  We create all watchpoints as hardware
11390      watchpoints here even if hardware watchpoints are turned off, a call
11391      to update_watchpoint later in this function will cause the type to
11392      drop back to bp_watchpoint (software watchpoint) if required.  */
11393
11394   if (accessflag == hw_read)
11395     bp_type = bp_read_watchpoint;
11396   else if (accessflag == hw_access)
11397     bp_type = bp_access_watchpoint;
11398   else
11399     bp_type = bp_hardware_watchpoint;
11400
11401   w = XCNEW (struct watchpoint);
11402   b = &w->base;
11403   if (use_mask)
11404     init_raw_breakpoint_without_location (b, NULL, bp_type,
11405                                           &masked_watchpoint_breakpoint_ops);
11406   else
11407     init_raw_breakpoint_without_location (b, NULL, bp_type,
11408                                           &watchpoint_breakpoint_ops);
11409   b->thread = thread;
11410   b->disposition = disp_donttouch;
11411   b->pspace = current_program_space;
11412   w->exp = exp;
11413   w->exp_valid_block = exp_valid_block;
11414   w->cond_exp_valid_block = cond_exp_valid_block;
11415   if (just_location)
11416     {
11417       struct type *t = value_type (val);
11418       CORE_ADDR addr = value_as_address (val);
11419       char *name;
11420
11421       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11422       name = type_to_string (t);
11423
11424       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11425                                           core_addr_to_string (addr));
11426       xfree (name);
11427
11428       w->exp_string = xstrprintf ("-location %.*s",
11429                                   (int) (exp_end - exp_start), exp_start);
11430
11431       /* The above expression is in C.  */
11432       b->language = language_c;
11433     }
11434   else
11435     w->exp_string = savestring (exp_start, exp_end - exp_start);
11436
11437   if (use_mask)
11438     {
11439       w->hw_wp_mask = mask;
11440     }
11441   else
11442     {
11443       w->val = val;
11444       w->val_valid = 1;
11445     }
11446
11447   if (cond_start)
11448     b->cond_string = savestring (cond_start, cond_end - cond_start);
11449   else
11450     b->cond_string = 0;
11451
11452   if (frame)
11453     {
11454       w->watchpoint_frame = get_frame_id (frame);
11455       w->watchpoint_thread = inferior_ptid;
11456     }
11457   else
11458     {
11459       w->watchpoint_frame = null_frame_id;
11460       w->watchpoint_thread = null_ptid;
11461     }
11462
11463   if (scope_breakpoint != NULL)
11464     {
11465       /* The scope breakpoint is related to the watchpoint.  We will
11466          need to act on them together.  */
11467       b->related_breakpoint = scope_breakpoint;
11468       scope_breakpoint->related_breakpoint = b;
11469     }
11470
11471   if (!just_location)
11472     value_free_to_mark (mark);
11473
11474   TRY_CATCH (e, RETURN_MASK_ALL)
11475     {
11476       /* Finally update the new watchpoint.  This creates the locations
11477          that should be inserted.  */
11478       update_watchpoint (w, 1);
11479     }
11480   if (e.reason < 0)
11481     {
11482       delete_breakpoint (b);
11483       throw_exception (e);
11484     }
11485
11486   install_breakpoint (internal, b, 1);
11487   do_cleanups (back_to);
11488 }
11489
11490 /* Return count of debug registers needed to watch the given expression.
11491    If the watchpoint cannot be handled in hardware return zero.  */
11492
11493 static int
11494 can_use_hardware_watchpoint (struct value *v)
11495 {
11496   int found_memory_cnt = 0;
11497   struct value *head = v;
11498
11499   /* Did the user specifically forbid us to use hardware watchpoints? */
11500   if (!can_use_hw_watchpoints)
11501     return 0;
11502
11503   /* Make sure that the value of the expression depends only upon
11504      memory contents, and values computed from them within GDB.  If we
11505      find any register references or function calls, we can't use a
11506      hardware watchpoint.
11507
11508      The idea here is that evaluating an expression generates a series
11509      of values, one holding the value of every subexpression.  (The
11510      expression a*b+c has five subexpressions: a, b, a*b, c, and
11511      a*b+c.)  GDB's values hold almost enough information to establish
11512      the criteria given above --- they identify memory lvalues,
11513      register lvalues, computed values, etcetera.  So we can evaluate
11514      the expression, and then scan the chain of values that leaves
11515      behind to decide whether we can detect any possible change to the
11516      expression's final value using only hardware watchpoints.
11517
11518      However, I don't think that the values returned by inferior
11519      function calls are special in any way.  So this function may not
11520      notice that an expression involving an inferior function call
11521      can't be watched with hardware watchpoints.  FIXME.  */
11522   for (; v; v = value_next (v))
11523     {
11524       if (VALUE_LVAL (v) == lval_memory)
11525         {
11526           if (v != head && value_lazy (v))
11527             /* A lazy memory lvalue in the chain is one that GDB never
11528                needed to fetch; we either just used its address (e.g.,
11529                `a' in `a.b') or we never needed it at all (e.g., `a'
11530                in `a,b').  This doesn't apply to HEAD; if that is
11531                lazy then it was not readable, but watch it anyway.  */
11532             ;
11533           else
11534             {
11535               /* Ahh, memory we actually used!  Check if we can cover
11536                  it with hardware watchpoints.  */
11537               struct type *vtype = check_typedef (value_type (v));
11538
11539               /* We only watch structs and arrays if user asked for it
11540                  explicitly, never if they just happen to appear in a
11541                  middle of some value chain.  */
11542               if (v == head
11543                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11544                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11545                 {
11546                   CORE_ADDR vaddr = value_address (v);
11547                   int len;
11548                   int num_regs;
11549
11550                   len = (target_exact_watchpoints
11551                          && is_scalar_type_recursive (vtype))?
11552                     1 : TYPE_LENGTH (value_type (v));
11553
11554                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11555                   if (!num_regs)
11556                     return 0;
11557                   else
11558                     found_memory_cnt += num_regs;
11559                 }
11560             }
11561         }
11562       else if (VALUE_LVAL (v) != not_lval
11563                && deprecated_value_modifiable (v) == 0)
11564         return 0;       /* These are values from the history (e.g., $1).  */
11565       else if (VALUE_LVAL (v) == lval_register)
11566         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11567     }
11568
11569   /* The expression itself looks suitable for using a hardware
11570      watchpoint, but give the target machine a chance to reject it.  */
11571   return found_memory_cnt;
11572 }
11573
11574 void
11575 watch_command_wrapper (char *arg, int from_tty, int internal)
11576 {
11577   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11578 }
11579
11580 /* A helper function that looks for the "-location" argument and then
11581    calls watch_command_1.  */
11582
11583 static void
11584 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11585 {
11586   int just_location = 0;
11587
11588   if (arg
11589       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11590           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11591     {
11592       arg = skip_spaces (arg);
11593       just_location = 1;
11594     }
11595
11596   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11597 }
11598
11599 static void
11600 watch_command (char *arg, int from_tty)
11601 {
11602   watch_maybe_just_location (arg, hw_write, from_tty);
11603 }
11604
11605 void
11606 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11607 {
11608   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11609 }
11610
11611 static void
11612 rwatch_command (char *arg, int from_tty)
11613 {
11614   watch_maybe_just_location (arg, hw_read, from_tty);
11615 }
11616
11617 void
11618 awatch_command_wrapper (char *arg, int from_tty, int internal)
11619 {
11620   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11621 }
11622
11623 static void
11624 awatch_command (char *arg, int from_tty)
11625 {
11626   watch_maybe_just_location (arg, hw_access, from_tty);
11627 }
11628 \f
11629
11630 /* Helper routines for the until_command routine in infcmd.c.  Here
11631    because it uses the mechanisms of breakpoints.  */
11632
11633 struct until_break_command_continuation_args
11634 {
11635   struct breakpoint *breakpoint;
11636   struct breakpoint *breakpoint2;
11637   int thread_num;
11638 };
11639
11640 /* This function is called by fetch_inferior_event via the
11641    cmd_continuation pointer, to complete the until command.  It takes
11642    care of cleaning up the temporary breakpoints set up by the until
11643    command.  */
11644 static void
11645 until_break_command_continuation (void *arg, int err)
11646 {
11647   struct until_break_command_continuation_args *a = arg;
11648
11649   delete_breakpoint (a->breakpoint);
11650   if (a->breakpoint2)
11651     delete_breakpoint (a->breakpoint2);
11652   delete_longjmp_breakpoint (a->thread_num);
11653 }
11654
11655 void
11656 until_break_command (char *arg, int from_tty, int anywhere)
11657 {
11658   struct symtabs_and_lines sals;
11659   struct symtab_and_line sal;
11660   struct frame_info *frame;
11661   struct gdbarch *frame_gdbarch;
11662   struct frame_id stack_frame_id;
11663   struct frame_id caller_frame_id;
11664   struct breakpoint *breakpoint;
11665   struct breakpoint *breakpoint2 = NULL;
11666   struct cleanup *old_chain;
11667   int thread;
11668   struct thread_info *tp;
11669
11670   clear_proceed_status (0);
11671
11672   /* Set a breakpoint where the user wants it and at return from
11673      this function.  */
11674
11675   if (last_displayed_sal_is_valid ())
11676     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11677                           get_last_displayed_symtab (),
11678                           get_last_displayed_line ());
11679   else
11680     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11681                           (struct symtab *) NULL, 0);
11682
11683   if (sals.nelts != 1)
11684     error (_("Couldn't get information on specified line."));
11685
11686   sal = sals.sals[0];
11687   xfree (sals.sals);    /* malloc'd, so freed.  */
11688
11689   if (*arg)
11690     error (_("Junk at end of arguments."));
11691
11692   resolve_sal_pc (&sal);
11693
11694   tp = inferior_thread ();
11695   thread = tp->num;
11696
11697   old_chain = make_cleanup (null_cleanup, NULL);
11698
11699   /* Note linespec handling above invalidates the frame chain.
11700      Installing a breakpoint also invalidates the frame chain (as it
11701      may need to switch threads), so do any frame handling before
11702      that.  */
11703
11704   frame = get_selected_frame (NULL);
11705   frame_gdbarch = get_frame_arch (frame);
11706   stack_frame_id = get_stack_frame_id (frame);
11707   caller_frame_id = frame_unwind_caller_id (frame);
11708
11709   /* Keep within the current frame, or in frames called by the current
11710      one.  */
11711
11712   if (frame_id_p (caller_frame_id))
11713     {
11714       struct symtab_and_line sal2;
11715
11716       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11717       sal2.pc = frame_unwind_caller_pc (frame);
11718       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11719                                               sal2,
11720                                               caller_frame_id,
11721                                               bp_until);
11722       make_cleanup_delete_breakpoint (breakpoint2);
11723
11724       set_longjmp_breakpoint (tp, caller_frame_id);
11725       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11726     }
11727
11728   /* set_momentary_breakpoint could invalidate FRAME.  */
11729   frame = NULL;
11730
11731   if (anywhere)
11732     /* If the user told us to continue until a specified location,
11733        we don't specify a frame at which we need to stop.  */
11734     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11735                                            null_frame_id, bp_until);
11736   else
11737     /* Otherwise, specify the selected frame, because we want to stop
11738        only at the very same frame.  */
11739     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11740                                            stack_frame_id, bp_until);
11741   make_cleanup_delete_breakpoint (breakpoint);
11742
11743   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11744
11745   /* If we are running asynchronously, and proceed call above has
11746      actually managed to start the target, arrange for breakpoints to
11747      be deleted when the target stops.  Otherwise, we're already
11748      stopped and delete breakpoints via cleanup chain.  */
11749
11750   if (target_can_async_p () && is_running (inferior_ptid))
11751     {
11752       struct until_break_command_continuation_args *args;
11753       args = xmalloc (sizeof (*args));
11754
11755       args->breakpoint = breakpoint;
11756       args->breakpoint2 = breakpoint2;
11757       args->thread_num = thread;
11758
11759       discard_cleanups (old_chain);
11760       add_continuation (inferior_thread (),
11761                         until_break_command_continuation, args,
11762                         xfree);
11763     }
11764   else
11765     do_cleanups (old_chain);
11766 }
11767
11768 /* This function attempts to parse an optional "if <cond>" clause
11769    from the arg string.  If one is not found, it returns NULL.
11770
11771    Else, it returns a pointer to the condition string.  (It does not
11772    attempt to evaluate the string against a particular block.)  And,
11773    it updates arg to point to the first character following the parsed
11774    if clause in the arg string.  */
11775
11776 char *
11777 ep_parse_optional_if_clause (char **arg)
11778 {
11779   char *cond_string;
11780
11781   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11782     return NULL;
11783
11784   /* Skip the "if" keyword.  */
11785   (*arg) += 2;
11786
11787   /* Skip any extra leading whitespace, and record the start of the
11788      condition string.  */
11789   *arg = skip_spaces (*arg);
11790   cond_string = *arg;
11791
11792   /* Assume that the condition occupies the remainder of the arg
11793      string.  */
11794   (*arg) += strlen (cond_string);
11795
11796   return cond_string;
11797 }
11798
11799 /* Commands to deal with catching events, such as signals, exceptions,
11800    process start/exit, etc.  */
11801
11802 typedef enum
11803 {
11804   catch_fork_temporary, catch_vfork_temporary,
11805   catch_fork_permanent, catch_vfork_permanent
11806 }
11807 catch_fork_kind;
11808
11809 static void
11810 catch_fork_command_1 (char *arg, int from_tty, 
11811                       struct cmd_list_element *command)
11812 {
11813   struct gdbarch *gdbarch = get_current_arch ();
11814   char *cond_string = NULL;
11815   catch_fork_kind fork_kind;
11816   int tempflag;
11817
11818   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11819   tempflag = (fork_kind == catch_fork_temporary
11820               || fork_kind == catch_vfork_temporary);
11821
11822   if (!arg)
11823     arg = "";
11824   arg = skip_spaces (arg);
11825
11826   /* The allowed syntax is:
11827      catch [v]fork
11828      catch [v]fork if <cond>
11829
11830      First, check if there's an if clause.  */
11831   cond_string = ep_parse_optional_if_clause (&arg);
11832
11833   if ((*arg != '\0') && !isspace (*arg))
11834     error (_("Junk at end of arguments."));
11835
11836   /* If this target supports it, create a fork or vfork catchpoint
11837      and enable reporting of such events.  */
11838   switch (fork_kind)
11839     {
11840     case catch_fork_temporary:
11841     case catch_fork_permanent:
11842       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11843                                           &catch_fork_breakpoint_ops);
11844       break;
11845     case catch_vfork_temporary:
11846     case catch_vfork_permanent:
11847       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11848                                           &catch_vfork_breakpoint_ops);
11849       break;
11850     default:
11851       error (_("unsupported or unknown fork kind; cannot catch it"));
11852       break;
11853     }
11854 }
11855
11856 static void
11857 catch_exec_command_1 (char *arg, int from_tty, 
11858                       struct cmd_list_element *command)
11859 {
11860   struct exec_catchpoint *c;
11861   struct gdbarch *gdbarch = get_current_arch ();
11862   int tempflag;
11863   char *cond_string = NULL;
11864
11865   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11866
11867   if (!arg)
11868     arg = "";
11869   arg = skip_spaces (arg);
11870
11871   /* The allowed syntax is:
11872      catch exec
11873      catch exec if <cond>
11874
11875      First, check if there's an if clause.  */
11876   cond_string = ep_parse_optional_if_clause (&arg);
11877
11878   if ((*arg != '\0') && !isspace (*arg))
11879     error (_("Junk at end of arguments."));
11880
11881   c = XNEW (struct exec_catchpoint);
11882   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11883                    &catch_exec_breakpoint_ops);
11884   c->exec_pathname = NULL;
11885
11886   install_breakpoint (0, &c->base, 1);
11887 }
11888
11889 void
11890 init_ada_exception_breakpoint (struct breakpoint *b,
11891                                struct gdbarch *gdbarch,
11892                                struct symtab_and_line sal,
11893                                char *addr_string,
11894                                const struct breakpoint_ops *ops,
11895                                int tempflag,
11896                                int enabled,
11897                                int from_tty)
11898 {
11899   if (from_tty)
11900     {
11901       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11902       if (!loc_gdbarch)
11903         loc_gdbarch = gdbarch;
11904
11905       describe_other_breakpoints (loc_gdbarch,
11906                                   sal.pspace, sal.pc, sal.section, -1);
11907       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11908          version for exception catchpoints, because two catchpoints
11909          used for different exception names will use the same address.
11910          In this case, a "breakpoint ... also set at..." warning is
11911          unproductive.  Besides, the warning phrasing is also a bit
11912          inappropriate, we should use the word catchpoint, and tell
11913          the user what type of catchpoint it is.  The above is good
11914          enough for now, though.  */
11915     }
11916
11917   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11918
11919   b->enable_state = enabled ? bp_enabled : bp_disabled;
11920   b->disposition = tempflag ? disp_del : disp_donttouch;
11921   b->addr_string = addr_string;
11922   b->language = language_ada;
11923 }
11924
11925 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11926    filter list, or NULL if no filtering is required.  */
11927 static VEC(int) *
11928 catch_syscall_split_args (char *arg)
11929 {
11930   VEC(int) *result = NULL;
11931   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11932
11933   while (*arg != '\0')
11934     {
11935       int i, syscall_number;
11936       char *endptr;
11937       char cur_name[128];
11938       struct syscall s;
11939
11940       /* Skip whitespace.  */
11941       arg = skip_spaces (arg);
11942
11943       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11944         cur_name[i] = arg[i];
11945       cur_name[i] = '\0';
11946       arg += i;
11947
11948       /* Check if the user provided a syscall name or a number.  */
11949       syscall_number = (int) strtol (cur_name, &endptr, 0);
11950       if (*endptr == '\0')
11951         get_syscall_by_number (syscall_number, &s);
11952       else
11953         {
11954           /* We have a name.  Let's check if it's valid and convert it
11955              to a number.  */
11956           get_syscall_by_name (cur_name, &s);
11957
11958           if (s.number == UNKNOWN_SYSCALL)
11959             /* Here we have to issue an error instead of a warning,
11960                because GDB cannot do anything useful if there's no
11961                syscall number to be caught.  */
11962             error (_("Unknown syscall name '%s'."), cur_name);
11963         }
11964
11965       /* Ok, it's valid.  */
11966       VEC_safe_push (int, result, s.number);
11967     }
11968
11969   discard_cleanups (cleanup);
11970   return result;
11971 }
11972
11973 /* Implement the "catch syscall" command.  */
11974
11975 static void
11976 catch_syscall_command_1 (char *arg, int from_tty, 
11977                          struct cmd_list_element *command)
11978 {
11979   int tempflag;
11980   VEC(int) *filter;
11981   struct syscall s;
11982   struct gdbarch *gdbarch = get_current_arch ();
11983
11984   /* Checking if the feature if supported.  */
11985   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11986     error (_("The feature 'catch syscall' is not supported on \
11987 this architecture yet."));
11988
11989   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11990
11991   arg = skip_spaces (arg);
11992
11993   /* We need to do this first "dummy" translation in order
11994      to get the syscall XML file loaded or, most important,
11995      to display a warning to the user if there's no XML file
11996      for his/her architecture.  */
11997   get_syscall_by_number (0, &s);
11998
11999   /* The allowed syntax is:
12000      catch syscall
12001      catch syscall <name | number> [<name | number> ... <name | number>]
12002
12003      Let's check if there's a syscall name.  */
12004
12005   if (arg != NULL)
12006     filter = catch_syscall_split_args (arg);
12007   else
12008     filter = NULL;
12009
12010   create_syscall_event_catchpoint (tempflag, filter,
12011                                    &catch_syscall_breakpoint_ops);
12012 }
12013
12014 static void
12015 catch_command (char *arg, int from_tty)
12016 {
12017   error (_("Catch requires an event name."));
12018 }
12019 \f
12020
12021 static void
12022 tcatch_command (char *arg, int from_tty)
12023 {
12024   error (_("Catch requires an event name."));
12025 }
12026
12027 /* A qsort comparison function that sorts breakpoints in order.  */
12028
12029 static int
12030 compare_breakpoints (const void *a, const void *b)
12031 {
12032   const breakpoint_p *ba = a;
12033   uintptr_t ua = (uintptr_t) *ba;
12034   const breakpoint_p *bb = b;
12035   uintptr_t ub = (uintptr_t) *bb;
12036
12037   if ((*ba)->number < (*bb)->number)
12038     return -1;
12039   else if ((*ba)->number > (*bb)->number)
12040     return 1;
12041
12042   /* Now sort by address, in case we see, e..g, two breakpoints with
12043      the number 0.  */
12044   if (ua < ub)
12045     return -1;
12046   return ua > ub ? 1 : 0;
12047 }
12048
12049 /* Delete breakpoints by address or line.  */
12050
12051 static void
12052 clear_command (char *arg, int from_tty)
12053 {
12054   struct breakpoint *b, *prev;
12055   VEC(breakpoint_p) *found = 0;
12056   int ix;
12057   int default_match;
12058   struct symtabs_and_lines sals;
12059   struct symtab_and_line sal;
12060   int i;
12061   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12062
12063   if (arg)
12064     {
12065       sals = decode_line_with_current_source (arg,
12066                                               (DECODE_LINE_FUNFIRSTLINE
12067                                                | DECODE_LINE_LIST_MODE));
12068       make_cleanup (xfree, sals.sals);
12069       default_match = 0;
12070     }
12071   else
12072     {
12073       sals.sals = (struct symtab_and_line *)
12074         xmalloc (sizeof (struct symtab_and_line));
12075       make_cleanup (xfree, sals.sals);
12076       init_sal (&sal);          /* Initialize to zeroes.  */
12077
12078       /* Set sal's line, symtab, pc, and pspace to the values
12079          corresponding to the last call to print_frame_info.  If the
12080          codepoint is not valid, this will set all the fields to 0.  */
12081       get_last_displayed_sal (&sal);
12082       if (sal.symtab == 0)
12083         error (_("No source file specified."));
12084
12085       sals.sals[0] = sal;
12086       sals.nelts = 1;
12087
12088       default_match = 1;
12089     }
12090
12091   /* We don't call resolve_sal_pc here.  That's not as bad as it
12092      seems, because all existing breakpoints typically have both
12093      file/line and pc set.  So, if clear is given file/line, we can
12094      match this to existing breakpoint without obtaining pc at all.
12095
12096      We only support clearing given the address explicitly 
12097      present in breakpoint table.  Say, we've set breakpoint 
12098      at file:line.  There were several PC values for that file:line,
12099      due to optimization, all in one block.
12100
12101      We've picked one PC value.  If "clear" is issued with another
12102      PC corresponding to the same file:line, the breakpoint won't
12103      be cleared.  We probably can still clear the breakpoint, but 
12104      since the other PC value is never presented to user, user
12105      can only find it by guessing, and it does not seem important
12106      to support that.  */
12107
12108   /* For each line spec given, delete bps which correspond to it.  Do
12109      it in two passes, solely to preserve the current behavior that
12110      from_tty is forced true if we delete more than one
12111      breakpoint.  */
12112
12113   found = NULL;
12114   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12115   for (i = 0; i < sals.nelts; i++)
12116     {
12117       const char *sal_fullname;
12118
12119       /* If exact pc given, clear bpts at that pc.
12120          If line given (pc == 0), clear all bpts on specified line.
12121          If defaulting, clear all bpts on default line
12122          or at default pc.
12123
12124          defaulting    sal.pc != 0    tests to do
12125
12126          0              1             pc
12127          1              1             pc _and_ line
12128          0              0             line
12129          1              0             <can't happen> */
12130
12131       sal = sals.sals[i];
12132       sal_fullname = (sal.symtab == NULL
12133                       ? NULL : symtab_to_fullname (sal.symtab));
12134
12135       /* Find all matching breakpoints and add them to 'found'.  */
12136       ALL_BREAKPOINTS (b)
12137         {
12138           int match = 0;
12139           /* Are we going to delete b?  */
12140           if (b->type != bp_none && !is_watchpoint (b))
12141             {
12142               struct bp_location *loc = b->loc;
12143               for (; loc; loc = loc->next)
12144                 {
12145                   /* If the user specified file:line, don't allow a PC
12146                      match.  This matches historical gdb behavior.  */
12147                   int pc_match = (!sal.explicit_line
12148                                   && sal.pc
12149                                   && (loc->pspace == sal.pspace)
12150                                   && (loc->address == sal.pc)
12151                                   && (!section_is_overlay (loc->section)
12152                                       || loc->section == sal.section));
12153                   int line_match = 0;
12154
12155                   if ((default_match || sal.explicit_line)
12156                       && loc->symtab != NULL
12157                       && sal_fullname != NULL
12158                       && sal.pspace == loc->pspace
12159                       && loc->line_number == sal.line
12160                       && filename_cmp (symtab_to_fullname (loc->symtab),
12161                                        sal_fullname) == 0)
12162                     line_match = 1;
12163
12164                   if (pc_match || line_match)
12165                     {
12166                       match = 1;
12167                       break;
12168                     }
12169                 }
12170             }
12171
12172           if (match)
12173             VEC_safe_push(breakpoint_p, found, b);
12174         }
12175     }
12176
12177   /* Now go thru the 'found' chain and delete them.  */
12178   if (VEC_empty(breakpoint_p, found))
12179     {
12180       if (arg)
12181         error (_("No breakpoint at %s."), arg);
12182       else
12183         error (_("No breakpoint at this line."));
12184     }
12185
12186   /* Remove duplicates from the vec.  */
12187   qsort (VEC_address (breakpoint_p, found),
12188          VEC_length (breakpoint_p, found),
12189          sizeof (breakpoint_p),
12190          compare_breakpoints);
12191   prev = VEC_index (breakpoint_p, found, 0);
12192   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12193     {
12194       if (b == prev)
12195         {
12196           VEC_ordered_remove (breakpoint_p, found, ix);
12197           --ix;
12198         }
12199     }
12200
12201   if (VEC_length(breakpoint_p, found) > 1)
12202     from_tty = 1;       /* Always report if deleted more than one.  */
12203   if (from_tty)
12204     {
12205       if (VEC_length(breakpoint_p, found) == 1)
12206         printf_unfiltered (_("Deleted breakpoint "));
12207       else
12208         printf_unfiltered (_("Deleted breakpoints "));
12209     }
12210
12211   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12212     {
12213       if (from_tty)
12214         printf_unfiltered ("%d ", b->number);
12215       delete_breakpoint (b);
12216     }
12217   if (from_tty)
12218     putchar_unfiltered ('\n');
12219
12220   do_cleanups (cleanups);
12221 }
12222 \f
12223 /* Delete breakpoint in BS if they are `delete' breakpoints and
12224    all breakpoints that are marked for deletion, whether hit or not.
12225    This is called after any breakpoint is hit, or after errors.  */
12226
12227 void
12228 breakpoint_auto_delete (bpstat bs)
12229 {
12230   struct breakpoint *b, *b_tmp;
12231
12232   for (; bs; bs = bs->next)
12233     if (bs->breakpoint_at
12234         && bs->breakpoint_at->disposition == disp_del
12235         && bs->stop)
12236       delete_breakpoint (bs->breakpoint_at);
12237
12238   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12239   {
12240     if (b->disposition == disp_del_at_next_stop)
12241       delete_breakpoint (b);
12242   }
12243 }
12244
12245 /* A comparison function for bp_location AP and BP being interfaced to
12246    qsort.  Sort elements primarily by their ADDRESS (no matter what
12247    does breakpoint_address_is_meaningful say for its OWNER),
12248    secondarily by ordering first bp_permanent OWNERed elements and
12249    terciarily just ensuring the array is sorted stable way despite
12250    qsort being an unstable algorithm.  */
12251
12252 static int
12253 bp_location_compare (const void *ap, const void *bp)
12254 {
12255   struct bp_location *a = *(void **) ap;
12256   struct bp_location *b = *(void **) bp;
12257   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12258   int a_perm = a->owner->enable_state == bp_permanent;
12259   int b_perm = b->owner->enable_state == bp_permanent;
12260
12261   if (a->address != b->address)
12262     return (a->address > b->address) - (a->address < b->address);
12263
12264   /* Sort locations at the same address by their pspace number, keeping
12265      locations of the same inferior (in a multi-inferior environment)
12266      grouped.  */
12267
12268   if (a->pspace->num != b->pspace->num)
12269     return ((a->pspace->num > b->pspace->num)
12270             - (a->pspace->num < b->pspace->num));
12271
12272   /* Sort permanent breakpoints first.  */
12273   if (a_perm != b_perm)
12274     return (a_perm < b_perm) - (a_perm > b_perm);
12275
12276   /* Make the internal GDB representation stable across GDB runs
12277      where A and B memory inside GDB can differ.  Breakpoint locations of
12278      the same type at the same address can be sorted in arbitrary order.  */
12279
12280   if (a->owner->number != b->owner->number)
12281     return ((a->owner->number > b->owner->number)
12282             - (a->owner->number < b->owner->number));
12283
12284   return (a > b) - (a < b);
12285 }
12286
12287 /* Set bp_location_placed_address_before_address_max and
12288    bp_location_shadow_len_after_address_max according to the current
12289    content of the bp_location array.  */
12290
12291 static void
12292 bp_location_target_extensions_update (void)
12293 {
12294   struct bp_location *bl, **blp_tmp;
12295
12296   bp_location_placed_address_before_address_max = 0;
12297   bp_location_shadow_len_after_address_max = 0;
12298
12299   ALL_BP_LOCATIONS (bl, blp_tmp)
12300     {
12301       CORE_ADDR start, end, addr;
12302
12303       if (!bp_location_has_shadow (bl))
12304         continue;
12305
12306       start = bl->target_info.placed_address;
12307       end = start + bl->target_info.shadow_len;
12308
12309       gdb_assert (bl->address >= start);
12310       addr = bl->address - start;
12311       if (addr > bp_location_placed_address_before_address_max)
12312         bp_location_placed_address_before_address_max = addr;
12313
12314       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12315
12316       gdb_assert (bl->address < end);
12317       addr = end - bl->address;
12318       if (addr > bp_location_shadow_len_after_address_max)
12319         bp_location_shadow_len_after_address_max = addr;
12320     }
12321 }
12322
12323 /* Download tracepoint locations if they haven't been.  */
12324
12325 static void
12326 download_tracepoint_locations (void)
12327 {
12328   struct breakpoint *b;
12329   struct cleanup *old_chain;
12330
12331   if (!target_can_download_tracepoint ())
12332     return;
12333
12334   old_chain = save_current_space_and_thread ();
12335
12336   ALL_TRACEPOINTS (b)
12337     {
12338       struct bp_location *bl;
12339       struct tracepoint *t;
12340       int bp_location_downloaded = 0;
12341
12342       if ((b->type == bp_fast_tracepoint
12343            ? !may_insert_fast_tracepoints
12344            : !may_insert_tracepoints))
12345         continue;
12346
12347       for (bl = b->loc; bl; bl = bl->next)
12348         {
12349           /* In tracepoint, locations are _never_ duplicated, so
12350              should_be_inserted is equivalent to
12351              unduplicated_should_be_inserted.  */
12352           if (!should_be_inserted (bl) || bl->inserted)
12353             continue;
12354
12355           switch_to_program_space_and_thread (bl->pspace);
12356
12357           target_download_tracepoint (bl);
12358
12359           bl->inserted = 1;
12360           bp_location_downloaded = 1;
12361         }
12362       t = (struct tracepoint *) b;
12363       t->number_on_target = b->number;
12364       if (bp_location_downloaded)
12365         observer_notify_breakpoint_modified (b);
12366     }
12367
12368   do_cleanups (old_chain);
12369 }
12370
12371 /* Swap the insertion/duplication state between two locations.  */
12372
12373 static void
12374 swap_insertion (struct bp_location *left, struct bp_location *right)
12375 {
12376   const int left_inserted = left->inserted;
12377   const int left_duplicate = left->duplicate;
12378   const int left_needs_update = left->needs_update;
12379   const struct bp_target_info left_target_info = left->target_info;
12380
12381   /* Locations of tracepoints can never be duplicated.  */
12382   if (is_tracepoint (left->owner))
12383     gdb_assert (!left->duplicate);
12384   if (is_tracepoint (right->owner))
12385     gdb_assert (!right->duplicate);
12386
12387   left->inserted = right->inserted;
12388   left->duplicate = right->duplicate;
12389   left->needs_update = right->needs_update;
12390   left->target_info = right->target_info;
12391   right->inserted = left_inserted;
12392   right->duplicate = left_duplicate;
12393   right->needs_update = left_needs_update;
12394   right->target_info = left_target_info;
12395 }
12396
12397 /* Force the re-insertion of the locations at ADDRESS.  This is called
12398    once a new/deleted/modified duplicate location is found and we are evaluating
12399    conditions on the target's side.  Such conditions need to be updated on
12400    the target.  */
12401
12402 static void
12403 force_breakpoint_reinsertion (struct bp_location *bl)
12404 {
12405   struct bp_location **locp = NULL, **loc2p;
12406   struct bp_location *loc;
12407   CORE_ADDR address = 0;
12408   int pspace_num;
12409
12410   address = bl->address;
12411   pspace_num = bl->pspace->num;
12412
12413   /* This is only meaningful if the target is
12414      evaluating conditions and if the user has
12415      opted for condition evaluation on the target's
12416      side.  */
12417   if (gdb_evaluates_breakpoint_condition_p ()
12418       || !target_supports_evaluation_of_breakpoint_conditions ())
12419     return;
12420
12421   /* Flag all breakpoint locations with this address and
12422      the same program space as the location
12423      as "its condition has changed".  We need to
12424      update the conditions on the target's side.  */
12425   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12426     {
12427       loc = *loc2p;
12428
12429       if (!is_breakpoint (loc->owner)
12430           || pspace_num != loc->pspace->num)
12431         continue;
12432
12433       /* Flag the location appropriately.  We use a different state to
12434          let everyone know that we already updated the set of locations
12435          with addr bl->address and program space bl->pspace.  This is so
12436          we don't have to keep calling these functions just to mark locations
12437          that have already been marked.  */
12438       loc->condition_changed = condition_updated;
12439
12440       /* Free the agent expression bytecode as well.  We will compute
12441          it later on.  */
12442       if (loc->cond_bytecode)
12443         {
12444           free_agent_expr (loc->cond_bytecode);
12445           loc->cond_bytecode = NULL;
12446         }
12447     }
12448 }
12449
12450 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12451    into the inferior, only remove already-inserted locations that no
12452    longer should be inserted.  Functions that delete a breakpoint or
12453    breakpoints should pass false, so that deleting a breakpoint
12454    doesn't have the side effect of inserting the locations of other
12455    breakpoints that are marked not-inserted, but should_be_inserted
12456    returns true on them.
12457
12458    This behaviour is useful is situations close to tear-down -- e.g.,
12459    after an exec, while the target still has execution, but breakpoint
12460    shadows of the previous executable image should *NOT* be restored
12461    to the new image; or before detaching, where the target still has
12462    execution and wants to delete breakpoints from GDB's lists, and all
12463    breakpoints had already been removed from the inferior.  */
12464
12465 static void
12466 update_global_location_list (int should_insert)
12467 {
12468   struct breakpoint *b;
12469   struct bp_location **locp, *loc;
12470   struct cleanup *cleanups;
12471   /* Last breakpoint location address that was marked for update.  */
12472   CORE_ADDR last_addr = 0;
12473   /* Last breakpoint location program space that was marked for update.  */
12474   int last_pspace_num = -1;
12475
12476   /* Used in the duplicates detection below.  When iterating over all
12477      bp_locations, points to the first bp_location of a given address.
12478      Breakpoints and watchpoints of different types are never
12479      duplicates of each other.  Keep one pointer for each type of
12480      breakpoint/watchpoint, so we only need to loop over all locations
12481      once.  */
12482   struct bp_location *bp_loc_first;  /* breakpoint */
12483   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12484   struct bp_location *awp_loc_first; /* access watchpoint */
12485   struct bp_location *rwp_loc_first; /* read watchpoint */
12486
12487   /* Saved former bp_location array which we compare against the newly
12488      built bp_location from the current state of ALL_BREAKPOINTS.  */
12489   struct bp_location **old_location, **old_locp;
12490   unsigned old_location_count;
12491
12492   old_location = bp_location;
12493   old_location_count = bp_location_count;
12494   bp_location = NULL;
12495   bp_location_count = 0;
12496   cleanups = make_cleanup (xfree, old_location);
12497
12498   ALL_BREAKPOINTS (b)
12499     for (loc = b->loc; loc; loc = loc->next)
12500       bp_location_count++;
12501
12502   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12503   locp = bp_location;
12504   ALL_BREAKPOINTS (b)
12505     for (loc = b->loc; loc; loc = loc->next)
12506       *locp++ = loc;
12507   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12508          bp_location_compare);
12509
12510   bp_location_target_extensions_update ();
12511
12512   /* Identify bp_location instances that are no longer present in the
12513      new list, and therefore should be freed.  Note that it's not
12514      necessary that those locations should be removed from inferior --
12515      if there's another location at the same address (previously
12516      marked as duplicate), we don't need to remove/insert the
12517      location.
12518      
12519      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12520      and former bp_location array state respectively.  */
12521
12522   locp = bp_location;
12523   for (old_locp = old_location; old_locp < old_location + old_location_count;
12524        old_locp++)
12525     {
12526       struct bp_location *old_loc = *old_locp;
12527       struct bp_location **loc2p;
12528
12529       /* Tells if 'old_loc' is found among the new locations.  If
12530          not, we have to free it.  */
12531       int found_object = 0;
12532       /* Tells if the location should remain inserted in the target.  */
12533       int keep_in_target = 0;
12534       int removed = 0;
12535
12536       /* Skip LOCP entries which will definitely never be needed.
12537          Stop either at or being the one matching OLD_LOC.  */
12538       while (locp < bp_location + bp_location_count
12539              && (*locp)->address < old_loc->address)
12540         locp++;
12541
12542       for (loc2p = locp;
12543            (loc2p < bp_location + bp_location_count
12544             && (*loc2p)->address == old_loc->address);
12545            loc2p++)
12546         {
12547           /* Check if this is a new/duplicated location or a duplicated
12548              location that had its condition modified.  If so, we want to send
12549              its condition to the target if evaluation of conditions is taking
12550              place there.  */
12551           if ((*loc2p)->condition_changed == condition_modified
12552               && (last_addr != old_loc->address
12553                   || last_pspace_num != old_loc->pspace->num))
12554             {
12555               force_breakpoint_reinsertion (*loc2p);
12556               last_pspace_num = old_loc->pspace->num;
12557             }
12558
12559           if (*loc2p == old_loc)
12560             found_object = 1;
12561         }
12562
12563       /* We have already handled this address, update it so that we don't
12564          have to go through updates again.  */
12565       last_addr = old_loc->address;
12566
12567       /* Target-side condition evaluation: Handle deleted locations.  */
12568       if (!found_object)
12569         force_breakpoint_reinsertion (old_loc);
12570
12571       /* If this location is no longer present, and inserted, look if
12572          there's maybe a new location at the same address.  If so,
12573          mark that one inserted, and don't remove this one.  This is
12574          needed so that we don't have a time window where a breakpoint
12575          at certain location is not inserted.  */
12576
12577       if (old_loc->inserted)
12578         {
12579           /* If the location is inserted now, we might have to remove
12580              it.  */
12581
12582           if (found_object && should_be_inserted (old_loc))
12583             {
12584               /* The location is still present in the location list,
12585                  and still should be inserted.  Don't do anything.  */
12586               keep_in_target = 1;
12587             }
12588           else
12589             {
12590               /* This location still exists, but it won't be kept in the
12591                  target since it may have been disabled.  We proceed to
12592                  remove its target-side condition.  */
12593
12594               /* The location is either no longer present, or got
12595                  disabled.  See if there's another location at the
12596                  same address, in which case we don't need to remove
12597                  this one from the target.  */
12598
12599               /* OLD_LOC comes from existing struct breakpoint.  */
12600               if (breakpoint_address_is_meaningful (old_loc->owner))
12601                 {
12602                   for (loc2p = locp;
12603                        (loc2p < bp_location + bp_location_count
12604                         && (*loc2p)->address == old_loc->address);
12605                        loc2p++)
12606                     {
12607                       struct bp_location *loc2 = *loc2p;
12608
12609                       if (breakpoint_locations_match (loc2, old_loc))
12610                         {
12611                           /* Read watchpoint locations are switched to
12612                              access watchpoints, if the former are not
12613                              supported, but the latter are.  */
12614                           if (is_hardware_watchpoint (old_loc->owner))
12615                             {
12616                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12617                               loc2->watchpoint_type = old_loc->watchpoint_type;
12618                             }
12619
12620                           /* loc2 is a duplicated location. We need to check
12621                              if it should be inserted in case it will be
12622                              unduplicated.  */
12623                           if (loc2 != old_loc
12624                               && unduplicated_should_be_inserted (loc2))
12625                             {
12626                               swap_insertion (old_loc, loc2);
12627                               keep_in_target = 1;
12628                               break;
12629                             }
12630                         }
12631                     }
12632                 }
12633             }
12634
12635           if (!keep_in_target)
12636             {
12637               if (remove_breakpoint (old_loc, mark_uninserted))
12638                 {
12639                   /* This is just about all we can do.  We could keep
12640                      this location on the global list, and try to
12641                      remove it next time, but there's no particular
12642                      reason why we will succeed next time.
12643                      
12644                      Note that at this point, old_loc->owner is still
12645                      valid, as delete_breakpoint frees the breakpoint
12646                      only after calling us.  */
12647                   printf_filtered (_("warning: Error removing "
12648                                      "breakpoint %d\n"), 
12649                                    old_loc->owner->number);
12650                 }
12651               removed = 1;
12652             }
12653         }
12654
12655       if (!found_object)
12656         {
12657           if (removed && non_stop
12658               && breakpoint_address_is_meaningful (old_loc->owner)
12659               && !is_hardware_watchpoint (old_loc->owner))
12660             {
12661               /* This location was removed from the target.  In
12662                  non-stop mode, a race condition is possible where
12663                  we've removed a breakpoint, but stop events for that
12664                  breakpoint are already queued and will arrive later.
12665                  We apply an heuristic to be able to distinguish such
12666                  SIGTRAPs from other random SIGTRAPs: we keep this
12667                  breakpoint location for a bit, and will retire it
12668                  after we see some number of events.  The theory here
12669                  is that reporting of events should, "on the average",
12670                  be fair, so after a while we'll see events from all
12671                  threads that have anything of interest, and no longer
12672                  need to keep this breakpoint location around.  We
12673                  don't hold locations forever so to reduce chances of
12674                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12675                  SIGTRAP.
12676
12677                  The heuristic failing can be disastrous on
12678                  decr_pc_after_break targets.
12679
12680                  On decr_pc_after_break targets, like e.g., x86-linux,
12681                  if we fail to recognize a late breakpoint SIGTRAP,
12682                  because events_till_retirement has reached 0 too
12683                  soon, we'll fail to do the PC adjustment, and report
12684                  a random SIGTRAP to the user.  When the user resumes
12685                  the inferior, it will most likely immediately crash
12686                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12687                  corrupted, because of being resumed e.g., in the
12688                  middle of a multi-byte instruction, or skipped a
12689                  one-byte instruction.  This was actually seen happen
12690                  on native x86-linux, and should be less rare on
12691                  targets that do not support new thread events, like
12692                  remote, due to the heuristic depending on
12693                  thread_count.
12694
12695                  Mistaking a random SIGTRAP for a breakpoint trap
12696                  causes similar symptoms (PC adjustment applied when
12697                  it shouldn't), but then again, playing with SIGTRAPs
12698                  behind the debugger's back is asking for trouble.
12699
12700                  Since hardware watchpoint traps are always
12701                  distinguishable from other traps, so we don't need to
12702                  apply keep hardware watchpoint moribund locations
12703                  around.  We simply always ignore hardware watchpoint
12704                  traps we can no longer explain.  */
12705
12706               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12707               old_loc->owner = NULL;
12708
12709               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12710             }
12711           else
12712             {
12713               old_loc->owner = NULL;
12714               decref_bp_location (&old_loc);
12715             }
12716         }
12717     }
12718
12719   /* Rescan breakpoints at the same address and section, marking the
12720      first one as "first" and any others as "duplicates".  This is so
12721      that the bpt instruction is only inserted once.  If we have a
12722      permanent breakpoint at the same place as BPT, make that one the
12723      official one, and the rest as duplicates.  Permanent breakpoints
12724      are sorted first for the same address.
12725
12726      Do the same for hardware watchpoints, but also considering the
12727      watchpoint's type (regular/access/read) and length.  */
12728
12729   bp_loc_first = NULL;
12730   wp_loc_first = NULL;
12731   awp_loc_first = NULL;
12732   rwp_loc_first = NULL;
12733   ALL_BP_LOCATIONS (loc, locp)
12734     {
12735       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12736          non-NULL.  */
12737       struct bp_location **loc_first_p;
12738       b = loc->owner;
12739
12740       if (!unduplicated_should_be_inserted (loc)
12741           || !breakpoint_address_is_meaningful (b)
12742           /* Don't detect duplicate for tracepoint locations because they are
12743            never duplicated.  See the comments in field `duplicate' of
12744            `struct bp_location'.  */
12745           || is_tracepoint (b))
12746         {
12747           /* Clear the condition modification flag.  */
12748           loc->condition_changed = condition_unchanged;
12749           continue;
12750         }
12751
12752       /* Permanent breakpoint should always be inserted.  */
12753       if (b->enable_state == bp_permanent && ! loc->inserted)
12754         internal_error (__FILE__, __LINE__,
12755                         _("allegedly permanent breakpoint is not "
12756                         "actually inserted"));
12757
12758       if (b->type == bp_hardware_watchpoint)
12759         loc_first_p = &wp_loc_first;
12760       else if (b->type == bp_read_watchpoint)
12761         loc_first_p = &rwp_loc_first;
12762       else if (b->type == bp_access_watchpoint)
12763         loc_first_p = &awp_loc_first;
12764       else
12765         loc_first_p = &bp_loc_first;
12766
12767       if (*loc_first_p == NULL
12768           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12769           || !breakpoint_locations_match (loc, *loc_first_p))
12770         {
12771           *loc_first_p = loc;
12772           loc->duplicate = 0;
12773
12774           if (is_breakpoint (loc->owner) && loc->condition_changed)
12775             {
12776               loc->needs_update = 1;
12777               /* Clear the condition modification flag.  */
12778               loc->condition_changed = condition_unchanged;
12779             }
12780           continue;
12781         }
12782
12783
12784       /* This and the above ensure the invariant that the first location
12785          is not duplicated, and is the inserted one.
12786          All following are marked as duplicated, and are not inserted.  */
12787       if (loc->inserted)
12788         swap_insertion (loc, *loc_first_p);
12789       loc->duplicate = 1;
12790
12791       /* Clear the condition modification flag.  */
12792       loc->condition_changed = condition_unchanged;
12793
12794       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12795           && b->enable_state != bp_permanent)
12796         internal_error (__FILE__, __LINE__,
12797                         _("another breakpoint was inserted on top of "
12798                         "a permanent breakpoint"));
12799     }
12800
12801   if (breakpoints_always_inserted_mode ()
12802       && (have_live_inferiors ()
12803           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12804     {
12805       if (should_insert)
12806         insert_breakpoint_locations ();
12807       else
12808         {
12809           /* Though should_insert is false, we may need to update conditions
12810              on the target's side if it is evaluating such conditions.  We
12811              only update conditions for locations that are marked
12812              "needs_update".  */
12813           update_inserted_breakpoint_locations ();
12814         }
12815     }
12816
12817   if (should_insert)
12818     download_tracepoint_locations ();
12819
12820   do_cleanups (cleanups);
12821 }
12822
12823 void
12824 breakpoint_retire_moribund (void)
12825 {
12826   struct bp_location *loc;
12827   int ix;
12828
12829   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12830     if (--(loc->events_till_retirement) == 0)
12831       {
12832         decref_bp_location (&loc);
12833         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12834         --ix;
12835       }
12836 }
12837
12838 static void
12839 update_global_location_list_nothrow (int inserting)
12840 {
12841   volatile struct gdb_exception e;
12842
12843   TRY_CATCH (e, RETURN_MASK_ERROR)
12844     update_global_location_list (inserting);
12845 }
12846
12847 /* Clear BKP from a BPS.  */
12848
12849 static void
12850 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12851 {
12852   bpstat bs;
12853
12854   for (bs = bps; bs; bs = bs->next)
12855     if (bs->breakpoint_at == bpt)
12856       {
12857         bs->breakpoint_at = NULL;
12858         bs->old_val = NULL;
12859         /* bs->commands will be freed later.  */
12860       }
12861 }
12862
12863 /* Callback for iterate_over_threads.  */
12864 static int
12865 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12866 {
12867   struct breakpoint *bpt = data;
12868
12869   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12870   return 0;
12871 }
12872
12873 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12874    callbacks.  */
12875
12876 static void
12877 say_where (struct breakpoint *b)
12878 {
12879   struct value_print_options opts;
12880
12881   get_user_print_options (&opts);
12882
12883   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12884      single string.  */
12885   if (b->loc == NULL)
12886     {
12887       printf_filtered (_(" (%s) pending."), b->addr_string);
12888     }
12889   else
12890     {
12891       if (opts.addressprint || b->loc->symtab == NULL)
12892         {
12893           printf_filtered (" at ");
12894           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12895                           gdb_stdout);
12896         }
12897       if (b->loc->symtab != NULL)
12898         {
12899           /* If there is a single location, we can print the location
12900              more nicely.  */
12901           if (b->loc->next == NULL)
12902             printf_filtered (": file %s, line %d.",
12903                              symtab_to_filename_for_display (b->loc->symtab),
12904                              b->loc->line_number);
12905           else
12906             /* This is not ideal, but each location may have a
12907                different file name, and this at least reflects the
12908                real situation somewhat.  */
12909             printf_filtered (": %s.", b->addr_string);
12910         }
12911
12912       if (b->loc->next)
12913         {
12914           struct bp_location *loc = b->loc;
12915           int n = 0;
12916           for (; loc; loc = loc->next)
12917             ++n;
12918           printf_filtered (" (%d locations)", n);
12919         }
12920     }
12921 }
12922
12923 /* Default bp_location_ops methods.  */
12924
12925 static void
12926 bp_location_dtor (struct bp_location *self)
12927 {
12928   xfree (self->cond);
12929   if (self->cond_bytecode)
12930     free_agent_expr (self->cond_bytecode);
12931   xfree (self->function_name);
12932
12933   VEC_free (agent_expr_p, self->target_info.conditions);
12934   VEC_free (agent_expr_p, self->target_info.tcommands);
12935 }
12936
12937 static const struct bp_location_ops bp_location_ops =
12938 {
12939   bp_location_dtor
12940 };
12941
12942 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12943    inherit from.  */
12944
12945 static void
12946 base_breakpoint_dtor (struct breakpoint *self)
12947 {
12948   decref_counted_command_line (&self->commands);
12949   xfree (self->cond_string);
12950   xfree (self->extra_string);
12951   xfree (self->addr_string);
12952   xfree (self->filter);
12953   xfree (self->addr_string_range_end);
12954 }
12955
12956 static struct bp_location *
12957 base_breakpoint_allocate_location (struct breakpoint *self)
12958 {
12959   struct bp_location *loc;
12960
12961   loc = XNEW (struct bp_location);
12962   init_bp_location (loc, &bp_location_ops, self);
12963   return loc;
12964 }
12965
12966 static void
12967 base_breakpoint_re_set (struct breakpoint *b)
12968 {
12969   /* Nothing to re-set. */
12970 }
12971
12972 #define internal_error_pure_virtual_called() \
12973   gdb_assert_not_reached ("pure virtual function called")
12974
12975 static int
12976 base_breakpoint_insert_location (struct bp_location *bl)
12977 {
12978   internal_error_pure_virtual_called ();
12979 }
12980
12981 static int
12982 base_breakpoint_remove_location (struct bp_location *bl)
12983 {
12984   internal_error_pure_virtual_called ();
12985 }
12986
12987 static int
12988 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12989                                 struct address_space *aspace,
12990                                 CORE_ADDR bp_addr,
12991                                 const struct target_waitstatus *ws)
12992 {
12993   internal_error_pure_virtual_called ();
12994 }
12995
12996 static void
12997 base_breakpoint_check_status (bpstat bs)
12998 {
12999   /* Always stop.   */
13000 }
13001
13002 /* A "works_in_software_mode" breakpoint_ops method that just internal
13003    errors.  */
13004
13005 static int
13006 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13007 {
13008   internal_error_pure_virtual_called ();
13009 }
13010
13011 /* A "resources_needed" breakpoint_ops method that just internal
13012    errors.  */
13013
13014 static int
13015 base_breakpoint_resources_needed (const struct bp_location *bl)
13016 {
13017   internal_error_pure_virtual_called ();
13018 }
13019
13020 static enum print_stop_action
13021 base_breakpoint_print_it (bpstat bs)
13022 {
13023   internal_error_pure_virtual_called ();
13024 }
13025
13026 static void
13027 base_breakpoint_print_one_detail (const struct breakpoint *self,
13028                                   struct ui_out *uiout)
13029 {
13030   /* nothing */
13031 }
13032
13033 static void
13034 base_breakpoint_print_mention (struct breakpoint *b)
13035 {
13036   internal_error_pure_virtual_called ();
13037 }
13038
13039 static void
13040 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13041 {
13042   internal_error_pure_virtual_called ();
13043 }
13044
13045 static void
13046 base_breakpoint_create_sals_from_address (char **arg,
13047                                           struct linespec_result *canonical,
13048                                           enum bptype type_wanted,
13049                                           char *addr_start,
13050                                           char **copy_arg)
13051 {
13052   internal_error_pure_virtual_called ();
13053 }
13054
13055 static void
13056 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13057                                         struct linespec_result *c,
13058                                         char *cond_string,
13059                                         char *extra_string,
13060                                         enum bptype type_wanted,
13061                                         enum bpdisp disposition,
13062                                         int thread,
13063                                         int task, int ignore_count,
13064                                         const struct breakpoint_ops *o,
13065                                         int from_tty, int enabled,
13066                                         int internal, unsigned flags)
13067 {
13068   internal_error_pure_virtual_called ();
13069 }
13070
13071 static void
13072 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13073                                  struct symtabs_and_lines *sals)
13074 {
13075   internal_error_pure_virtual_called ();
13076 }
13077
13078 /* The default 'explains_signal' method.  */
13079
13080 static int
13081 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13082 {
13083   return 1;
13084 }
13085
13086 /* The default "after_condition_true" method.  */
13087
13088 static void
13089 base_breakpoint_after_condition_true (struct bpstats *bs)
13090 {
13091   /* Nothing to do.   */
13092 }
13093
13094 struct breakpoint_ops base_breakpoint_ops =
13095 {
13096   base_breakpoint_dtor,
13097   base_breakpoint_allocate_location,
13098   base_breakpoint_re_set,
13099   base_breakpoint_insert_location,
13100   base_breakpoint_remove_location,
13101   base_breakpoint_breakpoint_hit,
13102   base_breakpoint_check_status,
13103   base_breakpoint_resources_needed,
13104   base_breakpoint_works_in_software_mode,
13105   base_breakpoint_print_it,
13106   NULL,
13107   base_breakpoint_print_one_detail,
13108   base_breakpoint_print_mention,
13109   base_breakpoint_print_recreate,
13110   base_breakpoint_create_sals_from_address,
13111   base_breakpoint_create_breakpoints_sal,
13112   base_breakpoint_decode_linespec,
13113   base_breakpoint_explains_signal,
13114   base_breakpoint_after_condition_true,
13115 };
13116
13117 /* Default breakpoint_ops methods.  */
13118
13119 static void
13120 bkpt_re_set (struct breakpoint *b)
13121 {
13122   /* FIXME: is this still reachable?  */
13123   if (b->addr_string == NULL)
13124     {
13125       /* Anything without a string can't be re-set.  */
13126       delete_breakpoint (b);
13127       return;
13128     }
13129
13130   breakpoint_re_set_default (b);
13131 }
13132
13133 /* Copy SRC's shadow buffer and whatever else we'd set if we actually
13134    inserted DEST, so we can remove it later, in case SRC is removed
13135    first.  */
13136
13137 static void
13138 bp_target_info_copy_insertion_state (struct bp_target_info *dest,
13139                                      const struct bp_target_info *src)
13140 {
13141   dest->shadow_len = src->shadow_len;
13142   memcpy (dest->shadow_contents, src->shadow_contents, src->shadow_len);
13143   dest->placed_size = src->placed_size;
13144 }
13145
13146 static int
13147 bkpt_insert_location (struct bp_location *bl)
13148 {
13149   if (bl->loc_type == bp_loc_hardware_breakpoint)
13150     return target_insert_hw_breakpoint (bl->gdbarch,
13151                                         &bl->target_info);
13152   else
13153     {
13154       struct bp_target_info *bp_tgt = &bl->target_info;
13155       int ret;
13156       int sss_slot;
13157
13158       /* There is no need to insert a breakpoint if an unconditional
13159          raw/sss breakpoint is already inserted at that location.  */
13160       sss_slot = find_single_step_breakpoint (bp_tgt->placed_address_space,
13161                                               bp_tgt->placed_address);
13162       if (sss_slot >= 0)
13163         {
13164           struct bp_target_info *sss_bp_tgt = single_step_breakpoints[sss_slot];
13165
13166           bp_target_info_copy_insertion_state (bp_tgt, sss_bp_tgt);
13167           return 0;
13168         }
13169
13170       return target_insert_breakpoint (bl->gdbarch, bp_tgt);
13171     }
13172 }
13173
13174 static int
13175 bkpt_remove_location (struct bp_location *bl)
13176 {
13177   if (bl->loc_type == bp_loc_hardware_breakpoint)
13178     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13179   else
13180     {
13181       struct bp_target_info *bp_tgt = &bl->target_info;
13182       struct address_space *aspace = bp_tgt->placed_address_space;
13183       CORE_ADDR address = bp_tgt->placed_address;
13184
13185       /* Only remove the breakpoint if there is no raw/sss breakpoint
13186          still inserted at this location.  Otherwise, we would be
13187          effectively disabling the raw/sss breakpoint.  */
13188       if (single_step_breakpoint_inserted_here_p (aspace, address))
13189         return 0;
13190
13191       return target_remove_breakpoint (bl->gdbarch, bp_tgt);
13192     }
13193 }
13194
13195 static int
13196 bkpt_breakpoint_hit (const struct bp_location *bl,
13197                      struct address_space *aspace, CORE_ADDR bp_addr,
13198                      const struct target_waitstatus *ws)
13199 {
13200   if (ws->kind != TARGET_WAITKIND_STOPPED
13201       || ws->value.sig != GDB_SIGNAL_TRAP)
13202     return 0;
13203
13204   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13205                                  aspace, bp_addr))
13206     return 0;
13207
13208   if (overlay_debugging         /* unmapped overlay section */
13209       && section_is_overlay (bl->section)
13210       && !section_is_mapped (bl->section))
13211     return 0;
13212
13213   return 1;
13214 }
13215
13216 static int
13217 dprintf_breakpoint_hit (const struct bp_location *bl,
13218                         struct address_space *aspace, CORE_ADDR bp_addr,
13219                         const struct target_waitstatus *ws)
13220 {
13221   if (dprintf_style == dprintf_style_agent
13222       && target_can_run_breakpoint_commands ())
13223     {
13224       /* An agent-style dprintf never causes a stop.  If we see a trap
13225          for this address it must be for a breakpoint that happens to
13226          be set at the same address.  */
13227       return 0;
13228     }
13229
13230   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13231 }
13232
13233 static int
13234 bkpt_resources_needed (const struct bp_location *bl)
13235 {
13236   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13237
13238   return 1;
13239 }
13240
13241 static enum print_stop_action
13242 bkpt_print_it (bpstat bs)
13243 {
13244   struct breakpoint *b;
13245   const struct bp_location *bl;
13246   int bp_temp;
13247   struct ui_out *uiout = current_uiout;
13248
13249   gdb_assert (bs->bp_location_at != NULL);
13250
13251   bl = bs->bp_location_at;
13252   b = bs->breakpoint_at;
13253
13254   bp_temp = b->disposition == disp_del;
13255   if (bl->address != bl->requested_address)
13256     breakpoint_adjustment_warning (bl->requested_address,
13257                                    bl->address,
13258                                    b->number, 1);
13259   annotate_breakpoint (b->number);
13260   if (bp_temp)
13261     ui_out_text (uiout, "\nTemporary breakpoint ");
13262   else
13263     ui_out_text (uiout, "\nBreakpoint ");
13264   if (ui_out_is_mi_like_p (uiout))
13265     {
13266       ui_out_field_string (uiout, "reason",
13267                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13268       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13269     }
13270   ui_out_field_int (uiout, "bkptno", b->number);
13271   ui_out_text (uiout, ", ");
13272
13273   return PRINT_SRC_AND_LOC;
13274 }
13275
13276 static void
13277 bkpt_print_mention (struct breakpoint *b)
13278 {
13279   if (ui_out_is_mi_like_p (current_uiout))
13280     return;
13281
13282   switch (b->type)
13283     {
13284     case bp_breakpoint:
13285     case bp_gnu_ifunc_resolver:
13286       if (b->disposition == disp_del)
13287         printf_filtered (_("Temporary breakpoint"));
13288       else
13289         printf_filtered (_("Breakpoint"));
13290       printf_filtered (_(" %d"), b->number);
13291       if (b->type == bp_gnu_ifunc_resolver)
13292         printf_filtered (_(" at gnu-indirect-function resolver"));
13293       break;
13294     case bp_hardware_breakpoint:
13295       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13296       break;
13297     case bp_dprintf:
13298       printf_filtered (_("Dprintf %d"), b->number);
13299       break;
13300     }
13301
13302   say_where (b);
13303 }
13304
13305 static void
13306 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13307 {
13308   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13309     fprintf_unfiltered (fp, "tbreak");
13310   else if (tp->type == bp_breakpoint)
13311     fprintf_unfiltered (fp, "break");
13312   else if (tp->type == bp_hardware_breakpoint
13313            && tp->disposition == disp_del)
13314     fprintf_unfiltered (fp, "thbreak");
13315   else if (tp->type == bp_hardware_breakpoint)
13316     fprintf_unfiltered (fp, "hbreak");
13317   else
13318     internal_error (__FILE__, __LINE__,
13319                     _("unhandled breakpoint type %d"), (int) tp->type);
13320
13321   fprintf_unfiltered (fp, " %s", tp->addr_string);
13322   print_recreate_thread (tp, fp);
13323 }
13324
13325 static void
13326 bkpt_create_sals_from_address (char **arg,
13327                                struct linespec_result *canonical,
13328                                enum bptype type_wanted,
13329                                char *addr_start, char **copy_arg)
13330 {
13331   create_sals_from_address_default (arg, canonical, type_wanted,
13332                                     addr_start, copy_arg);
13333 }
13334
13335 static void
13336 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13337                              struct linespec_result *canonical,
13338                              char *cond_string,
13339                              char *extra_string,
13340                              enum bptype type_wanted,
13341                              enum bpdisp disposition,
13342                              int thread,
13343                              int task, int ignore_count,
13344                              const struct breakpoint_ops *ops,
13345                              int from_tty, int enabled,
13346                              int internal, unsigned flags)
13347 {
13348   create_breakpoints_sal_default (gdbarch, canonical,
13349                                   cond_string, extra_string,
13350                                   type_wanted,
13351                                   disposition, thread, task,
13352                                   ignore_count, ops, from_tty,
13353                                   enabled, internal, flags);
13354 }
13355
13356 static void
13357 bkpt_decode_linespec (struct breakpoint *b, char **s,
13358                       struct symtabs_and_lines *sals)
13359 {
13360   decode_linespec_default (b, s, sals);
13361 }
13362
13363 /* Virtual table for internal breakpoints.  */
13364
13365 static void
13366 internal_bkpt_re_set (struct breakpoint *b)
13367 {
13368   switch (b->type)
13369     {
13370       /* Delete overlay event and longjmp master breakpoints; they
13371          will be reset later by breakpoint_re_set.  */
13372     case bp_overlay_event:
13373     case bp_longjmp_master:
13374     case bp_std_terminate_master:
13375     case bp_exception_master:
13376       delete_breakpoint (b);
13377       break;
13378
13379       /* This breakpoint is special, it's set up when the inferior
13380          starts and we really don't want to touch it.  */
13381     case bp_shlib_event:
13382
13383       /* Like bp_shlib_event, this breakpoint type is special.  Once
13384          it is set up, we do not want to touch it.  */
13385     case bp_thread_event:
13386       break;
13387     }
13388 }
13389
13390 static void
13391 internal_bkpt_check_status (bpstat bs)
13392 {
13393   if (bs->breakpoint_at->type == bp_shlib_event)
13394     {
13395       /* If requested, stop when the dynamic linker notifies GDB of
13396          events.  This allows the user to get control and place
13397          breakpoints in initializer routines for dynamically loaded
13398          objects (among other things).  */
13399       bs->stop = stop_on_solib_events;
13400       bs->print = stop_on_solib_events;
13401     }
13402   else
13403     bs->stop = 0;
13404 }
13405
13406 static enum print_stop_action
13407 internal_bkpt_print_it (bpstat bs)
13408 {
13409   struct breakpoint *b;
13410
13411   b = bs->breakpoint_at;
13412
13413   switch (b->type)
13414     {
13415     case bp_shlib_event:
13416       /* Did we stop because the user set the stop_on_solib_events
13417          variable?  (If so, we report this as a generic, "Stopped due
13418          to shlib event" message.) */
13419       print_solib_event (0);
13420       break;
13421
13422     case bp_thread_event:
13423       /* Not sure how we will get here.
13424          GDB should not stop for these breakpoints.  */
13425       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13426       break;
13427
13428     case bp_overlay_event:
13429       /* By analogy with the thread event, GDB should not stop for these.  */
13430       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13431       break;
13432
13433     case bp_longjmp_master:
13434       /* These should never be enabled.  */
13435       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13436       break;
13437
13438     case bp_std_terminate_master:
13439       /* These should never be enabled.  */
13440       printf_filtered (_("std::terminate Master Breakpoint: "
13441                          "gdb should not stop!\n"));
13442       break;
13443
13444     case bp_exception_master:
13445       /* These should never be enabled.  */
13446       printf_filtered (_("Exception Master Breakpoint: "
13447                          "gdb should not stop!\n"));
13448       break;
13449     }
13450
13451   return PRINT_NOTHING;
13452 }
13453
13454 static void
13455 internal_bkpt_print_mention (struct breakpoint *b)
13456 {
13457   /* Nothing to mention.  These breakpoints are internal.  */
13458 }
13459
13460 /* Virtual table for momentary breakpoints  */
13461
13462 static void
13463 momentary_bkpt_re_set (struct breakpoint *b)
13464 {
13465   /* Keep temporary breakpoints, which can be encountered when we step
13466      over a dlopen call and solib_add is resetting the breakpoints.
13467      Otherwise these should have been blown away via the cleanup chain
13468      or by breakpoint_init_inferior when we rerun the executable.  */
13469 }
13470
13471 static void
13472 momentary_bkpt_check_status (bpstat bs)
13473 {
13474   /* Nothing.  The point of these breakpoints is causing a stop.  */
13475 }
13476
13477 static enum print_stop_action
13478 momentary_bkpt_print_it (bpstat bs)
13479 {
13480   struct ui_out *uiout = current_uiout;
13481
13482   if (ui_out_is_mi_like_p (uiout))
13483     {
13484       struct breakpoint *b = bs->breakpoint_at;
13485
13486       switch (b->type)
13487         {
13488         case bp_finish:
13489           ui_out_field_string
13490             (uiout, "reason",
13491              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13492           break;
13493
13494         case bp_until:
13495           ui_out_field_string
13496             (uiout, "reason",
13497              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13498           break;
13499         }
13500     }
13501
13502   return PRINT_UNKNOWN;
13503 }
13504
13505 static void
13506 momentary_bkpt_print_mention (struct breakpoint *b)
13507 {
13508   /* Nothing to mention.  These breakpoints are internal.  */
13509 }
13510
13511 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13512
13513    It gets cleared already on the removal of the first one of such placed
13514    breakpoints.  This is OK as they get all removed altogether.  */
13515
13516 static void
13517 longjmp_bkpt_dtor (struct breakpoint *self)
13518 {
13519   struct thread_info *tp = find_thread_id (self->thread);
13520
13521   if (tp)
13522     tp->initiating_frame = null_frame_id;
13523
13524   momentary_breakpoint_ops.dtor (self);
13525 }
13526
13527 /* Specific methods for probe breakpoints.  */
13528
13529 static int
13530 bkpt_probe_insert_location (struct bp_location *bl)
13531 {
13532   int v = bkpt_insert_location (bl);
13533
13534   if (v == 0)
13535     {
13536       /* The insertion was successful, now let's set the probe's semaphore
13537          if needed.  */
13538       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13539                                             bl->probe.objfile,
13540                                             bl->gdbarch);
13541     }
13542
13543   return v;
13544 }
13545
13546 static int
13547 bkpt_probe_remove_location (struct bp_location *bl)
13548 {
13549   /* Let's clear the semaphore before removing the location.  */
13550   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13551                                           bl->probe.objfile,
13552                                           bl->gdbarch);
13553
13554   return bkpt_remove_location (bl);
13555 }
13556
13557 static void
13558 bkpt_probe_create_sals_from_address (char **arg,
13559                                      struct linespec_result *canonical,
13560                                      enum bptype type_wanted,
13561                                      char *addr_start, char **copy_arg)
13562 {
13563   struct linespec_sals lsal;
13564
13565   lsal.sals = parse_probes (arg, canonical);
13566
13567   *copy_arg = xstrdup (canonical->addr_string);
13568   lsal.canonical = xstrdup (*copy_arg);
13569
13570   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13571 }
13572
13573 static void
13574 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13575                             struct symtabs_and_lines *sals)
13576 {
13577   *sals = parse_probes (s, NULL);
13578   if (!sals->sals)
13579     error (_("probe not found"));
13580 }
13581
13582 /* The breakpoint_ops structure to be used in tracepoints.  */
13583
13584 static void
13585 tracepoint_re_set (struct breakpoint *b)
13586 {
13587   breakpoint_re_set_default (b);
13588 }
13589
13590 static int
13591 tracepoint_breakpoint_hit (const struct bp_location *bl,
13592                            struct address_space *aspace, CORE_ADDR bp_addr,
13593                            const struct target_waitstatus *ws)
13594 {
13595   /* By definition, the inferior does not report stops at
13596      tracepoints.  */
13597   return 0;
13598 }
13599
13600 static void
13601 tracepoint_print_one_detail (const struct breakpoint *self,
13602                              struct ui_out *uiout)
13603 {
13604   struct tracepoint *tp = (struct tracepoint *) self;
13605   if (tp->static_trace_marker_id)
13606     {
13607       gdb_assert (self->type == bp_static_tracepoint);
13608
13609       ui_out_text (uiout, "\tmarker id is ");
13610       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13611                            tp->static_trace_marker_id);
13612       ui_out_text (uiout, "\n");
13613     }
13614 }
13615
13616 static void
13617 tracepoint_print_mention (struct breakpoint *b)
13618 {
13619   if (ui_out_is_mi_like_p (current_uiout))
13620     return;
13621
13622   switch (b->type)
13623     {
13624     case bp_tracepoint:
13625       printf_filtered (_("Tracepoint"));
13626       printf_filtered (_(" %d"), b->number);
13627       break;
13628     case bp_fast_tracepoint:
13629       printf_filtered (_("Fast tracepoint"));
13630       printf_filtered (_(" %d"), b->number);
13631       break;
13632     case bp_static_tracepoint:
13633       printf_filtered (_("Static tracepoint"));
13634       printf_filtered (_(" %d"), b->number);
13635       break;
13636     default:
13637       internal_error (__FILE__, __LINE__,
13638                       _("unhandled tracepoint type %d"), (int) b->type);
13639     }
13640
13641   say_where (b);
13642 }
13643
13644 static void
13645 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13646 {
13647   struct tracepoint *tp = (struct tracepoint *) self;
13648
13649   if (self->type == bp_fast_tracepoint)
13650     fprintf_unfiltered (fp, "ftrace");
13651   if (self->type == bp_static_tracepoint)
13652     fprintf_unfiltered (fp, "strace");
13653   else if (self->type == bp_tracepoint)
13654     fprintf_unfiltered (fp, "trace");
13655   else
13656     internal_error (__FILE__, __LINE__,
13657                     _("unhandled tracepoint type %d"), (int) self->type);
13658
13659   fprintf_unfiltered (fp, " %s", self->addr_string);
13660   print_recreate_thread (self, fp);
13661
13662   if (tp->pass_count)
13663     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13664 }
13665
13666 static void
13667 tracepoint_create_sals_from_address (char **arg,
13668                                      struct linespec_result *canonical,
13669                                      enum bptype type_wanted,
13670                                      char *addr_start, char **copy_arg)
13671 {
13672   create_sals_from_address_default (arg, canonical, type_wanted,
13673                                     addr_start, copy_arg);
13674 }
13675
13676 static void
13677 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13678                                    struct linespec_result *canonical,
13679                                    char *cond_string,
13680                                    char *extra_string,
13681                                    enum bptype type_wanted,
13682                                    enum bpdisp disposition,
13683                                    int thread,
13684                                    int task, int ignore_count,
13685                                    const struct breakpoint_ops *ops,
13686                                    int from_tty, int enabled,
13687                                    int internal, unsigned flags)
13688 {
13689   create_breakpoints_sal_default (gdbarch, canonical,
13690                                   cond_string, extra_string,
13691                                   type_wanted,
13692                                   disposition, thread, task,
13693                                   ignore_count, ops, from_tty,
13694                                   enabled, internal, flags);
13695 }
13696
13697 static void
13698 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13699                             struct symtabs_and_lines *sals)
13700 {
13701   decode_linespec_default (b, s, sals);
13702 }
13703
13704 struct breakpoint_ops tracepoint_breakpoint_ops;
13705
13706 /* The breakpoint_ops structure to be use on tracepoints placed in a
13707    static probe.  */
13708
13709 static void
13710 tracepoint_probe_create_sals_from_address (char **arg,
13711                                            struct linespec_result *canonical,
13712                                            enum bptype type_wanted,
13713                                            char *addr_start, char **copy_arg)
13714 {
13715   /* We use the same method for breakpoint on probes.  */
13716   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13717                                        addr_start, copy_arg);
13718 }
13719
13720 static void
13721 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13722                                   struct symtabs_and_lines *sals)
13723 {
13724   /* We use the same method for breakpoint on probes.  */
13725   bkpt_probe_decode_linespec (b, s, sals);
13726 }
13727
13728 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13729
13730 /* Dprintf breakpoint_ops methods.  */
13731
13732 static void
13733 dprintf_re_set (struct breakpoint *b)
13734 {
13735   breakpoint_re_set_default (b);
13736
13737   /* This breakpoint could have been pending, and be resolved now, and
13738      if so, we should now have the extra string.  If we don't, the
13739      dprintf was malformed when created, but we couldn't tell because
13740      we can't extract the extra string until the location is
13741      resolved.  */
13742   if (b->loc != NULL && b->extra_string == NULL)
13743     error (_("Format string required"));
13744
13745   /* 1 - connect to target 1, that can run breakpoint commands.
13746      2 - create a dprintf, which resolves fine.
13747      3 - disconnect from target 1
13748      4 - connect to target 2, that can NOT run breakpoint commands.
13749
13750      After steps #3/#4, you'll want the dprintf command list to
13751      be updated, because target 1 and 2 may well return different
13752      answers for target_can_run_breakpoint_commands().
13753      Given absence of finer grained resetting, we get to do
13754      it all the time.  */
13755   if (b->extra_string != NULL)
13756     update_dprintf_command_list (b);
13757 }
13758
13759 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13760
13761 static void
13762 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13763 {
13764   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13765                       tp->extra_string);
13766   print_recreate_thread (tp, fp);
13767 }
13768
13769 /* Implement the "after_condition_true" breakpoint_ops method for
13770    dprintf.
13771
13772    dprintf's are implemented with regular commands in their command
13773    list, but we run the commands here instead of before presenting the
13774    stop to the user, as dprintf's don't actually cause a stop.  This
13775    also makes it so that the commands of multiple dprintfs at the same
13776    address are all handled.  */
13777
13778 static void
13779 dprintf_after_condition_true (struct bpstats *bs)
13780 {
13781   struct cleanup *old_chain;
13782   struct bpstats tmp_bs = { NULL };
13783   struct bpstats *tmp_bs_p = &tmp_bs;
13784
13785   /* dprintf's never cause a stop.  This wasn't set in the
13786      check_status hook instead because that would make the dprintf's
13787      condition not be evaluated.  */
13788   bs->stop = 0;
13789
13790   /* Run the command list here.  Take ownership of it instead of
13791      copying.  We never want these commands to run later in
13792      bpstat_do_actions, if a breakpoint that causes a stop happens to
13793      be set at same address as this dprintf, or even if running the
13794      commands here throws.  */
13795   tmp_bs.commands = bs->commands;
13796   bs->commands = NULL;
13797   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13798
13799   bpstat_do_actions_1 (&tmp_bs_p);
13800
13801   /* 'tmp_bs.commands' will usually be NULL by now, but
13802      bpstat_do_actions_1 may return early without processing the whole
13803      list.  */
13804   do_cleanups (old_chain);
13805 }
13806
13807 /* The breakpoint_ops structure to be used on static tracepoints with
13808    markers (`-m').  */
13809
13810 static void
13811 strace_marker_create_sals_from_address (char **arg,
13812                                         struct linespec_result *canonical,
13813                                         enum bptype type_wanted,
13814                                         char *addr_start, char **copy_arg)
13815 {
13816   struct linespec_sals lsal;
13817
13818   lsal.sals = decode_static_tracepoint_spec (arg);
13819
13820   *copy_arg = savestring (addr_start, *arg - addr_start);
13821
13822   canonical->addr_string = xstrdup (*copy_arg);
13823   lsal.canonical = xstrdup (*copy_arg);
13824   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13825 }
13826
13827 static void
13828 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13829                                       struct linespec_result *canonical,
13830                                       char *cond_string,
13831                                       char *extra_string,
13832                                       enum bptype type_wanted,
13833                                       enum bpdisp disposition,
13834                                       int thread,
13835                                       int task, int ignore_count,
13836                                       const struct breakpoint_ops *ops,
13837                                       int from_tty, int enabled,
13838                                       int internal, unsigned flags)
13839 {
13840   int i;
13841   struct linespec_sals *lsal = VEC_index (linespec_sals,
13842                                           canonical->sals, 0);
13843
13844   /* If the user is creating a static tracepoint by marker id
13845      (strace -m MARKER_ID), then store the sals index, so that
13846      breakpoint_re_set can try to match up which of the newly
13847      found markers corresponds to this one, and, don't try to
13848      expand multiple locations for each sal, given than SALS
13849      already should contain all sals for MARKER_ID.  */
13850
13851   for (i = 0; i < lsal->sals.nelts; ++i)
13852     {
13853       struct symtabs_and_lines expanded;
13854       struct tracepoint *tp;
13855       struct cleanup *old_chain;
13856       char *addr_string;
13857
13858       expanded.nelts = 1;
13859       expanded.sals = &lsal->sals.sals[i];
13860
13861       addr_string = xstrdup (canonical->addr_string);
13862       old_chain = make_cleanup (xfree, addr_string);
13863
13864       tp = XCNEW (struct tracepoint);
13865       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13866                            addr_string, NULL,
13867                            cond_string, extra_string,
13868                            type_wanted, disposition,
13869                            thread, task, ignore_count, ops,
13870                            from_tty, enabled, internal, flags,
13871                            canonical->special_display);
13872       /* Given that its possible to have multiple markers with
13873          the same string id, if the user is creating a static
13874          tracepoint by marker id ("strace -m MARKER_ID"), then
13875          store the sals index, so that breakpoint_re_set can
13876          try to match up which of the newly found markers
13877          corresponds to this one  */
13878       tp->static_trace_marker_id_idx = i;
13879
13880       install_breakpoint (internal, &tp->base, 0);
13881
13882       discard_cleanups (old_chain);
13883     }
13884 }
13885
13886 static void
13887 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13888                                struct symtabs_and_lines *sals)
13889 {
13890   struct tracepoint *tp = (struct tracepoint *) b;
13891
13892   *sals = decode_static_tracepoint_spec (s);
13893   if (sals->nelts > tp->static_trace_marker_id_idx)
13894     {
13895       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13896       sals->nelts = 1;
13897     }
13898   else
13899     error (_("marker %s not found"), tp->static_trace_marker_id);
13900 }
13901
13902 static struct breakpoint_ops strace_marker_breakpoint_ops;
13903
13904 static int
13905 strace_marker_p (struct breakpoint *b)
13906 {
13907   return b->ops == &strace_marker_breakpoint_ops;
13908 }
13909
13910 /* Delete a breakpoint and clean up all traces of it in the data
13911    structures.  */
13912
13913 void
13914 delete_breakpoint (struct breakpoint *bpt)
13915 {
13916   struct breakpoint *b;
13917
13918   gdb_assert (bpt != NULL);
13919
13920   /* Has this bp already been deleted?  This can happen because
13921      multiple lists can hold pointers to bp's.  bpstat lists are
13922      especial culprits.
13923
13924      One example of this happening is a watchpoint's scope bp.  When
13925      the scope bp triggers, we notice that the watchpoint is out of
13926      scope, and delete it.  We also delete its scope bp.  But the
13927      scope bp is marked "auto-deleting", and is already on a bpstat.
13928      That bpstat is then checked for auto-deleting bp's, which are
13929      deleted.
13930
13931      A real solution to this problem might involve reference counts in
13932      bp's, and/or giving them pointers back to their referencing
13933      bpstat's, and teaching delete_breakpoint to only free a bp's
13934      storage when no more references were extent.  A cheaper bandaid
13935      was chosen.  */
13936   if (bpt->type == bp_none)
13937     return;
13938
13939   /* At least avoid this stale reference until the reference counting
13940      of breakpoints gets resolved.  */
13941   if (bpt->related_breakpoint != bpt)
13942     {
13943       struct breakpoint *related;
13944       struct watchpoint *w;
13945
13946       if (bpt->type == bp_watchpoint_scope)
13947         w = (struct watchpoint *) bpt->related_breakpoint;
13948       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13949         w = (struct watchpoint *) bpt;
13950       else
13951         w = NULL;
13952       if (w != NULL)
13953         watchpoint_del_at_next_stop (w);
13954
13955       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13956       for (related = bpt; related->related_breakpoint != bpt;
13957            related = related->related_breakpoint);
13958       related->related_breakpoint = bpt->related_breakpoint;
13959       bpt->related_breakpoint = bpt;
13960     }
13961
13962   /* watch_command_1 creates a watchpoint but only sets its number if
13963      update_watchpoint succeeds in creating its bp_locations.  If there's
13964      a problem in that process, we'll be asked to delete the half-created
13965      watchpoint.  In that case, don't announce the deletion.  */
13966   if (bpt->number)
13967     observer_notify_breakpoint_deleted (bpt);
13968
13969   if (breakpoint_chain == bpt)
13970     breakpoint_chain = bpt->next;
13971
13972   ALL_BREAKPOINTS (b)
13973     if (b->next == bpt)
13974     {
13975       b->next = bpt->next;
13976       break;
13977     }
13978
13979   /* Be sure no bpstat's are pointing at the breakpoint after it's
13980      been freed.  */
13981   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13982      in all threads for now.  Note that we cannot just remove bpstats
13983      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13984      commands are associated with the bpstat; if we remove it here,
13985      then the later call to bpstat_do_actions (&stop_bpstat); in
13986      event-top.c won't do anything, and temporary breakpoints with
13987      commands won't work.  */
13988
13989   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13990
13991   /* Now that breakpoint is removed from breakpoint list, update the
13992      global location list.  This will remove locations that used to
13993      belong to this breakpoint.  Do this before freeing the breakpoint
13994      itself, since remove_breakpoint looks at location's owner.  It
13995      might be better design to have location completely
13996      self-contained, but it's not the case now.  */
13997   update_global_location_list (0);
13998
13999   bpt->ops->dtor (bpt);
14000   /* On the chance that someone will soon try again to delete this
14001      same bp, we mark it as deleted before freeing its storage.  */
14002   bpt->type = bp_none;
14003   xfree (bpt);
14004 }
14005
14006 static void
14007 do_delete_breakpoint_cleanup (void *b)
14008 {
14009   delete_breakpoint (b);
14010 }
14011
14012 struct cleanup *
14013 make_cleanup_delete_breakpoint (struct breakpoint *b)
14014 {
14015   return make_cleanup (do_delete_breakpoint_cleanup, b);
14016 }
14017
14018 /* Iterator function to call a user-provided callback function once
14019    for each of B and its related breakpoints.  */
14020
14021 static void
14022 iterate_over_related_breakpoints (struct breakpoint *b,
14023                                   void (*function) (struct breakpoint *,
14024                                                     void *),
14025                                   void *data)
14026 {
14027   struct breakpoint *related;
14028
14029   related = b;
14030   do
14031     {
14032       struct breakpoint *next;
14033
14034       /* FUNCTION may delete RELATED.  */
14035       next = related->related_breakpoint;
14036
14037       if (next == related)
14038         {
14039           /* RELATED is the last ring entry.  */
14040           function (related, data);
14041
14042           /* FUNCTION may have deleted it, so we'd never reach back to
14043              B.  There's nothing left to do anyway, so just break
14044              out.  */
14045           break;
14046         }
14047       else
14048         function (related, data);
14049
14050       related = next;
14051     }
14052   while (related != b);
14053 }
14054
14055 static void
14056 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14057 {
14058   delete_breakpoint (b);
14059 }
14060
14061 /* A callback for map_breakpoint_numbers that calls
14062    delete_breakpoint.  */
14063
14064 static void
14065 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14066 {
14067   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14068 }
14069
14070 void
14071 delete_command (char *arg, int from_tty)
14072 {
14073   struct breakpoint *b, *b_tmp;
14074
14075   dont_repeat ();
14076
14077   if (arg == 0)
14078     {
14079       int breaks_to_delete = 0;
14080
14081       /* Delete all breakpoints if no argument.  Do not delete
14082          internal breakpoints, these have to be deleted with an
14083          explicit breakpoint number argument.  */
14084       ALL_BREAKPOINTS (b)
14085         if (user_breakpoint_p (b))
14086           {
14087             breaks_to_delete = 1;
14088             break;
14089           }
14090
14091       /* Ask user only if there are some breakpoints to delete.  */
14092       if (!from_tty
14093           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14094         {
14095           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14096             if (user_breakpoint_p (b))
14097               delete_breakpoint (b);
14098         }
14099     }
14100   else
14101     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14102 }
14103
14104 static int
14105 all_locations_are_pending (struct bp_location *loc)
14106 {
14107   for (; loc; loc = loc->next)
14108     if (!loc->shlib_disabled
14109         && !loc->pspace->executing_startup)
14110       return 0;
14111   return 1;
14112 }
14113
14114 /* Subroutine of update_breakpoint_locations to simplify it.
14115    Return non-zero if multiple fns in list LOC have the same name.
14116    Null names are ignored.  */
14117
14118 static int
14119 ambiguous_names_p (struct bp_location *loc)
14120 {
14121   struct bp_location *l;
14122   htab_t htab = htab_create_alloc (13, htab_hash_string,
14123                                    (int (*) (const void *, 
14124                                              const void *)) streq,
14125                                    NULL, xcalloc, xfree);
14126
14127   for (l = loc; l != NULL; l = l->next)
14128     {
14129       const char **slot;
14130       const char *name = l->function_name;
14131
14132       /* Allow for some names to be NULL, ignore them.  */
14133       if (name == NULL)
14134         continue;
14135
14136       slot = (const char **) htab_find_slot (htab, (const void *) name,
14137                                              INSERT);
14138       /* NOTE: We can assume slot != NULL here because xcalloc never
14139          returns NULL.  */
14140       if (*slot != NULL)
14141         {
14142           htab_delete (htab);
14143           return 1;
14144         }
14145       *slot = name;
14146     }
14147
14148   htab_delete (htab);
14149   return 0;
14150 }
14151
14152 /* When symbols change, it probably means the sources changed as well,
14153    and it might mean the static tracepoint markers are no longer at
14154    the same address or line numbers they used to be at last we
14155    checked.  Losing your static tracepoints whenever you rebuild is
14156    undesirable.  This function tries to resync/rematch gdb static
14157    tracepoints with the markers on the target, for static tracepoints
14158    that have not been set by marker id.  Static tracepoint that have
14159    been set by marker id are reset by marker id in breakpoint_re_set.
14160    The heuristic is:
14161
14162    1) For a tracepoint set at a specific address, look for a marker at
14163    the old PC.  If one is found there, assume to be the same marker.
14164    If the name / string id of the marker found is different from the
14165    previous known name, assume that means the user renamed the marker
14166    in the sources, and output a warning.
14167
14168    2) For a tracepoint set at a given line number, look for a marker
14169    at the new address of the old line number.  If one is found there,
14170    assume to be the same marker.  If the name / string id of the
14171    marker found is different from the previous known name, assume that
14172    means the user renamed the marker in the sources, and output a
14173    warning.
14174
14175    3) If a marker is no longer found at the same address or line, it
14176    may mean the marker no longer exists.  But it may also just mean
14177    the code changed a bit.  Maybe the user added a few lines of code
14178    that made the marker move up or down (in line number terms).  Ask
14179    the target for info about the marker with the string id as we knew
14180    it.  If found, update line number and address in the matching
14181    static tracepoint.  This will get confused if there's more than one
14182    marker with the same ID (possible in UST, although unadvised
14183    precisely because it confuses tools).  */
14184
14185 static struct symtab_and_line
14186 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14187 {
14188   struct tracepoint *tp = (struct tracepoint *) b;
14189   struct static_tracepoint_marker marker;
14190   CORE_ADDR pc;
14191
14192   pc = sal.pc;
14193   if (sal.line)
14194     find_line_pc (sal.symtab, sal.line, &pc);
14195
14196   if (target_static_tracepoint_marker_at (pc, &marker))
14197     {
14198       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14199         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14200                  b->number,
14201                  tp->static_trace_marker_id, marker.str_id);
14202
14203       xfree (tp->static_trace_marker_id);
14204       tp->static_trace_marker_id = xstrdup (marker.str_id);
14205       release_static_tracepoint_marker (&marker);
14206
14207       return sal;
14208     }
14209
14210   /* Old marker wasn't found on target at lineno.  Try looking it up
14211      by string ID.  */
14212   if (!sal.explicit_pc
14213       && sal.line != 0
14214       && sal.symtab != NULL
14215       && tp->static_trace_marker_id != NULL)
14216     {
14217       VEC(static_tracepoint_marker_p) *markers;
14218
14219       markers
14220         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14221
14222       if (!VEC_empty(static_tracepoint_marker_p, markers))
14223         {
14224           struct symtab_and_line sal2;
14225           struct symbol *sym;
14226           struct static_tracepoint_marker *tpmarker;
14227           struct ui_out *uiout = current_uiout;
14228
14229           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14230
14231           xfree (tp->static_trace_marker_id);
14232           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14233
14234           warning (_("marker for static tracepoint %d (%s) not "
14235                      "found at previous line number"),
14236                    b->number, tp->static_trace_marker_id);
14237
14238           init_sal (&sal2);
14239
14240           sal2.pc = tpmarker->address;
14241
14242           sal2 = find_pc_line (tpmarker->address, 0);
14243           sym = find_pc_sect_function (tpmarker->address, NULL);
14244           ui_out_text (uiout, "Now in ");
14245           if (sym)
14246             {
14247               ui_out_field_string (uiout, "func",
14248                                    SYMBOL_PRINT_NAME (sym));
14249               ui_out_text (uiout, " at ");
14250             }
14251           ui_out_field_string (uiout, "file",
14252                                symtab_to_filename_for_display (sal2.symtab));
14253           ui_out_text (uiout, ":");
14254
14255           if (ui_out_is_mi_like_p (uiout))
14256             {
14257               const char *fullname = symtab_to_fullname (sal2.symtab);
14258
14259               ui_out_field_string (uiout, "fullname", fullname);
14260             }
14261
14262           ui_out_field_int (uiout, "line", sal2.line);
14263           ui_out_text (uiout, "\n");
14264
14265           b->loc->line_number = sal2.line;
14266           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14267
14268           xfree (b->addr_string);
14269           b->addr_string = xstrprintf ("%s:%d",
14270                                    symtab_to_filename_for_display (sal2.symtab),
14271                                        b->loc->line_number);
14272
14273           /* Might be nice to check if function changed, and warn if
14274              so.  */
14275
14276           release_static_tracepoint_marker (tpmarker);
14277         }
14278     }
14279   return sal;
14280 }
14281
14282 /* Returns 1 iff locations A and B are sufficiently same that
14283    we don't need to report breakpoint as changed.  */
14284
14285 static int
14286 locations_are_equal (struct bp_location *a, struct bp_location *b)
14287 {
14288   while (a && b)
14289     {
14290       if (a->address != b->address)
14291         return 0;
14292
14293       if (a->shlib_disabled != b->shlib_disabled)
14294         return 0;
14295
14296       if (a->enabled != b->enabled)
14297         return 0;
14298
14299       a = a->next;
14300       b = b->next;
14301     }
14302
14303   if ((a == NULL) != (b == NULL))
14304     return 0;
14305
14306   return 1;
14307 }
14308
14309 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14310    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14311    a ranged breakpoint.  */
14312
14313 void
14314 update_breakpoint_locations (struct breakpoint *b,
14315                              struct symtabs_and_lines sals,
14316                              struct symtabs_and_lines sals_end)
14317 {
14318   int i;
14319   struct bp_location *existing_locations = b->loc;
14320
14321   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14322     {
14323       /* Ranged breakpoints have only one start location and one end
14324          location.  */
14325       b->enable_state = bp_disabled;
14326       update_global_location_list (1);
14327       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14328                            "multiple locations found\n"),
14329                          b->number);
14330       return;
14331     }
14332
14333   /* If there's no new locations, and all existing locations are
14334      pending, don't do anything.  This optimizes the common case where
14335      all locations are in the same shared library, that was unloaded.
14336      We'd like to retain the location, so that when the library is
14337      loaded again, we don't loose the enabled/disabled status of the
14338      individual locations.  */
14339   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14340     return;
14341
14342   b->loc = NULL;
14343
14344   for (i = 0; i < sals.nelts; ++i)
14345     {
14346       struct bp_location *new_loc;
14347
14348       switch_to_program_space_and_thread (sals.sals[i].pspace);
14349
14350       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14351
14352       /* Reparse conditions, they might contain references to the
14353          old symtab.  */
14354       if (b->cond_string != NULL)
14355         {
14356           const char *s;
14357           volatile struct gdb_exception e;
14358
14359           s = b->cond_string;
14360           TRY_CATCH (e, RETURN_MASK_ERROR)
14361             {
14362               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14363                                            block_for_pc (sals.sals[i].pc), 
14364                                            0);
14365             }
14366           if (e.reason < 0)
14367             {
14368               warning (_("failed to reevaluate condition "
14369                          "for breakpoint %d: %s"), 
14370                        b->number, e.message);
14371               new_loc->enabled = 0;
14372             }
14373         }
14374
14375       if (sals_end.nelts)
14376         {
14377           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14378
14379           new_loc->length = end - sals.sals[0].pc + 1;
14380         }
14381     }
14382
14383   /* Update locations of permanent breakpoints.  */
14384   if (b->enable_state == bp_permanent)
14385     make_breakpoint_permanent (b);
14386
14387   /* If possible, carry over 'disable' status from existing
14388      breakpoints.  */
14389   {
14390     struct bp_location *e = existing_locations;
14391     /* If there are multiple breakpoints with the same function name,
14392        e.g. for inline functions, comparing function names won't work.
14393        Instead compare pc addresses; this is just a heuristic as things
14394        may have moved, but in practice it gives the correct answer
14395        often enough until a better solution is found.  */
14396     int have_ambiguous_names = ambiguous_names_p (b->loc);
14397
14398     for (; e; e = e->next)
14399       {
14400         if (!e->enabled && e->function_name)
14401           {
14402             struct bp_location *l = b->loc;
14403             if (have_ambiguous_names)
14404               {
14405                 for (; l; l = l->next)
14406                   if (breakpoint_locations_match (e, l))
14407                     {
14408                       l->enabled = 0;
14409                       break;
14410                     }
14411               }
14412             else
14413               {
14414                 for (; l; l = l->next)
14415                   if (l->function_name
14416                       && strcmp (e->function_name, l->function_name) == 0)
14417                     {
14418                       l->enabled = 0;
14419                       break;
14420                     }
14421               }
14422           }
14423       }
14424   }
14425
14426   if (!locations_are_equal (existing_locations, b->loc))
14427     observer_notify_breakpoint_modified (b);
14428
14429   update_global_location_list (1);
14430 }
14431
14432 /* Find the SaL locations corresponding to the given ADDR_STRING.
14433    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14434
14435 static struct symtabs_and_lines
14436 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14437 {
14438   char *s;
14439   struct symtabs_and_lines sals = {0};
14440   volatile struct gdb_exception e;
14441
14442   gdb_assert (b->ops != NULL);
14443   s = addr_string;
14444
14445   TRY_CATCH (e, RETURN_MASK_ERROR)
14446     {
14447       b->ops->decode_linespec (b, &s, &sals);
14448     }
14449   if (e.reason < 0)
14450     {
14451       int not_found_and_ok = 0;
14452       /* For pending breakpoints, it's expected that parsing will
14453          fail until the right shared library is loaded.  User has
14454          already told to create pending breakpoints and don't need
14455          extra messages.  If breakpoint is in bp_shlib_disabled
14456          state, then user already saw the message about that
14457          breakpoint being disabled, and don't want to see more
14458          errors.  */
14459       if (e.error == NOT_FOUND_ERROR
14460           && (b->condition_not_parsed 
14461               || (b->loc && b->loc->shlib_disabled)
14462               || (b->loc && b->loc->pspace->executing_startup)
14463               || b->enable_state == bp_disabled))
14464         not_found_and_ok = 1;
14465
14466       if (!not_found_and_ok)
14467         {
14468           /* We surely don't want to warn about the same breakpoint
14469              10 times.  One solution, implemented here, is disable
14470              the breakpoint on error.  Another solution would be to
14471              have separate 'warning emitted' flag.  Since this
14472              happens only when a binary has changed, I don't know
14473              which approach is better.  */
14474           b->enable_state = bp_disabled;
14475           throw_exception (e);
14476         }
14477     }
14478
14479   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14480     {
14481       int i;
14482
14483       for (i = 0; i < sals.nelts; ++i)
14484         resolve_sal_pc (&sals.sals[i]);
14485       if (b->condition_not_parsed && s && s[0])
14486         {
14487           char *cond_string, *extra_string;
14488           int thread, task;
14489
14490           find_condition_and_thread (s, sals.sals[0].pc,
14491                                      &cond_string, &thread, &task,
14492                                      &extra_string);
14493           if (cond_string)
14494             b->cond_string = cond_string;
14495           b->thread = thread;
14496           b->task = task;
14497           if (extra_string)
14498             b->extra_string = extra_string;
14499           b->condition_not_parsed = 0;
14500         }
14501
14502       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14503         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14504
14505       *found = 1;
14506     }
14507   else
14508     *found = 0;
14509
14510   return sals;
14511 }
14512
14513 /* The default re_set method, for typical hardware or software
14514    breakpoints.  Reevaluate the breakpoint and recreate its
14515    locations.  */
14516
14517 static void
14518 breakpoint_re_set_default (struct breakpoint *b)
14519 {
14520   int found;
14521   struct symtabs_and_lines sals, sals_end;
14522   struct symtabs_and_lines expanded = {0};
14523   struct symtabs_and_lines expanded_end = {0};
14524
14525   sals = addr_string_to_sals (b, b->addr_string, &found);
14526   if (found)
14527     {
14528       make_cleanup (xfree, sals.sals);
14529       expanded = sals;
14530     }
14531
14532   if (b->addr_string_range_end)
14533     {
14534       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14535       if (found)
14536         {
14537           make_cleanup (xfree, sals_end.sals);
14538           expanded_end = sals_end;
14539         }
14540     }
14541
14542   update_breakpoint_locations (b, expanded, expanded_end);
14543 }
14544
14545 /* Default method for creating SALs from an address string.  It basically
14546    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14547
14548 static void
14549 create_sals_from_address_default (char **arg,
14550                                   struct linespec_result *canonical,
14551                                   enum bptype type_wanted,
14552                                   char *addr_start, char **copy_arg)
14553 {
14554   parse_breakpoint_sals (arg, canonical);
14555 }
14556
14557 /* Call create_breakpoints_sal for the given arguments.  This is the default
14558    function for the `create_breakpoints_sal' method of
14559    breakpoint_ops.  */
14560
14561 static void
14562 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14563                                 struct linespec_result *canonical,
14564                                 char *cond_string,
14565                                 char *extra_string,
14566                                 enum bptype type_wanted,
14567                                 enum bpdisp disposition,
14568                                 int thread,
14569                                 int task, int ignore_count,
14570                                 const struct breakpoint_ops *ops,
14571                                 int from_tty, int enabled,
14572                                 int internal, unsigned flags)
14573 {
14574   create_breakpoints_sal (gdbarch, canonical, cond_string,
14575                           extra_string,
14576                           type_wanted, disposition,
14577                           thread, task, ignore_count, ops, from_tty,
14578                           enabled, internal, flags);
14579 }
14580
14581 /* Decode the line represented by S by calling decode_line_full.  This is the
14582    default function for the `decode_linespec' method of breakpoint_ops.  */
14583
14584 static void
14585 decode_linespec_default (struct breakpoint *b, char **s,
14586                          struct symtabs_and_lines *sals)
14587 {
14588   struct linespec_result canonical;
14589
14590   init_linespec_result (&canonical);
14591   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14592                     (struct symtab *) NULL, 0,
14593                     &canonical, multiple_symbols_all,
14594                     b->filter);
14595
14596   /* We should get 0 or 1 resulting SALs.  */
14597   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14598
14599   if (VEC_length (linespec_sals, canonical.sals) > 0)
14600     {
14601       struct linespec_sals *lsal;
14602
14603       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14604       *sals = lsal->sals;
14605       /* Arrange it so the destructor does not free the
14606          contents.  */
14607       lsal->sals.sals = NULL;
14608     }
14609
14610   destroy_linespec_result (&canonical);
14611 }
14612
14613 /* Prepare the global context for a re-set of breakpoint B.  */
14614
14615 static struct cleanup *
14616 prepare_re_set_context (struct breakpoint *b)
14617 {
14618   struct cleanup *cleanups;
14619
14620   input_radix = b->input_radix;
14621   cleanups = save_current_space_and_thread ();
14622   if (b->pspace != NULL)
14623     switch_to_program_space_and_thread (b->pspace);
14624   set_language (b->language);
14625
14626   return cleanups;
14627 }
14628
14629 /* Reset a breakpoint given it's struct breakpoint * BINT.
14630    The value we return ends up being the return value from catch_errors.
14631    Unused in this case.  */
14632
14633 static int
14634 breakpoint_re_set_one (void *bint)
14635 {
14636   /* Get past catch_errs.  */
14637   struct breakpoint *b = (struct breakpoint *) bint;
14638   struct cleanup *cleanups;
14639
14640   cleanups = prepare_re_set_context (b);
14641   b->ops->re_set (b);
14642   do_cleanups (cleanups);
14643   return 0;
14644 }
14645
14646 /* Re-set all breakpoints after symbols have been re-loaded.  */
14647 void
14648 breakpoint_re_set (void)
14649 {
14650   struct breakpoint *b, *b_tmp;
14651   enum language save_language;
14652   int save_input_radix;
14653   struct cleanup *old_chain;
14654
14655   save_language = current_language->la_language;
14656   save_input_radix = input_radix;
14657   old_chain = save_current_program_space ();
14658
14659   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14660   {
14661     /* Format possible error msg.  */
14662     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14663                                 b->number);
14664     struct cleanup *cleanups = make_cleanup (xfree, message);
14665     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14666     do_cleanups (cleanups);
14667   }
14668   set_language (save_language);
14669   input_radix = save_input_radix;
14670
14671   jit_breakpoint_re_set ();
14672
14673   do_cleanups (old_chain);
14674
14675   create_overlay_event_breakpoint ();
14676   create_longjmp_master_breakpoint ();
14677   create_std_terminate_master_breakpoint ();
14678   create_exception_master_breakpoint ();
14679 }
14680 \f
14681 /* Reset the thread number of this breakpoint:
14682
14683    - If the breakpoint is for all threads, leave it as-is.
14684    - Else, reset it to the current thread for inferior_ptid.  */
14685 void
14686 breakpoint_re_set_thread (struct breakpoint *b)
14687 {
14688   if (b->thread != -1)
14689     {
14690       if (in_thread_list (inferior_ptid))
14691         b->thread = pid_to_thread_id (inferior_ptid);
14692
14693       /* We're being called after following a fork.  The new fork is
14694          selected as current, and unless this was a vfork will have a
14695          different program space from the original thread.  Reset that
14696          as well.  */
14697       b->loc->pspace = current_program_space;
14698     }
14699 }
14700
14701 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14702    If from_tty is nonzero, it prints a message to that effect,
14703    which ends with a period (no newline).  */
14704
14705 void
14706 set_ignore_count (int bptnum, int count, int from_tty)
14707 {
14708   struct breakpoint *b;
14709
14710   if (count < 0)
14711     count = 0;
14712
14713   ALL_BREAKPOINTS (b)
14714     if (b->number == bptnum)
14715     {
14716       if (is_tracepoint (b))
14717         {
14718           if (from_tty && count != 0)
14719             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14720                              bptnum);
14721           return;
14722         }
14723       
14724       b->ignore_count = count;
14725       if (from_tty)
14726         {
14727           if (count == 0)
14728             printf_filtered (_("Will stop next time "
14729                                "breakpoint %d is reached."),
14730                              bptnum);
14731           else if (count == 1)
14732             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14733                              bptnum);
14734           else
14735             printf_filtered (_("Will ignore next %d "
14736                                "crossings of breakpoint %d."),
14737                              count, bptnum);
14738         }
14739       observer_notify_breakpoint_modified (b);
14740       return;
14741     }
14742
14743   error (_("No breakpoint number %d."), bptnum);
14744 }
14745
14746 /* Command to set ignore-count of breakpoint N to COUNT.  */
14747
14748 static void
14749 ignore_command (char *args, int from_tty)
14750 {
14751   char *p = args;
14752   int num;
14753
14754   if (p == 0)
14755     error_no_arg (_("a breakpoint number"));
14756
14757   num = get_number (&p);
14758   if (num == 0)
14759     error (_("bad breakpoint number: '%s'"), args);
14760   if (*p == 0)
14761     error (_("Second argument (specified ignore-count) is missing."));
14762
14763   set_ignore_count (num,
14764                     longest_to_int (value_as_long (parse_and_eval (p))),
14765                     from_tty);
14766   if (from_tty)
14767     printf_filtered ("\n");
14768 }
14769 \f
14770 /* Call FUNCTION on each of the breakpoints
14771    whose numbers are given in ARGS.  */
14772
14773 static void
14774 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14775                                                       void *),
14776                         void *data)
14777 {
14778   int num;
14779   struct breakpoint *b, *tmp;
14780   int match;
14781   struct get_number_or_range_state state;
14782
14783   if (args == 0)
14784     error_no_arg (_("one or more breakpoint numbers"));
14785
14786   init_number_or_range (&state, args);
14787
14788   while (!state.finished)
14789     {
14790       const char *p = state.string;
14791
14792       match = 0;
14793
14794       num = get_number_or_range (&state);
14795       if (num == 0)
14796         {
14797           warning (_("bad breakpoint number at or near '%s'"), p);
14798         }
14799       else
14800         {
14801           ALL_BREAKPOINTS_SAFE (b, tmp)
14802             if (b->number == num)
14803               {
14804                 match = 1;
14805                 function (b, data);
14806                 break;
14807               }
14808           if (match == 0)
14809             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14810         }
14811     }
14812 }
14813
14814 static struct bp_location *
14815 find_location_by_number (char *number)
14816 {
14817   char *dot = strchr (number, '.');
14818   char *p1;
14819   int bp_num;
14820   int loc_num;
14821   struct breakpoint *b;
14822   struct bp_location *loc;  
14823
14824   *dot = '\0';
14825
14826   p1 = number;
14827   bp_num = get_number (&p1);
14828   if (bp_num == 0)
14829     error (_("Bad breakpoint number '%s'"), number);
14830
14831   ALL_BREAKPOINTS (b)
14832     if (b->number == bp_num)
14833       {
14834         break;
14835       }
14836
14837   if (!b || b->number != bp_num)
14838     error (_("Bad breakpoint number '%s'"), number);
14839   
14840   p1 = dot+1;
14841   loc_num = get_number (&p1);
14842   if (loc_num == 0)
14843     error (_("Bad breakpoint location number '%s'"), number);
14844
14845   --loc_num;
14846   loc = b->loc;
14847   for (;loc_num && loc; --loc_num, loc = loc->next)
14848     ;
14849   if (!loc)
14850     error (_("Bad breakpoint location number '%s'"), dot+1);
14851     
14852   return loc;  
14853 }
14854
14855
14856 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14857    If from_tty is nonzero, it prints a message to that effect,
14858    which ends with a period (no newline).  */
14859
14860 void
14861 disable_breakpoint (struct breakpoint *bpt)
14862 {
14863   /* Never disable a watchpoint scope breakpoint; we want to
14864      hit them when we leave scope so we can delete both the
14865      watchpoint and its scope breakpoint at that time.  */
14866   if (bpt->type == bp_watchpoint_scope)
14867     return;
14868
14869   /* You can't disable permanent breakpoints.  */
14870   if (bpt->enable_state == bp_permanent)
14871     return;
14872
14873   bpt->enable_state = bp_disabled;
14874
14875   /* Mark breakpoint locations modified.  */
14876   mark_breakpoint_modified (bpt);
14877
14878   if (target_supports_enable_disable_tracepoint ()
14879       && current_trace_status ()->running && is_tracepoint (bpt))
14880     {
14881       struct bp_location *location;
14882      
14883       for (location = bpt->loc; location; location = location->next)
14884         target_disable_tracepoint (location);
14885     }
14886
14887   update_global_location_list (0);
14888
14889   observer_notify_breakpoint_modified (bpt);
14890 }
14891
14892 /* A callback for iterate_over_related_breakpoints.  */
14893
14894 static void
14895 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14896 {
14897   disable_breakpoint (b);
14898 }
14899
14900 /* A callback for map_breakpoint_numbers that calls
14901    disable_breakpoint.  */
14902
14903 static void
14904 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14905 {
14906   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14907 }
14908
14909 static void
14910 disable_command (char *args, int from_tty)
14911 {
14912   if (args == 0)
14913     {
14914       struct breakpoint *bpt;
14915
14916       ALL_BREAKPOINTS (bpt)
14917         if (user_breakpoint_p (bpt))
14918           disable_breakpoint (bpt);
14919     }
14920   else
14921     {
14922       char *num = extract_arg (&args);
14923
14924       while (num)
14925         {
14926           if (strchr (num, '.'))
14927             {
14928               struct bp_location *loc = find_location_by_number (num);
14929
14930               if (loc)
14931                 {
14932                   if (loc->enabled)
14933                     {
14934                       loc->enabled = 0;
14935                       mark_breakpoint_location_modified (loc);
14936                     }
14937                   if (target_supports_enable_disable_tracepoint ()
14938                       && current_trace_status ()->running && loc->owner
14939                       && is_tracepoint (loc->owner))
14940                     target_disable_tracepoint (loc);
14941                 }
14942               update_global_location_list (0);
14943             }
14944           else
14945             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14946           num = extract_arg (&args);
14947         }
14948     }
14949 }
14950
14951 static void
14952 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14953                         int count)
14954 {
14955   int target_resources_ok;
14956
14957   if (bpt->type == bp_hardware_breakpoint)
14958     {
14959       int i;
14960       i = hw_breakpoint_used_count ();
14961       target_resources_ok = 
14962         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14963                                             i + 1, 0);
14964       if (target_resources_ok == 0)
14965         error (_("No hardware breakpoint support in the target."));
14966       else if (target_resources_ok < 0)
14967         error (_("Hardware breakpoints used exceeds limit."));
14968     }
14969
14970   if (is_watchpoint (bpt))
14971     {
14972       /* Initialize it just to avoid a GCC false warning.  */
14973       enum enable_state orig_enable_state = 0;
14974       volatile struct gdb_exception e;
14975
14976       TRY_CATCH (e, RETURN_MASK_ALL)
14977         {
14978           struct watchpoint *w = (struct watchpoint *) bpt;
14979
14980           orig_enable_state = bpt->enable_state;
14981           bpt->enable_state = bp_enabled;
14982           update_watchpoint (w, 1 /* reparse */);
14983         }
14984       if (e.reason < 0)
14985         {
14986           bpt->enable_state = orig_enable_state;
14987           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14988                              bpt->number);
14989           return;
14990         }
14991     }
14992
14993   if (bpt->enable_state != bp_permanent)
14994     bpt->enable_state = bp_enabled;
14995
14996   bpt->enable_state = bp_enabled;
14997
14998   /* Mark breakpoint locations modified.  */
14999   mark_breakpoint_modified (bpt);
15000
15001   if (target_supports_enable_disable_tracepoint ()
15002       && current_trace_status ()->running && is_tracepoint (bpt))
15003     {
15004       struct bp_location *location;
15005
15006       for (location = bpt->loc; location; location = location->next)
15007         target_enable_tracepoint (location);
15008     }
15009
15010   bpt->disposition = disposition;
15011   bpt->enable_count = count;
15012   update_global_location_list (1);
15013
15014   observer_notify_breakpoint_modified (bpt);
15015 }
15016
15017
15018 void
15019 enable_breakpoint (struct breakpoint *bpt)
15020 {
15021   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15022 }
15023
15024 static void
15025 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15026 {
15027   enable_breakpoint (bpt);
15028 }
15029
15030 /* A callback for map_breakpoint_numbers that calls
15031    enable_breakpoint.  */
15032
15033 static void
15034 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15035 {
15036   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15037 }
15038
15039 /* The enable command enables the specified breakpoints (or all defined
15040    breakpoints) so they once again become (or continue to be) effective
15041    in stopping the inferior.  */
15042
15043 static void
15044 enable_command (char *args, int from_tty)
15045 {
15046   if (args == 0)
15047     {
15048       struct breakpoint *bpt;
15049
15050       ALL_BREAKPOINTS (bpt)
15051         if (user_breakpoint_p (bpt))
15052           enable_breakpoint (bpt);
15053     }
15054   else
15055     {
15056       char *num = extract_arg (&args);
15057
15058       while (num)
15059         {
15060           if (strchr (num, '.'))
15061             {
15062               struct bp_location *loc = find_location_by_number (num);
15063
15064               if (loc)
15065                 {
15066                   if (!loc->enabled)
15067                     {
15068                       loc->enabled = 1;
15069                       mark_breakpoint_location_modified (loc);
15070                     }
15071                   if (target_supports_enable_disable_tracepoint ()
15072                       && current_trace_status ()->running && loc->owner
15073                       && is_tracepoint (loc->owner))
15074                     target_enable_tracepoint (loc);
15075                 }
15076               update_global_location_list (1);
15077             }
15078           else
15079             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15080           num = extract_arg (&args);
15081         }
15082     }
15083 }
15084
15085 /* This struct packages up disposition data for application to multiple
15086    breakpoints.  */
15087
15088 struct disp_data
15089 {
15090   enum bpdisp disp;
15091   int count;
15092 };
15093
15094 static void
15095 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15096 {
15097   struct disp_data disp_data = *(struct disp_data *) arg;
15098
15099   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15100 }
15101
15102 static void
15103 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15104 {
15105   struct disp_data disp = { disp_disable, 1 };
15106
15107   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15108 }
15109
15110 static void
15111 enable_once_command (char *args, int from_tty)
15112 {
15113   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15114 }
15115
15116 static void
15117 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15118 {
15119   struct disp_data disp = { disp_disable, *(int *) countptr };
15120
15121   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15122 }
15123
15124 static void
15125 enable_count_command (char *args, int from_tty)
15126 {
15127   int count = get_number (&args);
15128
15129   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15130 }
15131
15132 static void
15133 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15134 {
15135   struct disp_data disp = { disp_del, 1 };
15136
15137   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15138 }
15139
15140 static void
15141 enable_delete_command (char *args, int from_tty)
15142 {
15143   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15144 }
15145 \f
15146 static void
15147 set_breakpoint_cmd (char *args, int from_tty)
15148 {
15149 }
15150
15151 static void
15152 show_breakpoint_cmd (char *args, int from_tty)
15153 {
15154 }
15155
15156 /* Invalidate last known value of any hardware watchpoint if
15157    the memory which that value represents has been written to by
15158    GDB itself.  */
15159
15160 static void
15161 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15162                                       CORE_ADDR addr, ssize_t len,
15163                                       const bfd_byte *data)
15164 {
15165   struct breakpoint *bp;
15166
15167   ALL_BREAKPOINTS (bp)
15168     if (bp->enable_state == bp_enabled
15169         && bp->type == bp_hardware_watchpoint)
15170       {
15171         struct watchpoint *wp = (struct watchpoint *) bp;
15172
15173         if (wp->val_valid && wp->val)
15174           {
15175             struct bp_location *loc;
15176
15177             for (loc = bp->loc; loc != NULL; loc = loc->next)
15178               if (loc->loc_type == bp_loc_hardware_watchpoint
15179                   && loc->address + loc->length > addr
15180                   && addr + len > loc->address)
15181                 {
15182                   value_free (wp->val);
15183                   wp->val = NULL;
15184                   wp->val_valid = 0;
15185                 }
15186           }
15187       }
15188 }
15189
15190 /* Create and insert a raw software breakpoint at PC.  Return an
15191    identifier, which should be used to remove the breakpoint later.
15192    In general, places which call this should be using something on the
15193    breakpoint chain instead; this function should be eliminated
15194    someday.  */
15195
15196 void *
15197 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15198                                   struct address_space *aspace, CORE_ADDR pc)
15199 {
15200   struct bp_target_info *bp_tgt;
15201   struct bp_location *bl;
15202
15203   bp_tgt = XCNEW (struct bp_target_info);
15204
15205   bp_tgt->placed_address_space = aspace;
15206   bp_tgt->placed_address = pc;
15207
15208   /* If an unconditional non-raw breakpoint is already inserted at
15209      that location, there's no need to insert another.  However, with
15210      target-side evaluation of breakpoint conditions, if the
15211      breakpoint that is currently inserted on the target is
15212      conditional, we need to make it unconditional.  Note that a
15213      breakpoint with target-side commands is not reported even if
15214      unconditional, so we need to remove the commands from the target
15215      as well.  */
15216   bl = find_non_raw_software_breakpoint_inserted_here (aspace, pc);
15217   if (bl != NULL
15218       && VEC_empty (agent_expr_p, bl->target_info.conditions)
15219       && VEC_empty (agent_expr_p, bl->target_info.tcommands))
15220     {
15221       bp_target_info_copy_insertion_state (bp_tgt, &bl->target_info);
15222       return bp_tgt;
15223     }
15224
15225   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15226     {
15227       /* Could not insert the breakpoint.  */
15228       xfree (bp_tgt);
15229       return NULL;
15230     }
15231
15232   return bp_tgt;
15233 }
15234
15235 /* Remove a breakpoint BP inserted by
15236    deprecated_insert_raw_breakpoint.  */
15237
15238 int
15239 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15240 {
15241   struct bp_target_info *bp_tgt = bp;
15242   struct address_space *aspace = bp_tgt->placed_address_space;
15243   CORE_ADDR address = bp_tgt->placed_address;
15244   struct bp_location *bl;
15245   int ret;
15246
15247   bl = find_non_raw_software_breakpoint_inserted_here (aspace, address);
15248
15249   /* Only remove the raw breakpoint if there are no other non-raw
15250      breakpoints still inserted at this location.  Otherwise, we would
15251      be effectively disabling those breakpoints.  */
15252   if (bl == NULL)
15253     ret = target_remove_breakpoint (gdbarch, bp_tgt);
15254   else if (!VEC_empty (agent_expr_p, bl->target_info.conditions)
15255            || !VEC_empty (agent_expr_p, bl->target_info.tcommands))
15256     {
15257       /* The target is evaluating conditions, and when we inserted the
15258          software single-step breakpoint, we had made the breakpoint
15259          unconditional and command-less on the target side.  Reinsert
15260          to restore the conditions/commands.  */
15261       ret = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
15262     }
15263   else
15264     ret = 0;
15265
15266   xfree (bp_tgt);
15267
15268   return ret;
15269 }
15270
15271 /* Create and insert a breakpoint for software single step.  */
15272
15273 void
15274 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15275                                struct address_space *aspace, 
15276                                CORE_ADDR next_pc)
15277 {
15278   void **bpt_p;
15279
15280   if (single_step_breakpoints[0] == NULL)
15281     {
15282       bpt_p = &single_step_breakpoints[0];
15283       single_step_gdbarch[0] = gdbarch;
15284     }
15285   else
15286     {
15287       gdb_assert (single_step_breakpoints[1] == NULL);
15288       bpt_p = &single_step_breakpoints[1];
15289       single_step_gdbarch[1] = gdbarch;
15290     }
15291
15292   /* NOTE drow/2006-04-11: A future improvement to this function would
15293      be to only create the breakpoints once, and actually put them on
15294      the breakpoint chain.  That would let us use set_raw_breakpoint.
15295      We could adjust the addresses each time they were needed.  Doing
15296      this requires corresponding changes elsewhere where single step
15297      breakpoints are handled, however.  So, for now, we use this.  */
15298
15299   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15300   if (*bpt_p == NULL)
15301     error (_("Could not insert single-step breakpoint at %s"),
15302              paddress (gdbarch, next_pc));
15303 }
15304
15305 /* Check if the breakpoints used for software single stepping
15306    were inserted or not.  */
15307
15308 int
15309 single_step_breakpoints_inserted (void)
15310 {
15311   return (single_step_breakpoints[0] != NULL
15312           || single_step_breakpoints[1] != NULL);
15313 }
15314
15315 /* Remove and delete any breakpoints used for software single step.  */
15316
15317 void
15318 remove_single_step_breakpoints (void)
15319 {
15320   gdb_assert (single_step_breakpoints[0] != NULL);
15321
15322   /* See insert_single_step_breakpoint for more about this deprecated
15323      call.  */
15324   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15325                                     single_step_breakpoints[0]);
15326   single_step_gdbarch[0] = NULL;
15327   single_step_breakpoints[0] = NULL;
15328
15329   if (single_step_breakpoints[1] != NULL)
15330     {
15331       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15332                                         single_step_breakpoints[1]);
15333       single_step_gdbarch[1] = NULL;
15334       single_step_breakpoints[1] = NULL;
15335     }
15336 }
15337
15338 /* Delete software single step breakpoints without removing them from
15339    the inferior.  This is intended to be used if the inferior's address
15340    space where they were inserted is already gone, e.g. after exit or
15341    exec.  */
15342
15343 void
15344 cancel_single_step_breakpoints (void)
15345 {
15346   int i;
15347
15348   for (i = 0; i < 2; i++)
15349     if (single_step_breakpoints[i])
15350       {
15351         xfree (single_step_breakpoints[i]);
15352         single_step_breakpoints[i] = NULL;
15353         single_step_gdbarch[i] = NULL;
15354       }
15355 }
15356
15357 /* Detach software single-step breakpoints from INFERIOR_PTID without
15358    removing them.  */
15359
15360 static void
15361 detach_single_step_breakpoints (void)
15362 {
15363   int i;
15364
15365   for (i = 0; i < 2; i++)
15366     if (single_step_breakpoints[i])
15367       target_remove_breakpoint (single_step_gdbarch[i],
15368                                 single_step_breakpoints[i]);
15369 }
15370
15371 /* Find the software single-step breakpoint that inserted at PC.
15372    Returns its slot if found, and -1 if not found.  */
15373
15374 static int
15375 find_single_step_breakpoint (struct address_space *aspace,
15376                              CORE_ADDR pc)
15377 {
15378   int i;
15379
15380   for (i = 0; i < 2; i++)
15381     {
15382       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15383       if (bp_tgt
15384           && breakpoint_address_match (bp_tgt->placed_address_space,
15385                                        bp_tgt->placed_address,
15386                                        aspace, pc))
15387         return i;
15388     }
15389
15390   return -1;
15391 }
15392
15393 /* Check whether a software single-step breakpoint is inserted at
15394    PC.  */
15395
15396 int
15397 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15398                                         CORE_ADDR pc)
15399 {
15400   return find_single_step_breakpoint (aspace, pc) >= 0;
15401 }
15402
15403 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15404    non-zero otherwise.  */
15405 static int
15406 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15407 {
15408   if (syscall_catchpoint_p (bp)
15409       && bp->enable_state != bp_disabled
15410       && bp->enable_state != bp_call_disabled)
15411     return 1;
15412   else
15413     return 0;
15414 }
15415
15416 int
15417 catch_syscall_enabled (void)
15418 {
15419   struct catch_syscall_inferior_data *inf_data
15420     = get_catch_syscall_inferior_data (current_inferior ());
15421
15422   return inf_data->total_syscalls_count != 0;
15423 }
15424
15425 int
15426 catching_syscall_number (int syscall_number)
15427 {
15428   struct breakpoint *bp;
15429
15430   ALL_BREAKPOINTS (bp)
15431     if (is_syscall_catchpoint_enabled (bp))
15432       {
15433         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15434
15435         if (c->syscalls_to_be_caught)
15436           {
15437             int i, iter;
15438             for (i = 0;
15439                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15440                  i++)
15441               if (syscall_number == iter)
15442                 return 1;
15443           }
15444         else
15445           return 1;
15446       }
15447
15448   return 0;
15449 }
15450
15451 /* Complete syscall names.  Used by "catch syscall".  */
15452 static VEC (char_ptr) *
15453 catch_syscall_completer (struct cmd_list_element *cmd,
15454                          const char *text, const char *word)
15455 {
15456   const char **list = get_syscall_names ();
15457   VEC (char_ptr) *retlist
15458     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15459
15460   xfree (list);
15461   return retlist;
15462 }
15463
15464 /* Tracepoint-specific operations.  */
15465
15466 /* Set tracepoint count to NUM.  */
15467 static void
15468 set_tracepoint_count (int num)
15469 {
15470   tracepoint_count = num;
15471   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15472 }
15473
15474 static void
15475 trace_command (char *arg, int from_tty)
15476 {
15477   struct breakpoint_ops *ops;
15478   const char *arg_cp = arg;
15479
15480   if (arg && probe_linespec_to_ops (&arg_cp))
15481     ops = &tracepoint_probe_breakpoint_ops;
15482   else
15483     ops = &tracepoint_breakpoint_ops;
15484
15485   create_breakpoint (get_current_arch (),
15486                      arg,
15487                      NULL, 0, NULL, 1 /* parse arg */,
15488                      0 /* tempflag */,
15489                      bp_tracepoint /* type_wanted */,
15490                      0 /* Ignore count */,
15491                      pending_break_support,
15492                      ops,
15493                      from_tty,
15494                      1 /* enabled */,
15495                      0 /* internal */, 0);
15496 }
15497
15498 static void
15499 ftrace_command (char *arg, int from_tty)
15500 {
15501   create_breakpoint (get_current_arch (),
15502                      arg,
15503                      NULL, 0, NULL, 1 /* parse arg */,
15504                      0 /* tempflag */,
15505                      bp_fast_tracepoint /* type_wanted */,
15506                      0 /* Ignore count */,
15507                      pending_break_support,
15508                      &tracepoint_breakpoint_ops,
15509                      from_tty,
15510                      1 /* enabled */,
15511                      0 /* internal */, 0);
15512 }
15513
15514 /* strace command implementation.  Creates a static tracepoint.  */
15515
15516 static void
15517 strace_command (char *arg, int from_tty)
15518 {
15519   struct breakpoint_ops *ops;
15520
15521   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15522      or with a normal static tracepoint.  */
15523   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15524     ops = &strace_marker_breakpoint_ops;
15525   else
15526     ops = &tracepoint_breakpoint_ops;
15527
15528   create_breakpoint (get_current_arch (),
15529                      arg,
15530                      NULL, 0, NULL, 1 /* parse arg */,
15531                      0 /* tempflag */,
15532                      bp_static_tracepoint /* type_wanted */,
15533                      0 /* Ignore count */,
15534                      pending_break_support,
15535                      ops,
15536                      from_tty,
15537                      1 /* enabled */,
15538                      0 /* internal */, 0);
15539 }
15540
15541 /* Set up a fake reader function that gets command lines from a linked
15542    list that was acquired during tracepoint uploading.  */
15543
15544 static struct uploaded_tp *this_utp;
15545 static int next_cmd;
15546
15547 static char *
15548 read_uploaded_action (void)
15549 {
15550   char *rslt;
15551
15552   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15553
15554   next_cmd++;
15555
15556   return rslt;
15557 }
15558
15559 /* Given information about a tracepoint as recorded on a target (which
15560    can be either a live system or a trace file), attempt to create an
15561    equivalent GDB tracepoint.  This is not a reliable process, since
15562    the target does not necessarily have all the information used when
15563    the tracepoint was originally defined.  */
15564   
15565 struct tracepoint *
15566 create_tracepoint_from_upload (struct uploaded_tp *utp)
15567 {
15568   char *addr_str, small_buf[100];
15569   struct tracepoint *tp;
15570
15571   if (utp->at_string)
15572     addr_str = utp->at_string;
15573   else
15574     {
15575       /* In the absence of a source location, fall back to raw
15576          address.  Since there is no way to confirm that the address
15577          means the same thing as when the trace was started, warn the
15578          user.  */
15579       warning (_("Uploaded tracepoint %d has no "
15580                  "source location, using raw address"),
15581                utp->number);
15582       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15583       addr_str = small_buf;
15584     }
15585
15586   /* There's not much we can do with a sequence of bytecodes.  */
15587   if (utp->cond && !utp->cond_string)
15588     warning (_("Uploaded tracepoint %d condition "
15589                "has no source form, ignoring it"),
15590              utp->number);
15591
15592   if (!create_breakpoint (get_current_arch (),
15593                           addr_str,
15594                           utp->cond_string, -1, NULL,
15595                           0 /* parse cond/thread */,
15596                           0 /* tempflag */,
15597                           utp->type /* type_wanted */,
15598                           0 /* Ignore count */,
15599                           pending_break_support,
15600                           &tracepoint_breakpoint_ops,
15601                           0 /* from_tty */,
15602                           utp->enabled /* enabled */,
15603                           0 /* internal */,
15604                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15605     return NULL;
15606
15607   /* Get the tracepoint we just created.  */
15608   tp = get_tracepoint (tracepoint_count);
15609   gdb_assert (tp != NULL);
15610
15611   if (utp->pass > 0)
15612     {
15613       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15614                  tp->base.number);
15615
15616       trace_pass_command (small_buf, 0);
15617     }
15618
15619   /* If we have uploaded versions of the original commands, set up a
15620      special-purpose "reader" function and call the usual command line
15621      reader, then pass the result to the breakpoint command-setting
15622      function.  */
15623   if (!VEC_empty (char_ptr, utp->cmd_strings))
15624     {
15625       struct command_line *cmd_list;
15626
15627       this_utp = utp;
15628       next_cmd = 0;
15629
15630       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15631
15632       breakpoint_set_commands (&tp->base, cmd_list);
15633     }
15634   else if (!VEC_empty (char_ptr, utp->actions)
15635            || !VEC_empty (char_ptr, utp->step_actions))
15636     warning (_("Uploaded tracepoint %d actions "
15637                "have no source form, ignoring them"),
15638              utp->number);
15639
15640   /* Copy any status information that might be available.  */
15641   tp->base.hit_count = utp->hit_count;
15642   tp->traceframe_usage = utp->traceframe_usage;
15643
15644   return tp;
15645 }
15646   
15647 /* Print information on tracepoint number TPNUM_EXP, or all if
15648    omitted.  */
15649
15650 static void
15651 tracepoints_info (char *args, int from_tty)
15652 {
15653   struct ui_out *uiout = current_uiout;
15654   int num_printed;
15655
15656   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15657
15658   if (num_printed == 0)
15659     {
15660       if (args == NULL || *args == '\0')
15661         ui_out_message (uiout, 0, "No tracepoints.\n");
15662       else
15663         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15664     }
15665
15666   default_collect_info ();
15667 }
15668
15669 /* The 'enable trace' command enables tracepoints.
15670    Not supported by all targets.  */
15671 static void
15672 enable_trace_command (char *args, int from_tty)
15673 {
15674   enable_command (args, from_tty);
15675 }
15676
15677 /* The 'disable trace' command disables tracepoints.
15678    Not supported by all targets.  */
15679 static void
15680 disable_trace_command (char *args, int from_tty)
15681 {
15682   disable_command (args, from_tty);
15683 }
15684
15685 /* Remove a tracepoint (or all if no argument).  */
15686 static void
15687 delete_trace_command (char *arg, int from_tty)
15688 {
15689   struct breakpoint *b, *b_tmp;
15690
15691   dont_repeat ();
15692
15693   if (arg == 0)
15694     {
15695       int breaks_to_delete = 0;
15696
15697       /* Delete all breakpoints if no argument.
15698          Do not delete internal or call-dummy breakpoints, these
15699          have to be deleted with an explicit breakpoint number 
15700          argument.  */
15701       ALL_TRACEPOINTS (b)
15702         if (is_tracepoint (b) && user_breakpoint_p (b))
15703           {
15704             breaks_to_delete = 1;
15705             break;
15706           }
15707
15708       /* Ask user only if there are some breakpoints to delete.  */
15709       if (!from_tty
15710           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15711         {
15712           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15713             if (is_tracepoint (b) && user_breakpoint_p (b))
15714               delete_breakpoint (b);
15715         }
15716     }
15717   else
15718     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15719 }
15720
15721 /* Helper function for trace_pass_command.  */
15722
15723 static void
15724 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15725 {
15726   tp->pass_count = count;
15727   observer_notify_breakpoint_modified (&tp->base);
15728   if (from_tty)
15729     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15730                      tp->base.number, count);
15731 }
15732
15733 /* Set passcount for tracepoint.
15734
15735    First command argument is passcount, second is tracepoint number.
15736    If tracepoint number omitted, apply to most recently defined.
15737    Also accepts special argument "all".  */
15738
15739 static void
15740 trace_pass_command (char *args, int from_tty)
15741 {
15742   struct tracepoint *t1;
15743   unsigned int count;
15744
15745   if (args == 0 || *args == 0)
15746     error (_("passcount command requires an "
15747              "argument (count + optional TP num)"));
15748
15749   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15750
15751   args = skip_spaces (args);
15752   if (*args && strncasecmp (args, "all", 3) == 0)
15753     {
15754       struct breakpoint *b;
15755
15756       args += 3;                        /* Skip special argument "all".  */
15757       if (*args)
15758         error (_("Junk at end of arguments."));
15759
15760       ALL_TRACEPOINTS (b)
15761       {
15762         t1 = (struct tracepoint *) b;
15763         trace_pass_set_count (t1, count, from_tty);
15764       }
15765     }
15766   else if (*args == '\0')
15767     {
15768       t1 = get_tracepoint_by_number (&args, NULL);
15769       if (t1)
15770         trace_pass_set_count (t1, count, from_tty);
15771     }
15772   else
15773     {
15774       struct get_number_or_range_state state;
15775
15776       init_number_or_range (&state, args);
15777       while (!state.finished)
15778         {
15779           t1 = get_tracepoint_by_number (&args, &state);
15780           if (t1)
15781             trace_pass_set_count (t1, count, from_tty);
15782         }
15783     }
15784 }
15785
15786 struct tracepoint *
15787 get_tracepoint (int num)
15788 {
15789   struct breakpoint *t;
15790
15791   ALL_TRACEPOINTS (t)
15792     if (t->number == num)
15793       return (struct tracepoint *) t;
15794
15795   return NULL;
15796 }
15797
15798 /* Find the tracepoint with the given target-side number (which may be
15799    different from the tracepoint number after disconnecting and
15800    reconnecting).  */
15801
15802 struct tracepoint *
15803 get_tracepoint_by_number_on_target (int num)
15804 {
15805   struct breakpoint *b;
15806
15807   ALL_TRACEPOINTS (b)
15808     {
15809       struct tracepoint *t = (struct tracepoint *) b;
15810
15811       if (t->number_on_target == num)
15812         return t;
15813     }
15814
15815   return NULL;
15816 }
15817
15818 /* Utility: parse a tracepoint number and look it up in the list.
15819    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15820    If the argument is missing, the most recent tracepoint
15821    (tracepoint_count) is returned.  */
15822
15823 struct tracepoint *
15824 get_tracepoint_by_number (char **arg,
15825                           struct get_number_or_range_state *state)
15826 {
15827   struct breakpoint *t;
15828   int tpnum;
15829   char *instring = arg == NULL ? NULL : *arg;
15830
15831   if (state)
15832     {
15833       gdb_assert (!state->finished);
15834       tpnum = get_number_or_range (state);
15835     }
15836   else if (arg == NULL || *arg == NULL || ! **arg)
15837     tpnum = tracepoint_count;
15838   else
15839     tpnum = get_number (arg);
15840
15841   if (tpnum <= 0)
15842     {
15843       if (instring && *instring)
15844         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15845                          instring);
15846       else
15847         printf_filtered (_("No previous tracepoint\n"));
15848       return NULL;
15849     }
15850
15851   ALL_TRACEPOINTS (t)
15852     if (t->number == tpnum)
15853     {
15854       return (struct tracepoint *) t;
15855     }
15856
15857   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15858   return NULL;
15859 }
15860
15861 void
15862 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15863 {
15864   if (b->thread != -1)
15865     fprintf_unfiltered (fp, " thread %d", b->thread);
15866
15867   if (b->task != 0)
15868     fprintf_unfiltered (fp, " task %d", b->task);
15869
15870   fprintf_unfiltered (fp, "\n");
15871 }
15872
15873 /* Save information on user settable breakpoints (watchpoints, etc) to
15874    a new script file named FILENAME.  If FILTER is non-NULL, call it
15875    on each breakpoint and only include the ones for which it returns
15876    non-zero.  */
15877
15878 static void
15879 save_breakpoints (char *filename, int from_tty,
15880                   int (*filter) (const struct breakpoint *))
15881 {
15882   struct breakpoint *tp;
15883   int any = 0;
15884   struct cleanup *cleanup;
15885   struct ui_file *fp;
15886   int extra_trace_bits = 0;
15887
15888   if (filename == 0 || *filename == 0)
15889     error (_("Argument required (file name in which to save)"));
15890
15891   /* See if we have anything to save.  */
15892   ALL_BREAKPOINTS (tp)
15893   {
15894     /* Skip internal and momentary breakpoints.  */
15895     if (!user_breakpoint_p (tp))
15896       continue;
15897
15898     /* If we have a filter, only save the breakpoints it accepts.  */
15899     if (filter && !filter (tp))
15900       continue;
15901
15902     any = 1;
15903
15904     if (is_tracepoint (tp))
15905       {
15906         extra_trace_bits = 1;
15907
15908         /* We can stop searching.  */
15909         break;
15910       }
15911   }
15912
15913   if (!any)
15914     {
15915       warning (_("Nothing to save."));
15916       return;
15917     }
15918
15919   filename = tilde_expand (filename);
15920   cleanup = make_cleanup (xfree, filename);
15921   fp = gdb_fopen (filename, "w");
15922   if (!fp)
15923     error (_("Unable to open file '%s' for saving (%s)"),
15924            filename, safe_strerror (errno));
15925   make_cleanup_ui_file_delete (fp);
15926
15927   if (extra_trace_bits)
15928     save_trace_state_variables (fp);
15929
15930   ALL_BREAKPOINTS (tp)
15931   {
15932     /* Skip internal and momentary breakpoints.  */
15933     if (!user_breakpoint_p (tp))
15934       continue;
15935
15936     /* If we have a filter, only save the breakpoints it accepts.  */
15937     if (filter && !filter (tp))
15938       continue;
15939
15940     tp->ops->print_recreate (tp, fp);
15941
15942     /* Note, we can't rely on tp->number for anything, as we can't
15943        assume the recreated breakpoint numbers will match.  Use $bpnum
15944        instead.  */
15945
15946     if (tp->cond_string)
15947       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15948
15949     if (tp->ignore_count)
15950       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15951
15952     if (tp->type != bp_dprintf && tp->commands)
15953       {
15954         volatile struct gdb_exception ex;       
15955
15956         fprintf_unfiltered (fp, "  commands\n");
15957         
15958         ui_out_redirect (current_uiout, fp);
15959         TRY_CATCH (ex, RETURN_MASK_ALL)
15960           {
15961             print_command_lines (current_uiout, tp->commands->commands, 2);
15962           }
15963         ui_out_redirect (current_uiout, NULL);
15964
15965         if (ex.reason < 0)
15966           throw_exception (ex);
15967
15968         fprintf_unfiltered (fp, "  end\n");
15969       }
15970
15971     if (tp->enable_state == bp_disabled)
15972       fprintf_unfiltered (fp, "disable\n");
15973
15974     /* If this is a multi-location breakpoint, check if the locations
15975        should be individually disabled.  Watchpoint locations are
15976        special, and not user visible.  */
15977     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15978       {
15979         struct bp_location *loc;
15980         int n = 1;
15981
15982         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15983           if (!loc->enabled)
15984             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15985       }
15986   }
15987
15988   if (extra_trace_bits && *default_collect)
15989     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15990
15991   if (from_tty)
15992     printf_filtered (_("Saved to file '%s'.\n"), filename);
15993   do_cleanups (cleanup);
15994 }
15995
15996 /* The `save breakpoints' command.  */
15997
15998 static void
15999 save_breakpoints_command (char *args, int from_tty)
16000 {
16001   save_breakpoints (args, from_tty, NULL);
16002 }
16003
16004 /* The `save tracepoints' command.  */
16005
16006 static void
16007 save_tracepoints_command (char *args, int from_tty)
16008 {
16009   save_breakpoints (args, from_tty, is_tracepoint);
16010 }
16011
16012 /* Create a vector of all tracepoints.  */
16013
16014 VEC(breakpoint_p) *
16015 all_tracepoints (void)
16016 {
16017   VEC(breakpoint_p) *tp_vec = 0;
16018   struct breakpoint *tp;
16019
16020   ALL_TRACEPOINTS (tp)
16021   {
16022     VEC_safe_push (breakpoint_p, tp_vec, tp);
16023   }
16024
16025   return tp_vec;
16026 }
16027
16028 \f
16029 /* This help string is used for the break, hbreak, tbreak and thbreak
16030    commands.  It is defined as a macro to prevent duplication.
16031    COMMAND should be a string constant containing the name of the
16032    command.  */
16033 #define BREAK_ARGS_HELP(command) \
16034 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
16035 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
16036 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
16037 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
16038 LOCATION may be a line number, function name, or \"*\" and an address.\n\
16039 If a line number is specified, break at start of code for that line.\n\
16040 If a function is specified, break at start of code for that function.\n\
16041 If an address is specified, break at that exact address.\n\
16042 With no LOCATION, uses current execution address of the selected\n\
16043 stack frame.  This is useful for breaking on return to a stack frame.\n\
16044 \n\
16045 THREADNUM is the number from \"info threads\".\n\
16046 CONDITION is a boolean expression.\n\
16047 \n\
16048 Multiple breakpoints at one place are permitted, and useful if their\n\
16049 conditions are different.\n\
16050 \n\
16051 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
16052
16053 /* List of subcommands for "catch".  */
16054 static struct cmd_list_element *catch_cmdlist;
16055
16056 /* List of subcommands for "tcatch".  */
16057 static struct cmd_list_element *tcatch_cmdlist;
16058
16059 void
16060 add_catch_command (char *name, char *docstring,
16061                    cmd_sfunc_ftype *sfunc,
16062                    completer_ftype *completer,
16063                    void *user_data_catch,
16064                    void *user_data_tcatch)
16065 {
16066   struct cmd_list_element *command;
16067
16068   command = add_cmd (name, class_breakpoint, NULL, docstring,
16069                      &catch_cmdlist);
16070   set_cmd_sfunc (command, sfunc);
16071   set_cmd_context (command, user_data_catch);
16072   set_cmd_completer (command, completer);
16073
16074   command = add_cmd (name, class_breakpoint, NULL, docstring,
16075                      &tcatch_cmdlist);
16076   set_cmd_sfunc (command, sfunc);
16077   set_cmd_context (command, user_data_tcatch);
16078   set_cmd_completer (command, completer);
16079 }
16080
16081 static void
16082 clear_syscall_counts (struct inferior *inf)
16083 {
16084   struct catch_syscall_inferior_data *inf_data
16085     = get_catch_syscall_inferior_data (inf);
16086
16087   inf_data->total_syscalls_count = 0;
16088   inf_data->any_syscall_count = 0;
16089   VEC_free (int, inf_data->syscalls_counts);
16090 }
16091
16092 static void
16093 save_command (char *arg, int from_tty)
16094 {
16095   printf_unfiltered (_("\"save\" must be followed by "
16096                        "the name of a save subcommand.\n"));
16097   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16098 }
16099
16100 struct breakpoint *
16101 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16102                           void *data)
16103 {
16104   struct breakpoint *b, *b_tmp;
16105
16106   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16107     {
16108       if ((*callback) (b, data))
16109         return b;
16110     }
16111
16112   return NULL;
16113 }
16114
16115 /* Zero if any of the breakpoint's locations could be a location where
16116    functions have been inlined, nonzero otherwise.  */
16117
16118 static int
16119 is_non_inline_function (struct breakpoint *b)
16120 {
16121   /* The shared library event breakpoint is set on the address of a
16122      non-inline function.  */
16123   if (b->type == bp_shlib_event)
16124     return 1;
16125
16126   return 0;
16127 }
16128
16129 /* Nonzero if the specified PC cannot be a location where functions
16130    have been inlined.  */
16131
16132 int
16133 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16134                            const struct target_waitstatus *ws)
16135 {
16136   struct breakpoint *b;
16137   struct bp_location *bl;
16138
16139   ALL_BREAKPOINTS (b)
16140     {
16141       if (!is_non_inline_function (b))
16142         continue;
16143
16144       for (bl = b->loc; bl != NULL; bl = bl->next)
16145         {
16146           if (!bl->shlib_disabled
16147               && bpstat_check_location (bl, aspace, pc, ws))
16148             return 1;
16149         }
16150     }
16151
16152   return 0;
16153 }
16154
16155 /* Remove any references to OBJFILE which is going to be freed.  */
16156
16157 void
16158 breakpoint_free_objfile (struct objfile *objfile)
16159 {
16160   struct bp_location **locp, *loc;
16161
16162   ALL_BP_LOCATIONS (loc, locp)
16163     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16164       loc->symtab = NULL;
16165 }
16166
16167 void
16168 initialize_breakpoint_ops (void)
16169 {
16170   static int initialized = 0;
16171
16172   struct breakpoint_ops *ops;
16173
16174   if (initialized)
16175     return;
16176   initialized = 1;
16177
16178   /* The breakpoint_ops structure to be inherit by all kinds of
16179      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16180      internal and momentary breakpoints, etc.).  */
16181   ops = &bkpt_base_breakpoint_ops;
16182   *ops = base_breakpoint_ops;
16183   ops->re_set = bkpt_re_set;
16184   ops->insert_location = bkpt_insert_location;
16185   ops->remove_location = bkpt_remove_location;
16186   ops->breakpoint_hit = bkpt_breakpoint_hit;
16187   ops->create_sals_from_address = bkpt_create_sals_from_address;
16188   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16189   ops->decode_linespec = bkpt_decode_linespec;
16190
16191   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16192   ops = &bkpt_breakpoint_ops;
16193   *ops = bkpt_base_breakpoint_ops;
16194   ops->re_set = bkpt_re_set;
16195   ops->resources_needed = bkpt_resources_needed;
16196   ops->print_it = bkpt_print_it;
16197   ops->print_mention = bkpt_print_mention;
16198   ops->print_recreate = bkpt_print_recreate;
16199
16200   /* Ranged breakpoints.  */
16201   ops = &ranged_breakpoint_ops;
16202   *ops = bkpt_breakpoint_ops;
16203   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16204   ops->resources_needed = resources_needed_ranged_breakpoint;
16205   ops->print_it = print_it_ranged_breakpoint;
16206   ops->print_one = print_one_ranged_breakpoint;
16207   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16208   ops->print_mention = print_mention_ranged_breakpoint;
16209   ops->print_recreate = print_recreate_ranged_breakpoint;
16210
16211   /* Internal breakpoints.  */
16212   ops = &internal_breakpoint_ops;
16213   *ops = bkpt_base_breakpoint_ops;
16214   ops->re_set = internal_bkpt_re_set;
16215   ops->check_status = internal_bkpt_check_status;
16216   ops->print_it = internal_bkpt_print_it;
16217   ops->print_mention = internal_bkpt_print_mention;
16218
16219   /* Momentary breakpoints.  */
16220   ops = &momentary_breakpoint_ops;
16221   *ops = bkpt_base_breakpoint_ops;
16222   ops->re_set = momentary_bkpt_re_set;
16223   ops->check_status = momentary_bkpt_check_status;
16224   ops->print_it = momentary_bkpt_print_it;
16225   ops->print_mention = momentary_bkpt_print_mention;
16226
16227   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16228   ops = &longjmp_breakpoint_ops;
16229   *ops = momentary_breakpoint_ops;
16230   ops->dtor = longjmp_bkpt_dtor;
16231
16232   /* Probe breakpoints.  */
16233   ops = &bkpt_probe_breakpoint_ops;
16234   *ops = bkpt_breakpoint_ops;
16235   ops->insert_location = bkpt_probe_insert_location;
16236   ops->remove_location = bkpt_probe_remove_location;
16237   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16238   ops->decode_linespec = bkpt_probe_decode_linespec;
16239
16240   /* Watchpoints.  */
16241   ops = &watchpoint_breakpoint_ops;
16242   *ops = base_breakpoint_ops;
16243   ops->dtor = dtor_watchpoint;
16244   ops->re_set = re_set_watchpoint;
16245   ops->insert_location = insert_watchpoint;
16246   ops->remove_location = remove_watchpoint;
16247   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16248   ops->check_status = check_status_watchpoint;
16249   ops->resources_needed = resources_needed_watchpoint;
16250   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16251   ops->print_it = print_it_watchpoint;
16252   ops->print_mention = print_mention_watchpoint;
16253   ops->print_recreate = print_recreate_watchpoint;
16254   ops->explains_signal = explains_signal_watchpoint;
16255
16256   /* Masked watchpoints.  */
16257   ops = &masked_watchpoint_breakpoint_ops;
16258   *ops = watchpoint_breakpoint_ops;
16259   ops->insert_location = insert_masked_watchpoint;
16260   ops->remove_location = remove_masked_watchpoint;
16261   ops->resources_needed = resources_needed_masked_watchpoint;
16262   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16263   ops->print_it = print_it_masked_watchpoint;
16264   ops->print_one_detail = print_one_detail_masked_watchpoint;
16265   ops->print_mention = print_mention_masked_watchpoint;
16266   ops->print_recreate = print_recreate_masked_watchpoint;
16267
16268   /* Tracepoints.  */
16269   ops = &tracepoint_breakpoint_ops;
16270   *ops = base_breakpoint_ops;
16271   ops->re_set = tracepoint_re_set;
16272   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16273   ops->print_one_detail = tracepoint_print_one_detail;
16274   ops->print_mention = tracepoint_print_mention;
16275   ops->print_recreate = tracepoint_print_recreate;
16276   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16277   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16278   ops->decode_linespec = tracepoint_decode_linespec;
16279
16280   /* Probe tracepoints.  */
16281   ops = &tracepoint_probe_breakpoint_ops;
16282   *ops = tracepoint_breakpoint_ops;
16283   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16284   ops->decode_linespec = tracepoint_probe_decode_linespec;
16285
16286   /* Static tracepoints with marker (`-m').  */
16287   ops = &strace_marker_breakpoint_ops;
16288   *ops = tracepoint_breakpoint_ops;
16289   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16290   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16291   ops->decode_linespec = strace_marker_decode_linespec;
16292
16293   /* Fork catchpoints.  */
16294   ops = &catch_fork_breakpoint_ops;
16295   *ops = base_breakpoint_ops;
16296   ops->insert_location = insert_catch_fork;
16297   ops->remove_location = remove_catch_fork;
16298   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16299   ops->print_it = print_it_catch_fork;
16300   ops->print_one = print_one_catch_fork;
16301   ops->print_mention = print_mention_catch_fork;
16302   ops->print_recreate = print_recreate_catch_fork;
16303
16304   /* Vfork catchpoints.  */
16305   ops = &catch_vfork_breakpoint_ops;
16306   *ops = base_breakpoint_ops;
16307   ops->insert_location = insert_catch_vfork;
16308   ops->remove_location = remove_catch_vfork;
16309   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16310   ops->print_it = print_it_catch_vfork;
16311   ops->print_one = print_one_catch_vfork;
16312   ops->print_mention = print_mention_catch_vfork;
16313   ops->print_recreate = print_recreate_catch_vfork;
16314
16315   /* Exec catchpoints.  */
16316   ops = &catch_exec_breakpoint_ops;
16317   *ops = base_breakpoint_ops;
16318   ops->dtor = dtor_catch_exec;
16319   ops->insert_location = insert_catch_exec;
16320   ops->remove_location = remove_catch_exec;
16321   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16322   ops->print_it = print_it_catch_exec;
16323   ops->print_one = print_one_catch_exec;
16324   ops->print_mention = print_mention_catch_exec;
16325   ops->print_recreate = print_recreate_catch_exec;
16326
16327   /* Syscall catchpoints.  */
16328   ops = &catch_syscall_breakpoint_ops;
16329   *ops = base_breakpoint_ops;
16330   ops->dtor = dtor_catch_syscall;
16331   ops->insert_location = insert_catch_syscall;
16332   ops->remove_location = remove_catch_syscall;
16333   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16334   ops->print_it = print_it_catch_syscall;
16335   ops->print_one = print_one_catch_syscall;
16336   ops->print_mention = print_mention_catch_syscall;
16337   ops->print_recreate = print_recreate_catch_syscall;
16338
16339   /* Solib-related catchpoints.  */
16340   ops = &catch_solib_breakpoint_ops;
16341   *ops = base_breakpoint_ops;
16342   ops->dtor = dtor_catch_solib;
16343   ops->insert_location = insert_catch_solib;
16344   ops->remove_location = remove_catch_solib;
16345   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16346   ops->check_status = check_status_catch_solib;
16347   ops->print_it = print_it_catch_solib;
16348   ops->print_one = print_one_catch_solib;
16349   ops->print_mention = print_mention_catch_solib;
16350   ops->print_recreate = print_recreate_catch_solib;
16351
16352   ops = &dprintf_breakpoint_ops;
16353   *ops = bkpt_base_breakpoint_ops;
16354   ops->re_set = dprintf_re_set;
16355   ops->resources_needed = bkpt_resources_needed;
16356   ops->print_it = bkpt_print_it;
16357   ops->print_mention = bkpt_print_mention;
16358   ops->print_recreate = dprintf_print_recreate;
16359   ops->after_condition_true = dprintf_after_condition_true;
16360   ops->breakpoint_hit = dprintf_breakpoint_hit;
16361 }
16362
16363 /* Chain containing all defined "enable breakpoint" subcommands.  */
16364
16365 static struct cmd_list_element *enablebreaklist = NULL;
16366
16367 void
16368 _initialize_breakpoint (void)
16369 {
16370   struct cmd_list_element *c;
16371
16372   initialize_breakpoint_ops ();
16373
16374   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16375   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16376   observer_attach_inferior_exit (clear_syscall_counts);
16377   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16378
16379   breakpoint_objfile_key
16380     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16381
16382   catch_syscall_inferior_data
16383     = register_inferior_data_with_cleanup (NULL,
16384                                            catch_syscall_inferior_data_cleanup);
16385
16386   breakpoint_chain = 0;
16387   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16388      before a breakpoint is set.  */
16389   breakpoint_count = 0;
16390
16391   tracepoint_count = 0;
16392
16393   add_com ("ignore", class_breakpoint, ignore_command, _("\
16394 Set ignore-count of breakpoint number N to COUNT.\n\
16395 Usage is `ignore N COUNT'."));
16396   if (xdb_commands)
16397     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16398
16399   add_com ("commands", class_breakpoint, commands_command, _("\
16400 Set commands to be executed when a breakpoint is hit.\n\
16401 Give breakpoint number as argument after \"commands\".\n\
16402 With no argument, the targeted breakpoint is the last one set.\n\
16403 The commands themselves follow starting on the next line.\n\
16404 Type a line containing \"end\" to indicate the end of them.\n\
16405 Give \"silent\" as the first line to make the breakpoint silent;\n\
16406 then no output is printed when it is hit, except what the commands print."));
16407
16408   c = add_com ("condition", class_breakpoint, condition_command, _("\
16409 Specify breakpoint number N to break only if COND is true.\n\
16410 Usage is `condition N COND', where N is an integer and COND is an\n\
16411 expression to be evaluated whenever breakpoint N is reached."));
16412   set_cmd_completer (c, condition_completer);
16413
16414   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16415 Set a temporary breakpoint.\n\
16416 Like \"break\" except the breakpoint is only temporary,\n\
16417 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16418 by using \"enable delete\" on the breakpoint number.\n\
16419 \n"
16420 BREAK_ARGS_HELP ("tbreak")));
16421   set_cmd_completer (c, location_completer);
16422
16423   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16424 Set a hardware assisted breakpoint.\n\
16425 Like \"break\" except the breakpoint requires hardware support,\n\
16426 some target hardware may not have this support.\n\
16427 \n"
16428 BREAK_ARGS_HELP ("hbreak")));
16429   set_cmd_completer (c, location_completer);
16430
16431   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16432 Set a temporary hardware assisted breakpoint.\n\
16433 Like \"hbreak\" except the breakpoint is only temporary,\n\
16434 so it will be deleted when hit.\n\
16435 \n"
16436 BREAK_ARGS_HELP ("thbreak")));
16437   set_cmd_completer (c, location_completer);
16438
16439   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16440 Enable some breakpoints.\n\
16441 Give breakpoint numbers (separated by spaces) as arguments.\n\
16442 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16443 This is used to cancel the effect of the \"disable\" command.\n\
16444 With a subcommand you can enable temporarily."),
16445                   &enablelist, "enable ", 1, &cmdlist);
16446   if (xdb_commands)
16447     add_com ("ab", class_breakpoint, enable_command, _("\
16448 Enable some breakpoints.\n\
16449 Give breakpoint numbers (separated by spaces) as arguments.\n\
16450 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16451 This is used to cancel the effect of the \"disable\" command.\n\
16452 With a subcommand you can enable temporarily."));
16453
16454   add_com_alias ("en", "enable", class_breakpoint, 1);
16455
16456   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16457 Enable some breakpoints.\n\
16458 Give breakpoint numbers (separated by spaces) as arguments.\n\
16459 This is used to cancel the effect of the \"disable\" command.\n\
16460 May be abbreviated to simply \"enable\".\n"),
16461                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16462
16463   add_cmd ("once", no_class, enable_once_command, _("\
16464 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16465 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16466            &enablebreaklist);
16467
16468   add_cmd ("delete", no_class, enable_delete_command, _("\
16469 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16470 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16471            &enablebreaklist);
16472
16473   add_cmd ("count", no_class, enable_count_command, _("\
16474 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16475 If a breakpoint is hit while enabled in this fashion,\n\
16476 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16477            &enablebreaklist);
16478
16479   add_cmd ("delete", no_class, enable_delete_command, _("\
16480 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16481 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16482            &enablelist);
16483
16484   add_cmd ("once", no_class, enable_once_command, _("\
16485 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16486 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16487            &enablelist);
16488
16489   add_cmd ("count", no_class, enable_count_command, _("\
16490 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16491 If a breakpoint is hit while enabled in this fashion,\n\
16492 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16493            &enablelist);
16494
16495   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16496 Disable some breakpoints.\n\
16497 Arguments are breakpoint numbers with spaces in between.\n\
16498 To disable all breakpoints, give no argument.\n\
16499 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16500                   &disablelist, "disable ", 1, &cmdlist);
16501   add_com_alias ("dis", "disable", class_breakpoint, 1);
16502   add_com_alias ("disa", "disable", class_breakpoint, 1);
16503   if (xdb_commands)
16504     add_com ("sb", class_breakpoint, disable_command, _("\
16505 Disable some breakpoints.\n\
16506 Arguments are breakpoint numbers with spaces in between.\n\
16507 To disable all breakpoints, give no argument.\n\
16508 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16509
16510   add_cmd ("breakpoints", class_alias, disable_command, _("\
16511 Disable some breakpoints.\n\
16512 Arguments are breakpoint numbers with spaces in between.\n\
16513 To disable all breakpoints, give no argument.\n\
16514 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16515 This command may be abbreviated \"disable\"."),
16516            &disablelist);
16517
16518   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16519 Delete some breakpoints or auto-display expressions.\n\
16520 Arguments are breakpoint numbers with spaces in between.\n\
16521 To delete all breakpoints, give no argument.\n\
16522 \n\
16523 Also a prefix command for deletion of other GDB objects.\n\
16524 The \"unset\" command is also an alias for \"delete\"."),
16525                   &deletelist, "delete ", 1, &cmdlist);
16526   add_com_alias ("d", "delete", class_breakpoint, 1);
16527   add_com_alias ("del", "delete", class_breakpoint, 1);
16528   if (xdb_commands)
16529     add_com ("db", class_breakpoint, delete_command, _("\
16530 Delete some breakpoints.\n\
16531 Arguments are breakpoint numbers with spaces in between.\n\
16532 To delete all breakpoints, give no argument.\n"));
16533
16534   add_cmd ("breakpoints", class_alias, delete_command, _("\
16535 Delete some breakpoints or auto-display expressions.\n\
16536 Arguments are breakpoint numbers with spaces in between.\n\
16537 To delete all breakpoints, give no argument.\n\
16538 This command may be abbreviated \"delete\"."),
16539            &deletelist);
16540
16541   add_com ("clear", class_breakpoint, clear_command, _("\
16542 Clear breakpoint at specified line or function.\n\
16543 Argument may be line number, function name, or \"*\" and an address.\n\
16544 If line number is specified, all breakpoints in that line are cleared.\n\
16545 If function is specified, breakpoints at beginning of function are cleared.\n\
16546 If an address is specified, breakpoints at that address are cleared.\n\
16547 \n\
16548 With no argument, clears all breakpoints in the line that the selected frame\n\
16549 is executing in.\n\
16550 \n\
16551 See also the \"delete\" command which clears breakpoints by number."));
16552   add_com_alias ("cl", "clear", class_breakpoint, 1);
16553
16554   c = add_com ("break", class_breakpoint, break_command, _("\
16555 Set breakpoint at specified line or function.\n"
16556 BREAK_ARGS_HELP ("break")));
16557   set_cmd_completer (c, location_completer);
16558
16559   add_com_alias ("b", "break", class_run, 1);
16560   add_com_alias ("br", "break", class_run, 1);
16561   add_com_alias ("bre", "break", class_run, 1);
16562   add_com_alias ("brea", "break", class_run, 1);
16563
16564   if (xdb_commands)
16565    add_com_alias ("ba", "break", class_breakpoint, 1);
16566
16567   if (dbx_commands)
16568     {
16569       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16570 Break in function/address or break at a line in the current file."),
16571                              &stoplist, "stop ", 1, &cmdlist);
16572       add_cmd ("in", class_breakpoint, stopin_command,
16573                _("Break in function or address."), &stoplist);
16574       add_cmd ("at", class_breakpoint, stopat_command,
16575                _("Break at a line in the current file."), &stoplist);
16576       add_com ("status", class_info, breakpoints_info, _("\
16577 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16578 The \"Type\" column indicates one of:\n\
16579 \tbreakpoint     - normal breakpoint\n\
16580 \twatchpoint     - watchpoint\n\
16581 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16582 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16583 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16584 address and file/line number respectively.\n\
16585 \n\
16586 Convenience variable \"$_\" and default examine address for \"x\"\n\
16587 are set to the address of the last breakpoint listed unless the command\n\
16588 is prefixed with \"server \".\n\n\
16589 Convenience variable \"$bpnum\" contains the number of the last\n\
16590 breakpoint set."));
16591     }
16592
16593   add_info ("breakpoints", breakpoints_info, _("\
16594 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16595 The \"Type\" column indicates one of:\n\
16596 \tbreakpoint     - normal breakpoint\n\
16597 \twatchpoint     - watchpoint\n\
16598 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16599 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16600 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16601 address and file/line number respectively.\n\
16602 \n\
16603 Convenience variable \"$_\" and default examine address for \"x\"\n\
16604 are set to the address of the last breakpoint listed unless the command\n\
16605 is prefixed with \"server \".\n\n\
16606 Convenience variable \"$bpnum\" contains the number of the last\n\
16607 breakpoint set."));
16608
16609   add_info_alias ("b", "breakpoints", 1);
16610
16611   if (xdb_commands)
16612     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16613 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16614 The \"Type\" column indicates one of:\n\
16615 \tbreakpoint     - normal breakpoint\n\
16616 \twatchpoint     - watchpoint\n\
16617 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16618 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16619 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16620 address and file/line number respectively.\n\
16621 \n\
16622 Convenience variable \"$_\" and default examine address for \"x\"\n\
16623 are set to the address of the last breakpoint listed unless the command\n\
16624 is prefixed with \"server \".\n\n\
16625 Convenience variable \"$bpnum\" contains the number of the last\n\
16626 breakpoint set."));
16627
16628   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16629 Status of all breakpoints, or breakpoint number NUMBER.\n\
16630 The \"Type\" column indicates one of:\n\
16631 \tbreakpoint     - normal breakpoint\n\
16632 \twatchpoint     - watchpoint\n\
16633 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16634 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16635 \tuntil          - internal breakpoint used by the \"until\" command\n\
16636 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16637 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16638 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16639 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16640 address and file/line number respectively.\n\
16641 \n\
16642 Convenience variable \"$_\" and default examine address for \"x\"\n\
16643 are set to the address of the last breakpoint listed unless the command\n\
16644 is prefixed with \"server \".\n\n\
16645 Convenience variable \"$bpnum\" contains the number of the last\n\
16646 breakpoint set."),
16647            &maintenanceinfolist);
16648
16649   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16650 Set catchpoints to catch events."),
16651                   &catch_cmdlist, "catch ",
16652                   0/*allow-unknown*/, &cmdlist);
16653
16654   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16655 Set temporary catchpoints to catch events."),
16656                   &tcatch_cmdlist, "tcatch ",
16657                   0/*allow-unknown*/, &cmdlist);
16658
16659   add_catch_command ("fork", _("Catch calls to fork."),
16660                      catch_fork_command_1,
16661                      NULL,
16662                      (void *) (uintptr_t) catch_fork_permanent,
16663                      (void *) (uintptr_t) catch_fork_temporary);
16664   add_catch_command ("vfork", _("Catch calls to vfork."),
16665                      catch_fork_command_1,
16666                      NULL,
16667                      (void *) (uintptr_t) catch_vfork_permanent,
16668                      (void *) (uintptr_t) catch_vfork_temporary);
16669   add_catch_command ("exec", _("Catch calls to exec."),
16670                      catch_exec_command_1,
16671                      NULL,
16672                      CATCH_PERMANENT,
16673                      CATCH_TEMPORARY);
16674   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16675 Usage: catch load [REGEX]\n\
16676 If REGEX is given, only stop for libraries matching the regular expression."),
16677                      catch_load_command_1,
16678                      NULL,
16679                      CATCH_PERMANENT,
16680                      CATCH_TEMPORARY);
16681   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16682 Usage: catch unload [REGEX]\n\
16683 If REGEX is given, only stop for libraries matching the regular expression."),
16684                      catch_unload_command_1,
16685                      NULL,
16686                      CATCH_PERMANENT,
16687                      CATCH_TEMPORARY);
16688   add_catch_command ("syscall", _("\
16689 Catch system calls by their names and/or numbers.\n\
16690 Arguments say which system calls to catch.  If no arguments\n\
16691 are given, every system call will be caught.\n\
16692 Arguments, if given, should be one or more system call names\n\
16693 (if your system supports that), or system call numbers."),
16694                      catch_syscall_command_1,
16695                      catch_syscall_completer,
16696                      CATCH_PERMANENT,
16697                      CATCH_TEMPORARY);
16698
16699   c = add_com ("watch", class_breakpoint, watch_command, _("\
16700 Set a watchpoint for an expression.\n\
16701 Usage: watch [-l|-location] EXPRESSION\n\
16702 A watchpoint stops execution of your program whenever the value of\n\
16703 an expression changes.\n\
16704 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16705 the memory to which it refers."));
16706   set_cmd_completer (c, expression_completer);
16707
16708   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16709 Set a read watchpoint for an expression.\n\
16710 Usage: rwatch [-l|-location] EXPRESSION\n\
16711 A watchpoint stops execution of your program whenever the value of\n\
16712 an expression is read.\n\
16713 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16714 the memory to which it refers."));
16715   set_cmd_completer (c, expression_completer);
16716
16717   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16718 Set a watchpoint for an expression.\n\
16719 Usage: awatch [-l|-location] EXPRESSION\n\
16720 A watchpoint stops execution of your program whenever the value of\n\
16721 an expression is either read or written.\n\
16722 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16723 the memory to which it refers."));
16724   set_cmd_completer (c, expression_completer);
16725
16726   add_info ("watchpoints", watchpoints_info, _("\
16727 Status of specified watchpoints (all watchpoints if no argument)."));
16728
16729   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16730      respond to changes - contrary to the description.  */
16731   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16732                             &can_use_hw_watchpoints, _("\
16733 Set debugger's willingness to use watchpoint hardware."), _("\
16734 Show debugger's willingness to use watchpoint hardware."), _("\
16735 If zero, gdb will not use hardware for new watchpoints, even if\n\
16736 such is available.  (However, any hardware watchpoints that were\n\
16737 created before setting this to nonzero, will continue to use watchpoint\n\
16738 hardware.)"),
16739                             NULL,
16740                             show_can_use_hw_watchpoints,
16741                             &setlist, &showlist);
16742
16743   can_use_hw_watchpoints = 1;
16744
16745   /* Tracepoint manipulation commands.  */
16746
16747   c = add_com ("trace", class_breakpoint, trace_command, _("\
16748 Set a tracepoint at specified line or function.\n\
16749 \n"
16750 BREAK_ARGS_HELP ("trace") "\n\
16751 Do \"help tracepoints\" for info on other tracepoint commands."));
16752   set_cmd_completer (c, location_completer);
16753
16754   add_com_alias ("tp", "trace", class_alias, 0);
16755   add_com_alias ("tr", "trace", class_alias, 1);
16756   add_com_alias ("tra", "trace", class_alias, 1);
16757   add_com_alias ("trac", "trace", class_alias, 1);
16758
16759   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16760 Set a fast tracepoint at specified line or function.\n\
16761 \n"
16762 BREAK_ARGS_HELP ("ftrace") "\n\
16763 Do \"help tracepoints\" for info on other tracepoint commands."));
16764   set_cmd_completer (c, location_completer);
16765
16766   c = add_com ("strace", class_breakpoint, strace_command, _("\
16767 Set a static tracepoint at specified line, function or marker.\n\
16768 \n\
16769 strace [LOCATION] [if CONDITION]\n\
16770 LOCATION may be a line number, function name, \"*\" and an address,\n\
16771 or -m MARKER_ID.\n\
16772 If a line number is specified, probe the marker at start of code\n\
16773 for that line.  If a function is specified, probe the marker at start\n\
16774 of code for that function.  If an address is specified, probe the marker\n\
16775 at that exact address.  If a marker id is specified, probe the marker\n\
16776 with that name.  With no LOCATION, uses current execution address of\n\
16777 the selected stack frame.\n\
16778 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16779 This collects arbitrary user data passed in the probe point call to the\n\
16780 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16781 by printing the $_sdata variable like any other convenience variable.\n\
16782 \n\
16783 CONDITION is a boolean expression.\n\
16784 \n\
16785 Multiple tracepoints at one place are permitted, and useful if their\n\
16786 conditions are different.\n\
16787 \n\
16788 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16789 Do \"help tracepoints\" for info on other tracepoint commands."));
16790   set_cmd_completer (c, location_completer);
16791
16792   add_info ("tracepoints", tracepoints_info, _("\
16793 Status of specified tracepoints (all tracepoints if no argument).\n\
16794 Convenience variable \"$tpnum\" contains the number of the\n\
16795 last tracepoint set."));
16796
16797   add_info_alias ("tp", "tracepoints", 1);
16798
16799   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16800 Delete specified tracepoints.\n\
16801 Arguments are tracepoint numbers, separated by spaces.\n\
16802 No argument means delete all tracepoints."),
16803            &deletelist);
16804   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16805
16806   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16807 Disable specified tracepoints.\n\
16808 Arguments are tracepoint numbers, separated by spaces.\n\
16809 No argument means disable all tracepoints."),
16810            &disablelist);
16811   deprecate_cmd (c, "disable");
16812
16813   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16814 Enable specified tracepoints.\n\
16815 Arguments are tracepoint numbers, separated by spaces.\n\
16816 No argument means enable all tracepoints."),
16817            &enablelist);
16818   deprecate_cmd (c, "enable");
16819
16820   add_com ("passcount", class_trace, trace_pass_command, _("\
16821 Set the passcount for a tracepoint.\n\
16822 The trace will end when the tracepoint has been passed 'count' times.\n\
16823 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16824 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16825
16826   add_prefix_cmd ("save", class_breakpoint, save_command,
16827                   _("Save breakpoint definitions as a script."),
16828                   &save_cmdlist, "save ",
16829                   0/*allow-unknown*/, &cmdlist);
16830
16831   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16832 Save current breakpoint definitions as a script.\n\
16833 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16834 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16835 session to restore them."),
16836                &save_cmdlist);
16837   set_cmd_completer (c, filename_completer);
16838
16839   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16840 Save current tracepoint definitions as a script.\n\
16841 Use the 'source' command in another debug session to restore them."),
16842                &save_cmdlist);
16843   set_cmd_completer (c, filename_completer);
16844
16845   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16846   deprecate_cmd (c, "save tracepoints");
16847
16848   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16849 Breakpoint specific settings\n\
16850 Configure various breakpoint-specific variables such as\n\
16851 pending breakpoint behavior"),
16852                   &breakpoint_set_cmdlist, "set breakpoint ",
16853                   0/*allow-unknown*/, &setlist);
16854   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16855 Breakpoint specific settings\n\
16856 Configure various breakpoint-specific variables such as\n\
16857 pending breakpoint behavior"),
16858                   &breakpoint_show_cmdlist, "show breakpoint ",
16859                   0/*allow-unknown*/, &showlist);
16860
16861   add_setshow_auto_boolean_cmd ("pending", no_class,
16862                                 &pending_break_support, _("\
16863 Set debugger's behavior regarding pending breakpoints."), _("\
16864 Show debugger's behavior regarding pending breakpoints."), _("\
16865 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16866 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16867 an error.  If auto, an unrecognized breakpoint location results in a\n\
16868 user-query to see if a pending breakpoint should be created."),
16869                                 NULL,
16870                                 show_pending_break_support,
16871                                 &breakpoint_set_cmdlist,
16872                                 &breakpoint_show_cmdlist);
16873
16874   pending_break_support = AUTO_BOOLEAN_AUTO;
16875
16876   add_setshow_boolean_cmd ("auto-hw", no_class,
16877                            &automatic_hardware_breakpoints, _("\
16878 Set automatic usage of hardware breakpoints."), _("\
16879 Show automatic usage of hardware breakpoints."), _("\
16880 If set, the debugger will automatically use hardware breakpoints for\n\
16881 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16882 a warning will be emitted for such breakpoints."),
16883                            NULL,
16884                            show_automatic_hardware_breakpoints,
16885                            &breakpoint_set_cmdlist,
16886                            &breakpoint_show_cmdlist);
16887
16888   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16889                                 &always_inserted_mode, _("\
16890 Set mode for inserting breakpoints."), _("\
16891 Show mode for inserting breakpoints."), _("\
16892 When this mode is off, breakpoints are inserted in inferior when it is\n\
16893 resumed, and removed when execution stops.  When this mode is on,\n\
16894 breakpoints are inserted immediately and removed only when the user\n\
16895 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16896 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16897 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16898 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16899 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16900                                 NULL,
16901                                 &show_always_inserted_mode,
16902                                 &breakpoint_set_cmdlist,
16903                                 &breakpoint_show_cmdlist);
16904
16905   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16906                         condition_evaluation_enums,
16907                         &condition_evaluation_mode_1, _("\
16908 Set mode of breakpoint condition evaluation."), _("\
16909 Show mode of breakpoint condition evaluation."), _("\
16910 When this is set to \"host\", breakpoint conditions will be\n\
16911 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16912 breakpoint conditions will be downloaded to the target (if the target\n\
16913 supports such feature) and conditions will be evaluated on the target's side.\n\
16914 If this is set to \"auto\" (default), this will be automatically set to\n\
16915 \"target\" if it supports condition evaluation, otherwise it will\n\
16916 be set to \"gdb\""),
16917                            &set_condition_evaluation_mode,
16918                            &show_condition_evaluation_mode,
16919                            &breakpoint_set_cmdlist,
16920                            &breakpoint_show_cmdlist);
16921
16922   add_com ("break-range", class_breakpoint, break_range_command, _("\
16923 Set a breakpoint for an address range.\n\
16924 break-range START-LOCATION, END-LOCATION\n\
16925 where START-LOCATION and END-LOCATION can be one of the following:\n\
16926   LINENUM, for that line in the current file,\n\
16927   FILE:LINENUM, for that line in that file,\n\
16928   +OFFSET, for that number of lines after the current line\n\
16929            or the start of the range\n\
16930   FUNCTION, for the first line in that function,\n\
16931   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16932   *ADDRESS, for the instruction at that address.\n\
16933 \n\
16934 The breakpoint will stop execution of the inferior whenever it executes\n\
16935 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16936 range (including START-LOCATION and END-LOCATION)."));
16937
16938   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16939 Set a dynamic printf at specified line or function.\n\
16940 dprintf location,format string,arg1,arg2,...\n\
16941 location may be a line number, function name, or \"*\" and an address.\n\
16942 If a line number is specified, break at start of code for that line.\n\
16943 If a function is specified, break at start of code for that function."));
16944   set_cmd_completer (c, location_completer);
16945
16946   add_setshow_enum_cmd ("dprintf-style", class_support,
16947                         dprintf_style_enums, &dprintf_style, _("\
16948 Set the style of usage for dynamic printf."), _("\
16949 Show the style of usage for dynamic printf."), _("\
16950 This setting chooses how GDB will do a dynamic printf.\n\
16951 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16952 console, as with the \"printf\" command.\n\
16953 If the value is \"call\", the print is done by calling a function in your\n\
16954 program; by default printf(), but you can choose a different function or\n\
16955 output stream by setting dprintf-function and dprintf-channel."),
16956                         update_dprintf_commands, NULL,
16957                         &setlist, &showlist);
16958
16959   dprintf_function = xstrdup ("printf");
16960   add_setshow_string_cmd ("dprintf-function", class_support,
16961                           &dprintf_function, _("\
16962 Set the function to use for dynamic printf"), _("\
16963 Show the function to use for dynamic printf"), NULL,
16964                           update_dprintf_commands, NULL,
16965                           &setlist, &showlist);
16966
16967   dprintf_channel = xstrdup ("");
16968   add_setshow_string_cmd ("dprintf-channel", class_support,
16969                           &dprintf_channel, _("\
16970 Set the channel to use for dynamic printf"), _("\
16971 Show the channel to use for dynamic printf"), NULL,
16972                           update_dprintf_commands, NULL,
16973                           &setlist, &showlist);
16974
16975   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16976                            &disconnected_dprintf, _("\
16977 Set whether dprintf continues after GDB disconnects."), _("\
16978 Show whether dprintf continues after GDB disconnects."), _("\
16979 Use this to let dprintf commands continue to hit and produce output\n\
16980 even if GDB disconnects or detaches from the target."),
16981                            NULL,
16982                            NULL,
16983                            &setlist, &showlist);
16984
16985   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16986 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16987 (target agent only) This is useful for formatted output in user-defined commands."));
16988
16989   automatic_hardware_breakpoints = 1;
16990
16991   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16992   observer_attach_thread_exit (remove_threaded_breakpoints);
16993 }