Only leave dprintf inserted if it is marked as persistent (PR breakpoints/17012)
[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 "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "block.h"
51 #include "solib.h"
52 #include "solist.h"
53 #include "observer.h"
54 #include "memattr.h"
55 #include "ada-lang.h"
56 #include "top.h"
57 #include "valprint.h"
58 #include "jit.h"
59 #include "xml-syscall.h"
60 #include "parser-defs.h"
61 #include "gdb_regex.h"
62 #include "probe.h"
63 #include "cli/cli-utils.h"
64 #include "continuations.h"
65 #include "stack.h"
66 #include "skip.h"
67 #include "ax-gdb.h"
68 #include "dummy-frame.h"
69
70 #include "format.h"
71
72 /* readline include files */
73 #include "readline/readline.h"
74 #include "readline/history.h"
75
76 /* readline defines this.  */
77 #undef savestring
78
79 #include "mi/mi-common.h"
80 #include "extension.h"
81
82 /* Enums for exception-handling support.  */
83 enum exception_event_kind
84 {
85   EX_EVENT_THROW,
86   EX_EVENT_RETHROW,
87   EX_EVENT_CATCH
88 };
89
90 /* Prototypes for local functions.  */
91
92 static void enable_delete_command (char *, int);
93
94 static void enable_once_command (char *, int);
95
96 static void enable_count_command (char *, int);
97
98 static void disable_command (char *, int);
99
100 static void enable_command (char *, int);
101
102 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
103                                                       void *),
104                                     void *);
105
106 static void ignore_command (char *, int);
107
108 static int breakpoint_re_set_one (void *);
109
110 static void breakpoint_re_set_default (struct breakpoint *);
111
112 static void create_sals_from_address_default (char **,
113                                               struct linespec_result *,
114                                               enum bptype, char *,
115                                               char **);
116
117 static void create_breakpoints_sal_default (struct gdbarch *,
118                                             struct linespec_result *,
119                                             char *, char *, enum bptype,
120                                             enum bpdisp, int, int,
121                                             int,
122                                             const struct breakpoint_ops *,
123                                             int, int, int, unsigned);
124
125 static void decode_linespec_default (struct breakpoint *, char **,
126                                      struct symtabs_and_lines *);
127
128 static void clear_command (char *, int);
129
130 static void catch_command (char *, int);
131
132 static int can_use_hardware_watchpoint (struct value *);
133
134 static void break_command_1 (char *, int, int);
135
136 static void mention (struct breakpoint *);
137
138 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
139                                                                enum bptype,
140                                                                const struct breakpoint_ops *);
141 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
142                                                        const struct symtab_and_line *);
143
144 /* This function is used in gdbtk sources and thus can not be made
145    static.  */
146 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
147                                        struct symtab_and_line,
148                                        enum bptype,
149                                        const struct breakpoint_ops *);
150
151 static struct breakpoint *
152   momentary_breakpoint_from_master (struct breakpoint *orig,
153                                     enum bptype type,
154                                     const struct breakpoint_ops *ops,
155                                     int loc_enabled);
156
157 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
158
159 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
160                                             CORE_ADDR bpaddr,
161                                             enum bptype bptype);
162
163 static void describe_other_breakpoints (struct gdbarch *,
164                                         struct program_space *, CORE_ADDR,
165                                         struct obj_section *, int);
166
167 static int watchpoint_locations_match (struct bp_location *loc1,
168                                        struct bp_location *loc2);
169
170 static int breakpoint_location_address_match (struct bp_location *bl,
171                                               struct address_space *aspace,
172                                               CORE_ADDR addr);
173
174 static void breakpoints_info (char *, int);
175
176 static void watchpoints_info (char *, int);
177
178 static int breakpoint_1 (char *, int, 
179                          int (*) (const struct breakpoint *));
180
181 static int breakpoint_cond_eval (void *);
182
183 static void cleanup_executing_breakpoints (void *);
184
185 static void commands_command (char *, int);
186
187 static void condition_command (char *, int);
188
189 typedef enum
190   {
191     mark_inserted,
192     mark_uninserted
193   }
194 insertion_state_t;
195
196 static int remove_breakpoint (struct bp_location *, insertion_state_t);
197 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
198
199 static enum print_stop_action print_bp_stop_message (bpstat bs);
200
201 static int watchpoint_check (void *);
202
203 static void maintenance_info_breakpoints (char *, int);
204
205 static int hw_breakpoint_used_count (void);
206
207 static int hw_watchpoint_use_count (struct breakpoint *);
208
209 static int hw_watchpoint_used_count_others (struct breakpoint *except,
210                                             enum bptype type,
211                                             int *other_type_used);
212
213 static void hbreak_command (char *, int);
214
215 static void thbreak_command (char *, int);
216
217 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
218                                     int count);
219
220 static void stop_command (char *arg, int from_tty);
221
222 static void stopin_command (char *arg, int from_tty);
223
224 static void stopat_command (char *arg, int from_tty);
225
226 static void tcatch_command (char *arg, int from_tty);
227
228 static void free_bp_location (struct bp_location *loc);
229 static void incref_bp_location (struct bp_location *loc);
230 static void decref_bp_location (struct bp_location **loc);
231
232 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
233
234 /* update_global_location_list's modes of operation wrt to whether to
235    insert locations now.  */
236 enum ugll_insert_mode
237 {
238   /* Don't insert any breakpoint locations into the inferior, only
239      remove already-inserted locations that no longer should be
240      inserted.  Functions that delete a breakpoint or breakpoints
241      should specify this mode, so that deleting a breakpoint doesn't
242      have the side effect of inserting the locations of other
243      breakpoints that are marked not-inserted, but should_be_inserted
244      returns true on them.
245
246      This behavior is useful is situations close to tear-down -- e.g.,
247      after an exec, while the target still has execution, but
248      breakpoint shadows of the previous executable image should *NOT*
249      be restored to the new image; or before detaching, where the
250      target still has execution and wants to delete breakpoints from
251      GDB's lists, and all breakpoints had already been removed from
252      the inferior.  */
253   UGLL_DONT_INSERT,
254
255   /* May insert breakpoints iff breakpoints_should_be_inserted_now
256      claims breakpoints should be inserted now.  */
257   UGLL_MAY_INSERT,
258
259   /* Insert locations now, irrespective of
260      breakpoints_should_be_inserted_now.  E.g., say all threads are
261      stopped right now, and the user did "continue".  We need to
262      insert breakpoints _before_ resuming the target, but
263      UGLL_MAY_INSERT wouldn't insert them, because
264      breakpoints_should_be_inserted_now returns false at that point,
265      as no thread is running yet.  */
266   UGLL_INSERT
267 };
268
269 static void update_global_location_list (enum ugll_insert_mode);
270
271 static void update_global_location_list_nothrow (enum ugll_insert_mode);
272
273 static int is_hardware_watchpoint (const struct breakpoint *bpt);
274
275 static void insert_breakpoint_locations (void);
276
277 static int syscall_catchpoint_p (struct breakpoint *b);
278
279 static void tracepoints_info (char *, int);
280
281 static void delete_trace_command (char *, int);
282
283 static void enable_trace_command (char *, int);
284
285 static void disable_trace_command (char *, int);
286
287 static void trace_pass_command (char *, int);
288
289 static void set_tracepoint_count (int num);
290
291 static int is_masked_watchpoint (const struct breakpoint *b);
292
293 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
294
295 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
296    otherwise.  */
297
298 static int strace_marker_p (struct breakpoint *b);
299
300 /* The abstract base class all breakpoint_ops structures inherit
301    from.  */
302 struct breakpoint_ops base_breakpoint_ops;
303
304 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
305    that are implemented on top of software or hardware breakpoints
306    (user breakpoints, internal and momentary breakpoints, etc.).  */
307 static struct breakpoint_ops bkpt_base_breakpoint_ops;
308
309 /* Internal breakpoints class type.  */
310 static struct breakpoint_ops internal_breakpoint_ops;
311
312 /* Momentary breakpoints class type.  */
313 static struct breakpoint_ops momentary_breakpoint_ops;
314
315 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
316 static struct breakpoint_ops longjmp_breakpoint_ops;
317
318 /* The breakpoint_ops structure to be used in regular user created
319    breakpoints.  */
320 struct breakpoint_ops bkpt_breakpoint_ops;
321
322 /* Breakpoints set on probes.  */
323 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
324
325 /* Dynamic printf class type.  */
326 struct breakpoint_ops dprintf_breakpoint_ops;
327
328 /* The style in which to perform a dynamic printf.  This is a user
329    option because different output options have different tradeoffs;
330    if GDB does the printing, there is better error handling if there
331    is a problem with any of the arguments, but using an inferior
332    function lets you have special-purpose printers and sending of
333    output to the same place as compiled-in print functions.  */
334
335 static const char dprintf_style_gdb[] = "gdb";
336 static const char dprintf_style_call[] = "call";
337 static const char dprintf_style_agent[] = "agent";
338 static const char *const dprintf_style_enums[] = {
339   dprintf_style_gdb,
340   dprintf_style_call,
341   dprintf_style_agent,
342   NULL
343 };
344 static const char *dprintf_style = dprintf_style_gdb;
345
346 /* The function to use for dynamic printf if the preferred style is to
347    call into the inferior.  The value is simply a string that is
348    copied into the command, so it can be anything that GDB can
349    evaluate to a callable address, not necessarily a function name.  */
350
351 static char *dprintf_function = "";
352
353 /* The channel to use for dynamic printf if the preferred style is to
354    call into the inferior; if a nonempty string, it will be passed to
355    the call as the first argument, with the format string as the
356    second.  As with the dprintf function, this can be anything that
357    GDB knows how to evaluate, so in addition to common choices like
358    "stderr", this could be an app-specific expression like
359    "mystreams[curlogger]".  */
360
361 static char *dprintf_channel = "";
362
363 /* True if dprintf commands should continue to operate even if GDB
364    has disconnected.  */
365 static int disconnected_dprintf = 1;
366
367 /* A reference-counted struct command_line.  This lets multiple
368    breakpoints share a single command list.  */
369 struct counted_command_line
370 {
371   /* The reference count.  */
372   int refc;
373
374   /* The command list.  */
375   struct command_line *commands;
376 };
377
378 struct command_line *
379 breakpoint_commands (struct breakpoint *b)
380 {
381   return b->commands ? b->commands->commands : NULL;
382 }
383
384 /* Flag indicating that a command has proceeded the inferior past the
385    current breakpoint.  */
386
387 static int breakpoint_proceeded;
388
389 const char *
390 bpdisp_text (enum bpdisp disp)
391 {
392   /* NOTE: the following values are a part of MI protocol and
393      represent values of 'disp' field returned when inferior stops at
394      a breakpoint.  */
395   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
396
397   return bpdisps[(int) disp];
398 }
399
400 /* Prototypes for exported functions.  */
401 /* If FALSE, gdb will not use hardware support for watchpoints, even
402    if such is available.  */
403 static int can_use_hw_watchpoints;
404
405 static void
406 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
407                              struct cmd_list_element *c,
408                              const char *value)
409 {
410   fprintf_filtered (file,
411                     _("Debugger's willingness to use "
412                       "watchpoint hardware is %s.\n"),
413                     value);
414 }
415
416 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
417    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
418    for unrecognized breakpoint locations.
419    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
420 static enum auto_boolean pending_break_support;
421 static void
422 show_pending_break_support (struct ui_file *file, int from_tty,
423                             struct cmd_list_element *c,
424                             const char *value)
425 {
426   fprintf_filtered (file,
427                     _("Debugger's behavior regarding "
428                       "pending breakpoints is %s.\n"),
429                     value);
430 }
431
432 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
433    set with "break" but falling in read-only memory.
434    If 0, gdb will warn about such breakpoints, but won't automatically
435    use hardware breakpoints.  */
436 static int automatic_hardware_breakpoints;
437 static void
438 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
439                                      struct cmd_list_element *c,
440                                      const char *value)
441 {
442   fprintf_filtered (file,
443                     _("Automatic usage of hardware breakpoints is %s.\n"),
444                     value);
445 }
446
447 /* If on, GDB keeps breakpoints inserted even if the inferior is
448    stopped, and immediately inserts any new breakpoints as soon as
449    they're created.  If off (default), GDB keeps breakpoints off of
450    the target as long as possible.  That is, it delays inserting
451    breakpoints until the next resume, and removes them again when the
452    target fully stops.  This is a bit safer in case GDB crashes while
453    processing user input.  */
454 static int always_inserted_mode = 0;
455
456 static void
457 show_always_inserted_mode (struct ui_file *file, int from_tty,
458                      struct cmd_list_element *c, const char *value)
459 {
460   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
461                     value);
462 }
463
464 /* See breakpoint.h.  */
465
466 int
467 breakpoints_should_be_inserted_now (void)
468 {
469   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
470     {
471       /* If breakpoints are global, they should be inserted even if no
472          thread under gdb's control is running, or even if there are
473          no threads under GDB's control yet.  */
474       return 1;
475     }
476   else if (target_has_execution)
477     {
478       if (always_inserted_mode)
479         {
480           /* The user wants breakpoints inserted even if all threads
481              are stopped.  */
482           return 1;
483         }
484
485       if (threads_are_executing ())
486         return 1;
487     }
488   return 0;
489 }
490
491 static const char condition_evaluation_both[] = "host or target";
492
493 /* Modes for breakpoint condition evaluation.  */
494 static const char condition_evaluation_auto[] = "auto";
495 static const char condition_evaluation_host[] = "host";
496 static const char condition_evaluation_target[] = "target";
497 static const char *const condition_evaluation_enums[] = {
498   condition_evaluation_auto,
499   condition_evaluation_host,
500   condition_evaluation_target,
501   NULL
502 };
503
504 /* Global that holds the current mode for breakpoint condition evaluation.  */
505 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
506
507 /* Global that we use to display information to the user (gets its value from
508    condition_evaluation_mode_1.  */
509 static const char *condition_evaluation_mode = condition_evaluation_auto;
510
511 /* Translate a condition evaluation mode MODE into either "host"
512    or "target".  This is used mostly to translate from "auto" to the
513    real setting that is being used.  It returns the translated
514    evaluation mode.  */
515
516 static const char *
517 translate_condition_evaluation_mode (const char *mode)
518 {
519   if (mode == condition_evaluation_auto)
520     {
521       if (target_supports_evaluation_of_breakpoint_conditions ())
522         return condition_evaluation_target;
523       else
524         return condition_evaluation_host;
525     }
526   else
527     return mode;
528 }
529
530 /* Discovers what condition_evaluation_auto translates to.  */
531
532 static const char *
533 breakpoint_condition_evaluation_mode (void)
534 {
535   return translate_condition_evaluation_mode (condition_evaluation_mode);
536 }
537
538 /* Return true if GDB should evaluate breakpoint conditions or false
539    otherwise.  */
540
541 static int
542 gdb_evaluates_breakpoint_condition_p (void)
543 {
544   const char *mode = breakpoint_condition_evaluation_mode ();
545
546   return (mode == condition_evaluation_host);
547 }
548
549 void _initialize_breakpoint (void);
550
551 /* Are we executing breakpoint commands?  */
552 static int executing_breakpoint_commands;
553
554 /* Are overlay event breakpoints enabled? */
555 static int overlay_events_enabled;
556
557 /* See description in breakpoint.h. */
558 int target_exact_watchpoints = 0;
559
560 /* Walk the following statement or block through all breakpoints.
561    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
562    current breakpoint.  */
563
564 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
565
566 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
567         for (B = breakpoint_chain;      \
568              B ? (TMP=B->next, 1): 0;   \
569              B = TMP)
570
571 /* Similar iterator for the low-level breakpoints.  SAFE variant is
572    not provided so update_global_location_list must not be called
573    while executing the block of ALL_BP_LOCATIONS.  */
574
575 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
576         for (BP_TMP = bp_location;                                      \
577              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
578              BP_TMP++)
579
580 /* Iterates through locations with address ADDRESS for the currently selected
581    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
582    to where the loop should start from.
583    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
584    appropriate location to start with.  */
585
586 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
587         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
588              BP_LOCP_TMP = BP_LOCP_START;                               \
589              BP_LOCP_START                                              \
590              && (BP_LOCP_TMP < bp_location + bp_location_count          \
591              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
592              BP_LOCP_TMP++)
593
594 /* Iterator for tracepoints only.  */
595
596 #define ALL_TRACEPOINTS(B)  \
597   for (B = breakpoint_chain; B; B = B->next)  \
598     if (is_tracepoint (B))
599
600 /* Chains of all breakpoints defined.  */
601
602 struct breakpoint *breakpoint_chain;
603
604 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
605
606 static struct bp_location **bp_location;
607
608 /* Number of elements of BP_LOCATION.  */
609
610 static unsigned bp_location_count;
611
612 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
613    ADDRESS for the current elements of BP_LOCATION which get a valid
614    result from bp_location_has_shadow.  You can use it for roughly
615    limiting the subrange of BP_LOCATION to scan for shadow bytes for
616    an address you need to read.  */
617
618 static CORE_ADDR bp_location_placed_address_before_address_max;
619
620 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
621    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
622    BP_LOCATION which get a valid result from bp_location_has_shadow.
623    You can use it for roughly limiting the subrange of BP_LOCATION to
624    scan for shadow bytes for an address you need to read.  */
625
626 static CORE_ADDR bp_location_shadow_len_after_address_max;
627
628 /* The locations that no longer correspond to any breakpoint, unlinked
629    from bp_location array, but for which a hit may still be reported
630    by a target.  */
631 VEC(bp_location_p) *moribund_locations = NULL;
632
633 /* Number of last breakpoint made.  */
634
635 static int breakpoint_count;
636
637 /* The value of `breakpoint_count' before the last command that
638    created breakpoints.  If the last (break-like) command created more
639    than one breakpoint, then the difference between BREAKPOINT_COUNT
640    and PREV_BREAKPOINT_COUNT is more than one.  */
641 static int prev_breakpoint_count;
642
643 /* Number of last tracepoint made.  */
644
645 static int tracepoint_count;
646
647 static struct cmd_list_element *breakpoint_set_cmdlist;
648 static struct cmd_list_element *breakpoint_show_cmdlist;
649 struct cmd_list_element *save_cmdlist;
650
651 /* Return whether a breakpoint is an active enabled breakpoint.  */
652 static int
653 breakpoint_enabled (struct breakpoint *b)
654 {
655   return (b->enable_state == bp_enabled);
656 }
657
658 /* Set breakpoint count to NUM.  */
659
660 static void
661 set_breakpoint_count (int num)
662 {
663   prev_breakpoint_count = breakpoint_count;
664   breakpoint_count = num;
665   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
666 }
667
668 /* Used by `start_rbreak_breakpoints' below, to record the current
669    breakpoint count before "rbreak" creates any breakpoint.  */
670 static int rbreak_start_breakpoint_count;
671
672 /* Called at the start an "rbreak" command to record the first
673    breakpoint made.  */
674
675 void
676 start_rbreak_breakpoints (void)
677 {
678   rbreak_start_breakpoint_count = breakpoint_count;
679 }
680
681 /* Called at the end of an "rbreak" command to record the last
682    breakpoint made.  */
683
684 void
685 end_rbreak_breakpoints (void)
686 {
687   prev_breakpoint_count = rbreak_start_breakpoint_count;
688 }
689
690 /* Used in run_command to zero the hit count when a new run starts.  */
691
692 void
693 clear_breakpoint_hit_counts (void)
694 {
695   struct breakpoint *b;
696
697   ALL_BREAKPOINTS (b)
698     b->hit_count = 0;
699 }
700
701 /* Allocate a new counted_command_line with reference count of 1.
702    The new structure owns COMMANDS.  */
703
704 static struct counted_command_line *
705 alloc_counted_command_line (struct command_line *commands)
706 {
707   struct counted_command_line *result
708     = xmalloc (sizeof (struct counted_command_line));
709
710   result->refc = 1;
711   result->commands = commands;
712   return result;
713 }
714
715 /* Increment reference count.  This does nothing if CMD is NULL.  */
716
717 static void
718 incref_counted_command_line (struct counted_command_line *cmd)
719 {
720   if (cmd)
721     ++cmd->refc;
722 }
723
724 /* Decrement reference count.  If the reference count reaches 0,
725    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
726    nothing if *CMDP is NULL.  */
727
728 static void
729 decref_counted_command_line (struct counted_command_line **cmdp)
730 {
731   if (*cmdp)
732     {
733       if (--(*cmdp)->refc == 0)
734         {
735           free_command_lines (&(*cmdp)->commands);
736           xfree (*cmdp);
737         }
738       *cmdp = NULL;
739     }
740 }
741
742 /* A cleanup function that calls decref_counted_command_line.  */
743
744 static void
745 do_cleanup_counted_command_line (void *arg)
746 {
747   decref_counted_command_line (arg);
748 }
749
750 /* Create a cleanup that calls decref_counted_command_line on the
751    argument.  */
752
753 static struct cleanup *
754 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
755 {
756   return make_cleanup (do_cleanup_counted_command_line, cmdp);
757 }
758
759 \f
760 /* Return the breakpoint with the specified number, or NULL
761    if the number does not refer to an existing breakpoint.  */
762
763 struct breakpoint *
764 get_breakpoint (int num)
765 {
766   struct breakpoint *b;
767
768   ALL_BREAKPOINTS (b)
769     if (b->number == num)
770       return b;
771   
772   return NULL;
773 }
774
775 \f
776
777 /* Mark locations as "conditions have changed" in case the target supports
778    evaluating conditions on its side.  */
779
780 static void
781 mark_breakpoint_modified (struct breakpoint *b)
782 {
783   struct bp_location *loc;
784
785   /* This is only meaningful if the target is
786      evaluating conditions and if the user has
787      opted for condition evaluation on the target's
788      side.  */
789   if (gdb_evaluates_breakpoint_condition_p ()
790       || !target_supports_evaluation_of_breakpoint_conditions ())
791     return;
792
793   if (!is_breakpoint (b))
794     return;
795
796   for (loc = b->loc; loc; loc = loc->next)
797     loc->condition_changed = condition_modified;
798 }
799
800 /* Mark location as "conditions have changed" in case the target supports
801    evaluating conditions on its side.  */
802
803 static void
804 mark_breakpoint_location_modified (struct bp_location *loc)
805 {
806   /* This is only meaningful if the target is
807      evaluating conditions and if the user has
808      opted for condition evaluation on the target's
809      side.  */
810   if (gdb_evaluates_breakpoint_condition_p ()
811       || !target_supports_evaluation_of_breakpoint_conditions ())
812
813     return;
814
815   if (!is_breakpoint (loc->owner))
816     return;
817
818   loc->condition_changed = condition_modified;
819 }
820
821 /* Sets the condition-evaluation mode using the static global
822    condition_evaluation_mode.  */
823
824 static void
825 set_condition_evaluation_mode (char *args, int from_tty,
826                                struct cmd_list_element *c)
827 {
828   const char *old_mode, *new_mode;
829
830   if ((condition_evaluation_mode_1 == condition_evaluation_target)
831       && !target_supports_evaluation_of_breakpoint_conditions ())
832     {
833       condition_evaluation_mode_1 = condition_evaluation_mode;
834       warning (_("Target does not support breakpoint condition evaluation.\n"
835                  "Using host evaluation mode instead."));
836       return;
837     }
838
839   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
840   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
841
842   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
843      settings was "auto".  */
844   condition_evaluation_mode = condition_evaluation_mode_1;
845
846   /* Only update the mode if the user picked a different one.  */
847   if (new_mode != old_mode)
848     {
849       struct bp_location *loc, **loc_tmp;
850       /* If the user switched to a different evaluation mode, we
851          need to synch the changes with the target as follows:
852
853          "host" -> "target": Send all (valid) conditions to the target.
854          "target" -> "host": Remove all the conditions from the target.
855       */
856
857       if (new_mode == condition_evaluation_target)
858         {
859           /* Mark everything modified and synch conditions with the
860              target.  */
861           ALL_BP_LOCATIONS (loc, loc_tmp)
862             mark_breakpoint_location_modified (loc);
863         }
864       else
865         {
866           /* Manually mark non-duplicate locations to synch conditions
867              with the target.  We do this to remove all the conditions the
868              target knows about.  */
869           ALL_BP_LOCATIONS (loc, loc_tmp)
870             if (is_breakpoint (loc->owner) && loc->inserted)
871               loc->needs_update = 1;
872         }
873
874       /* Do the update.  */
875       update_global_location_list (UGLL_MAY_INSERT);
876     }
877
878   return;
879 }
880
881 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
882    what "auto" is translating to.  */
883
884 static void
885 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
886                                 struct cmd_list_element *c, const char *value)
887 {
888   if (condition_evaluation_mode == condition_evaluation_auto)
889     fprintf_filtered (file,
890                       _("Breakpoint condition evaluation "
891                         "mode is %s (currently %s).\n"),
892                       value,
893                       breakpoint_condition_evaluation_mode ());
894   else
895     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
896                       value);
897 }
898
899 /* A comparison function for bp_location AP and BP that is used by
900    bsearch.  This comparison function only cares about addresses, unlike
901    the more general bp_location_compare function.  */
902
903 static int
904 bp_location_compare_addrs (const void *ap, const void *bp)
905 {
906   struct bp_location *a = *(void **) ap;
907   struct bp_location *b = *(void **) bp;
908
909   if (a->address == b->address)
910     return 0;
911   else
912     return ((a->address > b->address) - (a->address < b->address));
913 }
914
915 /* Helper function to skip all bp_locations with addresses
916    less than ADDRESS.  It returns the first bp_location that
917    is greater than or equal to ADDRESS.  If none is found, just
918    return NULL.  */
919
920 static struct bp_location **
921 get_first_locp_gte_addr (CORE_ADDR address)
922 {
923   struct bp_location dummy_loc;
924   struct bp_location *dummy_locp = &dummy_loc;
925   struct bp_location **locp_found = NULL;
926
927   /* Initialize the dummy location's address field.  */
928   memset (&dummy_loc, 0, sizeof (struct bp_location));
929   dummy_loc.address = address;
930
931   /* Find a close match to the first location at ADDRESS.  */
932   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
933                         sizeof (struct bp_location **),
934                         bp_location_compare_addrs);
935
936   /* Nothing was found, nothing left to do.  */
937   if (locp_found == NULL)
938     return NULL;
939
940   /* We may have found a location that is at ADDRESS but is not the first in the
941      location's list.  Go backwards (if possible) and locate the first one.  */
942   while ((locp_found - 1) >= bp_location
943          && (*(locp_found - 1))->address == address)
944     locp_found--;
945
946   return locp_found;
947 }
948
949 void
950 set_breakpoint_condition (struct breakpoint *b, char *exp,
951                           int from_tty)
952 {
953   xfree (b->cond_string);
954   b->cond_string = NULL;
955
956   if (is_watchpoint (b))
957     {
958       struct watchpoint *w = (struct watchpoint *) b;
959
960       xfree (w->cond_exp);
961       w->cond_exp = NULL;
962     }
963   else
964     {
965       struct bp_location *loc;
966
967       for (loc = b->loc; loc; loc = loc->next)
968         {
969           xfree (loc->cond);
970           loc->cond = NULL;
971
972           /* No need to free the condition agent expression
973              bytecode (if we have one).  We will handle this
974              when we go through update_global_location_list.  */
975         }
976     }
977
978   if (*exp == 0)
979     {
980       if (from_tty)
981         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
982     }
983   else
984     {
985       const char *arg = exp;
986
987       /* I don't know if it matters whether this is the string the user
988          typed in or the decompiled expression.  */
989       b->cond_string = xstrdup (arg);
990       b->condition_not_parsed = 0;
991
992       if (is_watchpoint (b))
993         {
994           struct watchpoint *w = (struct watchpoint *) b;
995
996           innermost_block = NULL;
997           arg = exp;
998           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
999           if (*arg)
1000             error (_("Junk at end of expression"));
1001           w->cond_exp_valid_block = innermost_block;
1002         }
1003       else
1004         {
1005           struct bp_location *loc;
1006
1007           for (loc = b->loc; loc; loc = loc->next)
1008             {
1009               arg = exp;
1010               loc->cond =
1011                 parse_exp_1 (&arg, loc->address,
1012                              block_for_pc (loc->address), 0);
1013               if (*arg)
1014                 error (_("Junk at end of expression"));
1015             }
1016         }
1017     }
1018   mark_breakpoint_modified (b);
1019
1020   observer_notify_breakpoint_modified (b);
1021 }
1022
1023 /* Completion for the "condition" command.  */
1024
1025 static VEC (char_ptr) *
1026 condition_completer (struct cmd_list_element *cmd,
1027                      const char *text, const char *word)
1028 {
1029   const char *space;
1030
1031   text = skip_spaces_const (text);
1032   space = skip_to_space_const (text);
1033   if (*space == '\0')
1034     {
1035       int len;
1036       struct breakpoint *b;
1037       VEC (char_ptr) *result = NULL;
1038
1039       if (text[0] == '$')
1040         {
1041           /* We don't support completion of history indices.  */
1042           if (isdigit (text[1]))
1043             return NULL;
1044           return complete_internalvar (&text[1]);
1045         }
1046
1047       /* We're completing the breakpoint number.  */
1048       len = strlen (text);
1049
1050       ALL_BREAKPOINTS (b)
1051         {
1052           char number[50];
1053
1054           xsnprintf (number, sizeof (number), "%d", b->number);
1055
1056           if (strncmp (number, text, len) == 0)
1057             VEC_safe_push (char_ptr, result, xstrdup (number));
1058         }
1059
1060       return result;
1061     }
1062
1063   /* We're completing the expression part.  */
1064   text = skip_spaces_const (space);
1065   return expression_completer (cmd, text, word);
1066 }
1067
1068 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1069
1070 static void
1071 condition_command (char *arg, int from_tty)
1072 {
1073   struct breakpoint *b;
1074   char *p;
1075   int bnum;
1076
1077   if (arg == 0)
1078     error_no_arg (_("breakpoint number"));
1079
1080   p = arg;
1081   bnum = get_number (&p);
1082   if (bnum == 0)
1083     error (_("Bad breakpoint argument: '%s'"), arg);
1084
1085   ALL_BREAKPOINTS (b)
1086     if (b->number == bnum)
1087       {
1088         /* Check if this breakpoint has a "stop" method implemented in an
1089            extension language.  This method and conditions entered into GDB
1090            from the CLI are mutually exclusive.  */
1091         const struct extension_language_defn *extlang
1092           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1093
1094         if (extlang != NULL)
1095           {
1096             error (_("Only one stop condition allowed.  There is currently"
1097                      " a %s stop condition defined for this breakpoint."),
1098                    ext_lang_capitalized_name (extlang));
1099           }
1100         set_breakpoint_condition (b, p, from_tty);
1101
1102         if (is_breakpoint (b))
1103           update_global_location_list (UGLL_MAY_INSERT);
1104
1105         return;
1106       }
1107
1108   error (_("No breakpoint number %d."), bnum);
1109 }
1110
1111 /* Check that COMMAND do not contain commands that are suitable
1112    only for tracepoints and not suitable for ordinary breakpoints.
1113    Throw if any such commands is found.  */
1114
1115 static void
1116 check_no_tracepoint_commands (struct command_line *commands)
1117 {
1118   struct command_line *c;
1119
1120   for (c = commands; c; c = c->next)
1121     {
1122       int i;
1123
1124       if (c->control_type == while_stepping_control)
1125         error (_("The 'while-stepping' command can "
1126                  "only be used for tracepoints"));
1127
1128       for (i = 0; i < c->body_count; ++i)
1129         check_no_tracepoint_commands ((c->body_list)[i]);
1130
1131       /* Not that command parsing removes leading whitespace and comment
1132          lines and also empty lines.  So, we only need to check for
1133          command directly.  */
1134       if (strstr (c->line, "collect ") == c->line)
1135         error (_("The 'collect' command can only be used for tracepoints"));
1136
1137       if (strstr (c->line, "teval ") == c->line)
1138         error (_("The 'teval' command can only be used for tracepoints"));
1139     }
1140 }
1141
1142 /* Encapsulate tests for different types of tracepoints.  */
1143
1144 static int
1145 is_tracepoint_type (enum bptype type)
1146 {
1147   return (type == bp_tracepoint
1148           || type == bp_fast_tracepoint
1149           || type == bp_static_tracepoint);
1150 }
1151
1152 int
1153 is_tracepoint (const struct breakpoint *b)
1154 {
1155   return is_tracepoint_type (b->type);
1156 }
1157
1158 /* A helper function that validates that COMMANDS are valid for a
1159    breakpoint.  This function will throw an exception if a problem is
1160    found.  */
1161
1162 static void
1163 validate_commands_for_breakpoint (struct breakpoint *b,
1164                                   struct command_line *commands)
1165 {
1166   if (is_tracepoint (b))
1167     {
1168       struct tracepoint *t = (struct tracepoint *) b;
1169       struct command_line *c;
1170       struct command_line *while_stepping = 0;
1171
1172       /* Reset the while-stepping step count.  The previous commands
1173          might have included a while-stepping action, while the new
1174          ones might not.  */
1175       t->step_count = 0;
1176
1177       /* We need to verify that each top-level element of commands is
1178          valid for tracepoints, that there's at most one
1179          while-stepping element, and that the while-stepping's body
1180          has valid tracing commands excluding nested while-stepping.
1181          We also need to validate the tracepoint action line in the
1182          context of the tracepoint --- validate_actionline actually
1183          has side effects, like setting the tracepoint's
1184          while-stepping STEP_COUNT, in addition to checking if the
1185          collect/teval actions parse and make sense in the
1186          tracepoint's context.  */
1187       for (c = commands; c; c = c->next)
1188         {
1189           if (c->control_type == while_stepping_control)
1190             {
1191               if (b->type == bp_fast_tracepoint)
1192                 error (_("The 'while-stepping' command "
1193                          "cannot be used for fast tracepoint"));
1194               else if (b->type == bp_static_tracepoint)
1195                 error (_("The 'while-stepping' command "
1196                          "cannot be used for static tracepoint"));
1197
1198               if (while_stepping)
1199                 error (_("The 'while-stepping' command "
1200                          "can be used only once"));
1201               else
1202                 while_stepping = c;
1203             }
1204
1205           validate_actionline (c->line, b);
1206         }
1207       if (while_stepping)
1208         {
1209           struct command_line *c2;
1210
1211           gdb_assert (while_stepping->body_count == 1);
1212           c2 = while_stepping->body_list[0];
1213           for (; c2; c2 = c2->next)
1214             {
1215               if (c2->control_type == while_stepping_control)
1216                 error (_("The 'while-stepping' command cannot be nested"));
1217             }
1218         }
1219     }
1220   else
1221     {
1222       check_no_tracepoint_commands (commands);
1223     }
1224 }
1225
1226 /* Return a vector of all the static tracepoints set at ADDR.  The
1227    caller is responsible for releasing the vector.  */
1228
1229 VEC(breakpoint_p) *
1230 static_tracepoints_here (CORE_ADDR addr)
1231 {
1232   struct breakpoint *b;
1233   VEC(breakpoint_p) *found = 0;
1234   struct bp_location *loc;
1235
1236   ALL_BREAKPOINTS (b)
1237     if (b->type == bp_static_tracepoint)
1238       {
1239         for (loc = b->loc; loc; loc = loc->next)
1240           if (loc->address == addr)
1241             VEC_safe_push(breakpoint_p, found, b);
1242       }
1243
1244   return found;
1245 }
1246
1247 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1248    validate that only allowed commands are included.  */
1249
1250 void
1251 breakpoint_set_commands (struct breakpoint *b, 
1252                          struct command_line *commands)
1253 {
1254   validate_commands_for_breakpoint (b, commands);
1255
1256   decref_counted_command_line (&b->commands);
1257   b->commands = alloc_counted_command_line (commands);
1258   observer_notify_breakpoint_modified (b);
1259 }
1260
1261 /* Set the internal `silent' flag on the breakpoint.  Note that this
1262    is not the same as the "silent" that may appear in the breakpoint's
1263    commands.  */
1264
1265 void
1266 breakpoint_set_silent (struct breakpoint *b, int silent)
1267 {
1268   int old_silent = b->silent;
1269
1270   b->silent = silent;
1271   if (old_silent != silent)
1272     observer_notify_breakpoint_modified (b);
1273 }
1274
1275 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1276    breakpoint work for any thread.  */
1277
1278 void
1279 breakpoint_set_thread (struct breakpoint *b, int thread)
1280 {
1281   int old_thread = b->thread;
1282
1283   b->thread = thread;
1284   if (old_thread != thread)
1285     observer_notify_breakpoint_modified (b);
1286 }
1287
1288 /* Set the task for this breakpoint.  If TASK is 0, make the
1289    breakpoint work for any task.  */
1290
1291 void
1292 breakpoint_set_task (struct breakpoint *b, int task)
1293 {
1294   int old_task = b->task;
1295
1296   b->task = task;
1297   if (old_task != task)
1298     observer_notify_breakpoint_modified (b);
1299 }
1300
1301 void
1302 check_tracepoint_command (char *line, void *closure)
1303 {
1304   struct breakpoint *b = closure;
1305
1306   validate_actionline (line, b);
1307 }
1308
1309 /* A structure used to pass information through
1310    map_breakpoint_numbers.  */
1311
1312 struct commands_info
1313 {
1314   /* True if the command was typed at a tty.  */
1315   int from_tty;
1316
1317   /* The breakpoint range spec.  */
1318   char *arg;
1319
1320   /* Non-NULL if the body of the commands are being read from this
1321      already-parsed command.  */
1322   struct command_line *control;
1323
1324   /* The command lines read from the user, or NULL if they have not
1325      yet been read.  */
1326   struct counted_command_line *cmd;
1327 };
1328
1329 /* A callback for map_breakpoint_numbers that sets the commands for
1330    commands_command.  */
1331
1332 static void
1333 do_map_commands_command (struct breakpoint *b, void *data)
1334 {
1335   struct commands_info *info = data;
1336
1337   if (info->cmd == NULL)
1338     {
1339       struct command_line *l;
1340
1341       if (info->control != NULL)
1342         l = copy_command_lines (info->control->body_list[0]);
1343       else
1344         {
1345           struct cleanup *old_chain;
1346           char *str;
1347
1348           str = xstrprintf (_("Type commands for breakpoint(s) "
1349                               "%s, one per line."),
1350                             info->arg);
1351
1352           old_chain = make_cleanup (xfree, str);
1353
1354           l = read_command_lines (str,
1355                                   info->from_tty, 1,
1356                                   (is_tracepoint (b)
1357                                    ? check_tracepoint_command : 0),
1358                                   b);
1359
1360           do_cleanups (old_chain);
1361         }
1362
1363       info->cmd = alloc_counted_command_line (l);
1364     }
1365
1366   /* If a breakpoint was on the list more than once, we don't need to
1367      do anything.  */
1368   if (b->commands != info->cmd)
1369     {
1370       validate_commands_for_breakpoint (b, info->cmd->commands);
1371       incref_counted_command_line (info->cmd);
1372       decref_counted_command_line (&b->commands);
1373       b->commands = info->cmd;
1374       observer_notify_breakpoint_modified (b);
1375     }
1376 }
1377
1378 static void
1379 commands_command_1 (char *arg, int from_tty, 
1380                     struct command_line *control)
1381 {
1382   struct cleanup *cleanups;
1383   struct commands_info info;
1384
1385   info.from_tty = from_tty;
1386   info.control = control;
1387   info.cmd = NULL;
1388   /* If we read command lines from the user, then `info' will hold an
1389      extra reference to the commands that we must clean up.  */
1390   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1391
1392   if (arg == NULL || !*arg)
1393     {
1394       if (breakpoint_count - prev_breakpoint_count > 1)
1395         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1396                           breakpoint_count);
1397       else if (breakpoint_count > 0)
1398         arg = xstrprintf ("%d", breakpoint_count);
1399       else
1400         {
1401           /* So that we don't try to free the incoming non-NULL
1402              argument in the cleanup below.  Mapping breakpoint
1403              numbers will fail in this case.  */
1404           arg = NULL;
1405         }
1406     }
1407   else
1408     /* The command loop has some static state, so we need to preserve
1409        our argument.  */
1410     arg = xstrdup (arg);
1411
1412   if (arg != NULL)
1413     make_cleanup (xfree, arg);
1414
1415   info.arg = arg;
1416
1417   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1418
1419   if (info.cmd == NULL)
1420     error (_("No breakpoints specified."));
1421
1422   do_cleanups (cleanups);
1423 }
1424
1425 static void
1426 commands_command (char *arg, int from_tty)
1427 {
1428   commands_command_1 (arg, from_tty, NULL);
1429 }
1430
1431 /* Like commands_command, but instead of reading the commands from
1432    input stream, takes them from an already parsed command structure.
1433
1434    This is used by cli-script.c to DTRT with breakpoint commands
1435    that are part of if and while bodies.  */
1436 enum command_control_type
1437 commands_from_control_command (char *arg, struct command_line *cmd)
1438 {
1439   commands_command_1 (arg, 0, cmd);
1440   return simple_control;
1441 }
1442
1443 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1444
1445 static int
1446 bp_location_has_shadow (struct bp_location *bl)
1447 {
1448   if (bl->loc_type != bp_loc_software_breakpoint)
1449     return 0;
1450   if (!bl->inserted)
1451     return 0;
1452   if (bl->target_info.shadow_len == 0)
1453     /* BL isn't valid, or doesn't shadow memory.  */
1454     return 0;
1455   return 1;
1456 }
1457
1458 /* Update BUF, which is LEN bytes read from the target address
1459    MEMADDR, by replacing a memory breakpoint with its shadowed
1460    contents.
1461
1462    If READBUF is not NULL, this buffer must not overlap with the of
1463    the breakpoint location's shadow_contents buffer.  Otherwise, a
1464    failed assertion internal error will be raised.  */
1465
1466 static void
1467 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1468                             const gdb_byte *writebuf_org,
1469                             ULONGEST memaddr, LONGEST len,
1470                             struct bp_target_info *target_info,
1471                             struct gdbarch *gdbarch)
1472 {
1473   /* Now do full processing of the found relevant range of elements.  */
1474   CORE_ADDR bp_addr = 0;
1475   int bp_size = 0;
1476   int bptoffset = 0;
1477
1478   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1479                                  current_program_space->aspace, 0))
1480     {
1481       /* The breakpoint is inserted in a different address space.  */
1482       return;
1483     }
1484
1485   /* Addresses and length of the part of the breakpoint that
1486      we need to copy.  */
1487   bp_addr = target_info->placed_address;
1488   bp_size = target_info->shadow_len;
1489
1490   if (bp_addr + bp_size <= memaddr)
1491     {
1492       /* The breakpoint is entirely before the chunk of memory we are
1493          reading.  */
1494       return;
1495     }
1496
1497   if (bp_addr >= memaddr + len)
1498     {
1499       /* The breakpoint is entirely after the chunk of memory we are
1500          reading.  */
1501       return;
1502     }
1503
1504   /* Offset within shadow_contents.  */
1505   if (bp_addr < memaddr)
1506     {
1507       /* Only copy the second part of the breakpoint.  */
1508       bp_size -= memaddr - bp_addr;
1509       bptoffset = memaddr - bp_addr;
1510       bp_addr = memaddr;
1511     }
1512
1513   if (bp_addr + bp_size > memaddr + len)
1514     {
1515       /* Only copy the first part of the breakpoint.  */
1516       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1517     }
1518
1519   if (readbuf != NULL)
1520     {
1521       /* Verify that the readbuf buffer does not overlap with the
1522          shadow_contents buffer.  */
1523       gdb_assert (target_info->shadow_contents >= readbuf + len
1524                   || readbuf >= (target_info->shadow_contents
1525                                  + target_info->shadow_len));
1526
1527       /* Update the read buffer with this inserted breakpoint's
1528          shadow.  */
1529       memcpy (readbuf + bp_addr - memaddr,
1530               target_info->shadow_contents + bptoffset, bp_size);
1531     }
1532   else
1533     {
1534       const unsigned char *bp;
1535       CORE_ADDR addr = target_info->reqstd_address;
1536       int placed_size;
1537
1538       /* Update the shadow with what we want to write to memory.  */
1539       memcpy (target_info->shadow_contents + bptoffset,
1540               writebuf_org + bp_addr - memaddr, bp_size);
1541
1542       /* Determine appropriate breakpoint contents and size for this
1543          address.  */
1544       bp = gdbarch_breakpoint_from_pc (gdbarch, &addr, &placed_size);
1545
1546       /* Update the final write buffer with this inserted
1547          breakpoint's INSN.  */
1548       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1549     }
1550 }
1551
1552 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1553    by replacing any memory breakpoints with their shadowed contents.
1554
1555    If READBUF is not NULL, this buffer must not overlap with any of
1556    the breakpoint location's shadow_contents buffers.  Otherwise,
1557    a failed assertion internal error will be raised.
1558
1559    The range of shadowed area by each bp_location is:
1560      bl->address - bp_location_placed_address_before_address_max
1561      up to bl->address + bp_location_shadow_len_after_address_max
1562    The range we were requested to resolve shadows for is:
1563      memaddr ... memaddr + len
1564    Thus the safe cutoff boundaries for performance optimization are
1565      memaddr + len <= (bl->address
1566                        - bp_location_placed_address_before_address_max)
1567    and:
1568      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1569
1570 void
1571 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1572                         const gdb_byte *writebuf_org,
1573                         ULONGEST memaddr, LONGEST len)
1574 {
1575   /* Left boundary, right boundary and median element of our binary
1576      search.  */
1577   unsigned bc_l, bc_r, bc;
1578   size_t i;
1579
1580   /* Find BC_L which is a leftmost element which may affect BUF
1581      content.  It is safe to report lower value but a failure to
1582      report higher one.  */
1583
1584   bc_l = 0;
1585   bc_r = bp_location_count;
1586   while (bc_l + 1 < bc_r)
1587     {
1588       struct bp_location *bl;
1589
1590       bc = (bc_l + bc_r) / 2;
1591       bl = bp_location[bc];
1592
1593       /* Check first BL->ADDRESS will not overflow due to the added
1594          constant.  Then advance the left boundary only if we are sure
1595          the BC element can in no way affect the BUF content (MEMADDR
1596          to MEMADDR + LEN range).
1597
1598          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1599          offset so that we cannot miss a breakpoint with its shadow
1600          range tail still reaching MEMADDR.  */
1601
1602       if ((bl->address + bp_location_shadow_len_after_address_max
1603            >= bl->address)
1604           && (bl->address + bp_location_shadow_len_after_address_max
1605               <= memaddr))
1606         bc_l = bc;
1607       else
1608         bc_r = bc;
1609     }
1610
1611   /* Due to the binary search above, we need to make sure we pick the
1612      first location that's at BC_L's address.  E.g., if there are
1613      multiple locations at the same address, BC_L may end up pointing
1614      at a duplicate location, and miss the "master"/"inserted"
1615      location.  Say, given locations L1, L2 and L3 at addresses A and
1616      B:
1617
1618       L1@A, L2@A, L3@B, ...
1619
1620      BC_L could end up pointing at location L2, while the "master"
1621      location could be L1.  Since the `loc->inserted' flag is only set
1622      on "master" locations, we'd forget to restore the shadow of L1
1623      and L2.  */
1624   while (bc_l > 0
1625          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1626     bc_l--;
1627
1628   /* Now do full processing of the found relevant range of elements.  */
1629
1630   for (bc = bc_l; bc < bp_location_count; bc++)
1631   {
1632     struct bp_location *bl = bp_location[bc];
1633     CORE_ADDR bp_addr = 0;
1634     int bp_size = 0;
1635     int bptoffset = 0;
1636
1637     /* bp_location array has BL->OWNER always non-NULL.  */
1638     if (bl->owner->type == bp_none)
1639       warning (_("reading through apparently deleted breakpoint #%d?"),
1640                bl->owner->number);
1641
1642     /* Performance optimization: any further element can no longer affect BUF
1643        content.  */
1644
1645     if (bl->address >= bp_location_placed_address_before_address_max
1646         && memaddr + len <= (bl->address
1647                              - bp_location_placed_address_before_address_max))
1648       break;
1649
1650     if (!bp_location_has_shadow (bl))
1651       continue;
1652
1653     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1654                                 memaddr, len, &bl->target_info, bl->gdbarch);
1655   }
1656 }
1657
1658 \f
1659
1660 /* Return true if BPT is either a software breakpoint or a hardware
1661    breakpoint.  */
1662
1663 int
1664 is_breakpoint (const struct breakpoint *bpt)
1665 {
1666   return (bpt->type == bp_breakpoint
1667           || bpt->type == bp_hardware_breakpoint
1668           || bpt->type == bp_dprintf);
1669 }
1670
1671 /* Return true if BPT is of any hardware watchpoint kind.  */
1672
1673 static int
1674 is_hardware_watchpoint (const struct breakpoint *bpt)
1675 {
1676   return (bpt->type == bp_hardware_watchpoint
1677           || bpt->type == bp_read_watchpoint
1678           || bpt->type == bp_access_watchpoint);
1679 }
1680
1681 /* Return true if BPT is of any watchpoint kind, hardware or
1682    software.  */
1683
1684 int
1685 is_watchpoint (const struct breakpoint *bpt)
1686 {
1687   return (is_hardware_watchpoint (bpt)
1688           || bpt->type == bp_watchpoint);
1689 }
1690
1691 /* Returns true if the current thread and its running state are safe
1692    to evaluate or update watchpoint B.  Watchpoints on local
1693    expressions need to be evaluated in the context of the thread that
1694    was current when the watchpoint was created, and, that thread needs
1695    to be stopped to be able to select the correct frame context.
1696    Watchpoints on global expressions can be evaluated on any thread,
1697    and in any state.  It is presently left to the target allowing
1698    memory accesses when threads are running.  */
1699
1700 static int
1701 watchpoint_in_thread_scope (struct watchpoint *b)
1702 {
1703   return (b->base.pspace == current_program_space
1704           && (ptid_equal (b->watchpoint_thread, null_ptid)
1705               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1706                   && !is_executing (inferior_ptid))));
1707 }
1708
1709 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1710    associated bp_watchpoint_scope breakpoint.  */
1711
1712 static void
1713 watchpoint_del_at_next_stop (struct watchpoint *w)
1714 {
1715   struct breakpoint *b = &w->base;
1716
1717   if (b->related_breakpoint != b)
1718     {
1719       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1720       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1721       b->related_breakpoint->disposition = disp_del_at_next_stop;
1722       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1723       b->related_breakpoint = b;
1724     }
1725   b->disposition = disp_del_at_next_stop;
1726 }
1727
1728 /* Extract a bitfield value from value VAL using the bit parameters contained in
1729    watchpoint W.  */
1730
1731 static struct value *
1732 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1733 {
1734   struct value *bit_val;
1735
1736   if (val == NULL)
1737     return NULL;
1738
1739   bit_val = allocate_value (value_type (val));
1740
1741   unpack_value_bitfield (bit_val,
1742                          w->val_bitpos,
1743                          w->val_bitsize,
1744                          value_contents_for_printing (val),
1745                          value_offset (val),
1746                          val);
1747
1748   return bit_val;
1749 }
1750
1751 /* Assuming that B is a watchpoint:
1752    - Reparse watchpoint expression, if REPARSE is non-zero
1753    - Evaluate expression and store the result in B->val
1754    - Evaluate the condition if there is one, and store the result
1755      in b->loc->cond.
1756    - Update the list of values that must be watched in B->loc.
1757
1758    If the watchpoint disposition is disp_del_at_next_stop, then do
1759    nothing.  If this is local watchpoint that is out of scope, delete
1760    it.
1761
1762    Even with `set breakpoint always-inserted on' the watchpoints are
1763    removed + inserted on each stop here.  Normal breakpoints must
1764    never be removed because they might be missed by a running thread
1765    when debugging in non-stop mode.  On the other hand, hardware
1766    watchpoints (is_hardware_watchpoint; processed here) are specific
1767    to each LWP since they are stored in each LWP's hardware debug
1768    registers.  Therefore, such LWP must be stopped first in order to
1769    be able to modify its hardware watchpoints.
1770
1771    Hardware watchpoints must be reset exactly once after being
1772    presented to the user.  It cannot be done sooner, because it would
1773    reset the data used to present the watchpoint hit to the user.  And
1774    it must not be done later because it could display the same single
1775    watchpoint hit during multiple GDB stops.  Note that the latter is
1776    relevant only to the hardware watchpoint types bp_read_watchpoint
1777    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1778    not user-visible - its hit is suppressed if the memory content has
1779    not changed.
1780
1781    The following constraints influence the location where we can reset
1782    hardware watchpoints:
1783
1784    * target_stopped_by_watchpoint and target_stopped_data_address are
1785      called several times when GDB stops.
1786
1787    [linux] 
1788    * Multiple hardware watchpoints can be hit at the same time,
1789      causing GDB to stop.  GDB only presents one hardware watchpoint
1790      hit at a time as the reason for stopping, and all the other hits
1791      are presented later, one after the other, each time the user
1792      requests the execution to be resumed.  Execution is not resumed
1793      for the threads still having pending hit event stored in
1794      LWP_INFO->STATUS.  While the watchpoint is already removed from
1795      the inferior on the first stop the thread hit event is kept being
1796      reported from its cached value by linux_nat_stopped_data_address
1797      until the real thread resume happens after the watchpoint gets
1798      presented and thus its LWP_INFO->STATUS gets reset.
1799
1800    Therefore the hardware watchpoint hit can get safely reset on the
1801    watchpoint removal from inferior.  */
1802
1803 static void
1804 update_watchpoint (struct watchpoint *b, int reparse)
1805 {
1806   int within_current_scope;
1807   struct frame_id saved_frame_id;
1808   int frame_saved;
1809
1810   /* If this is a local watchpoint, we only want to check if the
1811      watchpoint frame is in scope if the current thread is the thread
1812      that was used to create the watchpoint.  */
1813   if (!watchpoint_in_thread_scope (b))
1814     return;
1815
1816   if (b->base.disposition == disp_del_at_next_stop)
1817     return;
1818  
1819   frame_saved = 0;
1820
1821   /* Determine if the watchpoint is within scope.  */
1822   if (b->exp_valid_block == NULL)
1823     within_current_scope = 1;
1824   else
1825     {
1826       struct frame_info *fi = get_current_frame ();
1827       struct gdbarch *frame_arch = get_frame_arch (fi);
1828       CORE_ADDR frame_pc = get_frame_pc (fi);
1829
1830       /* If we're in a function epilogue, unwinding may not work
1831          properly, so do not attempt to recreate locations at this
1832          point.  See similar comments in watchpoint_check.  */
1833       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1834         return;
1835
1836       /* Save the current frame's ID so we can restore it after
1837          evaluating the watchpoint expression on its own frame.  */
1838       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1839          took a frame parameter, so that we didn't have to change the
1840          selected frame.  */
1841       frame_saved = 1;
1842       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1843
1844       fi = frame_find_by_id (b->watchpoint_frame);
1845       within_current_scope = (fi != NULL);
1846       if (within_current_scope)
1847         select_frame (fi);
1848     }
1849
1850   /* We don't free locations.  They are stored in the bp_location array
1851      and update_global_location_list will eventually delete them and
1852      remove breakpoints if needed.  */
1853   b->base.loc = NULL;
1854
1855   if (within_current_scope && reparse)
1856     {
1857       const char *s;
1858
1859       if (b->exp)
1860         {
1861           xfree (b->exp);
1862           b->exp = NULL;
1863         }
1864       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1865       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1866       /* If the meaning of expression itself changed, the old value is
1867          no longer relevant.  We don't want to report a watchpoint hit
1868          to the user when the old value and the new value may actually
1869          be completely different objects.  */
1870       value_free (b->val);
1871       b->val = NULL;
1872       b->val_valid = 0;
1873
1874       /* Note that unlike with breakpoints, the watchpoint's condition
1875          expression is stored in the breakpoint object, not in the
1876          locations (re)created below.  */
1877       if (b->base.cond_string != NULL)
1878         {
1879           if (b->cond_exp != NULL)
1880             {
1881               xfree (b->cond_exp);
1882               b->cond_exp = NULL;
1883             }
1884
1885           s = b->base.cond_string;
1886           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1887         }
1888     }
1889
1890   /* If we failed to parse the expression, for example because
1891      it refers to a global variable in a not-yet-loaded shared library,
1892      don't try to insert watchpoint.  We don't automatically delete
1893      such watchpoint, though, since failure to parse expression
1894      is different from out-of-scope watchpoint.  */
1895   if (!target_has_execution)
1896     {
1897       /* Without execution, memory can't change.  No use to try and
1898          set watchpoint locations.  The watchpoint will be reset when
1899          the target gains execution, through breakpoint_re_set.  */
1900       if (!can_use_hw_watchpoints)
1901         {
1902           if (b->base.ops->works_in_software_mode (&b->base))
1903             b->base.type = bp_watchpoint;
1904           else
1905             error (_("Can't set read/access watchpoint when "
1906                      "hardware watchpoints are disabled."));
1907         }
1908     }
1909   else if (within_current_scope && b->exp)
1910     {
1911       int pc = 0;
1912       struct value *val_chain, *v, *result, *next;
1913       struct program_space *frame_pspace;
1914
1915       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1916
1917       /* Avoid setting b->val if it's already set.  The meaning of
1918          b->val is 'the last value' user saw, and we should update
1919          it only if we reported that last value to user.  As it
1920          happens, the code that reports it updates b->val directly.
1921          We don't keep track of the memory value for masked
1922          watchpoints.  */
1923       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1924         {
1925           if (b->val_bitsize != 0)
1926             {
1927               v = extract_bitfield_from_watchpoint_value (b, v);
1928               if (v != NULL)
1929                 release_value (v);
1930             }
1931           b->val = v;
1932           b->val_valid = 1;
1933         }
1934
1935       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1936
1937       /* Look at each value on the value chain.  */
1938       for (v = val_chain; v; v = value_next (v))
1939         {
1940           /* If it's a memory location, and GDB actually needed
1941              its contents to evaluate the expression, then we
1942              must watch it.  If the first value returned is
1943              still lazy, that means an error occurred reading it;
1944              watch it anyway in case it becomes readable.  */
1945           if (VALUE_LVAL (v) == lval_memory
1946               && (v == val_chain || ! value_lazy (v)))
1947             {
1948               struct type *vtype = check_typedef (value_type (v));
1949
1950               /* We only watch structs and arrays if user asked
1951                  for it explicitly, never if they just happen to
1952                  appear in the middle of some value chain.  */
1953               if (v == result
1954                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1955                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1956                 {
1957                   CORE_ADDR addr;
1958                   int type;
1959                   struct bp_location *loc, **tmp;
1960                   int bitpos = 0, bitsize = 0;
1961
1962                   if (value_bitsize (v) != 0)
1963                     {
1964                       /* Extract the bit parameters out from the bitfield
1965                          sub-expression.  */
1966                       bitpos = value_bitpos (v);
1967                       bitsize = value_bitsize (v);
1968                     }
1969                   else if (v == result && b->val_bitsize != 0)
1970                     {
1971                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
1972                         lvalue whose bit parameters are saved in the fields
1973                         VAL_BITPOS and VAL_BITSIZE.  */
1974                       bitpos = b->val_bitpos;
1975                       bitsize = b->val_bitsize;
1976                     }
1977
1978                   addr = value_address (v);
1979                   if (bitsize != 0)
1980                     {
1981                       /* Skip the bytes that don't contain the bitfield.  */
1982                       addr += bitpos / 8;
1983                     }
1984
1985                   type = hw_write;
1986                   if (b->base.type == bp_read_watchpoint)
1987                     type = hw_read;
1988                   else if (b->base.type == bp_access_watchpoint)
1989                     type = hw_access;
1990
1991                   loc = allocate_bp_location (&b->base);
1992                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1993                     ;
1994                   *tmp = loc;
1995                   loc->gdbarch = get_type_arch (value_type (v));
1996
1997                   loc->pspace = frame_pspace;
1998                   loc->address = addr;
1999
2000                   if (bitsize != 0)
2001                     {
2002                       /* Just cover the bytes that make up the bitfield.  */
2003                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2004                     }
2005                   else
2006                     loc->length = TYPE_LENGTH (value_type (v));
2007
2008                   loc->watchpoint_type = type;
2009                 }
2010             }
2011         }
2012
2013       /* Change the type of breakpoint between hardware assisted or
2014          an ordinary watchpoint depending on the hardware support
2015          and free hardware slots.  REPARSE is set when the inferior
2016          is started.  */
2017       if (reparse)
2018         {
2019           int reg_cnt;
2020           enum bp_loc_type loc_type;
2021           struct bp_location *bl;
2022
2023           reg_cnt = can_use_hardware_watchpoint (val_chain);
2024
2025           if (reg_cnt)
2026             {
2027               int i, target_resources_ok, other_type_used;
2028               enum bptype type;
2029
2030               /* Use an exact watchpoint when there's only one memory region to be
2031                  watched, and only one debug register is needed to watch it.  */
2032               b->exact = target_exact_watchpoints && reg_cnt == 1;
2033
2034               /* We need to determine how many resources are already
2035                  used for all other hardware watchpoints plus this one
2036                  to see if we still have enough resources to also fit
2037                  this watchpoint in as well.  */
2038
2039               /* If this is a software watchpoint, we try to turn it
2040                  to a hardware one -- count resources as if B was of
2041                  hardware watchpoint type.  */
2042               type = b->base.type;
2043               if (type == bp_watchpoint)
2044                 type = bp_hardware_watchpoint;
2045
2046               /* This watchpoint may or may not have been placed on
2047                  the list yet at this point (it won't be in the list
2048                  if we're trying to create it for the first time,
2049                  through watch_command), so always account for it
2050                  manually.  */
2051
2052               /* Count resources used by all watchpoints except B.  */
2053               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2054
2055               /* Add in the resources needed for B.  */
2056               i += hw_watchpoint_use_count (&b->base);
2057
2058               target_resources_ok
2059                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2060               if (target_resources_ok <= 0)
2061                 {
2062                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2063
2064                   if (target_resources_ok == 0 && !sw_mode)
2065                     error (_("Target does not support this type of "
2066                              "hardware watchpoint."));
2067                   else if (target_resources_ok < 0 && !sw_mode)
2068                     error (_("There are not enough available hardware "
2069                              "resources for this watchpoint."));
2070
2071                   /* Downgrade to software watchpoint.  */
2072                   b->base.type = bp_watchpoint;
2073                 }
2074               else
2075                 {
2076                   /* If this was a software watchpoint, we've just
2077                      found we have enough resources to turn it to a
2078                      hardware watchpoint.  Otherwise, this is a
2079                      nop.  */
2080                   b->base.type = type;
2081                 }
2082             }
2083           else if (!b->base.ops->works_in_software_mode (&b->base))
2084             {
2085               if (!can_use_hw_watchpoints)
2086                 error (_("Can't set read/access watchpoint when "
2087                          "hardware watchpoints are disabled."));
2088               else
2089                 error (_("Expression cannot be implemented with "
2090                          "read/access watchpoint."));
2091             }
2092           else
2093             b->base.type = bp_watchpoint;
2094
2095           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2096                       : bp_loc_hardware_watchpoint);
2097           for (bl = b->base.loc; bl; bl = bl->next)
2098             bl->loc_type = loc_type;
2099         }
2100
2101       for (v = val_chain; v; v = next)
2102         {
2103           next = value_next (v);
2104           if (v != b->val)
2105             value_free (v);
2106         }
2107
2108       /* If a software watchpoint is not watching any memory, then the
2109          above left it without any location set up.  But,
2110          bpstat_stop_status requires a location to be able to report
2111          stops, so make sure there's at least a dummy one.  */
2112       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2113         {
2114           struct breakpoint *base = &b->base;
2115           base->loc = allocate_bp_location (base);
2116           base->loc->pspace = frame_pspace;
2117           base->loc->address = -1;
2118           base->loc->length = -1;
2119           base->loc->watchpoint_type = -1;
2120         }
2121     }
2122   else if (!within_current_scope)
2123     {
2124       printf_filtered (_("\
2125 Watchpoint %d deleted because the program has left the block\n\
2126 in which its expression is valid.\n"),
2127                        b->base.number);
2128       watchpoint_del_at_next_stop (b);
2129     }
2130
2131   /* Restore the selected frame.  */
2132   if (frame_saved)
2133     select_frame (frame_find_by_id (saved_frame_id));
2134 }
2135
2136
2137 /* Returns 1 iff breakpoint location should be
2138    inserted in the inferior.  We don't differentiate the type of BL's owner
2139    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2140    breakpoint_ops is not defined, because in insert_bp_location,
2141    tracepoint's insert_location will not be called.  */
2142 static int
2143 should_be_inserted (struct bp_location *bl)
2144 {
2145   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2146     return 0;
2147
2148   if (bl->owner->disposition == disp_del_at_next_stop)
2149     return 0;
2150
2151   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2152     return 0;
2153
2154   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2155     return 0;
2156
2157   /* This is set for example, when we're attached to the parent of a
2158      vfork, and have detached from the child.  The child is running
2159      free, and we expect it to do an exec or exit, at which point the
2160      OS makes the parent schedulable again (and the target reports
2161      that the vfork is done).  Until the child is done with the shared
2162      memory region, do not insert breakpoints in the parent, otherwise
2163      the child could still trip on the parent's breakpoints.  Since
2164      the parent is blocked anyway, it won't miss any breakpoint.  */
2165   if (bl->pspace->breakpoints_not_allowed)
2166     return 0;
2167
2168   /* Don't insert a breakpoint if we're trying to step past its
2169      location.  */
2170   if ((bl->loc_type == bp_loc_software_breakpoint
2171        || bl->loc_type == bp_loc_hardware_breakpoint)
2172       && stepping_past_instruction_at (bl->pspace->aspace,
2173                                        bl->address))
2174     {
2175       if (debug_infrun)
2176         {
2177           fprintf_unfiltered (gdb_stdlog,
2178                               "infrun: skipping breakpoint: "
2179                               "stepping past insn at: %s\n",
2180                               paddress (bl->gdbarch, bl->address));
2181         }
2182       return 0;
2183     }
2184
2185   /* Don't insert watchpoints if we're trying to step past the
2186      instruction that triggered one.  */
2187   if ((bl->loc_type == bp_loc_hardware_watchpoint)
2188       && stepping_past_nonsteppable_watchpoint ())
2189     {
2190       if (debug_infrun)
2191         {
2192           fprintf_unfiltered (gdb_stdlog,
2193                               "infrun: stepping past non-steppable watchpoint. "
2194                               "skipping watchpoint at %s:%d\n",
2195                               paddress (bl->gdbarch, bl->address),
2196                               bl->length);
2197         }
2198       return 0;
2199     }
2200
2201   return 1;
2202 }
2203
2204 /* Same as should_be_inserted but does the check assuming
2205    that the location is not duplicated.  */
2206
2207 static int
2208 unduplicated_should_be_inserted (struct bp_location *bl)
2209 {
2210   int result;
2211   const int save_duplicate = bl->duplicate;
2212
2213   bl->duplicate = 0;
2214   result = should_be_inserted (bl);
2215   bl->duplicate = save_duplicate;
2216   return result;
2217 }
2218
2219 /* Parses a conditional described by an expression COND into an
2220    agent expression bytecode suitable for evaluation
2221    by the bytecode interpreter.  Return NULL if there was
2222    any error during parsing.  */
2223
2224 static struct agent_expr *
2225 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2226 {
2227   struct agent_expr *aexpr = NULL;
2228   volatile struct gdb_exception ex;
2229
2230   if (!cond)
2231     return NULL;
2232
2233   /* We don't want to stop processing, so catch any errors
2234      that may show up.  */
2235   TRY_CATCH (ex, RETURN_MASK_ERROR)
2236     {
2237       aexpr = gen_eval_for_expr (scope, cond);
2238     }
2239
2240   if (ex.reason < 0)
2241     {
2242       /* If we got here, it means the condition could not be parsed to a valid
2243          bytecode expression and thus can't be evaluated on the target's side.
2244          It's no use iterating through the conditions.  */
2245       return NULL;
2246     }
2247
2248   /* We have a valid agent expression.  */
2249   return aexpr;
2250 }
2251
2252 /* Based on location BL, create a list of breakpoint conditions to be
2253    passed on to the target.  If we have duplicated locations with different
2254    conditions, we will add such conditions to the list.  The idea is that the
2255    target will evaluate the list of conditions and will only notify GDB when
2256    one of them is true.  */
2257
2258 static void
2259 build_target_condition_list (struct bp_location *bl)
2260 {
2261   struct bp_location **locp = NULL, **loc2p;
2262   int null_condition_or_parse_error = 0;
2263   int modified = bl->needs_update;
2264   struct bp_location *loc;
2265
2266   /* Release conditions left over from a previous insert.  */
2267   VEC_free (agent_expr_p, bl->target_info.conditions);
2268
2269   /* This is only meaningful if the target is
2270      evaluating conditions and if the user has
2271      opted for condition evaluation on the target's
2272      side.  */
2273   if (gdb_evaluates_breakpoint_condition_p ()
2274       || !target_supports_evaluation_of_breakpoint_conditions ())
2275     return;
2276
2277   /* Do a first pass to check for locations with no assigned
2278      conditions or conditions that fail to parse to a valid agent expression
2279      bytecode.  If any of these happen, then it's no use to send conditions
2280      to the target since this location will always trigger and generate a
2281      response back to GDB.  */
2282   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2283     {
2284       loc = (*loc2p);
2285       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2286         {
2287           if (modified)
2288             {
2289               struct agent_expr *aexpr;
2290
2291               /* Re-parse the conditions since something changed.  In that
2292                  case we already freed the condition bytecodes (see
2293                  force_breakpoint_reinsertion).  We just
2294                  need to parse the condition to bytecodes again.  */
2295               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2296               loc->cond_bytecode = aexpr;
2297
2298               /* Check if we managed to parse the conditional expression
2299                  correctly.  If not, we will not send this condition
2300                  to the target.  */
2301               if (aexpr)
2302                 continue;
2303             }
2304
2305           /* If we have a NULL bytecode expression, it means something
2306              went wrong or we have a null condition expression.  */
2307           if (!loc->cond_bytecode)
2308             {
2309               null_condition_or_parse_error = 1;
2310               break;
2311             }
2312         }
2313     }
2314
2315   /* If any of these happened, it means we will have to evaluate the conditions
2316      for the location's address on gdb's side.  It is no use keeping bytecodes
2317      for all the other duplicate locations, thus we free all of them here.
2318
2319      This is so we have a finer control over which locations' conditions are
2320      being evaluated by GDB or the remote stub.  */
2321   if (null_condition_or_parse_error)
2322     {
2323       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2324         {
2325           loc = (*loc2p);
2326           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2327             {
2328               /* Only go as far as the first NULL bytecode is
2329                  located.  */
2330               if (!loc->cond_bytecode)
2331                 return;
2332
2333               free_agent_expr (loc->cond_bytecode);
2334               loc->cond_bytecode = NULL;
2335             }
2336         }
2337     }
2338
2339   /* No NULL conditions or failed bytecode generation.  Build a condition list
2340      for this location's address.  */
2341   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2342     {
2343       loc = (*loc2p);
2344       if (loc->cond
2345           && is_breakpoint (loc->owner)
2346           && loc->pspace->num == bl->pspace->num
2347           && loc->owner->enable_state == bp_enabled
2348           && loc->enabled)
2349         /* Add the condition to the vector.  This will be used later to send the
2350            conditions to the target.  */
2351         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2352                        loc->cond_bytecode);
2353     }
2354
2355   return;
2356 }
2357
2358 /* Parses a command described by string CMD into an agent expression
2359    bytecode suitable for evaluation by the bytecode interpreter.
2360    Return NULL if there was any error during parsing.  */
2361
2362 static struct agent_expr *
2363 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2364 {
2365   struct cleanup *old_cleanups = 0;
2366   struct expression *expr, **argvec;
2367   struct agent_expr *aexpr = NULL;
2368   volatile struct gdb_exception ex;
2369   const char *cmdrest;
2370   const char *format_start, *format_end;
2371   struct format_piece *fpieces;
2372   int nargs;
2373   struct gdbarch *gdbarch = get_current_arch ();
2374
2375   if (!cmd)
2376     return NULL;
2377
2378   cmdrest = cmd;
2379
2380   if (*cmdrest == ',')
2381     ++cmdrest;
2382   cmdrest = skip_spaces_const (cmdrest);
2383
2384   if (*cmdrest++ != '"')
2385     error (_("No format string following the location"));
2386
2387   format_start = cmdrest;
2388
2389   fpieces = parse_format_string (&cmdrest);
2390
2391   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2392
2393   format_end = cmdrest;
2394
2395   if (*cmdrest++ != '"')
2396     error (_("Bad format string, non-terminated '\"'."));
2397   
2398   cmdrest = skip_spaces_const (cmdrest);
2399
2400   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2401     error (_("Invalid argument syntax"));
2402
2403   if (*cmdrest == ',')
2404     cmdrest++;
2405   cmdrest = skip_spaces_const (cmdrest);
2406
2407   /* For each argument, make an expression.  */
2408
2409   argvec = (struct expression **) alloca (strlen (cmd)
2410                                          * sizeof (struct expression *));
2411
2412   nargs = 0;
2413   while (*cmdrest != '\0')
2414     {
2415       const char *cmd1;
2416
2417       cmd1 = cmdrest;
2418       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2419       argvec[nargs++] = expr;
2420       cmdrest = cmd1;
2421       if (*cmdrest == ',')
2422         ++cmdrest;
2423     }
2424
2425   /* We don't want to stop processing, so catch any errors
2426      that may show up.  */
2427   TRY_CATCH (ex, RETURN_MASK_ERROR)
2428     {
2429       aexpr = gen_printf (scope, gdbarch, 0, 0,
2430                           format_start, format_end - format_start,
2431                           fpieces, nargs, argvec);
2432     }
2433
2434   do_cleanups (old_cleanups);
2435
2436   if (ex.reason < 0)
2437     {
2438       /* If we got here, it means the command could not be parsed to a valid
2439          bytecode expression and thus can't be evaluated on the target's side.
2440          It's no use iterating through the other commands.  */
2441       return NULL;
2442     }
2443
2444   /* We have a valid agent expression, return it.  */
2445   return aexpr;
2446 }
2447
2448 /* Based on location BL, create a list of breakpoint commands to be
2449    passed on to the target.  If we have duplicated locations with
2450    different commands, we will add any such to the list.  */
2451
2452 static void
2453 build_target_command_list (struct bp_location *bl)
2454 {
2455   struct bp_location **locp = NULL, **loc2p;
2456   int null_command_or_parse_error = 0;
2457   int modified = bl->needs_update;
2458   struct bp_location *loc;
2459
2460   /* Release commands left over from a previous insert.  */
2461   VEC_free (agent_expr_p, bl->target_info.tcommands);
2462
2463   if (!target_can_run_breakpoint_commands ())
2464     return;
2465
2466   /* For now, limit to agent-style dprintf breakpoints.  */
2467   if (dprintf_style != dprintf_style_agent)
2468     return;
2469
2470   /* For now, if we have any duplicate location that isn't a dprintf,
2471      don't install the target-side commands, as that would make the
2472      breakpoint not be reported to the core, and we'd lose
2473      control.  */
2474   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2475     {
2476       loc = (*loc2p);
2477       if (is_breakpoint (loc->owner)
2478           && loc->pspace->num == bl->pspace->num
2479           && loc->owner->type != bp_dprintf)
2480         return;
2481     }
2482
2483   /* Do a first pass to check for locations with no assigned
2484      conditions or conditions that fail to parse to a valid agent expression
2485      bytecode.  If any of these happen, then it's no use to send conditions
2486      to the target since this location will always trigger and generate a
2487      response back to GDB.  */
2488   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2489     {
2490       loc = (*loc2p);
2491       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2492         {
2493           if (modified)
2494             {
2495               struct agent_expr *aexpr;
2496
2497               /* Re-parse the commands since something changed.  In that
2498                  case we already freed the command bytecodes (see
2499                  force_breakpoint_reinsertion).  We just
2500                  need to parse the command to bytecodes again.  */
2501               aexpr = parse_cmd_to_aexpr (bl->address,
2502                                           loc->owner->extra_string);
2503               loc->cmd_bytecode = aexpr;
2504
2505               if (!aexpr)
2506                 continue;
2507             }
2508
2509           /* If we have a NULL bytecode expression, it means something
2510              went wrong or we have a null command expression.  */
2511           if (!loc->cmd_bytecode)
2512             {
2513               null_command_or_parse_error = 1;
2514               break;
2515             }
2516         }
2517     }
2518
2519   /* If anything failed, then we're not doing target-side commands,
2520      and so clean up.  */
2521   if (null_command_or_parse_error)
2522     {
2523       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2524         {
2525           loc = (*loc2p);
2526           if (is_breakpoint (loc->owner)
2527               && loc->pspace->num == bl->pspace->num)
2528             {
2529               /* Only go as far as the first NULL bytecode is
2530                  located.  */
2531               if (loc->cmd_bytecode == NULL)
2532                 return;
2533
2534               free_agent_expr (loc->cmd_bytecode);
2535               loc->cmd_bytecode = NULL;
2536             }
2537         }
2538     }
2539
2540   /* No NULL commands or failed bytecode generation.  Build a command list
2541      for this location's address.  */
2542   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2543     {
2544       loc = (*loc2p);
2545       if (loc->owner->extra_string
2546           && is_breakpoint (loc->owner)
2547           && loc->pspace->num == bl->pspace->num
2548           && loc->owner->enable_state == bp_enabled
2549           && loc->enabled)
2550         /* Add the command to the vector.  This will be used later
2551            to send the commands to the target.  */
2552         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2553                        loc->cmd_bytecode);
2554     }
2555
2556   bl->target_info.persist = 0;
2557   /* Maybe flag this location as persistent.  */
2558   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2559     bl->target_info.persist = 1;
2560 }
2561
2562 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2563    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2564    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2565    Returns 0 for success, 1 if the bp_location type is not supported or
2566    -1 for failure.
2567
2568    NOTE drow/2003-09-09: This routine could be broken down to an
2569    object-style method for each breakpoint or catchpoint type.  */
2570 static int
2571 insert_bp_location (struct bp_location *bl,
2572                     struct ui_file *tmp_error_stream,
2573                     int *disabled_breaks,
2574                     int *hw_breakpoint_error,
2575                     int *hw_bp_error_explained_already)
2576 {
2577   enum errors bp_err = GDB_NO_ERROR;
2578   const char *bp_err_message = NULL;
2579   volatile struct gdb_exception e;
2580
2581   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2582     return 0;
2583
2584   /* Note we don't initialize bl->target_info, as that wipes out
2585      the breakpoint location's shadow_contents if the breakpoint
2586      is still inserted at that location.  This in turn breaks
2587      target_read_memory which depends on these buffers when
2588      a memory read is requested at the breakpoint location:
2589      Once the target_info has been wiped, we fail to see that
2590      we have a breakpoint inserted at that address and thus
2591      read the breakpoint instead of returning the data saved in
2592      the breakpoint location's shadow contents.  */
2593   bl->target_info.reqstd_address = bl->address;
2594   bl->target_info.placed_address_space = bl->pspace->aspace;
2595   bl->target_info.length = bl->length;
2596
2597   /* When working with target-side conditions, we must pass all the conditions
2598      for the same breakpoint address down to the target since GDB will not
2599      insert those locations.  With a list of breakpoint conditions, the target
2600      can decide when to stop and notify GDB.  */
2601
2602   if (is_breakpoint (bl->owner))
2603     {
2604       build_target_condition_list (bl);
2605       build_target_command_list (bl);
2606       /* Reset the modification marker.  */
2607       bl->needs_update = 0;
2608     }
2609
2610   if (bl->loc_type == bp_loc_software_breakpoint
2611       || bl->loc_type == bp_loc_hardware_breakpoint)
2612     {
2613       if (bl->owner->type != bp_hardware_breakpoint)
2614         {
2615           /* If the explicitly specified breakpoint type
2616              is not hardware breakpoint, check the memory map to see
2617              if the breakpoint address is in read only memory or not.
2618
2619              Two important cases are:
2620              - location type is not hardware breakpoint, memory
2621              is readonly.  We change the type of the location to
2622              hardware breakpoint.
2623              - location type is hardware breakpoint, memory is
2624              read-write.  This means we've previously made the
2625              location hardware one, but then the memory map changed,
2626              so we undo.
2627              
2628              When breakpoints are removed, remove_breakpoints will use
2629              location types we've just set here, the only possible
2630              problem is that memory map has changed during running
2631              program, but it's not going to work anyway with current
2632              gdb.  */
2633           struct mem_region *mr 
2634             = lookup_mem_region (bl->target_info.reqstd_address);
2635           
2636           if (mr)
2637             {
2638               if (automatic_hardware_breakpoints)
2639                 {
2640                   enum bp_loc_type new_type;
2641                   
2642                   if (mr->attrib.mode != MEM_RW)
2643                     new_type = bp_loc_hardware_breakpoint;
2644                   else 
2645                     new_type = bp_loc_software_breakpoint;
2646                   
2647                   if (new_type != bl->loc_type)
2648                     {
2649                       static int said = 0;
2650
2651                       bl->loc_type = new_type;
2652                       if (!said)
2653                         {
2654                           fprintf_filtered (gdb_stdout,
2655                                             _("Note: automatically using "
2656                                               "hardware breakpoints for "
2657                                               "read-only addresses.\n"));
2658                           said = 1;
2659                         }
2660                     }
2661                 }
2662               else if (bl->loc_type == bp_loc_software_breakpoint
2663                        && mr->attrib.mode != MEM_RW)
2664                 {
2665                   fprintf_unfiltered (tmp_error_stream,
2666                                       _("Cannot insert breakpoint %d.\n"
2667                                         "Cannot set software breakpoint "
2668                                         "at read-only address %s\n"),
2669                                       bl->owner->number,
2670                                       paddress (bl->gdbarch, bl->address));
2671                   return 1;
2672                 }
2673             }
2674         }
2675         
2676       /* First check to see if we have to handle an overlay.  */
2677       if (overlay_debugging == ovly_off
2678           || bl->section == NULL
2679           || !(section_is_overlay (bl->section)))
2680         {
2681           /* No overlay handling: just set the breakpoint.  */
2682           TRY_CATCH (e, RETURN_MASK_ALL)
2683             {
2684               int val;
2685
2686               val = bl->owner->ops->insert_location (bl);
2687               if (val)
2688                 bp_err = GENERIC_ERROR;
2689             }
2690           if (e.reason < 0)
2691             {
2692               bp_err = e.error;
2693               bp_err_message = e.message;
2694             }
2695         }
2696       else
2697         {
2698           /* This breakpoint is in an overlay section.
2699              Shall we set a breakpoint at the LMA?  */
2700           if (!overlay_events_enabled)
2701             {
2702               /* Yes -- overlay event support is not active, 
2703                  so we must try to set a breakpoint at the LMA.
2704                  This will not work for a hardware breakpoint.  */
2705               if (bl->loc_type == bp_loc_hardware_breakpoint)
2706                 warning (_("hardware breakpoint %d not supported in overlay!"),
2707                          bl->owner->number);
2708               else
2709                 {
2710                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2711                                                              bl->section);
2712                   /* Set a software (trap) breakpoint at the LMA.  */
2713                   bl->overlay_target_info = bl->target_info;
2714                   bl->overlay_target_info.reqstd_address = addr;
2715
2716                   /* No overlay handling: just set the breakpoint.  */
2717                   TRY_CATCH (e, RETURN_MASK_ALL)
2718                     {
2719                       int val;
2720
2721                       val = target_insert_breakpoint (bl->gdbarch,
2722                                                       &bl->overlay_target_info);
2723                       if (val)
2724                         bp_err = GENERIC_ERROR;
2725                     }
2726                   if (e.reason < 0)
2727                     {
2728                       bp_err = e.error;
2729                       bp_err_message = e.message;
2730                     }
2731
2732                   if (bp_err != GDB_NO_ERROR)
2733                     fprintf_unfiltered (tmp_error_stream,
2734                                         "Overlay breakpoint %d "
2735                                         "failed: in ROM?\n",
2736                                         bl->owner->number);
2737                 }
2738             }
2739           /* Shall we set a breakpoint at the VMA? */
2740           if (section_is_mapped (bl->section))
2741             {
2742               /* Yes.  This overlay section is mapped into memory.  */
2743               TRY_CATCH (e, RETURN_MASK_ALL)
2744                 {
2745                   int val;
2746
2747                   val = bl->owner->ops->insert_location (bl);
2748                   if (val)
2749                     bp_err = GENERIC_ERROR;
2750                 }
2751               if (e.reason < 0)
2752                 {
2753                   bp_err = e.error;
2754                   bp_err_message = e.message;
2755                 }
2756             }
2757           else
2758             {
2759               /* No.  This breakpoint will not be inserted.  
2760                  No error, but do not mark the bp as 'inserted'.  */
2761               return 0;
2762             }
2763         }
2764
2765       if (bp_err != GDB_NO_ERROR)
2766         {
2767           /* Can't set the breakpoint.  */
2768
2769           /* In some cases, we might not be able to insert a
2770              breakpoint in a shared library that has already been
2771              removed, but we have not yet processed the shlib unload
2772              event.  Unfortunately, some targets that implement
2773              breakpoint insertion themselves can't tell why the
2774              breakpoint insertion failed (e.g., the remote target
2775              doesn't define error codes), so we must treat generic
2776              errors as memory errors.  */
2777           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2778               && bl->loc_type == bp_loc_software_breakpoint
2779               && (solib_name_from_address (bl->pspace, bl->address)
2780                   || shared_objfile_contains_address_p (bl->pspace,
2781                                                         bl->address)))
2782             {
2783               /* See also: disable_breakpoints_in_shlibs.  */
2784               bl->shlib_disabled = 1;
2785               observer_notify_breakpoint_modified (bl->owner);
2786               if (!*disabled_breaks)
2787                 {
2788                   fprintf_unfiltered (tmp_error_stream, 
2789                                       "Cannot insert breakpoint %d.\n", 
2790                                       bl->owner->number);
2791                   fprintf_unfiltered (tmp_error_stream, 
2792                                       "Temporarily disabling shared "
2793                                       "library breakpoints:\n");
2794                 }
2795               *disabled_breaks = 1;
2796               fprintf_unfiltered (tmp_error_stream,
2797                                   "breakpoint #%d\n", bl->owner->number);
2798               return 0;
2799             }
2800           else
2801             {
2802               if (bl->loc_type == bp_loc_hardware_breakpoint)
2803                 {
2804                   *hw_breakpoint_error = 1;
2805                   *hw_bp_error_explained_already = bp_err_message != NULL;
2806                   fprintf_unfiltered (tmp_error_stream,
2807                                       "Cannot insert hardware breakpoint %d%s",
2808                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2809                   if (bp_err_message != NULL)
2810                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2811                 }
2812               else
2813                 {
2814                   if (bp_err_message == NULL)
2815                     {
2816                       char *message
2817                         = memory_error_message (TARGET_XFER_E_IO,
2818                                                 bl->gdbarch, bl->address);
2819                       struct cleanup *old_chain = make_cleanup (xfree, message);
2820
2821                       fprintf_unfiltered (tmp_error_stream,
2822                                           "Cannot insert breakpoint %d.\n"
2823                                           "%s\n",
2824                                           bl->owner->number, message);
2825                       do_cleanups (old_chain);
2826                     }
2827                   else
2828                     {
2829                       fprintf_unfiltered (tmp_error_stream,
2830                                           "Cannot insert breakpoint %d: %s\n",
2831                                           bl->owner->number,
2832                                           bp_err_message);
2833                     }
2834                 }
2835               return 1;
2836
2837             }
2838         }
2839       else
2840         bl->inserted = 1;
2841
2842       return 0;
2843     }
2844
2845   else if (bl->loc_type == bp_loc_hardware_watchpoint
2846            /* NOTE drow/2003-09-08: This state only exists for removing
2847               watchpoints.  It's not clear that it's necessary...  */
2848            && bl->owner->disposition != disp_del_at_next_stop)
2849     {
2850       int val;
2851
2852       gdb_assert (bl->owner->ops != NULL
2853                   && bl->owner->ops->insert_location != NULL);
2854
2855       val = bl->owner->ops->insert_location (bl);
2856
2857       /* If trying to set a read-watchpoint, and it turns out it's not
2858          supported, try emulating one with an access watchpoint.  */
2859       if (val == 1 && bl->watchpoint_type == hw_read)
2860         {
2861           struct bp_location *loc, **loc_temp;
2862
2863           /* But don't try to insert it, if there's already another
2864              hw_access location that would be considered a duplicate
2865              of this one.  */
2866           ALL_BP_LOCATIONS (loc, loc_temp)
2867             if (loc != bl
2868                 && loc->watchpoint_type == hw_access
2869                 && watchpoint_locations_match (bl, loc))
2870               {
2871                 bl->duplicate = 1;
2872                 bl->inserted = 1;
2873                 bl->target_info = loc->target_info;
2874                 bl->watchpoint_type = hw_access;
2875                 val = 0;
2876                 break;
2877               }
2878
2879           if (val == 1)
2880             {
2881               bl->watchpoint_type = hw_access;
2882               val = bl->owner->ops->insert_location (bl);
2883
2884               if (val)
2885                 /* Back to the original value.  */
2886                 bl->watchpoint_type = hw_read;
2887             }
2888         }
2889
2890       bl->inserted = (val == 0);
2891     }
2892
2893   else if (bl->owner->type == bp_catchpoint)
2894     {
2895       int val;
2896
2897       gdb_assert (bl->owner->ops != NULL
2898                   && bl->owner->ops->insert_location != NULL);
2899
2900       val = bl->owner->ops->insert_location (bl);
2901       if (val)
2902         {
2903           bl->owner->enable_state = bp_disabled;
2904
2905           if (val == 1)
2906             warning (_("\
2907 Error inserting catchpoint %d: Your system does not support this type\n\
2908 of catchpoint."), bl->owner->number);
2909           else
2910             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2911         }
2912
2913       bl->inserted = (val == 0);
2914
2915       /* We've already printed an error message if there was a problem
2916          inserting this catchpoint, and we've disabled the catchpoint,
2917          so just return success.  */
2918       return 0;
2919     }
2920
2921   return 0;
2922 }
2923
2924 /* This function is called when program space PSPACE is about to be
2925    deleted.  It takes care of updating breakpoints to not reference
2926    PSPACE anymore.  */
2927
2928 void
2929 breakpoint_program_space_exit (struct program_space *pspace)
2930 {
2931   struct breakpoint *b, *b_temp;
2932   struct bp_location *loc, **loc_temp;
2933
2934   /* Remove any breakpoint that was set through this program space.  */
2935   ALL_BREAKPOINTS_SAFE (b, b_temp)
2936     {
2937       if (b->pspace == pspace)
2938         delete_breakpoint (b);
2939     }
2940
2941   /* Breakpoints set through other program spaces could have locations
2942      bound to PSPACE as well.  Remove those.  */
2943   ALL_BP_LOCATIONS (loc, loc_temp)
2944     {
2945       struct bp_location *tmp;
2946
2947       if (loc->pspace == pspace)
2948         {
2949           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2950           if (loc->owner->loc == loc)
2951             loc->owner->loc = loc->next;
2952           else
2953             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2954               if (tmp->next == loc)
2955                 {
2956                   tmp->next = loc->next;
2957                   break;
2958                 }
2959         }
2960     }
2961
2962   /* Now update the global location list to permanently delete the
2963      removed locations above.  */
2964   update_global_location_list (UGLL_DONT_INSERT);
2965 }
2966
2967 /* Make sure all breakpoints are inserted in inferior.
2968    Throws exception on any error.
2969    A breakpoint that is already inserted won't be inserted
2970    again, so calling this function twice is safe.  */
2971 void
2972 insert_breakpoints (void)
2973 {
2974   struct breakpoint *bpt;
2975
2976   ALL_BREAKPOINTS (bpt)
2977     if (is_hardware_watchpoint (bpt))
2978       {
2979         struct watchpoint *w = (struct watchpoint *) bpt;
2980
2981         update_watchpoint (w, 0 /* don't reparse.  */);
2982       }
2983
2984   /* Updating watchpoints creates new locations, so update the global
2985      location list.  Explicitly tell ugll to insert locations and
2986      ignore breakpoints_always_inserted_mode.  */
2987   update_global_location_list (UGLL_INSERT);
2988 }
2989
2990 /* Invoke CALLBACK for each of bp_location.  */
2991
2992 void
2993 iterate_over_bp_locations (walk_bp_location_callback callback)
2994 {
2995   struct bp_location *loc, **loc_tmp;
2996
2997   ALL_BP_LOCATIONS (loc, loc_tmp)
2998     {
2999       callback (loc, NULL);
3000     }
3001 }
3002
3003 /* This is used when we need to synch breakpoint conditions between GDB and the
3004    target.  It is the case with deleting and disabling of breakpoints when using
3005    always-inserted mode.  */
3006
3007 static void
3008 update_inserted_breakpoint_locations (void)
3009 {
3010   struct bp_location *bl, **blp_tmp;
3011   int error_flag = 0;
3012   int val = 0;
3013   int disabled_breaks = 0;
3014   int hw_breakpoint_error = 0;
3015   int hw_bp_details_reported = 0;
3016
3017   struct ui_file *tmp_error_stream = mem_fileopen ();
3018   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3019
3020   /* Explicitly mark the warning -- this will only be printed if
3021      there was an error.  */
3022   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3023
3024   save_current_space_and_thread ();
3025
3026   ALL_BP_LOCATIONS (bl, blp_tmp)
3027     {
3028       /* We only want to update software breakpoints and hardware
3029          breakpoints.  */
3030       if (!is_breakpoint (bl->owner))
3031         continue;
3032
3033       /* We only want to update locations that are already inserted
3034          and need updating.  This is to avoid unwanted insertion during
3035          deletion of breakpoints.  */
3036       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3037         continue;
3038
3039       switch_to_program_space_and_thread (bl->pspace);
3040
3041       /* For targets that support global breakpoints, there's no need
3042          to select an inferior to insert breakpoint to.  In fact, even
3043          if we aren't attached to any process yet, we should still
3044          insert breakpoints.  */
3045       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3046           && ptid_equal (inferior_ptid, null_ptid))
3047         continue;
3048
3049       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3050                                     &hw_breakpoint_error, &hw_bp_details_reported);
3051       if (val)
3052         error_flag = val;
3053     }
3054
3055   if (error_flag)
3056     {
3057       target_terminal_ours_for_output ();
3058       error_stream (tmp_error_stream);
3059     }
3060
3061   do_cleanups (cleanups);
3062 }
3063
3064 /* Used when starting or continuing the program.  */
3065
3066 static void
3067 insert_breakpoint_locations (void)
3068 {
3069   struct breakpoint *bpt;
3070   struct bp_location *bl, **blp_tmp;
3071   int error_flag = 0;
3072   int val = 0;
3073   int disabled_breaks = 0;
3074   int hw_breakpoint_error = 0;
3075   int hw_bp_error_explained_already = 0;
3076
3077   struct ui_file *tmp_error_stream = mem_fileopen ();
3078   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3079   
3080   /* Explicitly mark the warning -- this will only be printed if
3081      there was an error.  */
3082   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3083
3084   save_current_space_and_thread ();
3085
3086   ALL_BP_LOCATIONS (bl, blp_tmp)
3087     {
3088       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3089         continue;
3090
3091       /* There is no point inserting thread-specific breakpoints if
3092          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3093          has BL->OWNER always non-NULL.  */
3094       if (bl->owner->thread != -1
3095           && !valid_thread_id (bl->owner->thread))
3096         continue;
3097
3098       switch_to_program_space_and_thread (bl->pspace);
3099
3100       /* For targets that support global breakpoints, there's no need
3101          to select an inferior to insert breakpoint to.  In fact, even
3102          if we aren't attached to any process yet, we should still
3103          insert breakpoints.  */
3104       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3105           && ptid_equal (inferior_ptid, null_ptid))
3106         continue;
3107
3108       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3109                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3110       if (val)
3111         error_flag = val;
3112     }
3113
3114   /* If we failed to insert all locations of a watchpoint, remove
3115      them, as half-inserted watchpoint is of limited use.  */
3116   ALL_BREAKPOINTS (bpt)  
3117     {
3118       int some_failed = 0;
3119       struct bp_location *loc;
3120
3121       if (!is_hardware_watchpoint (bpt))
3122         continue;
3123
3124       if (!breakpoint_enabled (bpt))
3125         continue;
3126
3127       if (bpt->disposition == disp_del_at_next_stop)
3128         continue;
3129       
3130       for (loc = bpt->loc; loc; loc = loc->next)
3131         if (!loc->inserted && should_be_inserted (loc))
3132           {
3133             some_failed = 1;
3134             break;
3135           }
3136       if (some_failed)
3137         {
3138           for (loc = bpt->loc; loc; loc = loc->next)
3139             if (loc->inserted)
3140               remove_breakpoint (loc, mark_uninserted);
3141
3142           hw_breakpoint_error = 1;
3143           fprintf_unfiltered (tmp_error_stream,
3144                               "Could not insert hardware watchpoint %d.\n", 
3145                               bpt->number);
3146           error_flag = -1;
3147         }
3148     }
3149
3150   if (error_flag)
3151     {
3152       /* If a hardware breakpoint or watchpoint was inserted, add a
3153          message about possibly exhausted resources.  */
3154       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3155         {
3156           fprintf_unfiltered (tmp_error_stream, 
3157                               "Could not insert hardware breakpoints:\n\
3158 You may have requested too many hardware breakpoints/watchpoints.\n");
3159         }
3160       target_terminal_ours_for_output ();
3161       error_stream (tmp_error_stream);
3162     }
3163
3164   do_cleanups (cleanups);
3165 }
3166
3167 /* Used when the program stops.
3168    Returns zero if successful, or non-zero if there was a problem
3169    removing a breakpoint location.  */
3170
3171 int
3172 remove_breakpoints (void)
3173 {
3174   struct bp_location *bl, **blp_tmp;
3175   int val = 0;
3176
3177   ALL_BP_LOCATIONS (bl, blp_tmp)
3178   {
3179     if (bl->inserted && !is_tracepoint (bl->owner))
3180       val |= remove_breakpoint (bl, mark_uninserted);
3181   }
3182   return val;
3183 }
3184
3185 /* When a thread exits, remove breakpoints that are related to
3186    that thread.  */
3187
3188 static void
3189 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3190 {
3191   struct breakpoint *b, *b_tmp;
3192
3193   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3194     {
3195       if (b->thread == tp->num && user_breakpoint_p (b))
3196         {
3197           b->disposition = disp_del_at_next_stop;
3198
3199           printf_filtered (_("\
3200 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3201                           b->number, tp->num);
3202
3203           /* Hide it from the user.  */
3204           b->number = 0;
3205        }
3206     }
3207 }
3208
3209 /* Remove breakpoints of process PID.  */
3210
3211 int
3212 remove_breakpoints_pid (int pid)
3213 {
3214   struct bp_location *bl, **blp_tmp;
3215   int val;
3216   struct inferior *inf = find_inferior_pid (pid);
3217
3218   ALL_BP_LOCATIONS (bl, blp_tmp)
3219   {
3220     if (bl->pspace != inf->pspace)
3221       continue;
3222
3223     if (bl->inserted && !bl->target_info.persist)
3224       {
3225         val = remove_breakpoint (bl, mark_uninserted);
3226         if (val != 0)
3227           return val;
3228       }
3229   }
3230   return 0;
3231 }
3232
3233 int
3234 reattach_breakpoints (int pid)
3235 {
3236   struct cleanup *old_chain;
3237   struct bp_location *bl, **blp_tmp;
3238   int val;
3239   struct ui_file *tmp_error_stream;
3240   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3241   struct inferior *inf;
3242   struct thread_info *tp;
3243
3244   tp = any_live_thread_of_process (pid);
3245   if (tp == NULL)
3246     return 1;
3247
3248   inf = find_inferior_pid (pid);
3249   old_chain = save_inferior_ptid ();
3250
3251   inferior_ptid = tp->ptid;
3252
3253   tmp_error_stream = mem_fileopen ();
3254   make_cleanup_ui_file_delete (tmp_error_stream);
3255
3256   ALL_BP_LOCATIONS (bl, blp_tmp)
3257   {
3258     if (bl->pspace != inf->pspace)
3259       continue;
3260
3261     if (bl->inserted)
3262       {
3263         bl->inserted = 0;
3264         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3265         if (val != 0)
3266           {
3267             do_cleanups (old_chain);
3268             return val;
3269           }
3270       }
3271   }
3272   do_cleanups (old_chain);
3273   return 0;
3274 }
3275
3276 static int internal_breakpoint_number = -1;
3277
3278 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3279    If INTERNAL is non-zero, the breakpoint number will be populated
3280    from internal_breakpoint_number and that variable decremented.
3281    Otherwise the breakpoint number will be populated from
3282    breakpoint_count and that value incremented.  Internal breakpoints
3283    do not set the internal var bpnum.  */
3284 static void
3285 set_breakpoint_number (int internal, struct breakpoint *b)
3286 {
3287   if (internal)
3288     b->number = internal_breakpoint_number--;
3289   else
3290     {
3291       set_breakpoint_count (breakpoint_count + 1);
3292       b->number = breakpoint_count;
3293     }
3294 }
3295
3296 static struct breakpoint *
3297 create_internal_breakpoint (struct gdbarch *gdbarch,
3298                             CORE_ADDR address, enum bptype type,
3299                             const struct breakpoint_ops *ops)
3300 {
3301   struct symtab_and_line sal;
3302   struct breakpoint *b;
3303
3304   init_sal (&sal);              /* Initialize to zeroes.  */
3305
3306   sal.pc = address;
3307   sal.section = find_pc_overlay (sal.pc);
3308   sal.pspace = current_program_space;
3309
3310   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3311   b->number = internal_breakpoint_number--;
3312   b->disposition = disp_donttouch;
3313
3314   return b;
3315 }
3316
3317 static const char *const longjmp_names[] =
3318   {
3319     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3320   };
3321 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3322
3323 /* Per-objfile data private to breakpoint.c.  */
3324 struct breakpoint_objfile_data
3325 {
3326   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3327   struct bound_minimal_symbol overlay_msym;
3328
3329   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3330   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3331
3332   /* True if we have looked for longjmp probes.  */
3333   int longjmp_searched;
3334
3335   /* SystemTap probe points for longjmp (if any).  */
3336   VEC (probe_p) *longjmp_probes;
3337
3338   /* Minimal symbol for "std::terminate()" (if any).  */
3339   struct bound_minimal_symbol terminate_msym;
3340
3341   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3342   struct bound_minimal_symbol exception_msym;
3343
3344   /* True if we have looked for exception probes.  */
3345   int exception_searched;
3346
3347   /* SystemTap probe points for unwinding (if any).  */
3348   VEC (probe_p) *exception_probes;
3349 };
3350
3351 static const struct objfile_data *breakpoint_objfile_key;
3352
3353 /* Minimal symbol not found sentinel.  */
3354 static struct minimal_symbol msym_not_found;
3355
3356 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3357
3358 static int
3359 msym_not_found_p (const struct minimal_symbol *msym)
3360 {
3361   return msym == &msym_not_found;
3362 }
3363
3364 /* Return per-objfile data needed by breakpoint.c.
3365    Allocate the data if necessary.  */
3366
3367 static struct breakpoint_objfile_data *
3368 get_breakpoint_objfile_data (struct objfile *objfile)
3369 {
3370   struct breakpoint_objfile_data *bp_objfile_data;
3371
3372   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3373   if (bp_objfile_data == NULL)
3374     {
3375       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3376                                        sizeof (*bp_objfile_data));
3377
3378       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3379       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3380     }
3381   return bp_objfile_data;
3382 }
3383
3384 static void
3385 free_breakpoint_probes (struct objfile *obj, void *data)
3386 {
3387   struct breakpoint_objfile_data *bp_objfile_data = data;
3388
3389   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3390   VEC_free (probe_p, bp_objfile_data->exception_probes);
3391 }
3392
3393 static void
3394 create_overlay_event_breakpoint (void)
3395 {
3396   struct objfile *objfile;
3397   const char *const func_name = "_ovly_debug_event";
3398
3399   ALL_OBJFILES (objfile)
3400     {
3401       struct breakpoint *b;
3402       struct breakpoint_objfile_data *bp_objfile_data;
3403       CORE_ADDR addr;
3404
3405       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3406
3407       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3408         continue;
3409
3410       if (bp_objfile_data->overlay_msym.minsym == NULL)
3411         {
3412           struct bound_minimal_symbol m;
3413
3414           m = lookup_minimal_symbol_text (func_name, objfile);
3415           if (m.minsym == NULL)
3416             {
3417               /* Avoid future lookups in this objfile.  */
3418               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3419               continue;
3420             }
3421           bp_objfile_data->overlay_msym = m;
3422         }
3423
3424       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3425       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3426                                       bp_overlay_event,
3427                                       &internal_breakpoint_ops);
3428       b->addr_string = xstrdup (func_name);
3429
3430       if (overlay_debugging == ovly_auto)
3431         {
3432           b->enable_state = bp_enabled;
3433           overlay_events_enabled = 1;
3434         }
3435       else
3436        {
3437          b->enable_state = bp_disabled;
3438          overlay_events_enabled = 0;
3439        }
3440     }
3441   update_global_location_list (UGLL_MAY_INSERT);
3442 }
3443
3444 static void
3445 create_longjmp_master_breakpoint (void)
3446 {
3447   struct program_space *pspace;
3448   struct cleanup *old_chain;
3449
3450   old_chain = save_current_program_space ();
3451
3452   ALL_PSPACES (pspace)
3453   {
3454     struct objfile *objfile;
3455
3456     set_current_program_space (pspace);
3457
3458     ALL_OBJFILES (objfile)
3459     {
3460       int i;
3461       struct gdbarch *gdbarch;
3462       struct breakpoint_objfile_data *bp_objfile_data;
3463
3464       gdbarch = get_objfile_arch (objfile);
3465
3466       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3467
3468       if (!bp_objfile_data->longjmp_searched)
3469         {
3470           VEC (probe_p) *ret;
3471
3472           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3473           if (ret != NULL)
3474             {
3475               /* We are only interested in checking one element.  */
3476               struct probe *p = VEC_index (probe_p, ret, 0);
3477
3478               if (!can_evaluate_probe_arguments (p))
3479                 {
3480                   /* We cannot use the probe interface here, because it does
3481                      not know how to evaluate arguments.  */
3482                   VEC_free (probe_p, ret);
3483                   ret = NULL;
3484                 }
3485             }
3486           bp_objfile_data->longjmp_probes = ret;
3487           bp_objfile_data->longjmp_searched = 1;
3488         }
3489
3490       if (bp_objfile_data->longjmp_probes != NULL)
3491         {
3492           int i;
3493           struct probe *probe;
3494           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3495
3496           for (i = 0;
3497                VEC_iterate (probe_p,
3498                             bp_objfile_data->longjmp_probes,
3499                             i, probe);
3500                ++i)
3501             {
3502               struct breakpoint *b;
3503
3504               b = create_internal_breakpoint (gdbarch,
3505                                               get_probe_address (probe,
3506                                                                  objfile),
3507                                               bp_longjmp_master,
3508                                               &internal_breakpoint_ops);
3509               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3510               b->enable_state = bp_disabled;
3511             }
3512
3513           continue;
3514         }
3515
3516       if (!gdbarch_get_longjmp_target_p (gdbarch))
3517         continue;
3518
3519       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3520         {
3521           struct breakpoint *b;
3522           const char *func_name;
3523           CORE_ADDR addr;
3524
3525           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3526             continue;
3527
3528           func_name = longjmp_names[i];
3529           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3530             {
3531               struct bound_minimal_symbol m;
3532
3533               m = lookup_minimal_symbol_text (func_name, objfile);
3534               if (m.minsym == NULL)
3535                 {
3536                   /* Prevent future lookups in this objfile.  */
3537                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3538                   continue;
3539                 }
3540               bp_objfile_data->longjmp_msym[i] = m;
3541             }
3542
3543           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3544           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3545                                           &internal_breakpoint_ops);
3546           b->addr_string = xstrdup (func_name);
3547           b->enable_state = bp_disabled;
3548         }
3549     }
3550   }
3551   update_global_location_list (UGLL_MAY_INSERT);
3552
3553   do_cleanups (old_chain);
3554 }
3555
3556 /* Create a master std::terminate breakpoint.  */
3557 static void
3558 create_std_terminate_master_breakpoint (void)
3559 {
3560   struct program_space *pspace;
3561   struct cleanup *old_chain;
3562   const char *const func_name = "std::terminate()";
3563
3564   old_chain = save_current_program_space ();
3565
3566   ALL_PSPACES (pspace)
3567   {
3568     struct objfile *objfile;
3569     CORE_ADDR addr;
3570
3571     set_current_program_space (pspace);
3572
3573     ALL_OBJFILES (objfile)
3574     {
3575       struct breakpoint *b;
3576       struct breakpoint_objfile_data *bp_objfile_data;
3577
3578       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3579
3580       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3581         continue;
3582
3583       if (bp_objfile_data->terminate_msym.minsym == NULL)
3584         {
3585           struct bound_minimal_symbol m;
3586
3587           m = lookup_minimal_symbol (func_name, NULL, objfile);
3588           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3589                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3590             {
3591               /* Prevent future lookups in this objfile.  */
3592               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3593               continue;
3594             }
3595           bp_objfile_data->terminate_msym = m;
3596         }
3597
3598       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3599       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3600                                       bp_std_terminate_master,
3601                                       &internal_breakpoint_ops);
3602       b->addr_string = xstrdup (func_name);
3603       b->enable_state = bp_disabled;
3604     }
3605   }
3606
3607   update_global_location_list (UGLL_MAY_INSERT);
3608
3609   do_cleanups (old_chain);
3610 }
3611
3612 /* Install a master breakpoint on the unwinder's debug hook.  */
3613
3614 static void
3615 create_exception_master_breakpoint (void)
3616 {
3617   struct objfile *objfile;
3618   const char *const func_name = "_Unwind_DebugHook";
3619
3620   ALL_OBJFILES (objfile)
3621     {
3622       struct breakpoint *b;
3623       struct gdbarch *gdbarch;
3624       struct breakpoint_objfile_data *bp_objfile_data;
3625       CORE_ADDR addr;
3626
3627       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3628
3629       /* We prefer the SystemTap probe point if it exists.  */
3630       if (!bp_objfile_data->exception_searched)
3631         {
3632           VEC (probe_p) *ret;
3633
3634           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3635
3636           if (ret != NULL)
3637             {
3638               /* We are only interested in checking one element.  */
3639               struct probe *p = VEC_index (probe_p, ret, 0);
3640
3641               if (!can_evaluate_probe_arguments (p))
3642                 {
3643                   /* We cannot use the probe interface here, because it does
3644                      not know how to evaluate arguments.  */
3645                   VEC_free (probe_p, ret);
3646                   ret = NULL;
3647                 }
3648             }
3649           bp_objfile_data->exception_probes = ret;
3650           bp_objfile_data->exception_searched = 1;
3651         }
3652
3653       if (bp_objfile_data->exception_probes != NULL)
3654         {
3655           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3656           int i;
3657           struct probe *probe;
3658
3659           for (i = 0;
3660                VEC_iterate (probe_p,
3661                             bp_objfile_data->exception_probes,
3662                             i, probe);
3663                ++i)
3664             {
3665               struct breakpoint *b;
3666
3667               b = create_internal_breakpoint (gdbarch,
3668                                               get_probe_address (probe,
3669                                                                  objfile),
3670                                               bp_exception_master,
3671                                               &internal_breakpoint_ops);
3672               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3673               b->enable_state = bp_disabled;
3674             }
3675
3676           continue;
3677         }
3678
3679       /* Otherwise, try the hook function.  */
3680
3681       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3682         continue;
3683
3684       gdbarch = get_objfile_arch (objfile);
3685
3686       if (bp_objfile_data->exception_msym.minsym == NULL)
3687         {
3688           struct bound_minimal_symbol debug_hook;
3689
3690           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3691           if (debug_hook.minsym == NULL)
3692             {
3693               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3694               continue;
3695             }
3696
3697           bp_objfile_data->exception_msym = debug_hook;
3698         }
3699
3700       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3701       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3702                                                  &current_target);
3703       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3704                                       &internal_breakpoint_ops);
3705       b->addr_string = xstrdup (func_name);
3706       b->enable_state = bp_disabled;
3707     }
3708
3709   update_global_location_list (UGLL_MAY_INSERT);
3710 }
3711
3712 void
3713 update_breakpoints_after_exec (void)
3714 {
3715   struct breakpoint *b, *b_tmp;
3716   struct bp_location *bploc, **bplocp_tmp;
3717
3718   /* We're about to delete breakpoints from GDB's lists.  If the
3719      INSERTED flag is true, GDB will try to lift the breakpoints by
3720      writing the breakpoints' "shadow contents" back into memory.  The
3721      "shadow contents" are NOT valid after an exec, so GDB should not
3722      do that.  Instead, the target is responsible from marking
3723      breakpoints out as soon as it detects an exec.  We don't do that
3724      here instead, because there may be other attempts to delete
3725      breakpoints after detecting an exec and before reaching here.  */
3726   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3727     if (bploc->pspace == current_program_space)
3728       gdb_assert (!bploc->inserted);
3729
3730   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3731   {
3732     if (b->pspace != current_program_space)
3733       continue;
3734
3735     /* Solib breakpoints must be explicitly reset after an exec().  */
3736     if (b->type == bp_shlib_event)
3737       {
3738         delete_breakpoint (b);
3739         continue;
3740       }
3741
3742     /* JIT breakpoints must be explicitly reset after an exec().  */
3743     if (b->type == bp_jit_event)
3744       {
3745         delete_breakpoint (b);
3746         continue;
3747       }
3748
3749     /* Thread event breakpoints must be set anew after an exec(),
3750        as must overlay event and longjmp master breakpoints.  */
3751     if (b->type == bp_thread_event || b->type == bp_overlay_event
3752         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3753         || b->type == bp_exception_master)
3754       {
3755         delete_breakpoint (b);
3756         continue;
3757       }
3758
3759     /* Step-resume breakpoints are meaningless after an exec().  */
3760     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3761       {
3762         delete_breakpoint (b);
3763         continue;
3764       }
3765
3766     /* Just like single-step breakpoints.  */
3767     if (b->type == bp_single_step)
3768       {
3769         delete_breakpoint (b);
3770         continue;
3771       }
3772
3773     /* Longjmp and longjmp-resume breakpoints are also meaningless
3774        after an exec.  */
3775     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3776         || b->type == bp_longjmp_call_dummy
3777         || b->type == bp_exception || b->type == bp_exception_resume)
3778       {
3779         delete_breakpoint (b);
3780         continue;
3781       }
3782
3783     if (b->type == bp_catchpoint)
3784       {
3785         /* For now, none of the bp_catchpoint breakpoints need to
3786            do anything at this point.  In the future, if some of
3787            the catchpoints need to something, we will need to add
3788            a new method, and call this method from here.  */
3789         continue;
3790       }
3791
3792     /* bp_finish is a special case.  The only way we ought to be able
3793        to see one of these when an exec() has happened, is if the user
3794        caught a vfork, and then said "finish".  Ordinarily a finish just
3795        carries them to the call-site of the current callee, by setting
3796        a temporary bp there and resuming.  But in this case, the finish
3797        will carry them entirely through the vfork & exec.
3798
3799        We don't want to allow a bp_finish to remain inserted now.  But
3800        we can't safely delete it, 'cause finish_command has a handle to
3801        the bp on a bpstat, and will later want to delete it.  There's a
3802        chance (and I've seen it happen) that if we delete the bp_finish
3803        here, that its storage will get reused by the time finish_command
3804        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3805        We really must allow finish_command to delete a bp_finish.
3806
3807        In the absence of a general solution for the "how do we know
3808        it's safe to delete something others may have handles to?"
3809        problem, what we'll do here is just uninsert the bp_finish, and
3810        let finish_command delete it.
3811
3812        (We know the bp_finish is "doomed" in the sense that it's
3813        momentary, and will be deleted as soon as finish_command sees
3814        the inferior stopped.  So it doesn't matter that the bp's
3815        address is probably bogus in the new a.out, unlike e.g., the
3816        solib breakpoints.)  */
3817
3818     if (b->type == bp_finish)
3819       {
3820         continue;
3821       }
3822
3823     /* Without a symbolic address, we have little hope of the
3824        pre-exec() address meaning the same thing in the post-exec()
3825        a.out.  */
3826     if (b->addr_string == NULL)
3827       {
3828         delete_breakpoint (b);
3829         continue;
3830       }
3831   }
3832 }
3833
3834 int
3835 detach_breakpoints (ptid_t ptid)
3836 {
3837   struct bp_location *bl, **blp_tmp;
3838   int val = 0;
3839   struct cleanup *old_chain = save_inferior_ptid ();
3840   struct inferior *inf = current_inferior ();
3841
3842   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3843     error (_("Cannot detach breakpoints of inferior_ptid"));
3844
3845   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3846   inferior_ptid = ptid;
3847   ALL_BP_LOCATIONS (bl, blp_tmp)
3848   {
3849     if (bl->pspace != inf->pspace)
3850       continue;
3851
3852     /* This function must physically remove breakpoints locations
3853        from the specified ptid, without modifying the breakpoint
3854        package's state.  Locations of type bp_loc_other are only
3855        maintained at GDB side.  So, there is no need to remove
3856        these bp_loc_other locations.  Moreover, removing these
3857        would modify the breakpoint package's state.  */
3858     if (bl->loc_type == bp_loc_other)
3859       continue;
3860
3861     if (bl->inserted)
3862       val |= remove_breakpoint_1 (bl, mark_inserted);
3863   }
3864
3865   do_cleanups (old_chain);
3866   return val;
3867 }
3868
3869 /* Remove the breakpoint location BL from the current address space.
3870    Note that this is used to detach breakpoints from a child fork.
3871    When we get here, the child isn't in the inferior list, and neither
3872    do we have objects to represent its address space --- we should
3873    *not* look at bl->pspace->aspace here.  */
3874
3875 static int
3876 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3877 {
3878   int val;
3879
3880   /* BL is never in moribund_locations by our callers.  */
3881   gdb_assert (bl->owner != NULL);
3882
3883   if (bl->permanent)
3884     /* Permanent breakpoints cannot be inserted or removed.  */
3885     return 0;
3886
3887   /* The type of none suggests that owner is actually deleted.
3888      This should not ever happen.  */
3889   gdb_assert (bl->owner->type != bp_none);
3890
3891   if (bl->loc_type == bp_loc_software_breakpoint
3892       || bl->loc_type == bp_loc_hardware_breakpoint)
3893     {
3894       /* "Normal" instruction breakpoint: either the standard
3895          trap-instruction bp (bp_breakpoint), or a
3896          bp_hardware_breakpoint.  */
3897
3898       /* First check to see if we have to handle an overlay.  */
3899       if (overlay_debugging == ovly_off
3900           || bl->section == NULL
3901           || !(section_is_overlay (bl->section)))
3902         {
3903           /* No overlay handling: just remove the breakpoint.  */
3904
3905           /* If we're trying to uninsert a memory breakpoint that we
3906              know is set in a dynamic object that is marked
3907              shlib_disabled, then either the dynamic object was
3908              removed with "remove-symbol-file" or with
3909              "nosharedlibrary".  In the former case, we don't know
3910              whether another dynamic object might have loaded over the
3911              breakpoint's address -- the user might well let us know
3912              about it next with add-symbol-file (the whole point of
3913              add-symbol-file is letting the user manually maintain a
3914              list of dynamically loaded objects).  If we have the
3915              breakpoint's shadow memory, that is, this is a software
3916              breakpoint managed by GDB, check whether the breakpoint
3917              is still inserted in memory, to avoid overwriting wrong
3918              code with stale saved shadow contents.  Note that HW
3919              breakpoints don't have shadow memory, as they're
3920              implemented using a mechanism that is not dependent on
3921              being able to modify the target's memory, and as such
3922              they should always be removed.  */
3923           if (bl->shlib_disabled
3924               && bl->target_info.shadow_len != 0
3925               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3926             val = 0;
3927           else
3928             val = bl->owner->ops->remove_location (bl);
3929         }
3930       else
3931         {
3932           /* This breakpoint is in an overlay section.
3933              Did we set a breakpoint at the LMA?  */
3934           if (!overlay_events_enabled)
3935               {
3936                 /* Yes -- overlay event support is not active, so we
3937                    should have set a breakpoint at the LMA.  Remove it.  
3938                 */
3939                 /* Ignore any failures: if the LMA is in ROM, we will
3940                    have already warned when we failed to insert it.  */
3941                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3942                   target_remove_hw_breakpoint (bl->gdbarch,
3943                                                &bl->overlay_target_info);
3944                 else
3945                   target_remove_breakpoint (bl->gdbarch,
3946                                             &bl->overlay_target_info);
3947               }
3948           /* Did we set a breakpoint at the VMA? 
3949              If so, we will have marked the breakpoint 'inserted'.  */
3950           if (bl->inserted)
3951             {
3952               /* Yes -- remove it.  Previously we did not bother to
3953                  remove the breakpoint if the section had been
3954                  unmapped, but let's not rely on that being safe.  We
3955                  don't know what the overlay manager might do.  */
3956
3957               /* However, we should remove *software* breakpoints only
3958                  if the section is still mapped, or else we overwrite
3959                  wrong code with the saved shadow contents.  */
3960               if (bl->loc_type == bp_loc_hardware_breakpoint
3961                   || section_is_mapped (bl->section))
3962                 val = bl->owner->ops->remove_location (bl);
3963               else
3964                 val = 0;
3965             }
3966           else
3967             {
3968               /* No -- not inserted, so no need to remove.  No error.  */
3969               val = 0;
3970             }
3971         }
3972
3973       /* In some cases, we might not be able to remove a breakpoint in
3974          a shared library that has already been removed, but we have
3975          not yet processed the shlib unload event.  Similarly for an
3976          unloaded add-symbol-file object - the user might not yet have
3977          had the chance to remove-symbol-file it.  shlib_disabled will
3978          be set if the library/object has already been removed, but
3979          the breakpoint hasn't been uninserted yet, e.g., after
3980          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3981          always-inserted mode.  */
3982       if (val
3983           && (bl->loc_type == bp_loc_software_breakpoint
3984               && (bl->shlib_disabled
3985                   || solib_name_from_address (bl->pspace, bl->address)
3986                   || shared_objfile_contains_address_p (bl->pspace,
3987                                                         bl->address))))
3988         val = 0;
3989
3990       if (val)
3991         return val;
3992       bl->inserted = (is == mark_inserted);
3993     }
3994   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3995     {
3996       gdb_assert (bl->owner->ops != NULL
3997                   && bl->owner->ops->remove_location != NULL);
3998
3999       bl->inserted = (is == mark_inserted);
4000       bl->owner->ops->remove_location (bl);
4001
4002       /* Failure to remove any of the hardware watchpoints comes here.  */
4003       if ((is == mark_uninserted) && (bl->inserted))
4004         warning (_("Could not remove hardware watchpoint %d."),
4005                  bl->owner->number);
4006     }
4007   else if (bl->owner->type == bp_catchpoint
4008            && breakpoint_enabled (bl->owner)
4009            && !bl->duplicate)
4010     {
4011       gdb_assert (bl->owner->ops != NULL
4012                   && bl->owner->ops->remove_location != NULL);
4013
4014       val = bl->owner->ops->remove_location (bl);
4015       if (val)
4016         return val;
4017
4018       bl->inserted = (is == mark_inserted);
4019     }
4020
4021   return 0;
4022 }
4023
4024 static int
4025 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4026 {
4027   int ret;
4028   struct cleanup *old_chain;
4029
4030   /* BL is never in moribund_locations by our callers.  */
4031   gdb_assert (bl->owner != NULL);
4032
4033   if (bl->permanent)
4034     /* Permanent breakpoints cannot be inserted or removed.  */
4035     return 0;
4036
4037   /* The type of none suggests that owner is actually deleted.
4038      This should not ever happen.  */
4039   gdb_assert (bl->owner->type != bp_none);
4040
4041   old_chain = save_current_space_and_thread ();
4042
4043   switch_to_program_space_and_thread (bl->pspace);
4044
4045   ret = remove_breakpoint_1 (bl, is);
4046
4047   do_cleanups (old_chain);
4048   return ret;
4049 }
4050
4051 /* Clear the "inserted" flag in all breakpoints.  */
4052
4053 void
4054 mark_breakpoints_out (void)
4055 {
4056   struct bp_location *bl, **blp_tmp;
4057
4058   ALL_BP_LOCATIONS (bl, blp_tmp)
4059     if (bl->pspace == current_program_space
4060         && !bl->permanent)
4061       bl->inserted = 0;
4062 }
4063
4064 /* Clear the "inserted" flag in all breakpoints and delete any
4065    breakpoints which should go away between runs of the program.
4066
4067    Plus other such housekeeping that has to be done for breakpoints
4068    between runs.
4069
4070    Note: this function gets called at the end of a run (by
4071    generic_mourn_inferior) and when a run begins (by
4072    init_wait_for_inferior).  */
4073
4074
4075
4076 void
4077 breakpoint_init_inferior (enum inf_context context)
4078 {
4079   struct breakpoint *b, *b_tmp;
4080   struct bp_location *bl, **blp_tmp;
4081   int ix;
4082   struct program_space *pspace = current_program_space;
4083
4084   /* If breakpoint locations are shared across processes, then there's
4085      nothing to do.  */
4086   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4087     return;
4088
4089   mark_breakpoints_out ();
4090
4091   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4092   {
4093     if (b->loc && b->loc->pspace != pspace)
4094       continue;
4095
4096     switch (b->type)
4097       {
4098       case bp_call_dummy:
4099       case bp_longjmp_call_dummy:
4100
4101         /* If the call dummy breakpoint is at the entry point it will
4102            cause problems when the inferior is rerun, so we better get
4103            rid of it.  */
4104
4105       case bp_watchpoint_scope:
4106
4107         /* Also get rid of scope breakpoints.  */
4108
4109       case bp_shlib_event:
4110
4111         /* Also remove solib event breakpoints.  Their addresses may
4112            have changed since the last time we ran the program.
4113            Actually we may now be debugging against different target;
4114            and so the solib backend that installed this breakpoint may
4115            not be used in by the target.  E.g.,
4116
4117            (gdb) file prog-linux
4118            (gdb) run               # native linux target
4119            ...
4120            (gdb) kill
4121            (gdb) file prog-win.exe
4122            (gdb) tar rem :9999     # remote Windows gdbserver.
4123         */
4124
4125       case bp_step_resume:
4126
4127         /* Also remove step-resume breakpoints.  */
4128
4129       case bp_single_step:
4130
4131         /* Also remove single-step breakpoints.  */
4132
4133         delete_breakpoint (b);
4134         break;
4135
4136       case bp_watchpoint:
4137       case bp_hardware_watchpoint:
4138       case bp_read_watchpoint:
4139       case bp_access_watchpoint:
4140         {
4141           struct watchpoint *w = (struct watchpoint *) b;
4142
4143           /* Likewise for watchpoints on local expressions.  */
4144           if (w->exp_valid_block != NULL)
4145             delete_breakpoint (b);
4146           else if (context == inf_starting)
4147             {
4148               /* Reset val field to force reread of starting value in
4149                  insert_breakpoints.  */
4150               if (w->val)
4151                 value_free (w->val);
4152               w->val = NULL;
4153               w->val_valid = 0;
4154           }
4155         }
4156         break;
4157       default:
4158         break;
4159       }
4160   }
4161
4162   /* Get rid of the moribund locations.  */
4163   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4164     decref_bp_location (&bl);
4165   VEC_free (bp_location_p, moribund_locations);
4166 }
4167
4168 /* These functions concern about actual breakpoints inserted in the
4169    target --- to e.g. check if we need to do decr_pc adjustment or if
4170    we need to hop over the bkpt --- so we check for address space
4171    match, not program space.  */
4172
4173 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4174    exists at PC.  It returns ordinary_breakpoint_here if it's an
4175    ordinary breakpoint, or permanent_breakpoint_here if it's a
4176    permanent breakpoint.
4177    - When continuing from a location with an ordinary breakpoint, we
4178      actually single step once before calling insert_breakpoints.
4179    - When continuing from a location with a permanent breakpoint, we
4180      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4181      the target, to advance the PC past the breakpoint.  */
4182
4183 enum breakpoint_here
4184 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4185 {
4186   struct bp_location *bl, **blp_tmp;
4187   int any_breakpoint_here = 0;
4188
4189   ALL_BP_LOCATIONS (bl, blp_tmp)
4190     {
4191       if (bl->loc_type != bp_loc_software_breakpoint
4192           && bl->loc_type != bp_loc_hardware_breakpoint)
4193         continue;
4194
4195       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4196       if ((breakpoint_enabled (bl->owner)
4197            || bl->permanent)
4198           && breakpoint_location_address_match (bl, aspace, pc))
4199         {
4200           if (overlay_debugging 
4201               && section_is_overlay (bl->section)
4202               && !section_is_mapped (bl->section))
4203             continue;           /* unmapped overlay -- can't be a match */
4204           else if (bl->permanent)
4205             return permanent_breakpoint_here;
4206           else
4207             any_breakpoint_here = 1;
4208         }
4209     }
4210
4211   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4212 }
4213
4214 /* Return true if there's a moribund breakpoint at PC.  */
4215
4216 int
4217 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4218 {
4219   struct bp_location *loc;
4220   int ix;
4221
4222   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4223     if (breakpoint_location_address_match (loc, aspace, pc))
4224       return 1;
4225
4226   return 0;
4227 }
4228
4229 /* Returns non-zero iff there's a breakpoint inserted at PC.  */
4230
4231 int
4232 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4233 {
4234   struct bp_location *bl, **blp_tmp;
4235
4236   ALL_BP_LOCATIONS (bl, blp_tmp)
4237     {
4238       if (bl->loc_type != bp_loc_software_breakpoint
4239           && bl->loc_type != bp_loc_hardware_breakpoint)
4240         continue;
4241
4242       if (bl->inserted
4243           && breakpoint_location_address_match (bl, aspace, pc))
4244         {
4245           if (overlay_debugging 
4246               && section_is_overlay (bl->section)
4247               && !section_is_mapped (bl->section))
4248             continue;           /* unmapped overlay -- can't be a match */
4249           else
4250             return 1;
4251         }
4252     }
4253   return 0;
4254 }
4255
4256 /* This function returns non-zero iff there is a software breakpoint
4257    inserted at PC.  */
4258
4259 int
4260 software_breakpoint_inserted_here_p (struct address_space *aspace,
4261                                      CORE_ADDR pc)
4262 {
4263   struct bp_location *bl, **blp_tmp;
4264
4265   ALL_BP_LOCATIONS (bl, blp_tmp)
4266     {
4267       if (bl->loc_type != bp_loc_software_breakpoint)
4268         continue;
4269
4270       if (bl->inserted
4271           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4272                                        aspace, pc))
4273         {
4274           if (overlay_debugging 
4275               && section_is_overlay (bl->section)
4276               && !section_is_mapped (bl->section))
4277             continue;           /* unmapped overlay -- can't be a match */
4278           else
4279             return 1;
4280         }
4281     }
4282
4283   return 0;
4284 }
4285
4286 int
4287 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4288                                        CORE_ADDR addr, ULONGEST len)
4289 {
4290   struct breakpoint *bpt;
4291
4292   ALL_BREAKPOINTS (bpt)
4293     {
4294       struct bp_location *loc;
4295
4296       if (bpt->type != bp_hardware_watchpoint
4297           && bpt->type != bp_access_watchpoint)
4298         continue;
4299
4300       if (!breakpoint_enabled (bpt))
4301         continue;
4302
4303       for (loc = bpt->loc; loc; loc = loc->next)
4304         if (loc->pspace->aspace == aspace && loc->inserted)
4305           {
4306             CORE_ADDR l, h;
4307
4308             /* Check for intersection.  */
4309             l = max (loc->address, addr);
4310             h = min (loc->address + loc->length, addr + len);
4311             if (l < h)
4312               return 1;
4313           }
4314     }
4315   return 0;
4316 }
4317 \f
4318
4319 /* bpstat stuff.  External routines' interfaces are documented
4320    in breakpoint.h.  */
4321
4322 int
4323 is_catchpoint (struct breakpoint *ep)
4324 {
4325   return (ep->type == bp_catchpoint);
4326 }
4327
4328 /* Frees any storage that is part of a bpstat.  Does not walk the
4329    'next' chain.  */
4330
4331 static void
4332 bpstat_free (bpstat bs)
4333 {
4334   if (bs->old_val != NULL)
4335     value_free (bs->old_val);
4336   decref_counted_command_line (&bs->commands);
4337   decref_bp_location (&bs->bp_location_at);
4338   xfree (bs);
4339 }
4340
4341 /* Clear a bpstat so that it says we are not at any breakpoint.
4342    Also free any storage that is part of a bpstat.  */
4343
4344 void
4345 bpstat_clear (bpstat *bsp)
4346 {
4347   bpstat p;
4348   bpstat q;
4349
4350   if (bsp == 0)
4351     return;
4352   p = *bsp;
4353   while (p != NULL)
4354     {
4355       q = p->next;
4356       bpstat_free (p);
4357       p = q;
4358     }
4359   *bsp = NULL;
4360 }
4361
4362 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4363    is part of the bpstat is copied as well.  */
4364
4365 bpstat
4366 bpstat_copy (bpstat bs)
4367 {
4368   bpstat p = NULL;
4369   bpstat tmp;
4370   bpstat retval = NULL;
4371
4372   if (bs == NULL)
4373     return bs;
4374
4375   for (; bs != NULL; bs = bs->next)
4376     {
4377       tmp = (bpstat) xmalloc (sizeof (*tmp));
4378       memcpy (tmp, bs, sizeof (*tmp));
4379       incref_counted_command_line (tmp->commands);
4380       incref_bp_location (tmp->bp_location_at);
4381       if (bs->old_val != NULL)
4382         {
4383           tmp->old_val = value_copy (bs->old_val);
4384           release_value (tmp->old_val);
4385         }
4386
4387       if (p == NULL)
4388         /* This is the first thing in the chain.  */
4389         retval = tmp;
4390       else
4391         p->next = tmp;
4392       p = tmp;
4393     }
4394   p->next = NULL;
4395   return retval;
4396 }
4397
4398 /* Find the bpstat associated with this breakpoint.  */
4399
4400 bpstat
4401 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4402 {
4403   if (bsp == NULL)
4404     return NULL;
4405
4406   for (; bsp != NULL; bsp = bsp->next)
4407     {
4408       if (bsp->breakpoint_at == breakpoint)
4409         return bsp;
4410     }
4411   return NULL;
4412 }
4413
4414 /* See breakpoint.h.  */
4415
4416 int
4417 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4418 {
4419   for (; bsp != NULL; bsp = bsp->next)
4420     {
4421       if (bsp->breakpoint_at == NULL)
4422         {
4423           /* A moribund location can never explain a signal other than
4424              GDB_SIGNAL_TRAP.  */
4425           if (sig == GDB_SIGNAL_TRAP)
4426             return 1;
4427         }
4428       else
4429         {
4430           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4431                                                         sig))
4432             return 1;
4433         }
4434     }
4435
4436   return 0;
4437 }
4438
4439 /* Put in *NUM the breakpoint number of the first breakpoint we are
4440    stopped at.  *BSP upon return is a bpstat which points to the
4441    remaining breakpoints stopped at (but which is not guaranteed to be
4442    good for anything but further calls to bpstat_num).
4443
4444    Return 0 if passed a bpstat which does not indicate any breakpoints.
4445    Return -1 if stopped at a breakpoint that has been deleted since
4446    we set it.
4447    Return 1 otherwise.  */
4448
4449 int
4450 bpstat_num (bpstat *bsp, int *num)
4451 {
4452   struct breakpoint *b;
4453
4454   if ((*bsp) == NULL)
4455     return 0;                   /* No more breakpoint values */
4456
4457   /* We assume we'll never have several bpstats that correspond to a
4458      single breakpoint -- otherwise, this function might return the
4459      same number more than once and this will look ugly.  */
4460   b = (*bsp)->breakpoint_at;
4461   *bsp = (*bsp)->next;
4462   if (b == NULL)
4463     return -1;                  /* breakpoint that's been deleted since */
4464
4465   *num = b->number;             /* We have its number */
4466   return 1;
4467 }
4468
4469 /* See breakpoint.h.  */
4470
4471 void
4472 bpstat_clear_actions (void)
4473 {
4474   struct thread_info *tp;
4475   bpstat bs;
4476
4477   if (ptid_equal (inferior_ptid, null_ptid))
4478     return;
4479
4480   tp = find_thread_ptid (inferior_ptid);
4481   if (tp == NULL)
4482     return;
4483
4484   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4485     {
4486       decref_counted_command_line (&bs->commands);
4487
4488       if (bs->old_val != NULL)
4489         {
4490           value_free (bs->old_val);
4491           bs->old_val = NULL;
4492         }
4493     }
4494 }
4495
4496 /* Called when a command is about to proceed the inferior.  */
4497
4498 static void
4499 breakpoint_about_to_proceed (void)
4500 {
4501   if (!ptid_equal (inferior_ptid, null_ptid))
4502     {
4503       struct thread_info *tp = inferior_thread ();
4504
4505       /* Allow inferior function calls in breakpoint commands to not
4506          interrupt the command list.  When the call finishes
4507          successfully, the inferior will be standing at the same
4508          breakpoint as if nothing happened.  */
4509       if (tp->control.in_infcall)
4510         return;
4511     }
4512
4513   breakpoint_proceeded = 1;
4514 }
4515
4516 /* Stub for cleaning up our state if we error-out of a breakpoint
4517    command.  */
4518 static void
4519 cleanup_executing_breakpoints (void *ignore)
4520 {
4521   executing_breakpoint_commands = 0;
4522 }
4523
4524 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4525    or its equivalent.  */
4526
4527 static int
4528 command_line_is_silent (struct command_line *cmd)
4529 {
4530   return cmd && (strcmp ("silent", cmd->line) == 0
4531                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4532 }
4533
4534 /* Execute all the commands associated with all the breakpoints at
4535    this location.  Any of these commands could cause the process to
4536    proceed beyond this point, etc.  We look out for such changes by
4537    checking the global "breakpoint_proceeded" after each command.
4538
4539    Returns true if a breakpoint command resumed the inferior.  In that
4540    case, it is the caller's responsibility to recall it again with the
4541    bpstat of the current thread.  */
4542
4543 static int
4544 bpstat_do_actions_1 (bpstat *bsp)
4545 {
4546   bpstat bs;
4547   struct cleanup *old_chain;
4548   int again = 0;
4549
4550   /* Avoid endless recursion if a `source' command is contained
4551      in bs->commands.  */
4552   if (executing_breakpoint_commands)
4553     return 0;
4554
4555   executing_breakpoint_commands = 1;
4556   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4557
4558   prevent_dont_repeat ();
4559
4560   /* This pointer will iterate over the list of bpstat's.  */
4561   bs = *bsp;
4562
4563   breakpoint_proceeded = 0;
4564   for (; bs != NULL; bs = bs->next)
4565     {
4566       struct counted_command_line *ccmd;
4567       struct command_line *cmd;
4568       struct cleanup *this_cmd_tree_chain;
4569
4570       /* Take ownership of the BSP's command tree, if it has one.
4571
4572          The command tree could legitimately contain commands like
4573          'step' and 'next', which call clear_proceed_status, which
4574          frees stop_bpstat's command tree.  To make sure this doesn't
4575          free the tree we're executing out from under us, we need to
4576          take ownership of the tree ourselves.  Since a given bpstat's
4577          commands are only executed once, we don't need to copy it; we
4578          can clear the pointer in the bpstat, and make sure we free
4579          the tree when we're done.  */
4580       ccmd = bs->commands;
4581       bs->commands = NULL;
4582       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4583       cmd = ccmd ? ccmd->commands : NULL;
4584       if (command_line_is_silent (cmd))
4585         {
4586           /* The action has been already done by bpstat_stop_status.  */
4587           cmd = cmd->next;
4588         }
4589
4590       while (cmd != NULL)
4591         {
4592           execute_control_command (cmd);
4593
4594           if (breakpoint_proceeded)
4595             break;
4596           else
4597             cmd = cmd->next;
4598         }
4599
4600       /* We can free this command tree now.  */
4601       do_cleanups (this_cmd_tree_chain);
4602
4603       if (breakpoint_proceeded)
4604         {
4605           if (target_can_async_p ())
4606             /* If we are in async mode, then the target might be still
4607                running, not stopped at any breakpoint, so nothing for
4608                us to do here -- just return to the event loop.  */
4609             ;
4610           else
4611             /* In sync mode, when execute_control_command returns
4612                we're already standing on the next breakpoint.
4613                Breakpoint commands for that stop were not run, since
4614                execute_command does not run breakpoint commands --
4615                only command_line_handler does, but that one is not
4616                involved in execution of breakpoint commands.  So, we
4617                can now execute breakpoint commands.  It should be
4618                noted that making execute_command do bpstat actions is
4619                not an option -- in this case we'll have recursive
4620                invocation of bpstat for each breakpoint with a
4621                command, and can easily blow up GDB stack.  Instead, we
4622                return true, which will trigger the caller to recall us
4623                with the new stop_bpstat.  */
4624             again = 1;
4625           break;
4626         }
4627     }
4628   do_cleanups (old_chain);
4629   return again;
4630 }
4631
4632 void
4633 bpstat_do_actions (void)
4634 {
4635   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4636
4637   /* Do any commands attached to breakpoint we are stopped at.  */
4638   while (!ptid_equal (inferior_ptid, null_ptid)
4639          && target_has_execution
4640          && !is_exited (inferior_ptid)
4641          && !is_executing (inferior_ptid))
4642     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4643        and only return when it is stopped at the next breakpoint, we
4644        keep doing breakpoint actions until it returns false to
4645        indicate the inferior was not resumed.  */
4646     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4647       break;
4648
4649   discard_cleanups (cleanup_if_error);
4650 }
4651
4652 /* Print out the (old or new) value associated with a watchpoint.  */
4653
4654 static void
4655 watchpoint_value_print (struct value *val, struct ui_file *stream)
4656 {
4657   if (val == NULL)
4658     fprintf_unfiltered (stream, _("<unreadable>"));
4659   else
4660     {
4661       struct value_print_options opts;
4662       get_user_print_options (&opts);
4663       value_print (val, stream, &opts);
4664     }
4665 }
4666
4667 /* Generic routine for printing messages indicating why we
4668    stopped.  The behavior of this function depends on the value
4669    'print_it' in the bpstat structure.  Under some circumstances we
4670    may decide not to print anything here and delegate the task to
4671    normal_stop().  */
4672
4673 static enum print_stop_action
4674 print_bp_stop_message (bpstat bs)
4675 {
4676   switch (bs->print_it)
4677     {
4678     case print_it_noop:
4679       /* Nothing should be printed for this bpstat entry.  */
4680       return PRINT_UNKNOWN;
4681       break;
4682
4683     case print_it_done:
4684       /* We still want to print the frame, but we already printed the
4685          relevant messages.  */
4686       return PRINT_SRC_AND_LOC;
4687       break;
4688
4689     case print_it_normal:
4690       {
4691         struct breakpoint *b = bs->breakpoint_at;
4692
4693         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4694            which has since been deleted.  */
4695         if (b == NULL)
4696           return PRINT_UNKNOWN;
4697
4698         /* Normal case.  Call the breakpoint's print_it method.  */
4699         return b->ops->print_it (bs);
4700       }
4701       break;
4702
4703     default:
4704       internal_error (__FILE__, __LINE__,
4705                       _("print_bp_stop_message: unrecognized enum value"));
4706       break;
4707     }
4708 }
4709
4710 /* A helper function that prints a shared library stopped event.  */
4711
4712 static void
4713 print_solib_event (int is_catchpoint)
4714 {
4715   int any_deleted
4716     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4717   int any_added
4718     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4719
4720   if (!is_catchpoint)
4721     {
4722       if (any_added || any_deleted)
4723         ui_out_text (current_uiout,
4724                      _("Stopped due to shared library event:\n"));
4725       else
4726         ui_out_text (current_uiout,
4727                      _("Stopped due to shared library event (no "
4728                        "libraries added or removed)\n"));
4729     }
4730
4731   if (ui_out_is_mi_like_p (current_uiout))
4732     ui_out_field_string (current_uiout, "reason",
4733                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4734
4735   if (any_deleted)
4736     {
4737       struct cleanup *cleanup;
4738       char *name;
4739       int ix;
4740
4741       ui_out_text (current_uiout, _("  Inferior unloaded "));
4742       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4743                                                     "removed");
4744       for (ix = 0;
4745            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4746                         ix, name);
4747            ++ix)
4748         {
4749           if (ix > 0)
4750             ui_out_text (current_uiout, "    ");
4751           ui_out_field_string (current_uiout, "library", name);
4752           ui_out_text (current_uiout, "\n");
4753         }
4754
4755       do_cleanups (cleanup);
4756     }
4757
4758   if (any_added)
4759     {
4760       struct so_list *iter;
4761       int ix;
4762       struct cleanup *cleanup;
4763
4764       ui_out_text (current_uiout, _("  Inferior loaded "));
4765       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4766                                                     "added");
4767       for (ix = 0;
4768            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4769                         ix, iter);
4770            ++ix)
4771         {
4772           if (ix > 0)
4773             ui_out_text (current_uiout, "    ");
4774           ui_out_field_string (current_uiout, "library", iter->so_name);
4775           ui_out_text (current_uiout, "\n");
4776         }
4777
4778       do_cleanups (cleanup);
4779     }
4780 }
4781
4782 /* Print a message indicating what happened.  This is called from
4783    normal_stop().  The input to this routine is the head of the bpstat
4784    list - a list of the eventpoints that caused this stop.  KIND is
4785    the target_waitkind for the stopping event.  This
4786    routine calls the generic print routine for printing a message
4787    about reasons for stopping.  This will print (for example) the
4788    "Breakpoint n," part of the output.  The return value of this
4789    routine is one of:
4790
4791    PRINT_UNKNOWN: Means we printed nothing.
4792    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4793    code to print the location.  An example is 
4794    "Breakpoint 1, " which should be followed by
4795    the location.
4796    PRINT_SRC_ONLY: Means we printed something, but there is no need
4797    to also print the location part of the message.
4798    An example is the catch/throw messages, which
4799    don't require a location appended to the end.
4800    PRINT_NOTHING: We have done some printing and we don't need any 
4801    further info to be printed.  */
4802
4803 enum print_stop_action
4804 bpstat_print (bpstat bs, int kind)
4805 {
4806   int val;
4807
4808   /* Maybe another breakpoint in the chain caused us to stop.
4809      (Currently all watchpoints go on the bpstat whether hit or not.
4810      That probably could (should) be changed, provided care is taken
4811      with respect to bpstat_explains_signal).  */
4812   for (; bs; bs = bs->next)
4813     {
4814       val = print_bp_stop_message (bs);
4815       if (val == PRINT_SRC_ONLY 
4816           || val == PRINT_SRC_AND_LOC 
4817           || val == PRINT_NOTHING)
4818         return val;
4819     }
4820
4821   /* If we had hit a shared library event breakpoint,
4822      print_bp_stop_message would print out this message.  If we hit an
4823      OS-level shared library event, do the same thing.  */
4824   if (kind == TARGET_WAITKIND_LOADED)
4825     {
4826       print_solib_event (0);
4827       return PRINT_NOTHING;
4828     }
4829
4830   /* We reached the end of the chain, or we got a null BS to start
4831      with and nothing was printed.  */
4832   return PRINT_UNKNOWN;
4833 }
4834
4835 /* Evaluate the expression EXP and return 1 if value is zero.
4836    This returns the inverse of the condition because it is called
4837    from catch_errors which returns 0 if an exception happened, and if an
4838    exception happens we want execution to stop.
4839    The argument is a "struct expression *" that has been cast to a
4840    "void *" to make it pass through catch_errors.  */
4841
4842 static int
4843 breakpoint_cond_eval (void *exp)
4844 {
4845   struct value *mark = value_mark ();
4846   int i = !value_true (evaluate_expression ((struct expression *) exp));
4847
4848   value_free_to_mark (mark);
4849   return i;
4850 }
4851
4852 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4853
4854 static bpstat
4855 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4856 {
4857   bpstat bs;
4858
4859   bs = (bpstat) xmalloc (sizeof (*bs));
4860   bs->next = NULL;
4861   **bs_link_pointer = bs;
4862   *bs_link_pointer = &bs->next;
4863   bs->breakpoint_at = bl->owner;
4864   bs->bp_location_at = bl;
4865   incref_bp_location (bl);
4866   /* If the condition is false, etc., don't do the commands.  */
4867   bs->commands = NULL;
4868   bs->old_val = NULL;
4869   bs->print_it = print_it_normal;
4870   return bs;
4871 }
4872 \f
4873 /* The target has stopped with waitstatus WS.  Check if any hardware
4874    watchpoints have triggered, according to the target.  */
4875
4876 int
4877 watchpoints_triggered (struct target_waitstatus *ws)
4878 {
4879   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4880   CORE_ADDR addr;
4881   struct breakpoint *b;
4882
4883   if (!stopped_by_watchpoint)
4884     {
4885       /* We were not stopped by a watchpoint.  Mark all watchpoints
4886          as not triggered.  */
4887       ALL_BREAKPOINTS (b)
4888         if (is_hardware_watchpoint (b))
4889           {
4890             struct watchpoint *w = (struct watchpoint *) b;
4891
4892             w->watchpoint_triggered = watch_triggered_no;
4893           }
4894
4895       return 0;
4896     }
4897
4898   if (!target_stopped_data_address (&current_target, &addr))
4899     {
4900       /* We were stopped by a watchpoint, but we don't know where.
4901          Mark all watchpoints as unknown.  */
4902       ALL_BREAKPOINTS (b)
4903         if (is_hardware_watchpoint (b))
4904           {
4905             struct watchpoint *w = (struct watchpoint *) b;
4906
4907             w->watchpoint_triggered = watch_triggered_unknown;
4908           }
4909
4910       return 1;
4911     }
4912
4913   /* The target could report the data address.  Mark watchpoints
4914      affected by this data address as triggered, and all others as not
4915      triggered.  */
4916
4917   ALL_BREAKPOINTS (b)
4918     if (is_hardware_watchpoint (b))
4919       {
4920         struct watchpoint *w = (struct watchpoint *) b;
4921         struct bp_location *loc;
4922
4923         w->watchpoint_triggered = watch_triggered_no;
4924         for (loc = b->loc; loc; loc = loc->next)
4925           {
4926             if (is_masked_watchpoint (b))
4927               {
4928                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4929                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4930
4931                 if (newaddr == start)
4932                   {
4933                     w->watchpoint_triggered = watch_triggered_yes;
4934                     break;
4935                   }
4936               }
4937             /* Exact match not required.  Within range is sufficient.  */
4938             else if (target_watchpoint_addr_within_range (&current_target,
4939                                                          addr, loc->address,
4940                                                          loc->length))
4941               {
4942                 w->watchpoint_triggered = watch_triggered_yes;
4943                 break;
4944               }
4945           }
4946       }
4947
4948   return 1;
4949 }
4950
4951 /* Possible return values for watchpoint_check (this can't be an enum
4952    because of check_errors).  */
4953 /* The watchpoint has been deleted.  */
4954 #define WP_DELETED 1
4955 /* The value has changed.  */
4956 #define WP_VALUE_CHANGED 2
4957 /* The value has not changed.  */
4958 #define WP_VALUE_NOT_CHANGED 3
4959 /* Ignore this watchpoint, no matter if the value changed or not.  */
4960 #define WP_IGNORE 4
4961
4962 #define BP_TEMPFLAG 1
4963 #define BP_HARDWAREFLAG 2
4964
4965 /* Evaluate watchpoint condition expression and check if its value
4966    changed.
4967
4968    P should be a pointer to struct bpstat, but is defined as a void *
4969    in order for this function to be usable with catch_errors.  */
4970
4971 static int
4972 watchpoint_check (void *p)
4973 {
4974   bpstat bs = (bpstat) p;
4975   struct watchpoint *b;
4976   struct frame_info *fr;
4977   int within_current_scope;
4978
4979   /* BS is built from an existing struct breakpoint.  */
4980   gdb_assert (bs->breakpoint_at != NULL);
4981   b = (struct watchpoint *) bs->breakpoint_at;
4982
4983   /* If this is a local watchpoint, we only want to check if the
4984      watchpoint frame is in scope if the current thread is the thread
4985      that was used to create the watchpoint.  */
4986   if (!watchpoint_in_thread_scope (b))
4987     return WP_IGNORE;
4988
4989   if (b->exp_valid_block == NULL)
4990     within_current_scope = 1;
4991   else
4992     {
4993       struct frame_info *frame = get_current_frame ();
4994       struct gdbarch *frame_arch = get_frame_arch (frame);
4995       CORE_ADDR frame_pc = get_frame_pc (frame);
4996
4997       /* in_function_epilogue_p() returns a non-zero value if we're
4998          still in the function but the stack frame has already been
4999          invalidated.  Since we can't rely on the values of local
5000          variables after the stack has been destroyed, we are treating
5001          the watchpoint in that state as `not changed' without further
5002          checking.  Don't mark watchpoints as changed if the current
5003          frame is in an epilogue - even if they are in some other
5004          frame, our view of the stack is likely to be wrong and
5005          frame_find_by_id could error out.  */
5006       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
5007         return WP_IGNORE;
5008
5009       fr = frame_find_by_id (b->watchpoint_frame);
5010       within_current_scope = (fr != NULL);
5011
5012       /* If we've gotten confused in the unwinder, we might have
5013          returned a frame that can't describe this variable.  */
5014       if (within_current_scope)
5015         {
5016           struct symbol *function;
5017
5018           function = get_frame_function (fr);
5019           if (function == NULL
5020               || !contained_in (b->exp_valid_block,
5021                                 SYMBOL_BLOCK_VALUE (function)))
5022             within_current_scope = 0;
5023         }
5024
5025       if (within_current_scope)
5026         /* If we end up stopping, the current frame will get selected
5027            in normal_stop.  So this call to select_frame won't affect
5028            the user.  */
5029         select_frame (fr);
5030     }
5031
5032   if (within_current_scope)
5033     {
5034       /* We use value_{,free_to_}mark because it could be a *long*
5035          time before we return to the command level and call
5036          free_all_values.  We can't call free_all_values because we
5037          might be in the middle of evaluating a function call.  */
5038
5039       int pc = 0;
5040       struct value *mark;
5041       struct value *new_val;
5042
5043       if (is_masked_watchpoint (&b->base))
5044         /* Since we don't know the exact trigger address (from
5045            stopped_data_address), just tell the user we've triggered
5046            a mask watchpoint.  */
5047         return WP_VALUE_CHANGED;
5048
5049       mark = value_mark ();
5050       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5051
5052       if (b->val_bitsize != 0)
5053         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5054
5055       /* We use value_equal_contents instead of value_equal because
5056          the latter coerces an array to a pointer, thus comparing just
5057          the address of the array instead of its contents.  This is
5058          not what we want.  */
5059       if ((b->val != NULL) != (new_val != NULL)
5060           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5061         {
5062           if (new_val != NULL)
5063             {
5064               release_value (new_val);
5065               value_free_to_mark (mark);
5066             }
5067           bs->old_val = b->val;
5068           b->val = new_val;
5069           b->val_valid = 1;
5070           return WP_VALUE_CHANGED;
5071         }
5072       else
5073         {
5074           /* Nothing changed.  */
5075           value_free_to_mark (mark);
5076           return WP_VALUE_NOT_CHANGED;
5077         }
5078     }
5079   else
5080     {
5081       struct ui_out *uiout = current_uiout;
5082
5083       /* This seems like the only logical thing to do because
5084          if we temporarily ignored the watchpoint, then when
5085          we reenter the block in which it is valid it contains
5086          garbage (in the case of a function, it may have two
5087          garbage values, one before and one after the prologue).
5088          So we can't even detect the first assignment to it and
5089          watch after that (since the garbage may or may not equal
5090          the first value assigned).  */
5091       /* We print all the stop information in
5092          breakpoint_ops->print_it, but in this case, by the time we
5093          call breakpoint_ops->print_it this bp will be deleted
5094          already.  So we have no choice but print the information
5095          here.  */
5096       if (ui_out_is_mi_like_p (uiout))
5097         ui_out_field_string
5098           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5099       ui_out_text (uiout, "\nWatchpoint ");
5100       ui_out_field_int (uiout, "wpnum", b->base.number);
5101       ui_out_text (uiout,
5102                    " deleted because the program has left the block in\n\
5103 which its expression is valid.\n");     
5104
5105       /* Make sure the watchpoint's commands aren't executed.  */
5106       decref_counted_command_line (&b->base.commands);
5107       watchpoint_del_at_next_stop (b);
5108
5109       return WP_DELETED;
5110     }
5111 }
5112
5113 /* Return true if it looks like target has stopped due to hitting
5114    breakpoint location BL.  This function does not check if we should
5115    stop, only if BL explains the stop.  */
5116
5117 static int
5118 bpstat_check_location (const struct bp_location *bl,
5119                        struct address_space *aspace, CORE_ADDR bp_addr,
5120                        const struct target_waitstatus *ws)
5121 {
5122   struct breakpoint *b = bl->owner;
5123
5124   /* BL is from an existing breakpoint.  */
5125   gdb_assert (b != NULL);
5126
5127   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5128 }
5129
5130 /* Determine if the watched values have actually changed, and we
5131    should stop.  If not, set BS->stop to 0.  */
5132
5133 static void
5134 bpstat_check_watchpoint (bpstat bs)
5135 {
5136   const struct bp_location *bl;
5137   struct watchpoint *b;
5138
5139   /* BS is built for existing struct breakpoint.  */
5140   bl = bs->bp_location_at;
5141   gdb_assert (bl != NULL);
5142   b = (struct watchpoint *) bs->breakpoint_at;
5143   gdb_assert (b != NULL);
5144
5145     {
5146       int must_check_value = 0;
5147       
5148       if (b->base.type == bp_watchpoint)
5149         /* For a software watchpoint, we must always check the
5150            watched value.  */
5151         must_check_value = 1;
5152       else if (b->watchpoint_triggered == watch_triggered_yes)
5153         /* We have a hardware watchpoint (read, write, or access)
5154            and the target earlier reported an address watched by
5155            this watchpoint.  */
5156         must_check_value = 1;
5157       else if (b->watchpoint_triggered == watch_triggered_unknown
5158                && b->base.type == bp_hardware_watchpoint)
5159         /* We were stopped by a hardware watchpoint, but the target could
5160            not report the data address.  We must check the watchpoint's
5161            value.  Access and read watchpoints are out of luck; without
5162            a data address, we can't figure it out.  */
5163         must_check_value = 1;
5164
5165       if (must_check_value)
5166         {
5167           char *message
5168             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5169                           b->base.number);
5170           struct cleanup *cleanups = make_cleanup (xfree, message);
5171           int e = catch_errors (watchpoint_check, bs, message,
5172                                 RETURN_MASK_ALL);
5173           do_cleanups (cleanups);
5174           switch (e)
5175             {
5176             case WP_DELETED:
5177               /* We've already printed what needs to be printed.  */
5178               bs->print_it = print_it_done;
5179               /* Stop.  */
5180               break;
5181             case WP_IGNORE:
5182               bs->print_it = print_it_noop;
5183               bs->stop = 0;
5184               break;
5185             case WP_VALUE_CHANGED:
5186               if (b->base.type == bp_read_watchpoint)
5187                 {
5188                   /* There are two cases to consider here:
5189
5190                      1. We're watching the triggered memory for reads.
5191                      In that case, trust the target, and always report
5192                      the watchpoint hit to the user.  Even though
5193                      reads don't cause value changes, the value may
5194                      have changed since the last time it was read, and
5195                      since we're not trapping writes, we will not see
5196                      those, and as such we should ignore our notion of
5197                      old value.
5198
5199                      2. We're watching the triggered memory for both
5200                      reads and writes.  There are two ways this may
5201                      happen:
5202
5203                      2.1. This is a target that can't break on data
5204                      reads only, but can break on accesses (reads or
5205                      writes), such as e.g., x86.  We detect this case
5206                      at the time we try to insert read watchpoints.
5207
5208                      2.2. Otherwise, the target supports read
5209                      watchpoints, but, the user set an access or write
5210                      watchpoint watching the same memory as this read
5211                      watchpoint.
5212
5213                      If we're watching memory writes as well as reads,
5214                      ignore watchpoint hits when we find that the
5215                      value hasn't changed, as reads don't cause
5216                      changes.  This still gives false positives when
5217                      the program writes the same value to memory as
5218                      what there was already in memory (we will confuse
5219                      it for a read), but it's much better than
5220                      nothing.  */
5221
5222                   int other_write_watchpoint = 0;
5223
5224                   if (bl->watchpoint_type == hw_read)
5225                     {
5226                       struct breakpoint *other_b;
5227
5228                       ALL_BREAKPOINTS (other_b)
5229                         if (other_b->type == bp_hardware_watchpoint
5230                             || other_b->type == bp_access_watchpoint)
5231                           {
5232                             struct watchpoint *other_w =
5233                               (struct watchpoint *) other_b;
5234
5235                             if (other_w->watchpoint_triggered
5236                                 == watch_triggered_yes)
5237                               {
5238                                 other_write_watchpoint = 1;
5239                                 break;
5240                               }
5241                           }
5242                     }
5243
5244                   if (other_write_watchpoint
5245                       || bl->watchpoint_type == hw_access)
5246                     {
5247                       /* We're watching the same memory for writes,
5248                          and the value changed since the last time we
5249                          updated it, so this trap must be for a write.
5250                          Ignore it.  */
5251                       bs->print_it = print_it_noop;
5252                       bs->stop = 0;
5253                     }
5254                 }
5255               break;
5256             case WP_VALUE_NOT_CHANGED:
5257               if (b->base.type == bp_hardware_watchpoint
5258                   || b->base.type == bp_watchpoint)
5259                 {
5260                   /* Don't stop: write watchpoints shouldn't fire if
5261                      the value hasn't changed.  */
5262                   bs->print_it = print_it_noop;
5263                   bs->stop = 0;
5264                 }
5265               /* Stop.  */
5266               break;
5267             default:
5268               /* Can't happen.  */
5269             case 0:
5270               /* Error from catch_errors.  */
5271               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5272               watchpoint_del_at_next_stop (b);
5273               /* We've already printed what needs to be printed.  */
5274               bs->print_it = print_it_done;
5275               break;
5276             }
5277         }
5278       else      /* must_check_value == 0 */
5279         {
5280           /* This is a case where some watchpoint(s) triggered, but
5281              not at the address of this watchpoint, or else no
5282              watchpoint triggered after all.  So don't print
5283              anything for this watchpoint.  */
5284           bs->print_it = print_it_noop;
5285           bs->stop = 0;
5286         }
5287     }
5288 }
5289
5290 /* For breakpoints that are currently marked as telling gdb to stop,
5291    check conditions (condition proper, frame, thread and ignore count)
5292    of breakpoint referred to by BS.  If we should not stop for this
5293    breakpoint, set BS->stop to 0.  */
5294
5295 static void
5296 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5297 {
5298   const struct bp_location *bl;
5299   struct breakpoint *b;
5300   int value_is_zero = 0;
5301   struct expression *cond;
5302
5303   gdb_assert (bs->stop);
5304
5305   /* BS is built for existing struct breakpoint.  */
5306   bl = bs->bp_location_at;
5307   gdb_assert (bl != NULL);
5308   b = bs->breakpoint_at;
5309   gdb_assert (b != NULL);
5310
5311   /* Even if the target evaluated the condition on its end and notified GDB, we
5312      need to do so again since GDB does not know if we stopped due to a
5313      breakpoint or a single step breakpoint.  */
5314
5315   if (frame_id_p (b->frame_id)
5316       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5317     {
5318       bs->stop = 0;
5319       return;
5320     }
5321
5322   /* If this is a thread/task-specific breakpoint, don't waste cpu
5323      evaluating the condition if this isn't the specified
5324      thread/task.  */
5325   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5326       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5327
5328     {
5329       bs->stop = 0;
5330       return;
5331     }
5332
5333   /* Evaluate extension language breakpoints that have a "stop" method
5334      implemented.  */
5335   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5336
5337   if (is_watchpoint (b))
5338     {
5339       struct watchpoint *w = (struct watchpoint *) b;
5340
5341       cond = w->cond_exp;
5342     }
5343   else
5344     cond = bl->cond;
5345
5346   if (cond && b->disposition != disp_del_at_next_stop)
5347     {
5348       int within_current_scope = 1;
5349       struct watchpoint * w;
5350
5351       /* We use value_mark and value_free_to_mark because it could
5352          be a long time before we return to the command level and
5353          call free_all_values.  We can't call free_all_values
5354          because we might be in the middle of evaluating a
5355          function call.  */
5356       struct value *mark = value_mark ();
5357
5358       if (is_watchpoint (b))
5359         w = (struct watchpoint *) b;
5360       else
5361         w = NULL;
5362
5363       /* Need to select the frame, with all that implies so that
5364          the conditions will have the right context.  Because we
5365          use the frame, we will not see an inlined function's
5366          variables when we arrive at a breakpoint at the start
5367          of the inlined function; the current frame will be the
5368          call site.  */
5369       if (w == NULL || w->cond_exp_valid_block == NULL)
5370         select_frame (get_current_frame ());
5371       else
5372         {
5373           struct frame_info *frame;
5374
5375           /* For local watchpoint expressions, which particular
5376              instance of a local is being watched matters, so we
5377              keep track of the frame to evaluate the expression
5378              in.  To evaluate the condition however, it doesn't
5379              really matter which instantiation of the function
5380              where the condition makes sense triggers the
5381              watchpoint.  This allows an expression like "watch
5382              global if q > 10" set in `func', catch writes to
5383              global on all threads that call `func', or catch
5384              writes on all recursive calls of `func' by a single
5385              thread.  We simply always evaluate the condition in
5386              the innermost frame that's executing where it makes
5387              sense to evaluate the condition.  It seems
5388              intuitive.  */
5389           frame = block_innermost_frame (w->cond_exp_valid_block);
5390           if (frame != NULL)
5391             select_frame (frame);
5392           else
5393             within_current_scope = 0;
5394         }
5395       if (within_current_scope)
5396         value_is_zero
5397           = catch_errors (breakpoint_cond_eval, cond,
5398                           "Error in testing breakpoint condition:\n",
5399                           RETURN_MASK_ALL);
5400       else
5401         {
5402           warning (_("Watchpoint condition cannot be tested "
5403                      "in the current scope"));
5404           /* If we failed to set the right context for this
5405              watchpoint, unconditionally report it.  */
5406           value_is_zero = 0;
5407         }
5408       /* FIXME-someday, should give breakpoint #.  */
5409       value_free_to_mark (mark);
5410     }
5411
5412   if (cond && value_is_zero)
5413     {
5414       bs->stop = 0;
5415     }
5416   else if (b->ignore_count > 0)
5417     {
5418       b->ignore_count--;
5419       bs->stop = 0;
5420       /* Increase the hit count even though we don't stop.  */
5421       ++(b->hit_count);
5422       observer_notify_breakpoint_modified (b);
5423     }   
5424 }
5425
5426
5427 /* Get a bpstat associated with having just stopped at address
5428    BP_ADDR in thread PTID.
5429
5430    Determine whether we stopped at a breakpoint, etc, or whether we
5431    don't understand this stop.  Result is a chain of bpstat's such
5432    that:
5433
5434    if we don't understand the stop, the result is a null pointer.
5435
5436    if we understand why we stopped, the result is not null.
5437
5438    Each element of the chain refers to a particular breakpoint or
5439    watchpoint at which we have stopped.  (We may have stopped for
5440    several reasons concurrently.)
5441
5442    Each element of the chain has valid next, breakpoint_at,
5443    commands, FIXME??? fields.  */
5444
5445 bpstat
5446 bpstat_stop_status (struct address_space *aspace,
5447                     CORE_ADDR bp_addr, ptid_t ptid,
5448                     const struct target_waitstatus *ws)
5449 {
5450   struct breakpoint *b = NULL;
5451   struct bp_location *bl;
5452   struct bp_location *loc;
5453   /* First item of allocated bpstat's.  */
5454   bpstat bs_head = NULL, *bs_link = &bs_head;
5455   /* Pointer to the last thing in the chain currently.  */
5456   bpstat bs;
5457   int ix;
5458   int need_remove_insert;
5459   int removed_any;
5460
5461   /* First, build the bpstat chain with locations that explain a
5462      target stop, while being careful to not set the target running,
5463      as that may invalidate locations (in particular watchpoint
5464      locations are recreated).  Resuming will happen here with
5465      breakpoint conditions or watchpoint expressions that include
5466      inferior function calls.  */
5467
5468   ALL_BREAKPOINTS (b)
5469     {
5470       if (!breakpoint_enabled (b))
5471         continue;
5472
5473       for (bl = b->loc; bl != NULL; bl = bl->next)
5474         {
5475           /* For hardware watchpoints, we look only at the first
5476              location.  The watchpoint_check function will work on the
5477              entire expression, not the individual locations.  For
5478              read watchpoints, the watchpoints_triggered function has
5479              checked all locations already.  */
5480           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5481             break;
5482
5483           if (!bl->enabled || bl->shlib_disabled)
5484             continue;
5485
5486           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5487             continue;
5488
5489           /* Come here if it's a watchpoint, or if the break address
5490              matches.  */
5491
5492           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5493                                                    explain stop.  */
5494
5495           /* Assume we stop.  Should we find a watchpoint that is not
5496              actually triggered, or if the condition of the breakpoint
5497              evaluates as false, we'll reset 'stop' to 0.  */
5498           bs->stop = 1;
5499           bs->print = 1;
5500
5501           /* If this is a scope breakpoint, mark the associated
5502              watchpoint as triggered so that we will handle the
5503              out-of-scope event.  We'll get to the watchpoint next
5504              iteration.  */
5505           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5506             {
5507               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5508
5509               w->watchpoint_triggered = watch_triggered_yes;
5510             }
5511         }
5512     }
5513
5514   /* Check if a moribund breakpoint explains the stop.  */
5515   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5516     {
5517       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5518         {
5519           bs = bpstat_alloc (loc, &bs_link);
5520           /* For hits of moribund locations, we should just proceed.  */
5521           bs->stop = 0;
5522           bs->print = 0;
5523           bs->print_it = print_it_noop;
5524         }
5525     }
5526
5527   /* A bit of special processing for shlib breakpoints.  We need to
5528      process solib loading here, so that the lists of loaded and
5529      unloaded libraries are correct before we handle "catch load" and
5530      "catch unload".  */
5531   for (bs = bs_head; bs != NULL; bs = bs->next)
5532     {
5533       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5534         {
5535           handle_solib_event ();
5536           break;
5537         }
5538     }
5539
5540   /* Now go through the locations that caused the target to stop, and
5541      check whether we're interested in reporting this stop to higher
5542      layers, or whether we should resume the target transparently.  */
5543
5544   removed_any = 0;
5545
5546   for (bs = bs_head; bs != NULL; bs = bs->next)
5547     {
5548       if (!bs->stop)
5549         continue;
5550
5551       b = bs->breakpoint_at;
5552       b->ops->check_status (bs);
5553       if (bs->stop)
5554         {
5555           bpstat_check_breakpoint_conditions (bs, ptid);
5556
5557           if (bs->stop)
5558             {
5559               ++(b->hit_count);
5560               observer_notify_breakpoint_modified (b);
5561
5562               /* We will stop here.  */
5563               if (b->disposition == disp_disable)
5564                 {
5565                   --(b->enable_count);
5566                   if (b->enable_count <= 0)
5567                     b->enable_state = bp_disabled;
5568                   removed_any = 1;
5569                 }
5570               if (b->silent)
5571                 bs->print = 0;
5572               bs->commands = b->commands;
5573               incref_counted_command_line (bs->commands);
5574               if (command_line_is_silent (bs->commands
5575                                           ? bs->commands->commands : NULL))
5576                 bs->print = 0;
5577
5578               b->ops->after_condition_true (bs);
5579             }
5580
5581         }
5582
5583       /* Print nothing for this entry if we don't stop or don't
5584          print.  */
5585       if (!bs->stop || !bs->print)
5586         bs->print_it = print_it_noop;
5587     }
5588
5589   /* If we aren't stopping, the value of some hardware watchpoint may
5590      not have changed, but the intermediate memory locations we are
5591      watching may have.  Don't bother if we're stopping; this will get
5592      done later.  */
5593   need_remove_insert = 0;
5594   if (! bpstat_causes_stop (bs_head))
5595     for (bs = bs_head; bs != NULL; bs = bs->next)
5596       if (!bs->stop
5597           && bs->breakpoint_at
5598           && is_hardware_watchpoint (bs->breakpoint_at))
5599         {
5600           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5601
5602           update_watchpoint (w, 0 /* don't reparse.  */);
5603           need_remove_insert = 1;
5604         }
5605
5606   if (need_remove_insert)
5607     update_global_location_list (UGLL_MAY_INSERT);
5608   else if (removed_any)
5609     update_global_location_list (UGLL_DONT_INSERT);
5610
5611   return bs_head;
5612 }
5613
5614 static void
5615 handle_jit_event (void)
5616 {
5617   struct frame_info *frame;
5618   struct gdbarch *gdbarch;
5619
5620   /* Switch terminal for any messages produced by
5621      breakpoint_re_set.  */
5622   target_terminal_ours_for_output ();
5623
5624   frame = get_current_frame ();
5625   gdbarch = get_frame_arch (frame);
5626
5627   jit_event_handler (gdbarch);
5628
5629   target_terminal_inferior ();
5630 }
5631
5632 /* Prepare WHAT final decision for infrun.  */
5633
5634 /* Decide what infrun needs to do with this bpstat.  */
5635
5636 struct bpstat_what
5637 bpstat_what (bpstat bs_head)
5638 {
5639   struct bpstat_what retval;
5640   int jit_event = 0;
5641   bpstat bs;
5642
5643   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5644   retval.call_dummy = STOP_NONE;
5645   retval.is_longjmp = 0;
5646
5647   for (bs = bs_head; bs != NULL; bs = bs->next)
5648     {
5649       /* Extract this BS's action.  After processing each BS, we check
5650          if its action overrides all we've seem so far.  */
5651       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5652       enum bptype bptype;
5653
5654       if (bs->breakpoint_at == NULL)
5655         {
5656           /* I suspect this can happen if it was a momentary
5657              breakpoint which has since been deleted.  */
5658           bptype = bp_none;
5659         }
5660       else
5661         bptype = bs->breakpoint_at->type;
5662
5663       switch (bptype)
5664         {
5665         case bp_none:
5666           break;
5667         case bp_breakpoint:
5668         case bp_hardware_breakpoint:
5669         case bp_single_step:
5670         case bp_until:
5671         case bp_finish:
5672         case bp_shlib_event:
5673           if (bs->stop)
5674             {
5675               if (bs->print)
5676                 this_action = BPSTAT_WHAT_STOP_NOISY;
5677               else
5678                 this_action = BPSTAT_WHAT_STOP_SILENT;
5679             }
5680           else
5681             this_action = BPSTAT_WHAT_SINGLE;
5682           break;
5683         case bp_watchpoint:
5684         case bp_hardware_watchpoint:
5685         case bp_read_watchpoint:
5686         case bp_access_watchpoint:
5687           if (bs->stop)
5688             {
5689               if (bs->print)
5690                 this_action = BPSTAT_WHAT_STOP_NOISY;
5691               else
5692                 this_action = BPSTAT_WHAT_STOP_SILENT;
5693             }
5694           else
5695             {
5696               /* There was a watchpoint, but we're not stopping.
5697                  This requires no further action.  */
5698             }
5699           break;
5700         case bp_longjmp:
5701         case bp_longjmp_call_dummy:
5702         case bp_exception:
5703           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5704           retval.is_longjmp = bptype != bp_exception;
5705           break;
5706         case bp_longjmp_resume:
5707         case bp_exception_resume:
5708           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5709           retval.is_longjmp = bptype == bp_longjmp_resume;
5710           break;
5711         case bp_step_resume:
5712           if (bs->stop)
5713             this_action = BPSTAT_WHAT_STEP_RESUME;
5714           else
5715             {
5716               /* It is for the wrong frame.  */
5717               this_action = BPSTAT_WHAT_SINGLE;
5718             }
5719           break;
5720         case bp_hp_step_resume:
5721           if (bs->stop)
5722             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5723           else
5724             {
5725               /* It is for the wrong frame.  */
5726               this_action = BPSTAT_WHAT_SINGLE;
5727             }
5728           break;
5729         case bp_watchpoint_scope:
5730         case bp_thread_event:
5731         case bp_overlay_event:
5732         case bp_longjmp_master:
5733         case bp_std_terminate_master:
5734         case bp_exception_master:
5735           this_action = BPSTAT_WHAT_SINGLE;
5736           break;
5737         case bp_catchpoint:
5738           if (bs->stop)
5739             {
5740               if (bs->print)
5741                 this_action = BPSTAT_WHAT_STOP_NOISY;
5742               else
5743                 this_action = BPSTAT_WHAT_STOP_SILENT;
5744             }
5745           else
5746             {
5747               /* There was a catchpoint, but we're not stopping.
5748                  This requires no further action.  */
5749             }
5750           break;
5751         case bp_jit_event:
5752           jit_event = 1;
5753           this_action = BPSTAT_WHAT_SINGLE;
5754           break;
5755         case bp_call_dummy:
5756           /* Make sure the action is stop (silent or noisy),
5757              so infrun.c pops the dummy frame.  */
5758           retval.call_dummy = STOP_STACK_DUMMY;
5759           this_action = BPSTAT_WHAT_STOP_SILENT;
5760           break;
5761         case bp_std_terminate:
5762           /* Make sure the action is stop (silent or noisy),
5763              so infrun.c pops the dummy frame.  */
5764           retval.call_dummy = STOP_STD_TERMINATE;
5765           this_action = BPSTAT_WHAT_STOP_SILENT;
5766           break;
5767         case bp_tracepoint:
5768         case bp_fast_tracepoint:
5769         case bp_static_tracepoint:
5770           /* Tracepoint hits should not be reported back to GDB, and
5771              if one got through somehow, it should have been filtered
5772              out already.  */
5773           internal_error (__FILE__, __LINE__,
5774                           _("bpstat_what: tracepoint encountered"));
5775           break;
5776         case bp_gnu_ifunc_resolver:
5777           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5778           this_action = BPSTAT_WHAT_SINGLE;
5779           break;
5780         case bp_gnu_ifunc_resolver_return:
5781           /* The breakpoint will be removed, execution will restart from the
5782              PC of the former breakpoint.  */
5783           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5784           break;
5785
5786         case bp_dprintf:
5787           if (bs->stop)
5788             this_action = BPSTAT_WHAT_STOP_SILENT;
5789           else
5790             this_action = BPSTAT_WHAT_SINGLE;
5791           break;
5792
5793         default:
5794           internal_error (__FILE__, __LINE__,
5795                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5796         }
5797
5798       retval.main_action = max (retval.main_action, this_action);
5799     }
5800
5801   /* These operations may affect the bs->breakpoint_at state so they are
5802      delayed after MAIN_ACTION is decided above.  */
5803
5804   if (jit_event)
5805     {
5806       if (debug_infrun)
5807         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5808
5809       handle_jit_event ();
5810     }
5811
5812   for (bs = bs_head; bs != NULL; bs = bs->next)
5813     {
5814       struct breakpoint *b = bs->breakpoint_at;
5815
5816       if (b == NULL)
5817         continue;
5818       switch (b->type)
5819         {
5820         case bp_gnu_ifunc_resolver:
5821           gnu_ifunc_resolver_stop (b);
5822           break;
5823         case bp_gnu_ifunc_resolver_return:
5824           gnu_ifunc_resolver_return_stop (b);
5825           break;
5826         }
5827     }
5828
5829   return retval;
5830 }
5831
5832 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5833    without hardware support).  This isn't related to a specific bpstat,
5834    just to things like whether watchpoints are set.  */
5835
5836 int
5837 bpstat_should_step (void)
5838 {
5839   struct breakpoint *b;
5840
5841   ALL_BREAKPOINTS (b)
5842     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5843       return 1;
5844   return 0;
5845 }
5846
5847 int
5848 bpstat_causes_stop (bpstat bs)
5849 {
5850   for (; bs != NULL; bs = bs->next)
5851     if (bs->stop)
5852       return 1;
5853
5854   return 0;
5855 }
5856
5857 \f
5858
5859 /* Compute a string of spaces suitable to indent the next line
5860    so it starts at the position corresponding to the table column
5861    named COL_NAME in the currently active table of UIOUT.  */
5862
5863 static char *
5864 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5865 {
5866   static char wrap_indent[80];
5867   int i, total_width, width, align;
5868   char *text;
5869
5870   total_width = 0;
5871   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5872     {
5873       if (strcmp (text, col_name) == 0)
5874         {
5875           gdb_assert (total_width < sizeof wrap_indent);
5876           memset (wrap_indent, ' ', total_width);
5877           wrap_indent[total_width] = 0;
5878
5879           return wrap_indent;
5880         }
5881
5882       total_width += width + 1;
5883     }
5884
5885   return NULL;
5886 }
5887
5888 /* Determine if the locations of this breakpoint will have their conditions
5889    evaluated by the target, host or a mix of both.  Returns the following:
5890
5891     "host": Host evals condition.
5892     "host or target": Host or Target evals condition.
5893     "target": Target evals condition.
5894 */
5895
5896 static const char *
5897 bp_condition_evaluator (struct breakpoint *b)
5898 {
5899   struct bp_location *bl;
5900   char host_evals = 0;
5901   char target_evals = 0;
5902
5903   if (!b)
5904     return NULL;
5905
5906   if (!is_breakpoint (b))
5907     return NULL;
5908
5909   if (gdb_evaluates_breakpoint_condition_p ()
5910       || !target_supports_evaluation_of_breakpoint_conditions ())
5911     return condition_evaluation_host;
5912
5913   for (bl = b->loc; bl; bl = bl->next)
5914     {
5915       if (bl->cond_bytecode)
5916         target_evals++;
5917       else
5918         host_evals++;
5919     }
5920
5921   if (host_evals && target_evals)
5922     return condition_evaluation_both;
5923   else if (target_evals)
5924     return condition_evaluation_target;
5925   else
5926     return condition_evaluation_host;
5927 }
5928
5929 /* Determine the breakpoint location's condition evaluator.  This is
5930    similar to bp_condition_evaluator, but for locations.  */
5931
5932 static const char *
5933 bp_location_condition_evaluator (struct bp_location *bl)
5934 {
5935   if (bl && !is_breakpoint (bl->owner))
5936     return NULL;
5937
5938   if (gdb_evaluates_breakpoint_condition_p ()
5939       || !target_supports_evaluation_of_breakpoint_conditions ())
5940     return condition_evaluation_host;
5941
5942   if (bl && bl->cond_bytecode)
5943     return condition_evaluation_target;
5944   else
5945     return condition_evaluation_host;
5946 }
5947
5948 /* Print the LOC location out of the list of B->LOC locations.  */
5949
5950 static void
5951 print_breakpoint_location (struct breakpoint *b,
5952                            struct bp_location *loc)
5953 {
5954   struct ui_out *uiout = current_uiout;
5955   struct cleanup *old_chain = save_current_program_space ();
5956
5957   if (loc != NULL && loc->shlib_disabled)
5958     loc = NULL;
5959
5960   if (loc != NULL)
5961     set_current_program_space (loc->pspace);
5962
5963   if (b->display_canonical)
5964     ui_out_field_string (uiout, "what", b->addr_string);
5965   else if (loc && loc->symtab)
5966     {
5967       struct symbol *sym 
5968         = find_pc_sect_function (loc->address, loc->section);
5969       if (sym)
5970         {
5971           ui_out_text (uiout, "in ");
5972           ui_out_field_string (uiout, "func",
5973                                SYMBOL_PRINT_NAME (sym));
5974           ui_out_text (uiout, " ");
5975           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5976           ui_out_text (uiout, "at ");
5977         }
5978       ui_out_field_string (uiout, "file",
5979                            symtab_to_filename_for_display (loc->symtab));
5980       ui_out_text (uiout, ":");
5981
5982       if (ui_out_is_mi_like_p (uiout))
5983         ui_out_field_string (uiout, "fullname",
5984                              symtab_to_fullname (loc->symtab));
5985       
5986       ui_out_field_int (uiout, "line", loc->line_number);
5987     }
5988   else if (loc)
5989     {
5990       struct ui_file *stb = mem_fileopen ();
5991       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5992
5993       print_address_symbolic (loc->gdbarch, loc->address, stb,
5994                               demangle, "");
5995       ui_out_field_stream (uiout, "at", stb);
5996
5997       do_cleanups (stb_chain);
5998     }
5999   else
6000     ui_out_field_string (uiout, "pending", b->addr_string);
6001
6002   if (loc && is_breakpoint (b)
6003       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6004       && bp_condition_evaluator (b) == condition_evaluation_both)
6005     {
6006       ui_out_text (uiout, " (");
6007       ui_out_field_string (uiout, "evaluated-by",
6008                            bp_location_condition_evaluator (loc));
6009       ui_out_text (uiout, ")");
6010     }
6011
6012   do_cleanups (old_chain);
6013 }
6014
6015 static const char *
6016 bptype_string (enum bptype type)
6017 {
6018   struct ep_type_description
6019     {
6020       enum bptype type;
6021       char *description;
6022     };
6023   static struct ep_type_description bptypes[] =
6024   {
6025     {bp_none, "?deleted?"},
6026     {bp_breakpoint, "breakpoint"},
6027     {bp_hardware_breakpoint, "hw breakpoint"},
6028     {bp_single_step, "sw single-step"},
6029     {bp_until, "until"},
6030     {bp_finish, "finish"},
6031     {bp_watchpoint, "watchpoint"},
6032     {bp_hardware_watchpoint, "hw watchpoint"},
6033     {bp_read_watchpoint, "read watchpoint"},
6034     {bp_access_watchpoint, "acc watchpoint"},
6035     {bp_longjmp, "longjmp"},
6036     {bp_longjmp_resume, "longjmp resume"},
6037     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6038     {bp_exception, "exception"},
6039     {bp_exception_resume, "exception resume"},
6040     {bp_step_resume, "step resume"},
6041     {bp_hp_step_resume, "high-priority step resume"},
6042     {bp_watchpoint_scope, "watchpoint scope"},
6043     {bp_call_dummy, "call dummy"},
6044     {bp_std_terminate, "std::terminate"},
6045     {bp_shlib_event, "shlib events"},
6046     {bp_thread_event, "thread events"},
6047     {bp_overlay_event, "overlay events"},
6048     {bp_longjmp_master, "longjmp master"},
6049     {bp_std_terminate_master, "std::terminate master"},
6050     {bp_exception_master, "exception master"},
6051     {bp_catchpoint, "catchpoint"},
6052     {bp_tracepoint, "tracepoint"},
6053     {bp_fast_tracepoint, "fast tracepoint"},
6054     {bp_static_tracepoint, "static tracepoint"},
6055     {bp_dprintf, "dprintf"},
6056     {bp_jit_event, "jit events"},
6057     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6058     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6059   };
6060
6061   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6062       || ((int) type != bptypes[(int) type].type))
6063     internal_error (__FILE__, __LINE__,
6064                     _("bptypes table does not describe type #%d."),
6065                     (int) type);
6066
6067   return bptypes[(int) type].description;
6068 }
6069
6070 /* For MI, output a field named 'thread-groups' with a list as the value.
6071    For CLI, prefix the list with the string 'inf'. */
6072
6073 static void
6074 output_thread_groups (struct ui_out *uiout,
6075                       const char *field_name,
6076                       VEC(int) *inf_num,
6077                       int mi_only)
6078 {
6079   struct cleanup *back_to;
6080   int is_mi = ui_out_is_mi_like_p (uiout);
6081   int inf;
6082   int i;
6083
6084   /* For backward compatibility, don't display inferiors in CLI unless
6085      there are several.  Always display them for MI. */
6086   if (!is_mi && mi_only)
6087     return;
6088
6089   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6090
6091   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6092     {
6093       if (is_mi)
6094         {
6095           char mi_group[10];
6096
6097           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6098           ui_out_field_string (uiout, NULL, mi_group);
6099         }
6100       else
6101         {
6102           if (i == 0)
6103             ui_out_text (uiout, " inf ");
6104           else
6105             ui_out_text (uiout, ", ");
6106         
6107           ui_out_text (uiout, plongest (inf));
6108         }
6109     }
6110
6111   do_cleanups (back_to);
6112 }
6113
6114 /* Print B to gdb_stdout.  */
6115
6116 static void
6117 print_one_breakpoint_location (struct breakpoint *b,
6118                                struct bp_location *loc,
6119                                int loc_number,
6120                                struct bp_location **last_loc,
6121                                int allflag)
6122 {
6123   struct command_line *l;
6124   static char bpenables[] = "nynny";
6125
6126   struct ui_out *uiout = current_uiout;
6127   int header_of_multiple = 0;
6128   int part_of_multiple = (loc != NULL);
6129   struct value_print_options opts;
6130
6131   get_user_print_options (&opts);
6132
6133   gdb_assert (!loc || loc_number != 0);
6134   /* See comment in print_one_breakpoint concerning treatment of
6135      breakpoints with single disabled location.  */
6136   if (loc == NULL 
6137       && (b->loc != NULL 
6138           && (b->loc->next != NULL || !b->loc->enabled)))
6139     header_of_multiple = 1;
6140   if (loc == NULL)
6141     loc = b->loc;
6142
6143   annotate_record ();
6144
6145   /* 1 */
6146   annotate_field (0);
6147   if (part_of_multiple)
6148     {
6149       char *formatted;
6150       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6151       ui_out_field_string (uiout, "number", formatted);
6152       xfree (formatted);
6153     }
6154   else
6155     {
6156       ui_out_field_int (uiout, "number", b->number);
6157     }
6158
6159   /* 2 */
6160   annotate_field (1);
6161   if (part_of_multiple)
6162     ui_out_field_skip (uiout, "type");
6163   else
6164     ui_out_field_string (uiout, "type", bptype_string (b->type));
6165
6166   /* 3 */
6167   annotate_field (2);
6168   if (part_of_multiple)
6169     ui_out_field_skip (uiout, "disp");
6170   else
6171     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6172
6173
6174   /* 4 */
6175   annotate_field (3);
6176   if (part_of_multiple)
6177     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6178   else
6179     ui_out_field_fmt (uiout, "enabled", "%c", 
6180                       bpenables[(int) b->enable_state]);
6181   ui_out_spaces (uiout, 2);
6182
6183   
6184   /* 5 and 6 */
6185   if (b->ops != NULL && b->ops->print_one != NULL)
6186     {
6187       /* Although the print_one can possibly print all locations,
6188          calling it here is not likely to get any nice result.  So,
6189          make sure there's just one location.  */
6190       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6191       b->ops->print_one (b, last_loc);
6192     }
6193   else
6194     switch (b->type)
6195       {
6196       case bp_none:
6197         internal_error (__FILE__, __LINE__,
6198                         _("print_one_breakpoint: bp_none encountered\n"));
6199         break;
6200
6201       case bp_watchpoint:
6202       case bp_hardware_watchpoint:
6203       case bp_read_watchpoint:
6204       case bp_access_watchpoint:
6205         {
6206           struct watchpoint *w = (struct watchpoint *) b;
6207
6208           /* Field 4, the address, is omitted (which makes the columns
6209              not line up too nicely with the headers, but the effect
6210              is relatively readable).  */
6211           if (opts.addressprint)
6212             ui_out_field_skip (uiout, "addr");
6213           annotate_field (5);
6214           ui_out_field_string (uiout, "what", w->exp_string);
6215         }
6216         break;
6217
6218       case bp_breakpoint:
6219       case bp_hardware_breakpoint:
6220       case bp_single_step:
6221       case bp_until:
6222       case bp_finish:
6223       case bp_longjmp:
6224       case bp_longjmp_resume:
6225       case bp_longjmp_call_dummy:
6226       case bp_exception:
6227       case bp_exception_resume:
6228       case bp_step_resume:
6229       case bp_hp_step_resume:
6230       case bp_watchpoint_scope:
6231       case bp_call_dummy:
6232       case bp_std_terminate:
6233       case bp_shlib_event:
6234       case bp_thread_event:
6235       case bp_overlay_event:
6236       case bp_longjmp_master:
6237       case bp_std_terminate_master:
6238       case bp_exception_master:
6239       case bp_tracepoint:
6240       case bp_fast_tracepoint:
6241       case bp_static_tracepoint:
6242       case bp_dprintf:
6243       case bp_jit_event:
6244       case bp_gnu_ifunc_resolver:
6245       case bp_gnu_ifunc_resolver_return:
6246         if (opts.addressprint)
6247           {
6248             annotate_field (4);
6249             if (header_of_multiple)
6250               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6251             else if (b->loc == NULL || loc->shlib_disabled)
6252               ui_out_field_string (uiout, "addr", "<PENDING>");
6253             else
6254               ui_out_field_core_addr (uiout, "addr",
6255                                       loc->gdbarch, loc->address);
6256           }
6257         annotate_field (5);
6258         if (!header_of_multiple)
6259           print_breakpoint_location (b, loc);
6260         if (b->loc)
6261           *last_loc = b->loc;
6262         break;
6263       }
6264
6265
6266   if (loc != NULL && !header_of_multiple)
6267     {
6268       struct inferior *inf;
6269       VEC(int) *inf_num = NULL;
6270       int mi_only = 1;
6271
6272       ALL_INFERIORS (inf)
6273         {
6274           if (inf->pspace == loc->pspace)
6275             VEC_safe_push (int, inf_num, inf->num);
6276         }
6277
6278         /* For backward compatibility, don't display inferiors in CLI unless
6279            there are several.  Always display for MI. */
6280         if (allflag
6281             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6282                 && (number_of_program_spaces () > 1
6283                     || number_of_inferiors () > 1)
6284                 /* LOC is for existing B, it cannot be in
6285                    moribund_locations and thus having NULL OWNER.  */
6286                 && loc->owner->type != bp_catchpoint))
6287         mi_only = 0;
6288       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6289       VEC_free (int, inf_num);
6290     }
6291
6292   if (!part_of_multiple)
6293     {
6294       if (b->thread != -1)
6295         {
6296           /* FIXME: This seems to be redundant and lost here; see the
6297              "stop only in" line a little further down.  */
6298           ui_out_text (uiout, " thread ");
6299           ui_out_field_int (uiout, "thread", b->thread);
6300         }
6301       else if (b->task != 0)
6302         {
6303           ui_out_text (uiout, " task ");
6304           ui_out_field_int (uiout, "task", b->task);
6305         }
6306     }
6307
6308   ui_out_text (uiout, "\n");
6309
6310   if (!part_of_multiple)
6311     b->ops->print_one_detail (b, uiout);
6312
6313   if (part_of_multiple && frame_id_p (b->frame_id))
6314     {
6315       annotate_field (6);
6316       ui_out_text (uiout, "\tstop only in stack frame at ");
6317       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6318          the frame ID.  */
6319       ui_out_field_core_addr (uiout, "frame",
6320                               b->gdbarch, b->frame_id.stack_addr);
6321       ui_out_text (uiout, "\n");
6322     }
6323   
6324   if (!part_of_multiple && b->cond_string)
6325     {
6326       annotate_field (7);
6327       if (is_tracepoint (b))
6328         ui_out_text (uiout, "\ttrace only if ");
6329       else
6330         ui_out_text (uiout, "\tstop only if ");
6331       ui_out_field_string (uiout, "cond", b->cond_string);
6332
6333       /* Print whether the target is doing the breakpoint's condition
6334          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6335       if (is_breakpoint (b)
6336           && breakpoint_condition_evaluation_mode ()
6337           == condition_evaluation_target)
6338         {
6339           ui_out_text (uiout, " (");
6340           ui_out_field_string (uiout, "evaluated-by",
6341                                bp_condition_evaluator (b));
6342           ui_out_text (uiout, " evals)");
6343         }
6344       ui_out_text (uiout, "\n");
6345     }
6346
6347   if (!part_of_multiple && b->thread != -1)
6348     {
6349       /* FIXME should make an annotation for this.  */
6350       ui_out_text (uiout, "\tstop only in thread ");
6351       ui_out_field_int (uiout, "thread", b->thread);
6352       ui_out_text (uiout, "\n");
6353     }
6354   
6355   if (!part_of_multiple)
6356     {
6357       if (b->hit_count)
6358         {
6359           /* FIXME should make an annotation for this.  */
6360           if (is_catchpoint (b))
6361             ui_out_text (uiout, "\tcatchpoint");
6362           else if (is_tracepoint (b))
6363             ui_out_text (uiout, "\ttracepoint");
6364           else
6365             ui_out_text (uiout, "\tbreakpoint");
6366           ui_out_text (uiout, " already hit ");
6367           ui_out_field_int (uiout, "times", b->hit_count);
6368           if (b->hit_count == 1)
6369             ui_out_text (uiout, " time\n");
6370           else
6371             ui_out_text (uiout, " times\n");
6372         }
6373       else
6374         {
6375           /* Output the count also if it is zero, but only if this is mi.  */
6376           if (ui_out_is_mi_like_p (uiout))
6377             ui_out_field_int (uiout, "times", b->hit_count);
6378         }
6379     }
6380
6381   if (!part_of_multiple && b->ignore_count)
6382     {
6383       annotate_field (8);
6384       ui_out_text (uiout, "\tignore next ");
6385       ui_out_field_int (uiout, "ignore", b->ignore_count);
6386       ui_out_text (uiout, " hits\n");
6387     }
6388
6389   /* Note that an enable count of 1 corresponds to "enable once"
6390      behavior, which is reported by the combination of enablement and
6391      disposition, so we don't need to mention it here.  */
6392   if (!part_of_multiple && b->enable_count > 1)
6393     {
6394       annotate_field (8);
6395       ui_out_text (uiout, "\tdisable after ");
6396       /* Tweak the wording to clarify that ignore and enable counts
6397          are distinct, and have additive effect.  */
6398       if (b->ignore_count)
6399         ui_out_text (uiout, "additional ");
6400       else
6401         ui_out_text (uiout, "next ");
6402       ui_out_field_int (uiout, "enable", b->enable_count);
6403       ui_out_text (uiout, " hits\n");
6404     }
6405
6406   if (!part_of_multiple && is_tracepoint (b))
6407     {
6408       struct tracepoint *tp = (struct tracepoint *) b;
6409
6410       if (tp->traceframe_usage)
6411         {
6412           ui_out_text (uiout, "\ttrace buffer usage ");
6413           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6414           ui_out_text (uiout, " bytes\n");
6415         }
6416     }
6417
6418   l = b->commands ? b->commands->commands : NULL;
6419   if (!part_of_multiple && l)
6420     {
6421       struct cleanup *script_chain;
6422
6423       annotate_field (9);
6424       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6425       print_command_lines (uiout, l, 4);
6426       do_cleanups (script_chain);
6427     }
6428
6429   if (is_tracepoint (b))
6430     {
6431       struct tracepoint *t = (struct tracepoint *) b;
6432
6433       if (!part_of_multiple && t->pass_count)
6434         {
6435           annotate_field (10);
6436           ui_out_text (uiout, "\tpass count ");
6437           ui_out_field_int (uiout, "pass", t->pass_count);
6438           ui_out_text (uiout, " \n");
6439         }
6440
6441       /* Don't display it when tracepoint or tracepoint location is
6442          pending.   */
6443       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6444         {
6445           annotate_field (11);
6446
6447           if (ui_out_is_mi_like_p (uiout))
6448             ui_out_field_string (uiout, "installed",
6449                                  loc->inserted ? "y" : "n");
6450           else
6451             {
6452               if (loc->inserted)
6453                 ui_out_text (uiout, "\t");
6454               else
6455                 ui_out_text (uiout, "\tnot ");
6456               ui_out_text (uiout, "installed on target\n");
6457             }
6458         }
6459     }
6460
6461   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6462     {
6463       if (is_watchpoint (b))
6464         {
6465           struct watchpoint *w = (struct watchpoint *) b;
6466
6467           ui_out_field_string (uiout, "original-location", w->exp_string);
6468         }
6469       else if (b->addr_string)
6470         ui_out_field_string (uiout, "original-location", b->addr_string);
6471     }
6472 }
6473
6474 static void
6475 print_one_breakpoint (struct breakpoint *b,
6476                       struct bp_location **last_loc, 
6477                       int allflag)
6478 {
6479   struct cleanup *bkpt_chain;
6480   struct ui_out *uiout = current_uiout;
6481
6482   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6483
6484   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6485   do_cleanups (bkpt_chain);
6486
6487   /* If this breakpoint has custom print function,
6488      it's already printed.  Otherwise, print individual
6489      locations, if any.  */
6490   if (b->ops == NULL || b->ops->print_one == NULL)
6491     {
6492       /* If breakpoint has a single location that is disabled, we
6493          print it as if it had several locations, since otherwise it's
6494          hard to represent "breakpoint enabled, location disabled"
6495          situation.
6496
6497          Note that while hardware watchpoints have several locations
6498          internally, that's not a property exposed to user.  */
6499       if (b->loc 
6500           && !is_hardware_watchpoint (b)
6501           && (b->loc->next || !b->loc->enabled))
6502         {
6503           struct bp_location *loc;
6504           int n = 1;
6505
6506           for (loc = b->loc; loc; loc = loc->next, ++n)
6507             {
6508               struct cleanup *inner2 =
6509                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6510               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6511               do_cleanups (inner2);
6512             }
6513         }
6514     }
6515 }
6516
6517 static int
6518 breakpoint_address_bits (struct breakpoint *b)
6519 {
6520   int print_address_bits = 0;
6521   struct bp_location *loc;
6522
6523   for (loc = b->loc; loc; loc = loc->next)
6524     {
6525       int addr_bit;
6526
6527       /* Software watchpoints that aren't watching memory don't have
6528          an address to print.  */
6529       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6530         continue;
6531
6532       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6533       if (addr_bit > print_address_bits)
6534         print_address_bits = addr_bit;
6535     }
6536
6537   return print_address_bits;
6538 }
6539
6540 struct captured_breakpoint_query_args
6541   {
6542     int bnum;
6543   };
6544
6545 static int
6546 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6547 {
6548   struct captured_breakpoint_query_args *args = data;
6549   struct breakpoint *b;
6550   struct bp_location *dummy_loc = NULL;
6551
6552   ALL_BREAKPOINTS (b)
6553     {
6554       if (args->bnum == b->number)
6555         {
6556           print_one_breakpoint (b, &dummy_loc, 0);
6557           return GDB_RC_OK;
6558         }
6559     }
6560   return GDB_RC_NONE;
6561 }
6562
6563 enum gdb_rc
6564 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6565                       char **error_message)
6566 {
6567   struct captured_breakpoint_query_args args;
6568
6569   args.bnum = bnum;
6570   /* For the moment we don't trust print_one_breakpoint() to not throw
6571      an error.  */
6572   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6573                                  error_message, RETURN_MASK_ALL) < 0)
6574     return GDB_RC_FAIL;
6575   else
6576     return GDB_RC_OK;
6577 }
6578
6579 /* Return true if this breakpoint was set by the user, false if it is
6580    internal or momentary.  */
6581
6582 int
6583 user_breakpoint_p (struct breakpoint *b)
6584 {
6585   return b->number > 0;
6586 }
6587
6588 /* Print information on user settable breakpoint (watchpoint, etc)
6589    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6590    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6591    FILTER is non-NULL, call it on each breakpoint and only include the
6592    ones for which it returns non-zero.  Return the total number of
6593    breakpoints listed.  */
6594
6595 static int
6596 breakpoint_1 (char *args, int allflag, 
6597               int (*filter) (const struct breakpoint *))
6598 {
6599   struct breakpoint *b;
6600   struct bp_location *last_loc = NULL;
6601   int nr_printable_breakpoints;
6602   struct cleanup *bkpttbl_chain;
6603   struct value_print_options opts;
6604   int print_address_bits = 0;
6605   int print_type_col_width = 14;
6606   struct ui_out *uiout = current_uiout;
6607
6608   get_user_print_options (&opts);
6609
6610   /* Compute the number of rows in the table, as well as the size
6611      required for address fields.  */
6612   nr_printable_breakpoints = 0;
6613   ALL_BREAKPOINTS (b)
6614     {
6615       /* If we have a filter, only list the breakpoints it accepts.  */
6616       if (filter && !filter (b))
6617         continue;
6618
6619       /* If we have an "args" string, it is a list of breakpoints to 
6620          accept.  Skip the others.  */
6621       if (args != NULL && *args != '\0')
6622         {
6623           if (allflag && parse_and_eval_long (args) != b->number)
6624             continue;
6625           if (!allflag && !number_is_in_list (args, b->number))
6626             continue;
6627         }
6628
6629       if (allflag || user_breakpoint_p (b))
6630         {
6631           int addr_bit, type_len;
6632
6633           addr_bit = breakpoint_address_bits (b);
6634           if (addr_bit > print_address_bits)
6635             print_address_bits = addr_bit;
6636
6637           type_len = strlen (bptype_string (b->type));
6638           if (type_len > print_type_col_width)
6639             print_type_col_width = type_len;
6640
6641           nr_printable_breakpoints++;
6642         }
6643     }
6644
6645   if (opts.addressprint)
6646     bkpttbl_chain 
6647       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6648                                              nr_printable_breakpoints,
6649                                              "BreakpointTable");
6650   else
6651     bkpttbl_chain 
6652       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6653                                              nr_printable_breakpoints,
6654                                              "BreakpointTable");
6655
6656   if (nr_printable_breakpoints > 0)
6657     annotate_breakpoints_headers ();
6658   if (nr_printable_breakpoints > 0)
6659     annotate_field (0);
6660   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6661   if (nr_printable_breakpoints > 0)
6662     annotate_field (1);
6663   ui_out_table_header (uiout, print_type_col_width, ui_left,
6664                        "type", "Type");                         /* 2 */
6665   if (nr_printable_breakpoints > 0)
6666     annotate_field (2);
6667   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6668   if (nr_printable_breakpoints > 0)
6669     annotate_field (3);
6670   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6671   if (opts.addressprint)
6672     {
6673       if (nr_printable_breakpoints > 0)
6674         annotate_field (4);
6675       if (print_address_bits <= 32)
6676         ui_out_table_header (uiout, 10, ui_left, 
6677                              "addr", "Address");                /* 5 */
6678       else
6679         ui_out_table_header (uiout, 18, ui_left, 
6680                              "addr", "Address");                /* 5 */
6681     }
6682   if (nr_printable_breakpoints > 0)
6683     annotate_field (5);
6684   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6685   ui_out_table_body (uiout);
6686   if (nr_printable_breakpoints > 0)
6687     annotate_breakpoints_table ();
6688
6689   ALL_BREAKPOINTS (b)
6690     {
6691       QUIT;
6692       /* If we have a filter, only list the breakpoints it accepts.  */
6693       if (filter && !filter (b))
6694         continue;
6695
6696       /* If we have an "args" string, it is a list of breakpoints to 
6697          accept.  Skip the others.  */
6698
6699       if (args != NULL && *args != '\0')
6700         {
6701           if (allflag)  /* maintenance info breakpoint */
6702             {
6703               if (parse_and_eval_long (args) != b->number)
6704                 continue;
6705             }
6706           else          /* all others */
6707             {
6708               if (!number_is_in_list (args, b->number))
6709                 continue;
6710             }
6711         }
6712       /* We only print out user settable breakpoints unless the
6713          allflag is set.  */
6714       if (allflag || user_breakpoint_p (b))
6715         print_one_breakpoint (b, &last_loc, allflag);
6716     }
6717
6718   do_cleanups (bkpttbl_chain);
6719
6720   if (nr_printable_breakpoints == 0)
6721     {
6722       /* If there's a filter, let the caller decide how to report
6723          empty list.  */
6724       if (!filter)
6725         {
6726           if (args == NULL || *args == '\0')
6727             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6728           else
6729             ui_out_message (uiout, 0, 
6730                             "No breakpoint or watchpoint matching '%s'.\n",
6731                             args);
6732         }
6733     }
6734   else
6735     {
6736       if (last_loc && !server_command)
6737         set_next_address (last_loc->gdbarch, last_loc->address);
6738     }
6739
6740   /* FIXME?  Should this be moved up so that it is only called when
6741      there have been breakpoints? */
6742   annotate_breakpoints_table_end ();
6743
6744   return nr_printable_breakpoints;
6745 }
6746
6747 /* Display the value of default-collect in a way that is generally
6748    compatible with the breakpoint list.  */
6749
6750 static void
6751 default_collect_info (void)
6752 {
6753   struct ui_out *uiout = current_uiout;
6754
6755   /* If it has no value (which is frequently the case), say nothing; a
6756      message like "No default-collect." gets in user's face when it's
6757      not wanted.  */
6758   if (!*default_collect)
6759     return;
6760
6761   /* The following phrase lines up nicely with per-tracepoint collect
6762      actions.  */
6763   ui_out_text (uiout, "default collect ");
6764   ui_out_field_string (uiout, "default-collect", default_collect);
6765   ui_out_text (uiout, " \n");
6766 }
6767   
6768 static void
6769 breakpoints_info (char *args, int from_tty)
6770 {
6771   breakpoint_1 (args, 0, NULL);
6772
6773   default_collect_info ();
6774 }
6775
6776 static void
6777 watchpoints_info (char *args, int from_tty)
6778 {
6779   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6780   struct ui_out *uiout = current_uiout;
6781
6782   if (num_printed == 0)
6783     {
6784       if (args == NULL || *args == '\0')
6785         ui_out_message (uiout, 0, "No watchpoints.\n");
6786       else
6787         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6788     }
6789 }
6790
6791 static void
6792 maintenance_info_breakpoints (char *args, int from_tty)
6793 {
6794   breakpoint_1 (args, 1, NULL);
6795
6796   default_collect_info ();
6797 }
6798
6799 static int
6800 breakpoint_has_pc (struct breakpoint *b,
6801                    struct program_space *pspace,
6802                    CORE_ADDR pc, struct obj_section *section)
6803 {
6804   struct bp_location *bl = b->loc;
6805
6806   for (; bl; bl = bl->next)
6807     {
6808       if (bl->pspace == pspace
6809           && bl->address == pc
6810           && (!overlay_debugging || bl->section == section))
6811         return 1;         
6812     }
6813   return 0;
6814 }
6815
6816 /* Print a message describing any user-breakpoints set at PC.  This
6817    concerns with logical breakpoints, so we match program spaces, not
6818    address spaces.  */
6819
6820 static void
6821 describe_other_breakpoints (struct gdbarch *gdbarch,
6822                             struct program_space *pspace, CORE_ADDR pc,
6823                             struct obj_section *section, int thread)
6824 {
6825   int others = 0;
6826   struct breakpoint *b;
6827
6828   ALL_BREAKPOINTS (b)
6829     others += (user_breakpoint_p (b)
6830                && breakpoint_has_pc (b, pspace, pc, section));
6831   if (others > 0)
6832     {
6833       if (others == 1)
6834         printf_filtered (_("Note: breakpoint "));
6835       else /* if (others == ???) */
6836         printf_filtered (_("Note: breakpoints "));
6837       ALL_BREAKPOINTS (b)
6838         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6839           {
6840             others--;
6841             printf_filtered ("%d", b->number);
6842             if (b->thread == -1 && thread != -1)
6843               printf_filtered (" (all threads)");
6844             else if (b->thread != -1)
6845               printf_filtered (" (thread %d)", b->thread);
6846             printf_filtered ("%s%s ",
6847                              ((b->enable_state == bp_disabled
6848                                || b->enable_state == bp_call_disabled)
6849                               ? " (disabled)"
6850                               : ""),
6851                              (others > 1) ? "," 
6852                              : ((others == 1) ? " and" : ""));
6853           }
6854       printf_filtered (_("also set at pc "));
6855       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6856       printf_filtered (".\n");
6857     }
6858 }
6859 \f
6860
6861 /* Return true iff it is meaningful to use the address member of
6862    BPT.  For some breakpoint types, the address member is irrelevant
6863    and it makes no sense to attempt to compare it to other addresses
6864    (or use it for any other purpose either).
6865
6866    More specifically, each of the following breakpoint types will
6867    always have a zero valued address and we don't want to mark
6868    breakpoints of any of these types to be a duplicate of an actual
6869    breakpoint at address zero:
6870
6871       bp_watchpoint
6872       bp_catchpoint
6873
6874 */
6875
6876 static int
6877 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6878 {
6879   enum bptype type = bpt->type;
6880
6881   return (type != bp_watchpoint && type != bp_catchpoint);
6882 }
6883
6884 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6885    true if LOC1 and LOC2 represent the same watchpoint location.  */
6886
6887 static int
6888 watchpoint_locations_match (struct bp_location *loc1, 
6889                             struct bp_location *loc2)
6890 {
6891   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6892   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6893
6894   /* Both of them must exist.  */
6895   gdb_assert (w1 != NULL);
6896   gdb_assert (w2 != NULL);
6897
6898   /* If the target can evaluate the condition expression in hardware,
6899      then we we need to insert both watchpoints even if they are at
6900      the same place.  Otherwise the watchpoint will only trigger when
6901      the condition of whichever watchpoint was inserted evaluates to
6902      true, not giving a chance for GDB to check the condition of the
6903      other watchpoint.  */
6904   if ((w1->cond_exp
6905        && target_can_accel_watchpoint_condition (loc1->address, 
6906                                                  loc1->length,
6907                                                  loc1->watchpoint_type,
6908                                                  w1->cond_exp))
6909       || (w2->cond_exp
6910           && target_can_accel_watchpoint_condition (loc2->address, 
6911                                                     loc2->length,
6912                                                     loc2->watchpoint_type,
6913                                                     w2->cond_exp)))
6914     return 0;
6915
6916   /* Note that this checks the owner's type, not the location's.  In
6917      case the target does not support read watchpoints, but does
6918      support access watchpoints, we'll have bp_read_watchpoint
6919      watchpoints with hw_access locations.  Those should be considered
6920      duplicates of hw_read locations.  The hw_read locations will
6921      become hw_access locations later.  */
6922   return (loc1->owner->type == loc2->owner->type
6923           && loc1->pspace->aspace == loc2->pspace->aspace
6924           && loc1->address == loc2->address
6925           && loc1->length == loc2->length);
6926 }
6927
6928 /* See breakpoint.h.  */
6929
6930 int
6931 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6932                           struct address_space *aspace2, CORE_ADDR addr2)
6933 {
6934   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6935            || aspace1 == aspace2)
6936           && addr1 == addr2);
6937 }
6938
6939 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6940    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6941    matches ASPACE2.  On targets that have global breakpoints, the address
6942    space doesn't really matter.  */
6943
6944 static int
6945 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6946                                 int len1, struct address_space *aspace2,
6947                                 CORE_ADDR addr2)
6948 {
6949   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6950            || aspace1 == aspace2)
6951           && addr2 >= addr1 && addr2 < addr1 + len1);
6952 }
6953
6954 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6955    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6956    matches the breakpoint's address space.  On targets that have global
6957    breakpoints, the address space doesn't really matter.  */
6958
6959 static int
6960 breakpoint_location_address_match (struct bp_location *bl,
6961                                    struct address_space *aspace,
6962                                    CORE_ADDR addr)
6963 {
6964   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6965                                     aspace, addr)
6966           || (bl->length
6967               && breakpoint_address_match_range (bl->pspace->aspace,
6968                                                  bl->address, bl->length,
6969                                                  aspace, addr)));
6970 }
6971
6972 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6973    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6974    true, otherwise returns false.  */
6975
6976 static int
6977 tracepoint_locations_match (struct bp_location *loc1,
6978                             struct bp_location *loc2)
6979 {
6980   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6981     /* Since tracepoint locations are never duplicated with others', tracepoint
6982        locations at the same address of different tracepoints are regarded as
6983        different locations.  */
6984     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6985   else
6986     return 0;
6987 }
6988
6989 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6990    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6991    represent the same location.  */
6992
6993 static int
6994 breakpoint_locations_match (struct bp_location *loc1, 
6995                             struct bp_location *loc2)
6996 {
6997   int hw_point1, hw_point2;
6998
6999   /* Both of them must not be in moribund_locations.  */
7000   gdb_assert (loc1->owner != NULL);
7001   gdb_assert (loc2->owner != NULL);
7002
7003   hw_point1 = is_hardware_watchpoint (loc1->owner);
7004   hw_point2 = is_hardware_watchpoint (loc2->owner);
7005
7006   if (hw_point1 != hw_point2)
7007     return 0;
7008   else if (hw_point1)
7009     return watchpoint_locations_match (loc1, loc2);
7010   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7011     return tracepoint_locations_match (loc1, loc2);
7012   else
7013     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7014     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7015                                      loc2->pspace->aspace, loc2->address)
7016             && loc1->length == loc2->length);
7017 }
7018
7019 static void
7020 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7021                                int bnum, int have_bnum)
7022 {
7023   /* The longest string possibly returned by hex_string_custom
7024      is 50 chars.  These must be at least that big for safety.  */
7025   char astr1[64];
7026   char astr2[64];
7027
7028   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7029   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7030   if (have_bnum)
7031     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7032              bnum, astr1, astr2);
7033   else
7034     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7035 }
7036
7037 /* Adjust a breakpoint's address to account for architectural
7038    constraints on breakpoint placement.  Return the adjusted address.
7039    Note: Very few targets require this kind of adjustment.  For most
7040    targets, this function is simply the identity function.  */
7041
7042 static CORE_ADDR
7043 adjust_breakpoint_address (struct gdbarch *gdbarch,
7044                            CORE_ADDR bpaddr, enum bptype bptype)
7045 {
7046   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7047     {
7048       /* Very few targets need any kind of breakpoint adjustment.  */
7049       return bpaddr;
7050     }
7051   else if (bptype == bp_watchpoint
7052            || bptype == bp_hardware_watchpoint
7053            || bptype == bp_read_watchpoint
7054            || bptype == bp_access_watchpoint
7055            || bptype == bp_catchpoint)
7056     {
7057       /* Watchpoints and the various bp_catch_* eventpoints should not
7058          have their addresses modified.  */
7059       return bpaddr;
7060     }
7061   else if (bptype == bp_single_step)
7062     {
7063       /* Single-step breakpoints should not have their addresses
7064          modified.  If there's any architectural constrain that
7065          applies to this address, then it should have already been
7066          taken into account when the breakpoint was created in the
7067          first place.  If we didn't do this, stepping through e.g.,
7068          Thumb-2 IT blocks would break.  */
7069       return bpaddr;
7070     }
7071   else
7072     {
7073       CORE_ADDR adjusted_bpaddr;
7074
7075       /* Some targets have architectural constraints on the placement
7076          of breakpoint instructions.  Obtain the adjusted address.  */
7077       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7078
7079       /* An adjusted breakpoint address can significantly alter
7080          a user's expectations.  Print a warning if an adjustment
7081          is required.  */
7082       if (adjusted_bpaddr != bpaddr)
7083         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7084
7085       return adjusted_bpaddr;
7086     }
7087 }
7088
7089 void
7090 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7091                   struct breakpoint *owner)
7092 {
7093   memset (loc, 0, sizeof (*loc));
7094
7095   gdb_assert (ops != NULL);
7096
7097   loc->ops = ops;
7098   loc->owner = owner;
7099   loc->cond = NULL;
7100   loc->cond_bytecode = NULL;
7101   loc->shlib_disabled = 0;
7102   loc->enabled = 1;
7103
7104   switch (owner->type)
7105     {
7106     case bp_breakpoint:
7107     case bp_single_step:
7108     case bp_until:
7109     case bp_finish:
7110     case bp_longjmp:
7111     case bp_longjmp_resume:
7112     case bp_longjmp_call_dummy:
7113     case bp_exception:
7114     case bp_exception_resume:
7115     case bp_step_resume:
7116     case bp_hp_step_resume:
7117     case bp_watchpoint_scope:
7118     case bp_call_dummy:
7119     case bp_std_terminate:
7120     case bp_shlib_event:
7121     case bp_thread_event:
7122     case bp_overlay_event:
7123     case bp_jit_event:
7124     case bp_longjmp_master:
7125     case bp_std_terminate_master:
7126     case bp_exception_master:
7127     case bp_gnu_ifunc_resolver:
7128     case bp_gnu_ifunc_resolver_return:
7129     case bp_dprintf:
7130       loc->loc_type = bp_loc_software_breakpoint;
7131       mark_breakpoint_location_modified (loc);
7132       break;
7133     case bp_hardware_breakpoint:
7134       loc->loc_type = bp_loc_hardware_breakpoint;
7135       mark_breakpoint_location_modified (loc);
7136       break;
7137     case bp_hardware_watchpoint:
7138     case bp_read_watchpoint:
7139     case bp_access_watchpoint:
7140       loc->loc_type = bp_loc_hardware_watchpoint;
7141       break;
7142     case bp_watchpoint:
7143     case bp_catchpoint:
7144     case bp_tracepoint:
7145     case bp_fast_tracepoint:
7146     case bp_static_tracepoint:
7147       loc->loc_type = bp_loc_other;
7148       break;
7149     default:
7150       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7151     }
7152
7153   loc->refc = 1;
7154 }
7155
7156 /* Allocate a struct bp_location.  */
7157
7158 static struct bp_location *
7159 allocate_bp_location (struct breakpoint *bpt)
7160 {
7161   return bpt->ops->allocate_location (bpt);
7162 }
7163
7164 static void
7165 free_bp_location (struct bp_location *loc)
7166 {
7167   loc->ops->dtor (loc);
7168   xfree (loc);
7169 }
7170
7171 /* Increment reference count.  */
7172
7173 static void
7174 incref_bp_location (struct bp_location *bl)
7175 {
7176   ++bl->refc;
7177 }
7178
7179 /* Decrement reference count.  If the reference count reaches 0,
7180    destroy the bp_location.  Sets *BLP to NULL.  */
7181
7182 static void
7183 decref_bp_location (struct bp_location **blp)
7184 {
7185   gdb_assert ((*blp)->refc > 0);
7186
7187   if (--(*blp)->refc == 0)
7188     free_bp_location (*blp);
7189   *blp = NULL;
7190 }
7191
7192 /* Add breakpoint B at the end of the global breakpoint chain.  */
7193
7194 static void
7195 add_to_breakpoint_chain (struct breakpoint *b)
7196 {
7197   struct breakpoint *b1;
7198
7199   /* Add this breakpoint to the end of the chain so that a list of
7200      breakpoints will come out in order of increasing numbers.  */
7201
7202   b1 = breakpoint_chain;
7203   if (b1 == 0)
7204     breakpoint_chain = b;
7205   else
7206     {
7207       while (b1->next)
7208         b1 = b1->next;
7209       b1->next = b;
7210     }
7211 }
7212
7213 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7214
7215 static void
7216 init_raw_breakpoint_without_location (struct breakpoint *b,
7217                                       struct gdbarch *gdbarch,
7218                                       enum bptype bptype,
7219                                       const struct breakpoint_ops *ops)
7220 {
7221   memset (b, 0, sizeof (*b));
7222
7223   gdb_assert (ops != NULL);
7224
7225   b->ops = ops;
7226   b->type = bptype;
7227   b->gdbarch = gdbarch;
7228   b->language = current_language->la_language;
7229   b->input_radix = input_radix;
7230   b->thread = -1;
7231   b->enable_state = bp_enabled;
7232   b->next = 0;
7233   b->silent = 0;
7234   b->ignore_count = 0;
7235   b->commands = NULL;
7236   b->frame_id = null_frame_id;
7237   b->condition_not_parsed = 0;
7238   b->py_bp_object = NULL;
7239   b->related_breakpoint = b;
7240 }
7241
7242 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7243    that has type BPTYPE and has no locations as yet.  */
7244
7245 static struct breakpoint *
7246 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7247                                      enum bptype bptype,
7248                                      const struct breakpoint_ops *ops)
7249 {
7250   struct breakpoint *b = XNEW (struct breakpoint);
7251
7252   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7253   add_to_breakpoint_chain (b);
7254   return b;
7255 }
7256
7257 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7258    resolutions should be made as the user specified the location explicitly
7259    enough.  */
7260
7261 static void
7262 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7263 {
7264   gdb_assert (loc->owner != NULL);
7265
7266   if (loc->owner->type == bp_breakpoint
7267       || loc->owner->type == bp_hardware_breakpoint
7268       || is_tracepoint (loc->owner))
7269     {
7270       int is_gnu_ifunc;
7271       const char *function_name;
7272       CORE_ADDR func_addr;
7273
7274       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7275                                           &func_addr, NULL, &is_gnu_ifunc);
7276
7277       if (is_gnu_ifunc && !explicit_loc)
7278         {
7279           struct breakpoint *b = loc->owner;
7280
7281           gdb_assert (loc->pspace == current_program_space);
7282           if (gnu_ifunc_resolve_name (function_name,
7283                                       &loc->requested_address))
7284             {
7285               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7286               loc->address = adjust_breakpoint_address (loc->gdbarch,
7287                                                         loc->requested_address,
7288                                                         b->type);
7289             }
7290           else if (b->type == bp_breakpoint && b->loc == loc
7291                    && loc->next == NULL && b->related_breakpoint == b)
7292             {
7293               /* Create only the whole new breakpoint of this type but do not
7294                  mess more complicated breakpoints with multiple locations.  */
7295               b->type = bp_gnu_ifunc_resolver;
7296               /* Remember the resolver's address for use by the return
7297                  breakpoint.  */
7298               loc->related_address = func_addr;
7299             }
7300         }
7301
7302       if (function_name)
7303         loc->function_name = xstrdup (function_name);
7304     }
7305 }
7306
7307 /* Attempt to determine architecture of location identified by SAL.  */
7308 struct gdbarch *
7309 get_sal_arch (struct symtab_and_line sal)
7310 {
7311   if (sal.section)
7312     return get_objfile_arch (sal.section->objfile);
7313   if (sal.symtab)
7314     return get_objfile_arch (SYMTAB_OBJFILE (sal.symtab));
7315
7316   return NULL;
7317 }
7318
7319 /* Low level routine for partially initializing a breakpoint of type
7320    BPTYPE.  The newly created breakpoint's address, section, source
7321    file name, and line number are provided by SAL.
7322
7323    It is expected that the caller will complete the initialization of
7324    the newly created breakpoint struct as well as output any status
7325    information regarding the creation of a new breakpoint.  */
7326
7327 static void
7328 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7329                      struct symtab_and_line sal, enum bptype bptype,
7330                      const struct breakpoint_ops *ops)
7331 {
7332   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7333
7334   add_location_to_breakpoint (b, &sal);
7335
7336   if (bptype != bp_catchpoint)
7337     gdb_assert (sal.pspace != NULL);
7338
7339   /* Store the program space that was used to set the breakpoint,
7340      except for ordinary breakpoints, which are independent of the
7341      program space.  */
7342   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7343     b->pspace = sal.pspace;
7344 }
7345
7346 /* set_raw_breakpoint is a low level routine for allocating and
7347    partially initializing a breakpoint of type BPTYPE.  The newly
7348    created breakpoint's address, section, source file name, and line
7349    number are provided by SAL.  The newly created and partially
7350    initialized breakpoint is added to the breakpoint chain and
7351    is also returned as the value of this function.
7352
7353    It is expected that the caller will complete the initialization of
7354    the newly created breakpoint struct as well as output any status
7355    information regarding the creation of a new breakpoint.  In
7356    particular, set_raw_breakpoint does NOT set the breakpoint
7357    number!  Care should be taken to not allow an error to occur
7358    prior to completing the initialization of the breakpoint.  If this
7359    should happen, a bogus breakpoint will be left on the chain.  */
7360
7361 struct breakpoint *
7362 set_raw_breakpoint (struct gdbarch *gdbarch,
7363                     struct symtab_and_line sal, enum bptype bptype,
7364                     const struct breakpoint_ops *ops)
7365 {
7366   struct breakpoint *b = XNEW (struct breakpoint);
7367
7368   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7369   add_to_breakpoint_chain (b);
7370   return b;
7371 }
7372
7373
7374 /* Note that the breakpoint object B describes a permanent breakpoint
7375    instruction, hard-wired into the inferior's code.  */
7376 void
7377 make_breakpoint_permanent (struct breakpoint *b)
7378 {
7379   struct bp_location *bl;
7380
7381   /* By definition, permanent breakpoints are already present in the
7382      code.  Mark all locations as inserted.  For now,
7383      make_breakpoint_permanent is called in just one place, so it's
7384      hard to say if it's reasonable to have permanent breakpoint with
7385      multiple locations or not, but it's easy to implement.  */
7386   for (bl = b->loc; bl; bl = bl->next)
7387     {
7388       bl->permanent = 1;
7389       bl->inserted = 1;
7390     }
7391 }
7392
7393 /* Call this routine when stepping and nexting to enable a breakpoint
7394    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7395    initiated the operation.  */
7396
7397 void
7398 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7399 {
7400   struct breakpoint *b, *b_tmp;
7401   int thread = tp->num;
7402
7403   /* To avoid having to rescan all objfile symbols at every step,
7404      we maintain a list of continually-inserted but always disabled
7405      longjmp "master" breakpoints.  Here, we simply create momentary
7406      clones of those and enable them for the requested thread.  */
7407   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7408     if (b->pspace == current_program_space
7409         && (b->type == bp_longjmp_master
7410             || b->type == bp_exception_master))
7411       {
7412         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7413         struct breakpoint *clone;
7414
7415         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7416            after their removal.  */
7417         clone = momentary_breakpoint_from_master (b, type,
7418                                                   &longjmp_breakpoint_ops, 1);
7419         clone->thread = thread;
7420       }
7421
7422   tp->initiating_frame = frame;
7423 }
7424
7425 /* Delete all longjmp breakpoints from THREAD.  */
7426 void
7427 delete_longjmp_breakpoint (int thread)
7428 {
7429   struct breakpoint *b, *b_tmp;
7430
7431   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7432     if (b->type == bp_longjmp || b->type == bp_exception)
7433       {
7434         if (b->thread == thread)
7435           delete_breakpoint (b);
7436       }
7437 }
7438
7439 void
7440 delete_longjmp_breakpoint_at_next_stop (int thread)
7441 {
7442   struct breakpoint *b, *b_tmp;
7443
7444   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7445     if (b->type == bp_longjmp || b->type == bp_exception)
7446       {
7447         if (b->thread == thread)
7448           b->disposition = disp_del_at_next_stop;
7449       }
7450 }
7451
7452 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7453    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7454    pointer to any of them.  Return NULL if this system cannot place longjmp
7455    breakpoints.  */
7456
7457 struct breakpoint *
7458 set_longjmp_breakpoint_for_call_dummy (void)
7459 {
7460   struct breakpoint *b, *retval = NULL;
7461
7462   ALL_BREAKPOINTS (b)
7463     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7464       {
7465         struct breakpoint *new_b;
7466
7467         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7468                                                   &momentary_breakpoint_ops,
7469                                                   1);
7470         new_b->thread = pid_to_thread_id (inferior_ptid);
7471
7472         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7473
7474         gdb_assert (new_b->related_breakpoint == new_b);
7475         if (retval == NULL)
7476           retval = new_b;
7477         new_b->related_breakpoint = retval;
7478         while (retval->related_breakpoint != new_b->related_breakpoint)
7479           retval = retval->related_breakpoint;
7480         retval->related_breakpoint = new_b;
7481       }
7482
7483   return retval;
7484 }
7485
7486 /* Verify all existing dummy frames and their associated breakpoints for
7487    TP.  Remove those which can no longer be found in the current frame
7488    stack.
7489
7490    You should call this function only at places where it is safe to currently
7491    unwind the whole stack.  Failed stack unwind would discard live dummy
7492    frames.  */
7493
7494 void
7495 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7496 {
7497   struct breakpoint *b, *b_tmp;
7498
7499   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7500     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7501       {
7502         struct breakpoint *dummy_b = b->related_breakpoint;
7503
7504         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7505           dummy_b = dummy_b->related_breakpoint;
7506         if (dummy_b->type != bp_call_dummy
7507             || frame_find_by_id (dummy_b->frame_id) != NULL)
7508           continue;
7509         
7510         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7511
7512         while (b->related_breakpoint != b)
7513           {
7514             if (b_tmp == b->related_breakpoint)
7515               b_tmp = b->related_breakpoint->next;
7516             delete_breakpoint (b->related_breakpoint);
7517           }
7518         delete_breakpoint (b);
7519       }
7520 }
7521
7522 void
7523 enable_overlay_breakpoints (void)
7524 {
7525   struct breakpoint *b;
7526
7527   ALL_BREAKPOINTS (b)
7528     if (b->type == bp_overlay_event)
7529     {
7530       b->enable_state = bp_enabled;
7531       update_global_location_list (UGLL_MAY_INSERT);
7532       overlay_events_enabled = 1;
7533     }
7534 }
7535
7536 void
7537 disable_overlay_breakpoints (void)
7538 {
7539   struct breakpoint *b;
7540
7541   ALL_BREAKPOINTS (b)
7542     if (b->type == bp_overlay_event)
7543     {
7544       b->enable_state = bp_disabled;
7545       update_global_location_list (UGLL_DONT_INSERT);
7546       overlay_events_enabled = 0;
7547     }
7548 }
7549
7550 /* Set an active std::terminate breakpoint for each std::terminate
7551    master breakpoint.  */
7552 void
7553 set_std_terminate_breakpoint (void)
7554 {
7555   struct breakpoint *b, *b_tmp;
7556
7557   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7558     if (b->pspace == current_program_space
7559         && b->type == bp_std_terminate_master)
7560       {
7561         momentary_breakpoint_from_master (b, bp_std_terminate,
7562                                           &momentary_breakpoint_ops, 1);
7563       }
7564 }
7565
7566 /* Delete all the std::terminate breakpoints.  */
7567 void
7568 delete_std_terminate_breakpoint (void)
7569 {
7570   struct breakpoint *b, *b_tmp;
7571
7572   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7573     if (b->type == bp_std_terminate)
7574       delete_breakpoint (b);
7575 }
7576
7577 struct breakpoint *
7578 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7579 {
7580   struct breakpoint *b;
7581
7582   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7583                                   &internal_breakpoint_ops);
7584
7585   b->enable_state = bp_enabled;
7586   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7587   b->addr_string
7588     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7589
7590   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7591
7592   return b;
7593 }
7594
7595 void
7596 remove_thread_event_breakpoints (void)
7597 {
7598   struct breakpoint *b, *b_tmp;
7599
7600   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7601     if (b->type == bp_thread_event
7602         && b->loc->pspace == current_program_space)
7603       delete_breakpoint (b);
7604 }
7605
7606 struct lang_and_radix
7607   {
7608     enum language lang;
7609     int radix;
7610   };
7611
7612 /* Create a breakpoint for JIT code registration and unregistration.  */
7613
7614 struct breakpoint *
7615 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7616 {
7617   struct breakpoint *b;
7618
7619   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7620                                   &internal_breakpoint_ops);
7621   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7622   return b;
7623 }
7624
7625 /* Remove JIT code registration and unregistration breakpoint(s).  */
7626
7627 void
7628 remove_jit_event_breakpoints (void)
7629 {
7630   struct breakpoint *b, *b_tmp;
7631
7632   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7633     if (b->type == bp_jit_event
7634         && b->loc->pspace == current_program_space)
7635       delete_breakpoint (b);
7636 }
7637
7638 void
7639 remove_solib_event_breakpoints (void)
7640 {
7641   struct breakpoint *b, *b_tmp;
7642
7643   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7644     if (b->type == bp_shlib_event
7645         && b->loc->pspace == current_program_space)
7646       delete_breakpoint (b);
7647 }
7648
7649 /* See breakpoint.h.  */
7650
7651 void
7652 remove_solib_event_breakpoints_at_next_stop (void)
7653 {
7654   struct breakpoint *b, *b_tmp;
7655
7656   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7657     if (b->type == bp_shlib_event
7658         && b->loc->pspace == current_program_space)
7659       b->disposition = disp_del_at_next_stop;
7660 }
7661
7662 /* Helper for create_solib_event_breakpoint /
7663    create_and_insert_solib_event_breakpoint.  Allows specifying which
7664    INSERT_MODE to pass through to update_global_location_list.  */
7665
7666 static struct breakpoint *
7667 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7668                                  enum ugll_insert_mode insert_mode)
7669 {
7670   struct breakpoint *b;
7671
7672   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7673                                   &internal_breakpoint_ops);
7674   update_global_location_list_nothrow (insert_mode);
7675   return b;
7676 }
7677
7678 struct breakpoint *
7679 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7680 {
7681   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7682 }
7683
7684 /* See breakpoint.h.  */
7685
7686 struct breakpoint *
7687 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7688 {
7689   struct breakpoint *b;
7690
7691   /* Explicitly tell update_global_location_list to insert
7692      locations.  */
7693   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7694   if (!b->loc->inserted)
7695     {
7696       delete_breakpoint (b);
7697       return NULL;
7698     }
7699   return b;
7700 }
7701
7702 /* Disable any breakpoints that are on code in shared libraries.  Only
7703    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7704
7705 void
7706 disable_breakpoints_in_shlibs (void)
7707 {
7708   struct bp_location *loc, **locp_tmp;
7709
7710   ALL_BP_LOCATIONS (loc, locp_tmp)
7711   {
7712     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7713     struct breakpoint *b = loc->owner;
7714
7715     /* We apply the check to all breakpoints, including disabled for
7716        those with loc->duplicate set.  This is so that when breakpoint
7717        becomes enabled, or the duplicate is removed, gdb will try to
7718        insert all breakpoints.  If we don't set shlib_disabled here,
7719        we'll try to insert those breakpoints and fail.  */
7720     if (((b->type == bp_breakpoint)
7721          || (b->type == bp_jit_event)
7722          || (b->type == bp_hardware_breakpoint)
7723          || (is_tracepoint (b)))
7724         && loc->pspace == current_program_space
7725         && !loc->shlib_disabled
7726         && solib_name_from_address (loc->pspace, loc->address)
7727         )
7728       {
7729         loc->shlib_disabled = 1;
7730       }
7731   }
7732 }
7733
7734 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7735    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7736    disabled ones can just stay disabled.  */
7737
7738 static void
7739 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7740 {
7741   struct bp_location *loc, **locp_tmp;
7742   int disabled_shlib_breaks = 0;
7743
7744   /* SunOS a.out shared libraries are always mapped, so do not
7745      disable breakpoints; they will only be reported as unloaded
7746      through clear_solib when GDB discards its shared library
7747      list.  See clear_solib for more information.  */
7748   if (exec_bfd != NULL
7749       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7750     return;
7751
7752   ALL_BP_LOCATIONS (loc, locp_tmp)
7753   {
7754     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7755     struct breakpoint *b = loc->owner;
7756
7757     if (solib->pspace == loc->pspace
7758         && !loc->shlib_disabled
7759         && (((b->type == bp_breakpoint
7760               || b->type == bp_jit_event
7761               || b->type == bp_hardware_breakpoint)
7762              && (loc->loc_type == bp_loc_hardware_breakpoint
7763                  || loc->loc_type == bp_loc_software_breakpoint))
7764             || is_tracepoint (b))
7765         && solib_contains_address_p (solib, loc->address))
7766       {
7767         loc->shlib_disabled = 1;
7768         /* At this point, we cannot rely on remove_breakpoint
7769            succeeding so we must mark the breakpoint as not inserted
7770            to prevent future errors occurring in remove_breakpoints.  */
7771         loc->inserted = 0;
7772
7773         /* This may cause duplicate notifications for the same breakpoint.  */
7774         observer_notify_breakpoint_modified (b);
7775
7776         if (!disabled_shlib_breaks)
7777           {
7778             target_terminal_ours_for_output ();
7779             warning (_("Temporarily disabling breakpoints "
7780                        "for unloaded shared library \"%s\""),
7781                      solib->so_name);
7782           }
7783         disabled_shlib_breaks = 1;
7784       }
7785   }
7786 }
7787
7788 /* Disable any breakpoints and tracepoints in OBJFILE upon
7789    notification of free_objfile.  Only apply to enabled breakpoints,
7790    disabled ones can just stay disabled.  */
7791
7792 static void
7793 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7794 {
7795   struct breakpoint *b;
7796
7797   if (objfile == NULL)
7798     return;
7799
7800   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7801      managed by the user with add-symbol-file/remove-symbol-file.
7802      Similarly to how breakpoints in shared libraries are handled in
7803      response to "nosharedlibrary", mark breakpoints in such modules
7804      shlib_disabled so they end up uninserted on the next global
7805      location list update.  Shared libraries not loaded by the user
7806      aren't handled here -- they're already handled in
7807      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7808      solib_unloaded observer.  We skip objfiles that are not
7809      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7810      main objfile).  */
7811   if ((objfile->flags & OBJF_SHARED) == 0
7812       || (objfile->flags & OBJF_USERLOADED) == 0)
7813     return;
7814
7815   ALL_BREAKPOINTS (b)
7816     {
7817       struct bp_location *loc;
7818       int bp_modified = 0;
7819
7820       if (!is_breakpoint (b) && !is_tracepoint (b))
7821         continue;
7822
7823       for (loc = b->loc; loc != NULL; loc = loc->next)
7824         {
7825           CORE_ADDR loc_addr = loc->address;
7826
7827           if (loc->loc_type != bp_loc_hardware_breakpoint
7828               && loc->loc_type != bp_loc_software_breakpoint)
7829             continue;
7830
7831           if (loc->shlib_disabled != 0)
7832             continue;
7833
7834           if (objfile->pspace != loc->pspace)
7835             continue;
7836
7837           if (loc->loc_type != bp_loc_hardware_breakpoint
7838               && loc->loc_type != bp_loc_software_breakpoint)
7839             continue;
7840
7841           if (is_addr_in_objfile (loc_addr, objfile))
7842             {
7843               loc->shlib_disabled = 1;
7844               /* At this point, we don't know whether the object was
7845                  unmapped from the inferior or not, so leave the
7846                  inserted flag alone.  We'll handle failure to
7847                  uninsert quietly, in case the object was indeed
7848                  unmapped.  */
7849
7850               mark_breakpoint_location_modified (loc);
7851
7852               bp_modified = 1;
7853             }
7854         }
7855
7856       if (bp_modified)
7857         observer_notify_breakpoint_modified (b);
7858     }
7859 }
7860
7861 /* FORK & VFORK catchpoints.  */
7862
7863 /* An instance of this type is used to represent a fork or vfork
7864    catchpoint.  It includes a "struct breakpoint" as a kind of base
7865    class; users downcast to "struct breakpoint *" when needed.  A
7866    breakpoint is really of this type iff its ops pointer points to
7867    CATCH_FORK_BREAKPOINT_OPS.  */
7868
7869 struct fork_catchpoint
7870 {
7871   /* The base class.  */
7872   struct breakpoint base;
7873
7874   /* Process id of a child process whose forking triggered this
7875      catchpoint.  This field is only valid immediately after this
7876      catchpoint has triggered.  */
7877   ptid_t forked_inferior_pid;
7878 };
7879
7880 /* Implement the "insert" breakpoint_ops method for fork
7881    catchpoints.  */
7882
7883 static int
7884 insert_catch_fork (struct bp_location *bl)
7885 {
7886   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7887 }
7888
7889 /* Implement the "remove" breakpoint_ops method for fork
7890    catchpoints.  */
7891
7892 static int
7893 remove_catch_fork (struct bp_location *bl)
7894 {
7895   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7896 }
7897
7898 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7899    catchpoints.  */
7900
7901 static int
7902 breakpoint_hit_catch_fork (const struct bp_location *bl,
7903                            struct address_space *aspace, CORE_ADDR bp_addr,
7904                            const struct target_waitstatus *ws)
7905 {
7906   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7907
7908   if (ws->kind != TARGET_WAITKIND_FORKED)
7909     return 0;
7910
7911   c->forked_inferior_pid = ws->value.related_pid;
7912   return 1;
7913 }
7914
7915 /* Implement the "print_it" breakpoint_ops method for fork
7916    catchpoints.  */
7917
7918 static enum print_stop_action
7919 print_it_catch_fork (bpstat bs)
7920 {
7921   struct ui_out *uiout = current_uiout;
7922   struct breakpoint *b = bs->breakpoint_at;
7923   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7924
7925   annotate_catchpoint (b->number);
7926   if (b->disposition == disp_del)
7927     ui_out_text (uiout, "\nTemporary catchpoint ");
7928   else
7929     ui_out_text (uiout, "\nCatchpoint ");
7930   if (ui_out_is_mi_like_p (uiout))
7931     {
7932       ui_out_field_string (uiout, "reason",
7933                            async_reason_lookup (EXEC_ASYNC_FORK));
7934       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7935     }
7936   ui_out_field_int (uiout, "bkptno", b->number);
7937   ui_out_text (uiout, " (forked process ");
7938   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7939   ui_out_text (uiout, "), ");
7940   return PRINT_SRC_AND_LOC;
7941 }
7942
7943 /* Implement the "print_one" breakpoint_ops method for fork
7944    catchpoints.  */
7945
7946 static void
7947 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7948 {
7949   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7950   struct value_print_options opts;
7951   struct ui_out *uiout = current_uiout;
7952
7953   get_user_print_options (&opts);
7954
7955   /* Field 4, the address, is omitted (which makes the columns not
7956      line up too nicely with the headers, but the effect is relatively
7957      readable).  */
7958   if (opts.addressprint)
7959     ui_out_field_skip (uiout, "addr");
7960   annotate_field (5);
7961   ui_out_text (uiout, "fork");
7962   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7963     {
7964       ui_out_text (uiout, ", process ");
7965       ui_out_field_int (uiout, "what",
7966                         ptid_get_pid (c->forked_inferior_pid));
7967       ui_out_spaces (uiout, 1);
7968     }
7969
7970   if (ui_out_is_mi_like_p (uiout))
7971     ui_out_field_string (uiout, "catch-type", "fork");
7972 }
7973
7974 /* Implement the "print_mention" breakpoint_ops method for fork
7975    catchpoints.  */
7976
7977 static void
7978 print_mention_catch_fork (struct breakpoint *b)
7979 {
7980   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7981 }
7982
7983 /* Implement the "print_recreate" breakpoint_ops method for fork
7984    catchpoints.  */
7985
7986 static void
7987 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7988 {
7989   fprintf_unfiltered (fp, "catch fork");
7990   print_recreate_thread (b, fp);
7991 }
7992
7993 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7994
7995 static struct breakpoint_ops catch_fork_breakpoint_ops;
7996
7997 /* Implement the "insert" breakpoint_ops method for vfork
7998    catchpoints.  */
7999
8000 static int
8001 insert_catch_vfork (struct bp_location *bl)
8002 {
8003   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8004 }
8005
8006 /* Implement the "remove" breakpoint_ops method for vfork
8007    catchpoints.  */
8008
8009 static int
8010 remove_catch_vfork (struct bp_location *bl)
8011 {
8012   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8013 }
8014
8015 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8016    catchpoints.  */
8017
8018 static int
8019 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8020                             struct address_space *aspace, CORE_ADDR bp_addr,
8021                             const struct target_waitstatus *ws)
8022 {
8023   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8024
8025   if (ws->kind != TARGET_WAITKIND_VFORKED)
8026     return 0;
8027
8028   c->forked_inferior_pid = ws->value.related_pid;
8029   return 1;
8030 }
8031
8032 /* Implement the "print_it" breakpoint_ops method for vfork
8033    catchpoints.  */
8034
8035 static enum print_stop_action
8036 print_it_catch_vfork (bpstat bs)
8037 {
8038   struct ui_out *uiout = current_uiout;
8039   struct breakpoint *b = bs->breakpoint_at;
8040   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8041
8042   annotate_catchpoint (b->number);
8043   if (b->disposition == disp_del)
8044     ui_out_text (uiout, "\nTemporary catchpoint ");
8045   else
8046     ui_out_text (uiout, "\nCatchpoint ");
8047   if (ui_out_is_mi_like_p (uiout))
8048     {
8049       ui_out_field_string (uiout, "reason",
8050                            async_reason_lookup (EXEC_ASYNC_VFORK));
8051       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8052     }
8053   ui_out_field_int (uiout, "bkptno", b->number);
8054   ui_out_text (uiout, " (vforked process ");
8055   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8056   ui_out_text (uiout, "), ");
8057   return PRINT_SRC_AND_LOC;
8058 }
8059
8060 /* Implement the "print_one" breakpoint_ops method for vfork
8061    catchpoints.  */
8062
8063 static void
8064 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8065 {
8066   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8067   struct value_print_options opts;
8068   struct ui_out *uiout = current_uiout;
8069
8070   get_user_print_options (&opts);
8071   /* Field 4, the address, is omitted (which makes the columns not
8072      line up too nicely with the headers, but the effect is relatively
8073      readable).  */
8074   if (opts.addressprint)
8075     ui_out_field_skip (uiout, "addr");
8076   annotate_field (5);
8077   ui_out_text (uiout, "vfork");
8078   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8079     {
8080       ui_out_text (uiout, ", process ");
8081       ui_out_field_int (uiout, "what",
8082                         ptid_get_pid (c->forked_inferior_pid));
8083       ui_out_spaces (uiout, 1);
8084     }
8085
8086   if (ui_out_is_mi_like_p (uiout))
8087     ui_out_field_string (uiout, "catch-type", "vfork");
8088 }
8089
8090 /* Implement the "print_mention" breakpoint_ops method for vfork
8091    catchpoints.  */
8092
8093 static void
8094 print_mention_catch_vfork (struct breakpoint *b)
8095 {
8096   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8097 }
8098
8099 /* Implement the "print_recreate" breakpoint_ops method for vfork
8100    catchpoints.  */
8101
8102 static void
8103 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8104 {
8105   fprintf_unfiltered (fp, "catch vfork");
8106   print_recreate_thread (b, fp);
8107 }
8108
8109 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8110
8111 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8112
8113 /* An instance of this type is used to represent an solib catchpoint.
8114    It includes a "struct breakpoint" as a kind of base class; users
8115    downcast to "struct breakpoint *" when needed.  A breakpoint is
8116    really of this type iff its ops pointer points to
8117    CATCH_SOLIB_BREAKPOINT_OPS.  */
8118
8119 struct solib_catchpoint
8120 {
8121   /* The base class.  */
8122   struct breakpoint base;
8123
8124   /* True for "catch load", false for "catch unload".  */
8125   unsigned char is_load;
8126
8127   /* Regular expression to match, if any.  COMPILED is only valid when
8128      REGEX is non-NULL.  */
8129   char *regex;
8130   regex_t compiled;
8131 };
8132
8133 static void
8134 dtor_catch_solib (struct breakpoint *b)
8135 {
8136   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8137
8138   if (self->regex)
8139     regfree (&self->compiled);
8140   xfree (self->regex);
8141
8142   base_breakpoint_ops.dtor (b);
8143 }
8144
8145 static int
8146 insert_catch_solib (struct bp_location *ignore)
8147 {
8148   return 0;
8149 }
8150
8151 static int
8152 remove_catch_solib (struct bp_location *ignore)
8153 {
8154   return 0;
8155 }
8156
8157 static int
8158 breakpoint_hit_catch_solib (const struct bp_location *bl,
8159                             struct address_space *aspace,
8160                             CORE_ADDR bp_addr,
8161                             const struct target_waitstatus *ws)
8162 {
8163   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8164   struct breakpoint *other;
8165
8166   if (ws->kind == TARGET_WAITKIND_LOADED)
8167     return 1;
8168
8169   ALL_BREAKPOINTS (other)
8170   {
8171     struct bp_location *other_bl;
8172
8173     if (other == bl->owner)
8174       continue;
8175
8176     if (other->type != bp_shlib_event)
8177       continue;
8178
8179     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8180       continue;
8181
8182     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8183       {
8184         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8185           return 1;
8186       }
8187   }
8188
8189   return 0;
8190 }
8191
8192 static void
8193 check_status_catch_solib (struct bpstats *bs)
8194 {
8195   struct solib_catchpoint *self
8196     = (struct solib_catchpoint *) bs->breakpoint_at;
8197   int ix;
8198
8199   if (self->is_load)
8200     {
8201       struct so_list *iter;
8202
8203       for (ix = 0;
8204            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8205                         ix, iter);
8206            ++ix)
8207         {
8208           if (!self->regex
8209               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8210             return;
8211         }
8212     }
8213   else
8214     {
8215       char *iter;
8216
8217       for (ix = 0;
8218            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8219                         ix, iter);
8220            ++ix)
8221         {
8222           if (!self->regex
8223               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8224             return;
8225         }
8226     }
8227
8228   bs->stop = 0;
8229   bs->print_it = print_it_noop;
8230 }
8231
8232 static enum print_stop_action
8233 print_it_catch_solib (bpstat bs)
8234 {
8235   struct breakpoint *b = bs->breakpoint_at;
8236   struct ui_out *uiout = current_uiout;
8237
8238   annotate_catchpoint (b->number);
8239   if (b->disposition == disp_del)
8240     ui_out_text (uiout, "\nTemporary catchpoint ");
8241   else
8242     ui_out_text (uiout, "\nCatchpoint ");
8243   ui_out_field_int (uiout, "bkptno", b->number);
8244   ui_out_text (uiout, "\n");
8245   if (ui_out_is_mi_like_p (uiout))
8246     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8247   print_solib_event (1);
8248   return PRINT_SRC_AND_LOC;
8249 }
8250
8251 static void
8252 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8253 {
8254   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8255   struct value_print_options opts;
8256   struct ui_out *uiout = current_uiout;
8257   char *msg;
8258
8259   get_user_print_options (&opts);
8260   /* Field 4, the address, is omitted (which makes the columns not
8261      line up too nicely with the headers, but the effect is relatively
8262      readable).  */
8263   if (opts.addressprint)
8264     {
8265       annotate_field (4);
8266       ui_out_field_skip (uiout, "addr");
8267     }
8268
8269   annotate_field (5);
8270   if (self->is_load)
8271     {
8272       if (self->regex)
8273         msg = xstrprintf (_("load of library matching %s"), self->regex);
8274       else
8275         msg = xstrdup (_("load of library"));
8276     }
8277   else
8278     {
8279       if (self->regex)
8280         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8281       else
8282         msg = xstrdup (_("unload of library"));
8283     }
8284   ui_out_field_string (uiout, "what", msg);
8285   xfree (msg);
8286
8287   if (ui_out_is_mi_like_p (uiout))
8288     ui_out_field_string (uiout, "catch-type",
8289                          self->is_load ? "load" : "unload");
8290 }
8291
8292 static void
8293 print_mention_catch_solib (struct breakpoint *b)
8294 {
8295   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8296
8297   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8298                    self->is_load ? "load" : "unload");
8299 }
8300
8301 static void
8302 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8303 {
8304   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8305
8306   fprintf_unfiltered (fp, "%s %s",
8307                       b->disposition == disp_del ? "tcatch" : "catch",
8308                       self->is_load ? "load" : "unload");
8309   if (self->regex)
8310     fprintf_unfiltered (fp, " %s", self->regex);
8311   fprintf_unfiltered (fp, "\n");
8312 }
8313
8314 static struct breakpoint_ops catch_solib_breakpoint_ops;
8315
8316 /* Shared helper function (MI and CLI) for creating and installing
8317    a shared object event catchpoint.  If IS_LOAD is non-zero then
8318    the events to be caught are load events, otherwise they are
8319    unload events.  If IS_TEMP is non-zero the catchpoint is a
8320    temporary one.  If ENABLED is non-zero the catchpoint is
8321    created in an enabled state.  */
8322
8323 void
8324 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8325 {
8326   struct solib_catchpoint *c;
8327   struct gdbarch *gdbarch = get_current_arch ();
8328   struct cleanup *cleanup;
8329
8330   if (!arg)
8331     arg = "";
8332   arg = skip_spaces (arg);
8333
8334   c = XCNEW (struct solib_catchpoint);
8335   cleanup = make_cleanup (xfree, c);
8336
8337   if (*arg != '\0')
8338     {
8339       int errcode;
8340
8341       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8342       if (errcode != 0)
8343         {
8344           char *err = get_regcomp_error (errcode, &c->compiled);
8345
8346           make_cleanup (xfree, err);
8347           error (_("Invalid regexp (%s): %s"), err, arg);
8348         }
8349       c->regex = xstrdup (arg);
8350     }
8351
8352   c->is_load = is_load;
8353   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8354                    &catch_solib_breakpoint_ops);
8355
8356   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8357
8358   discard_cleanups (cleanup);
8359   install_breakpoint (0, &c->base, 1);
8360 }
8361
8362 /* A helper function that does all the work for "catch load" and
8363    "catch unload".  */
8364
8365 static void
8366 catch_load_or_unload (char *arg, int from_tty, int is_load,
8367                       struct cmd_list_element *command)
8368 {
8369   int tempflag;
8370   const int enabled = 1;
8371
8372   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8373
8374   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8375 }
8376
8377 static void
8378 catch_load_command_1 (char *arg, int from_tty,
8379                       struct cmd_list_element *command)
8380 {
8381   catch_load_or_unload (arg, from_tty, 1, command);
8382 }
8383
8384 static void
8385 catch_unload_command_1 (char *arg, int from_tty,
8386                         struct cmd_list_element *command)
8387 {
8388   catch_load_or_unload (arg, from_tty, 0, command);
8389 }
8390
8391 /* An instance of this type is used to represent a syscall catchpoint.
8392    It includes a "struct breakpoint" as a kind of base class; users
8393    downcast to "struct breakpoint *" when needed.  A breakpoint is
8394    really of this type iff its ops pointer points to
8395    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8396
8397 struct syscall_catchpoint
8398 {
8399   /* The base class.  */
8400   struct breakpoint base;
8401
8402   /* Syscall numbers used for the 'catch syscall' feature.  If no
8403      syscall has been specified for filtering, its value is NULL.
8404      Otherwise, it holds a list of all syscalls to be caught.  The
8405      list elements are allocated with xmalloc.  */
8406   VEC(int) *syscalls_to_be_caught;
8407 };
8408
8409 /* Implement the "dtor" breakpoint_ops method for syscall
8410    catchpoints.  */
8411
8412 static void
8413 dtor_catch_syscall (struct breakpoint *b)
8414 {
8415   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8416
8417   VEC_free (int, c->syscalls_to_be_caught);
8418
8419   base_breakpoint_ops.dtor (b);
8420 }
8421
8422 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8423
8424 struct catch_syscall_inferior_data
8425 {
8426   /* We keep a count of the number of times the user has requested a
8427      particular syscall to be tracked, and pass this information to the
8428      target.  This lets capable targets implement filtering directly.  */
8429
8430   /* Number of times that "any" syscall is requested.  */
8431   int any_syscall_count;
8432
8433   /* Count of each system call.  */
8434   VEC(int) *syscalls_counts;
8435
8436   /* This counts all syscall catch requests, so we can readily determine
8437      if any catching is necessary.  */
8438   int total_syscalls_count;
8439 };
8440
8441 static struct catch_syscall_inferior_data*
8442 get_catch_syscall_inferior_data (struct inferior *inf)
8443 {
8444   struct catch_syscall_inferior_data *inf_data;
8445
8446   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8447   if (inf_data == NULL)
8448     {
8449       inf_data = XCNEW (struct catch_syscall_inferior_data);
8450       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8451     }
8452
8453   return inf_data;
8454 }
8455
8456 static void
8457 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8458 {
8459   xfree (arg);
8460 }
8461
8462
8463 /* Implement the "insert" breakpoint_ops method for syscall
8464    catchpoints.  */
8465
8466 static int
8467 insert_catch_syscall (struct bp_location *bl)
8468 {
8469   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8470   struct inferior *inf = current_inferior ();
8471   struct catch_syscall_inferior_data *inf_data
8472     = get_catch_syscall_inferior_data (inf);
8473
8474   ++inf_data->total_syscalls_count;
8475   if (!c->syscalls_to_be_caught)
8476     ++inf_data->any_syscall_count;
8477   else
8478     {
8479       int i, iter;
8480
8481       for (i = 0;
8482            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8483            i++)
8484         {
8485           int elem;
8486
8487           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8488             {
8489               int old_size = VEC_length (int, inf_data->syscalls_counts);
8490               uintptr_t vec_addr_offset
8491                 = old_size * ((uintptr_t) sizeof (int));
8492               uintptr_t vec_addr;
8493               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8494               vec_addr = ((uintptr_t) VEC_address (int,
8495                                                   inf_data->syscalls_counts)
8496                           + vec_addr_offset);
8497               memset ((void *) vec_addr, 0,
8498                       (iter + 1 - old_size) * sizeof (int));
8499             }
8500           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8501           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8502         }
8503     }
8504
8505   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8506                                         inf_data->total_syscalls_count != 0,
8507                                         inf_data->any_syscall_count,
8508                                         VEC_length (int,
8509                                                     inf_data->syscalls_counts),
8510                                         VEC_address (int,
8511                                                      inf_data->syscalls_counts));
8512 }
8513
8514 /* Implement the "remove" breakpoint_ops method for syscall
8515    catchpoints.  */
8516
8517 static int
8518 remove_catch_syscall (struct bp_location *bl)
8519 {
8520   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8521   struct inferior *inf = current_inferior ();
8522   struct catch_syscall_inferior_data *inf_data
8523     = get_catch_syscall_inferior_data (inf);
8524
8525   --inf_data->total_syscalls_count;
8526   if (!c->syscalls_to_be_caught)
8527     --inf_data->any_syscall_count;
8528   else
8529     {
8530       int i, iter;
8531
8532       for (i = 0;
8533            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8534            i++)
8535         {
8536           int elem;
8537           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8538             /* Shouldn't happen.  */
8539             continue;
8540           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8541           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8542         }
8543     }
8544
8545   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8546                                         inf_data->total_syscalls_count != 0,
8547                                         inf_data->any_syscall_count,
8548                                         VEC_length (int,
8549                                                     inf_data->syscalls_counts),
8550                                         VEC_address (int,
8551                                                      inf_data->syscalls_counts));
8552 }
8553
8554 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8555    catchpoints.  */
8556
8557 static int
8558 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8559                               struct address_space *aspace, CORE_ADDR bp_addr,
8560                               const struct target_waitstatus *ws)
8561 {
8562   /* We must check if we are catching specific syscalls in this
8563      breakpoint.  If we are, then we must guarantee that the called
8564      syscall is the same syscall we are catching.  */
8565   int syscall_number = 0;
8566   const struct syscall_catchpoint *c
8567     = (const struct syscall_catchpoint *) bl->owner;
8568
8569   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8570       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8571     return 0;
8572
8573   syscall_number = ws->value.syscall_number;
8574
8575   /* Now, checking if the syscall is the same.  */
8576   if (c->syscalls_to_be_caught)
8577     {
8578       int i, iter;
8579
8580       for (i = 0;
8581            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8582            i++)
8583         if (syscall_number == iter)
8584           return 1;
8585
8586       return 0;
8587     }
8588
8589   return 1;
8590 }
8591
8592 /* Implement the "print_it" breakpoint_ops method for syscall
8593    catchpoints.  */
8594
8595 static enum print_stop_action
8596 print_it_catch_syscall (bpstat bs)
8597 {
8598   struct ui_out *uiout = current_uiout;
8599   struct breakpoint *b = bs->breakpoint_at;
8600   /* These are needed because we want to know in which state a
8601      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8602      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8603      must print "called syscall" or "returned from syscall".  */
8604   ptid_t ptid;
8605   struct target_waitstatus last;
8606   struct syscall s;
8607   struct gdbarch *gdbarch = bs->bp_location_at->gdbarch;
8608
8609   get_last_target_status (&ptid, &last);
8610
8611   get_syscall_by_number (gdbarch, last.value.syscall_number, &s);
8612
8613   annotate_catchpoint (b->number);
8614
8615   if (b->disposition == disp_del)
8616     ui_out_text (uiout, "\nTemporary catchpoint ");
8617   else
8618     ui_out_text (uiout, "\nCatchpoint ");
8619   if (ui_out_is_mi_like_p (uiout))
8620     {
8621       ui_out_field_string (uiout, "reason",
8622                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8623                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8624                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8625       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8626     }
8627   ui_out_field_int (uiout, "bkptno", b->number);
8628
8629   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8630     ui_out_text (uiout, " (call to syscall ");
8631   else
8632     ui_out_text (uiout, " (returned from syscall ");
8633
8634   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8635     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8636   if (s.name != NULL)
8637     ui_out_field_string (uiout, "syscall-name", s.name);
8638
8639   ui_out_text (uiout, "), ");
8640
8641   return PRINT_SRC_AND_LOC;
8642 }
8643
8644 /* Implement the "print_one" breakpoint_ops method for syscall
8645    catchpoints.  */
8646
8647 static void
8648 print_one_catch_syscall (struct breakpoint *b,
8649                          struct bp_location **last_loc)
8650 {
8651   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8652   struct value_print_options opts;
8653   struct ui_out *uiout = current_uiout;
8654   struct gdbarch *gdbarch = b->loc->gdbarch;
8655
8656   get_user_print_options (&opts);
8657   /* Field 4, the address, is omitted (which makes the columns not
8658      line up too nicely with the headers, but the effect is relatively
8659      readable).  */
8660   if (opts.addressprint)
8661     ui_out_field_skip (uiout, "addr");
8662   annotate_field (5);
8663
8664   if (c->syscalls_to_be_caught
8665       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8666     ui_out_text (uiout, "syscalls \"");
8667   else
8668     ui_out_text (uiout, "syscall \"");
8669
8670   if (c->syscalls_to_be_caught)
8671     {
8672       int i, iter;
8673       char *text = xstrprintf ("%s", "");
8674
8675       for (i = 0;
8676            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8677            i++)
8678         {
8679           char *x = text;
8680           struct syscall s;
8681           get_syscall_by_number (gdbarch, iter, &s);
8682
8683           if (s.name != NULL)
8684             text = xstrprintf ("%s%s, ", text, s.name);
8685           else
8686             text = xstrprintf ("%s%d, ", text, iter);
8687
8688           /* We have to xfree the last 'text' (now stored at 'x')
8689              because xstrprintf dynamically allocates new space for it
8690              on every call.  */
8691           xfree (x);
8692         }
8693       /* Remove the last comma.  */
8694       text[strlen (text) - 2] = '\0';
8695       ui_out_field_string (uiout, "what", text);
8696     }
8697   else
8698     ui_out_field_string (uiout, "what", "<any syscall>");
8699   ui_out_text (uiout, "\" ");
8700
8701   if (ui_out_is_mi_like_p (uiout))
8702     ui_out_field_string (uiout, "catch-type", "syscall");
8703 }
8704
8705 /* Implement the "print_mention" breakpoint_ops method for syscall
8706    catchpoints.  */
8707
8708 static void
8709 print_mention_catch_syscall (struct breakpoint *b)
8710 {
8711   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8712   struct gdbarch *gdbarch = b->loc->gdbarch;
8713
8714   if (c->syscalls_to_be_caught)
8715     {
8716       int i, iter;
8717
8718       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8719         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8720       else
8721         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8722
8723       for (i = 0;
8724            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8725            i++)
8726         {
8727           struct syscall s;
8728           get_syscall_by_number (gdbarch, iter, &s);
8729
8730           if (s.name)
8731             printf_filtered (" '%s' [%d]", s.name, s.number);
8732           else
8733             printf_filtered (" %d", s.number);
8734         }
8735       printf_filtered (")");
8736     }
8737   else
8738     printf_filtered (_("Catchpoint %d (any syscall)"),
8739                      b->number);
8740 }
8741
8742 /* Implement the "print_recreate" breakpoint_ops method for syscall
8743    catchpoints.  */
8744
8745 static void
8746 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8747 {
8748   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8749   struct gdbarch *gdbarch = b->loc->gdbarch;
8750
8751   fprintf_unfiltered (fp, "catch syscall");
8752
8753   if (c->syscalls_to_be_caught)
8754     {
8755       int i, iter;
8756
8757       for (i = 0;
8758            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8759            i++)
8760         {
8761           struct syscall s;
8762
8763           get_syscall_by_number (gdbarch, iter, &s);
8764           if (s.name)
8765             fprintf_unfiltered (fp, " %s", s.name);
8766           else
8767             fprintf_unfiltered (fp, " %d", s.number);
8768         }
8769     }
8770   print_recreate_thread (b, fp);
8771 }
8772
8773 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8774
8775 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8776
8777 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8778
8779 static int
8780 syscall_catchpoint_p (struct breakpoint *b)
8781 {
8782   return (b->ops == &catch_syscall_breakpoint_ops);
8783 }
8784
8785 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8786    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8787    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8788    the breakpoint_ops structure associated to the catchpoint.  */
8789
8790 void
8791 init_catchpoint (struct breakpoint *b,
8792                  struct gdbarch *gdbarch, int tempflag,
8793                  char *cond_string,
8794                  const struct breakpoint_ops *ops)
8795 {
8796   struct symtab_and_line sal;
8797
8798   init_sal (&sal);
8799   sal.pspace = current_program_space;
8800
8801   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8802
8803   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8804   b->disposition = tempflag ? disp_del : disp_donttouch;
8805 }
8806
8807 void
8808 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8809 {
8810   add_to_breakpoint_chain (b);
8811   set_breakpoint_number (internal, b);
8812   if (is_tracepoint (b))
8813     set_tracepoint_count (breakpoint_count);
8814   if (!internal)
8815     mention (b);
8816   observer_notify_breakpoint_created (b);
8817
8818   if (update_gll)
8819     update_global_location_list (UGLL_MAY_INSERT);
8820 }
8821
8822 static void
8823 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8824                                     int tempflag, char *cond_string,
8825                                     const struct breakpoint_ops *ops)
8826 {
8827   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8828
8829   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8830
8831   c->forked_inferior_pid = null_ptid;
8832
8833   install_breakpoint (0, &c->base, 1);
8834 }
8835
8836 /* Exec catchpoints.  */
8837
8838 /* An instance of this type is used to represent an exec catchpoint.
8839    It includes a "struct breakpoint" as a kind of base class; users
8840    downcast to "struct breakpoint *" when needed.  A breakpoint is
8841    really of this type iff its ops pointer points to
8842    CATCH_EXEC_BREAKPOINT_OPS.  */
8843
8844 struct exec_catchpoint
8845 {
8846   /* The base class.  */
8847   struct breakpoint base;
8848
8849   /* Filename of a program whose exec triggered this catchpoint.
8850      This field is only valid immediately after this catchpoint has
8851      triggered.  */
8852   char *exec_pathname;
8853 };
8854
8855 /* Implement the "dtor" breakpoint_ops method for exec
8856    catchpoints.  */
8857
8858 static void
8859 dtor_catch_exec (struct breakpoint *b)
8860 {
8861   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8862
8863   xfree (c->exec_pathname);
8864
8865   base_breakpoint_ops.dtor (b);
8866 }
8867
8868 static int
8869 insert_catch_exec (struct bp_location *bl)
8870 {
8871   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8872 }
8873
8874 static int
8875 remove_catch_exec (struct bp_location *bl)
8876 {
8877   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8878 }
8879
8880 static int
8881 breakpoint_hit_catch_exec (const struct bp_location *bl,
8882                            struct address_space *aspace, CORE_ADDR bp_addr,
8883                            const struct target_waitstatus *ws)
8884 {
8885   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8886
8887   if (ws->kind != TARGET_WAITKIND_EXECD)
8888     return 0;
8889
8890   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8891   return 1;
8892 }
8893
8894 static enum print_stop_action
8895 print_it_catch_exec (bpstat bs)
8896 {
8897   struct ui_out *uiout = current_uiout;
8898   struct breakpoint *b = bs->breakpoint_at;
8899   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8900
8901   annotate_catchpoint (b->number);
8902   if (b->disposition == disp_del)
8903     ui_out_text (uiout, "\nTemporary catchpoint ");
8904   else
8905     ui_out_text (uiout, "\nCatchpoint ");
8906   if (ui_out_is_mi_like_p (uiout))
8907     {
8908       ui_out_field_string (uiout, "reason",
8909                            async_reason_lookup (EXEC_ASYNC_EXEC));
8910       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8911     }
8912   ui_out_field_int (uiout, "bkptno", b->number);
8913   ui_out_text (uiout, " (exec'd ");
8914   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8915   ui_out_text (uiout, "), ");
8916
8917   return PRINT_SRC_AND_LOC;
8918 }
8919
8920 static void
8921 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8922 {
8923   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8924   struct value_print_options opts;
8925   struct ui_out *uiout = current_uiout;
8926
8927   get_user_print_options (&opts);
8928
8929   /* Field 4, the address, is omitted (which makes the columns
8930      not line up too nicely with the headers, but the effect
8931      is relatively readable).  */
8932   if (opts.addressprint)
8933     ui_out_field_skip (uiout, "addr");
8934   annotate_field (5);
8935   ui_out_text (uiout, "exec");
8936   if (c->exec_pathname != NULL)
8937     {
8938       ui_out_text (uiout, ", program \"");
8939       ui_out_field_string (uiout, "what", c->exec_pathname);
8940       ui_out_text (uiout, "\" ");
8941     }
8942
8943   if (ui_out_is_mi_like_p (uiout))
8944     ui_out_field_string (uiout, "catch-type", "exec");
8945 }
8946
8947 static void
8948 print_mention_catch_exec (struct breakpoint *b)
8949 {
8950   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8951 }
8952
8953 /* Implement the "print_recreate" breakpoint_ops method for exec
8954    catchpoints.  */
8955
8956 static void
8957 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8958 {
8959   fprintf_unfiltered (fp, "catch exec");
8960   print_recreate_thread (b, fp);
8961 }
8962
8963 static struct breakpoint_ops catch_exec_breakpoint_ops;
8964
8965 static void
8966 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8967                                  const struct breakpoint_ops *ops)
8968 {
8969   struct syscall_catchpoint *c;
8970   struct gdbarch *gdbarch = get_current_arch ();
8971
8972   c = XNEW (struct syscall_catchpoint);
8973   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8974   c->syscalls_to_be_caught = filter;
8975
8976   install_breakpoint (0, &c->base, 1);
8977 }
8978
8979 static int
8980 hw_breakpoint_used_count (void)
8981 {
8982   int i = 0;
8983   struct breakpoint *b;
8984   struct bp_location *bl;
8985
8986   ALL_BREAKPOINTS (b)
8987   {
8988     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8989       for (bl = b->loc; bl; bl = bl->next)
8990         {
8991           /* Special types of hardware breakpoints may use more than
8992              one register.  */
8993           i += b->ops->resources_needed (bl);
8994         }
8995   }
8996
8997   return i;
8998 }
8999
9000 /* Returns the resources B would use if it were a hardware
9001    watchpoint.  */
9002
9003 static int
9004 hw_watchpoint_use_count (struct breakpoint *b)
9005 {
9006   int i = 0;
9007   struct bp_location *bl;
9008
9009   if (!breakpoint_enabled (b))
9010     return 0;
9011
9012   for (bl = b->loc; bl; bl = bl->next)
9013     {
9014       /* Special types of hardware watchpoints may use more than
9015          one register.  */
9016       i += b->ops->resources_needed (bl);
9017     }
9018
9019   return i;
9020 }
9021
9022 /* Returns the sum the used resources of all hardware watchpoints of
9023    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
9024    the sum of the used resources of all hardware watchpoints of other
9025    types _not_ TYPE.  */
9026
9027 static int
9028 hw_watchpoint_used_count_others (struct breakpoint *except,
9029                                  enum bptype type, int *other_type_used)
9030 {
9031   int i = 0;
9032   struct breakpoint *b;
9033
9034   *other_type_used = 0;
9035   ALL_BREAKPOINTS (b)
9036     {
9037       if (b == except)
9038         continue;
9039       if (!breakpoint_enabled (b))
9040         continue;
9041
9042       if (b->type == type)
9043         i += hw_watchpoint_use_count (b);
9044       else if (is_hardware_watchpoint (b))
9045         *other_type_used = 1;
9046     }
9047
9048   return i;
9049 }
9050
9051 void
9052 disable_watchpoints_before_interactive_call_start (void)
9053 {
9054   struct breakpoint *b;
9055
9056   ALL_BREAKPOINTS (b)
9057   {
9058     if (is_watchpoint (b) && breakpoint_enabled (b))
9059       {
9060         b->enable_state = bp_call_disabled;
9061         update_global_location_list (UGLL_DONT_INSERT);
9062       }
9063   }
9064 }
9065
9066 void
9067 enable_watchpoints_after_interactive_call_stop (void)
9068 {
9069   struct breakpoint *b;
9070
9071   ALL_BREAKPOINTS (b)
9072   {
9073     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9074       {
9075         b->enable_state = bp_enabled;
9076         update_global_location_list (UGLL_MAY_INSERT);
9077       }
9078   }
9079 }
9080
9081 void
9082 disable_breakpoints_before_startup (void)
9083 {
9084   current_program_space->executing_startup = 1;
9085   update_global_location_list (UGLL_DONT_INSERT);
9086 }
9087
9088 void
9089 enable_breakpoints_after_startup (void)
9090 {
9091   current_program_space->executing_startup = 0;
9092   breakpoint_re_set ();
9093 }
9094
9095 /* Create a new single-step breakpoint for thread THREAD, with no
9096    locations.  */
9097
9098 static struct breakpoint *
9099 new_single_step_breakpoint (int thread, struct gdbarch *gdbarch)
9100 {
9101   struct breakpoint *b = XNEW (struct breakpoint);
9102
9103   init_raw_breakpoint_without_location (b, gdbarch, bp_single_step,
9104                                         &momentary_breakpoint_ops);
9105
9106   b->disposition = disp_donttouch;
9107   b->frame_id = null_frame_id;
9108
9109   b->thread = thread;
9110   gdb_assert (b->thread != 0);
9111
9112   add_to_breakpoint_chain (b);
9113
9114   return b;
9115 }
9116
9117 /* Set a momentary breakpoint of type TYPE at address specified by
9118    SAL.  If FRAME_ID is valid, the breakpoint is restricted to that
9119    frame.  */
9120
9121 struct breakpoint *
9122 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9123                           struct frame_id frame_id, enum bptype type)
9124 {
9125   struct breakpoint *b;
9126
9127   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9128      tail-called one.  */
9129   gdb_assert (!frame_id_artificial_p (frame_id));
9130
9131   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9132   b->enable_state = bp_enabled;
9133   b->disposition = disp_donttouch;
9134   b->frame_id = frame_id;
9135
9136   /* If we're debugging a multi-threaded program, then we want
9137      momentary breakpoints to be active in only a single thread of
9138      control.  */
9139   if (in_thread_list (inferior_ptid))
9140     b->thread = pid_to_thread_id (inferior_ptid);
9141
9142   update_global_location_list_nothrow (UGLL_MAY_INSERT);
9143
9144   return b;
9145 }
9146
9147 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9148    The new breakpoint will have type TYPE, use OPS as its
9149    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9150
9151 static struct breakpoint *
9152 momentary_breakpoint_from_master (struct breakpoint *orig,
9153                                   enum bptype type,
9154                                   const struct breakpoint_ops *ops,
9155                                   int loc_enabled)
9156 {
9157   struct breakpoint *copy;
9158
9159   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9160   copy->loc = allocate_bp_location (copy);
9161   set_breakpoint_location_function (copy->loc, 1);
9162
9163   copy->loc->gdbarch = orig->loc->gdbarch;
9164   copy->loc->requested_address = orig->loc->requested_address;
9165   copy->loc->address = orig->loc->address;
9166   copy->loc->section = orig->loc->section;
9167   copy->loc->pspace = orig->loc->pspace;
9168   copy->loc->probe = orig->loc->probe;
9169   copy->loc->line_number = orig->loc->line_number;
9170   copy->loc->symtab = orig->loc->symtab;
9171   copy->loc->enabled = loc_enabled;
9172   copy->frame_id = orig->frame_id;
9173   copy->thread = orig->thread;
9174   copy->pspace = orig->pspace;
9175
9176   copy->enable_state = bp_enabled;
9177   copy->disposition = disp_donttouch;
9178   copy->number = internal_breakpoint_number--;
9179
9180   update_global_location_list_nothrow (UGLL_DONT_INSERT);
9181   return copy;
9182 }
9183
9184 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9185    ORIG is NULL.  */
9186
9187 struct breakpoint *
9188 clone_momentary_breakpoint (struct breakpoint *orig)
9189 {
9190   /* If there's nothing to clone, then return nothing.  */
9191   if (orig == NULL)
9192     return NULL;
9193
9194   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9195 }
9196
9197 struct breakpoint *
9198 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9199                                 enum bptype type)
9200 {
9201   struct symtab_and_line sal;
9202
9203   sal = find_pc_line (pc, 0);
9204   sal.pc = pc;
9205   sal.section = find_pc_overlay (pc);
9206   sal.explicit_pc = 1;
9207
9208   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9209 }
9210 \f
9211
9212 /* Tell the user we have just set a breakpoint B.  */
9213
9214 static void
9215 mention (struct breakpoint *b)
9216 {
9217   b->ops->print_mention (b);
9218   if (ui_out_is_mi_like_p (current_uiout))
9219     return;
9220   printf_filtered ("\n");
9221 }
9222 \f
9223
9224 static int bp_loc_is_permanent (struct bp_location *loc);
9225
9226 static struct bp_location *
9227 add_location_to_breakpoint (struct breakpoint *b,
9228                             const struct symtab_and_line *sal)
9229 {
9230   struct bp_location *loc, **tmp;
9231   CORE_ADDR adjusted_address;
9232   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9233
9234   if (loc_gdbarch == NULL)
9235     loc_gdbarch = b->gdbarch;
9236
9237   /* Adjust the breakpoint's address prior to allocating a location.
9238      Once we call allocate_bp_location(), that mostly uninitialized
9239      location will be placed on the location chain.  Adjustment of the
9240      breakpoint may cause target_read_memory() to be called and we do
9241      not want its scan of the location chain to find a breakpoint and
9242      location that's only been partially initialized.  */
9243   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9244                                                 sal->pc, b->type);
9245
9246   /* Sort the locations by their ADDRESS.  */
9247   loc = allocate_bp_location (b);
9248   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9249        tmp = &((*tmp)->next))
9250     ;
9251   loc->next = *tmp;
9252   *tmp = loc;
9253
9254   loc->requested_address = sal->pc;
9255   loc->address = adjusted_address;
9256   loc->pspace = sal->pspace;
9257   loc->probe.probe = sal->probe;
9258   loc->probe.objfile = sal->objfile;
9259   gdb_assert (loc->pspace != NULL);
9260   loc->section = sal->section;
9261   loc->gdbarch = loc_gdbarch;
9262   loc->line_number = sal->line;
9263   loc->symtab = sal->symtab;
9264
9265   set_breakpoint_location_function (loc,
9266                                     sal->explicit_pc || sal->explicit_line);
9267
9268   if (bp_loc_is_permanent (loc))
9269     {
9270       loc->inserted = 1;
9271       loc->permanent = 1;
9272     }
9273
9274   return loc;
9275 }
9276 \f
9277
9278 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9279    return 0 otherwise.  */
9280
9281 static int
9282 bp_loc_is_permanent (struct bp_location *loc)
9283 {
9284   int len;
9285   CORE_ADDR addr;
9286   const gdb_byte *bpoint;
9287   gdb_byte *target_mem;
9288   struct cleanup *cleanup;
9289   int retval = 0;
9290
9291   gdb_assert (loc != NULL);
9292
9293   /* bp_call_dummy breakpoint locations are usually memory locations
9294      where GDB just wrote a breakpoint instruction, making it look
9295      as if there is a permanent breakpoint at that location.  Considering
9296      it permanent makes GDB rely on that breakpoint instruction to stop
9297      the program, thus removing the need to insert its own breakpoint
9298      there.  This is normally expected to work, except that some versions
9299      of QEMU (Eg: QEMU 2.0.0 for SPARC) just report a fatal problem (Trap
9300      0x02 while interrupts disabled, Error state) instead of reporting
9301      a SIGTRAP.  QEMU should probably be fixed, but in the interest of
9302      compatibility with versions that behave this way, we always consider
9303      bp_call_dummy breakpoint locations as non-permanent.  */
9304   if (loc->owner->type == bp_call_dummy)
9305     return 0;
9306
9307   addr = loc->address;
9308   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9309
9310   /* Software breakpoints unsupported?  */
9311   if (bpoint == NULL)
9312     return 0;
9313
9314   target_mem = alloca (len);
9315
9316   /* Enable the automatic memory restoration from breakpoints while
9317      we read the memory.  Otherwise we could say about our temporary
9318      breakpoints they are permanent.  */
9319   cleanup = save_current_space_and_thread ();
9320
9321   switch_to_program_space_and_thread (loc->pspace);
9322   make_show_memory_breakpoints_cleanup (0);
9323
9324   if (target_read_memory (loc->address, target_mem, len) == 0
9325       && memcmp (target_mem, bpoint, len) == 0)
9326     retval = 1;
9327
9328   do_cleanups (cleanup);
9329
9330   return retval;
9331 }
9332
9333 /* Build a command list for the dprintf corresponding to the current
9334    settings of the dprintf style options.  */
9335
9336 static void
9337 update_dprintf_command_list (struct breakpoint *b)
9338 {
9339   char *dprintf_args = b->extra_string;
9340   char *printf_line = NULL;
9341
9342   if (!dprintf_args)
9343     return;
9344
9345   dprintf_args = skip_spaces (dprintf_args);
9346
9347   /* Allow a comma, as it may have terminated a location, but don't
9348      insist on it.  */
9349   if (*dprintf_args == ',')
9350     ++dprintf_args;
9351   dprintf_args = skip_spaces (dprintf_args);
9352
9353   if (*dprintf_args != '"')
9354     error (_("Bad format string, missing '\"'."));
9355
9356   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9357     printf_line = xstrprintf ("printf %s", dprintf_args);
9358   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9359     {
9360       if (!dprintf_function)
9361         error (_("No function supplied for dprintf call"));
9362
9363       if (dprintf_channel && strlen (dprintf_channel) > 0)
9364         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9365                                   dprintf_function,
9366                                   dprintf_channel,
9367                                   dprintf_args);
9368       else
9369         printf_line = xstrprintf ("call (void) %s (%s)",
9370                                   dprintf_function,
9371                                   dprintf_args);
9372     }
9373   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9374     {
9375       if (target_can_run_breakpoint_commands ())
9376         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9377       else
9378         {
9379           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9380           printf_line = xstrprintf ("printf %s", dprintf_args);
9381         }
9382     }
9383   else
9384     internal_error (__FILE__, __LINE__,
9385                     _("Invalid dprintf style."));
9386
9387   gdb_assert (printf_line != NULL);
9388   /* Manufacture a printf sequence.  */
9389   {
9390     struct command_line *printf_cmd_line
9391       = xmalloc (sizeof (struct command_line));
9392
9393     printf_cmd_line = xmalloc (sizeof (struct command_line));
9394     printf_cmd_line->control_type = simple_control;
9395     printf_cmd_line->body_count = 0;
9396     printf_cmd_line->body_list = NULL;
9397     printf_cmd_line->next = NULL;
9398     printf_cmd_line->line = printf_line;
9399
9400     breakpoint_set_commands (b, printf_cmd_line);
9401   }
9402 }
9403
9404 /* Update all dprintf commands, making their command lists reflect
9405    current style settings.  */
9406
9407 static void
9408 update_dprintf_commands (char *args, int from_tty,
9409                          struct cmd_list_element *c)
9410 {
9411   struct breakpoint *b;
9412
9413   ALL_BREAKPOINTS (b)
9414     {
9415       if (b->type == bp_dprintf)
9416         update_dprintf_command_list (b);
9417     }
9418 }
9419
9420 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9421    as textual description of the location, and COND_STRING
9422    as condition expression.  */
9423
9424 static void
9425 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9426                      struct symtabs_and_lines sals, char *addr_string,
9427                      char *filter, char *cond_string,
9428                      char *extra_string,
9429                      enum bptype type, enum bpdisp disposition,
9430                      int thread, int task, int ignore_count,
9431                      const struct breakpoint_ops *ops, int from_tty,
9432                      int enabled, int internal, unsigned flags,
9433                      int display_canonical)
9434 {
9435   int i;
9436
9437   if (type == bp_hardware_breakpoint)
9438     {
9439       int target_resources_ok;
9440
9441       i = hw_breakpoint_used_count ();
9442       target_resources_ok =
9443         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9444                                             i + 1, 0);
9445       if (target_resources_ok == 0)
9446         error (_("No hardware breakpoint support in the target."));
9447       else if (target_resources_ok < 0)
9448         error (_("Hardware breakpoints used exceeds limit."));
9449     }
9450
9451   gdb_assert (sals.nelts > 0);
9452
9453   for (i = 0; i < sals.nelts; ++i)
9454     {
9455       struct symtab_and_line sal = sals.sals[i];
9456       struct bp_location *loc;
9457
9458       if (from_tty)
9459         {
9460           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9461           if (!loc_gdbarch)
9462             loc_gdbarch = gdbarch;
9463
9464           describe_other_breakpoints (loc_gdbarch,
9465                                       sal.pspace, sal.pc, sal.section, thread);
9466         }
9467
9468       if (i == 0)
9469         {
9470           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9471           b->thread = thread;
9472           b->task = task;
9473
9474           b->cond_string = cond_string;
9475           b->extra_string = extra_string;
9476           b->ignore_count = ignore_count;
9477           b->enable_state = enabled ? bp_enabled : bp_disabled;
9478           b->disposition = disposition;
9479
9480           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9481             b->loc->inserted = 1;
9482
9483           if (type == bp_static_tracepoint)
9484             {
9485               struct tracepoint *t = (struct tracepoint *) b;
9486               struct static_tracepoint_marker marker;
9487
9488               if (strace_marker_p (b))
9489                 {
9490                   /* We already know the marker exists, otherwise, we
9491                      wouldn't see a sal for it.  */
9492                   char *p = &addr_string[3];
9493                   char *endp;
9494                   char *marker_str;
9495
9496                   p = skip_spaces (p);
9497
9498                   endp = skip_to_space (p);
9499
9500                   marker_str = savestring (p, endp - p);
9501                   t->static_trace_marker_id = marker_str;
9502
9503                   printf_filtered (_("Probed static tracepoint "
9504                                      "marker \"%s\"\n"),
9505                                    t->static_trace_marker_id);
9506                 }
9507               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9508                 {
9509                   t->static_trace_marker_id = xstrdup (marker.str_id);
9510                   release_static_tracepoint_marker (&marker);
9511
9512                   printf_filtered (_("Probed static tracepoint "
9513                                      "marker \"%s\"\n"),
9514                                    t->static_trace_marker_id);
9515                 }
9516               else
9517                 warning (_("Couldn't determine the static "
9518                            "tracepoint marker to probe"));
9519             }
9520
9521           loc = b->loc;
9522         }
9523       else
9524         {
9525           loc = add_location_to_breakpoint (b, &sal);
9526           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9527             loc->inserted = 1;
9528         }
9529
9530       if (b->cond_string)
9531         {
9532           const char *arg = b->cond_string;
9533
9534           loc->cond = parse_exp_1 (&arg, loc->address,
9535                                    block_for_pc (loc->address), 0);
9536           if (*arg)
9537               error (_("Garbage '%s' follows condition"), arg);
9538         }
9539
9540       /* Dynamic printf requires and uses additional arguments on the
9541          command line, otherwise it's an error.  */
9542       if (type == bp_dprintf)
9543         {
9544           if (b->extra_string)
9545             update_dprintf_command_list (b);
9546           else
9547             error (_("Format string required"));
9548         }
9549       else if (b->extra_string)
9550         error (_("Garbage '%s' at end of command"), b->extra_string);
9551     }
9552
9553   b->display_canonical = display_canonical;
9554   if (addr_string)
9555     b->addr_string = addr_string;
9556   else
9557     /* addr_string has to be used or breakpoint_re_set will delete
9558        me.  */
9559     b->addr_string
9560       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9561   b->filter = filter;
9562 }
9563
9564 static void
9565 create_breakpoint_sal (struct gdbarch *gdbarch,
9566                        struct symtabs_and_lines sals, char *addr_string,
9567                        char *filter, char *cond_string,
9568                        char *extra_string,
9569                        enum bptype type, enum bpdisp disposition,
9570                        int thread, int task, int ignore_count,
9571                        const struct breakpoint_ops *ops, int from_tty,
9572                        int enabled, int internal, unsigned flags,
9573                        int display_canonical)
9574 {
9575   struct breakpoint *b;
9576   struct cleanup *old_chain;
9577
9578   if (is_tracepoint_type (type))
9579     {
9580       struct tracepoint *t;
9581
9582       t = XCNEW (struct tracepoint);
9583       b = &t->base;
9584     }
9585   else
9586     b = XNEW (struct breakpoint);
9587
9588   old_chain = make_cleanup (xfree, b);
9589
9590   init_breakpoint_sal (b, gdbarch,
9591                        sals, addr_string,
9592                        filter, cond_string, extra_string,
9593                        type, disposition,
9594                        thread, task, ignore_count,
9595                        ops, from_tty,
9596                        enabled, internal, flags,
9597                        display_canonical);
9598   discard_cleanups (old_chain);
9599
9600   install_breakpoint (internal, b, 0);
9601 }
9602
9603 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9604    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9605    value.  COND_STRING, if not NULL, specified the condition to be
9606    used for all breakpoints.  Essentially the only case where
9607    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9608    function.  In that case, it's still not possible to specify
9609    separate conditions for different overloaded functions, so
9610    we take just a single condition string.
9611    
9612    NOTE: If the function succeeds, the caller is expected to cleanup
9613    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9614    array contents).  If the function fails (error() is called), the
9615    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9616    COND and SALS arrays and each of those arrays contents.  */
9617
9618 static void
9619 create_breakpoints_sal (struct gdbarch *gdbarch,
9620                         struct linespec_result *canonical,
9621                         char *cond_string, char *extra_string,
9622                         enum bptype type, enum bpdisp disposition,
9623                         int thread, int task, int ignore_count,
9624                         const struct breakpoint_ops *ops, int from_tty,
9625                         int enabled, int internal, unsigned flags)
9626 {
9627   int i;
9628   struct linespec_sals *lsal;
9629
9630   if (canonical->pre_expanded)
9631     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9632
9633   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9634     {
9635       /* Note that 'addr_string' can be NULL in the case of a plain
9636          'break', without arguments.  */
9637       char *addr_string = (canonical->addr_string
9638                            ? xstrdup (canonical->addr_string)
9639                            : NULL);
9640       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9641       struct cleanup *inner = make_cleanup (xfree, addr_string);
9642
9643       make_cleanup (xfree, filter_string);
9644       create_breakpoint_sal (gdbarch, lsal->sals,
9645                              addr_string,
9646                              filter_string,
9647                              cond_string, extra_string,
9648                              type, disposition,
9649                              thread, task, ignore_count, ops,
9650                              from_tty, enabled, internal, flags,
9651                              canonical->special_display);
9652       discard_cleanups (inner);
9653     }
9654 }
9655
9656 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9657    followed by conditionals.  On return, SALS contains an array of SAL
9658    addresses found.  ADDR_STRING contains a vector of (canonical)
9659    address strings.  ADDRESS points to the end of the SAL.
9660
9661    The array and the line spec strings are allocated on the heap, it is
9662    the caller's responsibility to free them.  */
9663
9664 static void
9665 parse_breakpoint_sals (char **address,
9666                        struct linespec_result *canonical)
9667 {
9668   /* If no arg given, or if first arg is 'if ', use the default
9669      breakpoint.  */
9670   if ((*address) == NULL
9671       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9672     {
9673       /* The last displayed codepoint, if it's valid, is our default breakpoint
9674          address.  */
9675       if (last_displayed_sal_is_valid ())
9676         {
9677           struct linespec_sals lsal;
9678           struct symtab_and_line sal;
9679           CORE_ADDR pc;
9680
9681           init_sal (&sal);              /* Initialize to zeroes.  */
9682           lsal.sals.sals = (struct symtab_and_line *)
9683             xmalloc (sizeof (struct symtab_and_line));
9684
9685           /* Set sal's pspace, pc, symtab, and line to the values
9686              corresponding to the last call to print_frame_info.
9687              Be sure to reinitialize LINE with NOTCURRENT == 0
9688              as the breakpoint line number is inappropriate otherwise.
9689              find_pc_line would adjust PC, re-set it back.  */
9690           get_last_displayed_sal (&sal);
9691           pc = sal.pc;
9692           sal = find_pc_line (pc, 0);
9693
9694           /* "break" without arguments is equivalent to "break *PC"
9695              where PC is the last displayed codepoint's address.  So
9696              make sure to set sal.explicit_pc to prevent GDB from
9697              trying to expand the list of sals to include all other
9698              instances with the same symtab and line.  */
9699           sal.pc = pc;
9700           sal.explicit_pc = 1;
9701
9702           lsal.sals.sals[0] = sal;
9703           lsal.sals.nelts = 1;
9704           lsal.canonical = NULL;
9705
9706           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9707         }
9708       else
9709         error (_("No default breakpoint address now."));
9710     }
9711   else
9712     {
9713       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9714
9715       /* Force almost all breakpoints to be in terms of the
9716          current_source_symtab (which is decode_line_1's default).
9717          This should produce the results we want almost all of the
9718          time while leaving default_breakpoint_* alone.
9719
9720          ObjC: However, don't match an Objective-C method name which
9721          may have a '+' or '-' succeeded by a '['.  */
9722       if (last_displayed_sal_is_valid ()
9723           && (!cursal.symtab
9724               || ((strchr ("+-", (*address)[0]) != NULL)
9725                   && ((*address)[1] != '['))))
9726         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9727                           get_last_displayed_symtab (),
9728                           get_last_displayed_line (),
9729                           canonical, NULL, NULL);
9730       else
9731         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9732                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9733     }
9734 }
9735
9736
9737 /* Convert each SAL into a real PC.  Verify that the PC can be
9738    inserted as a breakpoint.  If it can't throw an error.  */
9739
9740 static void
9741 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9742 {    
9743   int i;
9744
9745   for (i = 0; i < sals->nelts; i++)
9746     resolve_sal_pc (&sals->sals[i]);
9747 }
9748
9749 /* Fast tracepoints may have restrictions on valid locations.  For
9750    instance, a fast tracepoint using a jump instead of a trap will
9751    likely have to overwrite more bytes than a trap would, and so can
9752    only be placed where the instruction is longer than the jump, or a
9753    multi-instruction sequence does not have a jump into the middle of
9754    it, etc.  */
9755
9756 static void
9757 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9758                             struct symtabs_and_lines *sals)
9759 {
9760   int i, rslt;
9761   struct symtab_and_line *sal;
9762   char *msg;
9763   struct cleanup *old_chain;
9764
9765   for (i = 0; i < sals->nelts; i++)
9766     {
9767       struct gdbarch *sarch;
9768
9769       sal = &sals->sals[i];
9770
9771       sarch = get_sal_arch (*sal);
9772       /* We fall back to GDBARCH if there is no architecture
9773          associated with SAL.  */
9774       if (sarch == NULL)
9775         sarch = gdbarch;
9776       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9777                                                NULL, &msg);
9778       old_chain = make_cleanup (xfree, msg);
9779
9780       if (!rslt)
9781         error (_("May not have a fast tracepoint at 0x%s%s"),
9782                paddress (sarch, sal->pc), (msg ? msg : ""));
9783
9784       do_cleanups (old_chain);
9785     }
9786 }
9787
9788 /* Issue an invalid thread ID error.  */
9789
9790 static void ATTRIBUTE_NORETURN
9791 invalid_thread_id_error (int id)
9792 {
9793   error (_("Unknown thread %d."), id);
9794 }
9795
9796 /* Given TOK, a string specification of condition and thread, as
9797    accepted by the 'break' command, extract the condition
9798    string and thread number and set *COND_STRING and *THREAD.
9799    PC identifies the context at which the condition should be parsed.
9800    If no condition is found, *COND_STRING is set to NULL.
9801    If no thread is found, *THREAD is set to -1.  */
9802
9803 static void
9804 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9805                            char **cond_string, int *thread, int *task,
9806                            char **rest)
9807 {
9808   *cond_string = NULL;
9809   *thread = -1;
9810   *task = 0;
9811   *rest = NULL;
9812
9813   while (tok && *tok)
9814     {
9815       const char *end_tok;
9816       int toklen;
9817       const char *cond_start = NULL;
9818       const char *cond_end = NULL;
9819
9820       tok = skip_spaces_const (tok);
9821
9822       if ((*tok == '"' || *tok == ',') && rest)
9823         {
9824           *rest = savestring (tok, strlen (tok));
9825           return;
9826         }
9827
9828       end_tok = skip_to_space_const (tok);
9829
9830       toklen = end_tok - tok;
9831
9832       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9833         {
9834           struct expression *expr;
9835
9836           tok = cond_start = end_tok + 1;
9837           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9838           xfree (expr);
9839           cond_end = tok;
9840           *cond_string = savestring (cond_start, cond_end - cond_start);
9841         }
9842       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9843         {
9844           char *tmptok;
9845
9846           tok = end_tok + 1;
9847           *thread = strtol (tok, &tmptok, 0);
9848           if (tok == tmptok)
9849             error (_("Junk after thread keyword."));
9850           if (!valid_thread_id (*thread))
9851             invalid_thread_id_error (*thread);
9852           tok = tmptok;
9853         }
9854       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9855         {
9856           char *tmptok;
9857
9858           tok = end_tok + 1;
9859           *task = strtol (tok, &tmptok, 0);
9860           if (tok == tmptok)
9861             error (_("Junk after task keyword."));
9862           if (!valid_task_id (*task))
9863             error (_("Unknown task %d."), *task);
9864           tok = tmptok;
9865         }
9866       else if (rest)
9867         {
9868           *rest = savestring (tok, strlen (tok));
9869           return;
9870         }
9871       else
9872         error (_("Junk at end of arguments."));
9873     }
9874 }
9875
9876 /* Decode a static tracepoint marker spec.  */
9877
9878 static struct symtabs_and_lines
9879 decode_static_tracepoint_spec (char **arg_p)
9880 {
9881   VEC(static_tracepoint_marker_p) *markers = NULL;
9882   struct symtabs_and_lines sals;
9883   struct cleanup *old_chain;
9884   char *p = &(*arg_p)[3];
9885   char *endp;
9886   char *marker_str;
9887   int i;
9888
9889   p = skip_spaces (p);
9890
9891   endp = skip_to_space (p);
9892
9893   marker_str = savestring (p, endp - p);
9894   old_chain = make_cleanup (xfree, marker_str);
9895
9896   markers = target_static_tracepoint_markers_by_strid (marker_str);
9897   if (VEC_empty(static_tracepoint_marker_p, markers))
9898     error (_("No known static tracepoint marker named %s"), marker_str);
9899
9900   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9901   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9902
9903   for (i = 0; i < sals.nelts; i++)
9904     {
9905       struct static_tracepoint_marker *marker;
9906
9907       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9908
9909       init_sal (&sals.sals[i]);
9910
9911       sals.sals[i] = find_pc_line (marker->address, 0);
9912       sals.sals[i].pc = marker->address;
9913
9914       release_static_tracepoint_marker (marker);
9915     }
9916
9917   do_cleanups (old_chain);
9918
9919   *arg_p = endp;
9920   return sals;
9921 }
9922
9923 /* Set a breakpoint.  This function is shared between CLI and MI
9924    functions for setting a breakpoint.  This function has two major
9925    modes of operations, selected by the PARSE_ARG parameter.  If
9926    non-zero, the function will parse ARG, extracting location,
9927    condition, thread and extra string.  Otherwise, ARG is just the
9928    breakpoint's location, with condition, thread, and extra string
9929    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9930    If INTERNAL is non-zero, the breakpoint number will be allocated
9931    from the internal breakpoint count.  Returns true if any breakpoint
9932    was created; false otherwise.  */
9933
9934 int
9935 create_breakpoint (struct gdbarch *gdbarch,
9936                    char *arg, char *cond_string,
9937                    int thread, char *extra_string,
9938                    int parse_arg,
9939                    int tempflag, enum bptype type_wanted,
9940                    int ignore_count,
9941                    enum auto_boolean pending_break_support,
9942                    const struct breakpoint_ops *ops,
9943                    int from_tty, int enabled, int internal,
9944                    unsigned flags)
9945 {
9946   volatile struct gdb_exception e;
9947   char *copy_arg = NULL;
9948   char *addr_start = arg;
9949   struct linespec_result canonical;
9950   struct cleanup *old_chain;
9951   struct cleanup *bkpt_chain = NULL;
9952   int pending = 0;
9953   int task = 0;
9954   int prev_bkpt_count = breakpoint_count;
9955
9956   gdb_assert (ops != NULL);
9957
9958   init_linespec_result (&canonical);
9959
9960   TRY_CATCH (e, RETURN_MASK_ALL)
9961     {
9962       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9963                                      addr_start, &copy_arg);
9964     }
9965
9966   /* If caller is interested in rc value from parse, set value.  */
9967   switch (e.reason)
9968     {
9969     case GDB_NO_ERROR:
9970       if (VEC_empty (linespec_sals, canonical.sals))
9971         return 0;
9972       break;
9973     case RETURN_ERROR:
9974       switch (e.error)
9975         {
9976         case NOT_FOUND_ERROR:
9977
9978           /* If pending breakpoint support is turned off, throw
9979              error.  */
9980
9981           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9982             throw_exception (e);
9983
9984           exception_print (gdb_stderr, e);
9985
9986           /* If pending breakpoint support is auto query and the user
9987              selects no, then simply return the error code.  */
9988           if (pending_break_support == AUTO_BOOLEAN_AUTO
9989               && !nquery (_("Make %s pending on future shared library load? "),
9990                           bptype_string (type_wanted)))
9991             return 0;
9992
9993           /* At this point, either the user was queried about setting
9994              a pending breakpoint and selected yes, or pending
9995              breakpoint behavior is on and thus a pending breakpoint
9996              is defaulted on behalf of the user.  */
9997           {
9998             struct linespec_sals lsal;
9999
10000             copy_arg = xstrdup (addr_start);
10001             lsal.canonical = xstrdup (copy_arg);
10002             lsal.sals.nelts = 1;
10003             lsal.sals.sals = XNEW (struct symtab_and_line);
10004             init_sal (&lsal.sals.sals[0]);
10005             pending = 1;
10006             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
10007           }
10008           break;
10009         default:
10010           throw_exception (e);
10011         }
10012       break;
10013     default:
10014       throw_exception (e);
10015     }
10016
10017   /* Create a chain of things that always need to be cleaned up.  */
10018   old_chain = make_cleanup_destroy_linespec_result (&canonical);
10019
10020   /* ----------------------------- SNIP -----------------------------
10021      Anything added to the cleanup chain beyond this point is assumed
10022      to be part of a breakpoint.  If the breakpoint create succeeds
10023      then the memory is not reclaimed.  */
10024   bkpt_chain = make_cleanup (null_cleanup, 0);
10025
10026   /* Resolve all line numbers to PC's and verify that the addresses
10027      are ok for the target.  */
10028   if (!pending)
10029     {
10030       int ix;
10031       struct linespec_sals *iter;
10032
10033       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10034         breakpoint_sals_to_pc (&iter->sals);
10035     }
10036
10037   /* Fast tracepoints may have additional restrictions on location.  */
10038   if (!pending && type_wanted == bp_fast_tracepoint)
10039     {
10040       int ix;
10041       struct linespec_sals *iter;
10042
10043       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10044         check_fast_tracepoint_sals (gdbarch, &iter->sals);
10045     }
10046
10047   /* Verify that condition can be parsed, before setting any
10048      breakpoints.  Allocate a separate condition expression for each
10049      breakpoint.  */
10050   if (!pending)
10051     {
10052       if (parse_arg)
10053         {
10054           char *rest;
10055           struct linespec_sals *lsal;
10056
10057           lsal = VEC_index (linespec_sals, canonical.sals, 0);
10058
10059           /* Here we only parse 'arg' to separate condition
10060              from thread number, so parsing in context of first
10061              sal is OK.  When setting the breakpoint we'll
10062              re-parse it in context of each sal.  */
10063
10064           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
10065                                      &thread, &task, &rest);
10066           if (cond_string)
10067             make_cleanup (xfree, cond_string);
10068           if (rest)
10069             make_cleanup (xfree, rest);
10070           if (rest)
10071             extra_string = rest;
10072         }
10073       else
10074         {
10075           if (*arg != '\0')
10076             error (_("Garbage '%s' at end of location"), arg);
10077
10078           /* Create a private copy of condition string.  */
10079           if (cond_string)
10080             {
10081               cond_string = xstrdup (cond_string);
10082               make_cleanup (xfree, cond_string);
10083             }
10084           /* Create a private copy of any extra string.  */
10085           if (extra_string)
10086             {
10087               extra_string = xstrdup (extra_string);
10088               make_cleanup (xfree, extra_string);
10089             }
10090         }
10091
10092       ops->create_breakpoints_sal (gdbarch, &canonical,
10093                                    cond_string, extra_string, type_wanted,
10094                                    tempflag ? disp_del : disp_donttouch,
10095                                    thread, task, ignore_count, ops,
10096                                    from_tty, enabled, internal, flags);
10097     }
10098   else
10099     {
10100       struct breakpoint *b;
10101
10102       make_cleanup (xfree, copy_arg);
10103
10104       if (is_tracepoint_type (type_wanted))
10105         {
10106           struct tracepoint *t;
10107
10108           t = XCNEW (struct tracepoint);
10109           b = &t->base;
10110         }
10111       else
10112         b = XNEW (struct breakpoint);
10113
10114       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10115
10116       b->addr_string = copy_arg;
10117       if (parse_arg)
10118         b->cond_string = NULL;
10119       else
10120         {
10121           /* Create a private copy of condition string.  */
10122           if (cond_string)
10123             {
10124               cond_string = xstrdup (cond_string);
10125               make_cleanup (xfree, cond_string);
10126             }
10127           b->cond_string = cond_string;
10128         }
10129       b->extra_string = NULL;
10130       b->ignore_count = ignore_count;
10131       b->disposition = tempflag ? disp_del : disp_donttouch;
10132       b->condition_not_parsed = 1;
10133       b->enable_state = enabled ? bp_enabled : bp_disabled;
10134       if ((type_wanted != bp_breakpoint
10135            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10136         b->pspace = current_program_space;
10137
10138       install_breakpoint (internal, b, 0);
10139     }
10140   
10141   if (VEC_length (linespec_sals, canonical.sals) > 1)
10142     {
10143       warning (_("Multiple breakpoints were set.\nUse the "
10144                  "\"delete\" command to delete unwanted breakpoints."));
10145       prev_breakpoint_count = prev_bkpt_count;
10146     }
10147
10148   /* That's it.  Discard the cleanups for data inserted into the
10149      breakpoint.  */
10150   discard_cleanups (bkpt_chain);
10151   /* But cleanup everything else.  */
10152   do_cleanups (old_chain);
10153
10154   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10155   update_global_location_list (UGLL_MAY_INSERT);
10156
10157   return 1;
10158 }
10159
10160 /* Set a breakpoint.
10161    ARG is a string describing breakpoint address,
10162    condition, and thread.
10163    FLAG specifies if a breakpoint is hardware on,
10164    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10165    and BP_TEMPFLAG.  */
10166
10167 static void
10168 break_command_1 (char *arg, int flag, int from_tty)
10169 {
10170   int tempflag = flag & BP_TEMPFLAG;
10171   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10172                              ? bp_hardware_breakpoint
10173                              : bp_breakpoint);
10174   struct breakpoint_ops *ops;
10175   const char *arg_cp = arg;
10176
10177   /* Matching breakpoints on probes.  */
10178   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10179     ops = &bkpt_probe_breakpoint_ops;
10180   else
10181     ops = &bkpt_breakpoint_ops;
10182
10183   create_breakpoint (get_current_arch (),
10184                      arg,
10185                      NULL, 0, NULL, 1 /* parse arg */,
10186                      tempflag, type_wanted,
10187                      0 /* Ignore count */,
10188                      pending_break_support,
10189                      ops,
10190                      from_tty,
10191                      1 /* enabled */,
10192                      0 /* internal */,
10193                      0);
10194 }
10195
10196 /* Helper function for break_command_1 and disassemble_command.  */
10197
10198 void
10199 resolve_sal_pc (struct symtab_and_line *sal)
10200 {
10201   CORE_ADDR pc;
10202
10203   if (sal->pc == 0 && sal->symtab != NULL)
10204     {
10205       if (!find_line_pc (sal->symtab, sal->line, &pc))
10206         error (_("No line %d in file \"%s\"."),
10207                sal->line, symtab_to_filename_for_display (sal->symtab));
10208       sal->pc = pc;
10209
10210       /* If this SAL corresponds to a breakpoint inserted using a line
10211          number, then skip the function prologue if necessary.  */
10212       if (sal->explicit_line)
10213         skip_prologue_sal (sal);
10214     }
10215
10216   if (sal->section == 0 && sal->symtab != NULL)
10217     {
10218       const struct blockvector *bv;
10219       const struct block *b;
10220       struct symbol *sym;
10221
10222       bv = blockvector_for_pc_sect (sal->pc, 0, &b,
10223                                     SYMTAB_COMPUNIT (sal->symtab));
10224       if (bv != NULL)
10225         {
10226           sym = block_linkage_function (b);
10227           if (sym != NULL)
10228             {
10229               fixup_symbol_section (sym, SYMTAB_OBJFILE (sal->symtab));
10230               sal->section = SYMBOL_OBJ_SECTION (SYMTAB_OBJFILE (sal->symtab),
10231                                                  sym);
10232             }
10233           else
10234             {
10235               /* It really is worthwhile to have the section, so we'll
10236                  just have to look harder. This case can be executed
10237                  if we have line numbers but no functions (as can
10238                  happen in assembly source).  */
10239
10240               struct bound_minimal_symbol msym;
10241               struct cleanup *old_chain = save_current_space_and_thread ();
10242
10243               switch_to_program_space_and_thread (sal->pspace);
10244
10245               msym = lookup_minimal_symbol_by_pc (sal->pc);
10246               if (msym.minsym)
10247                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10248
10249               do_cleanups (old_chain);
10250             }
10251         }
10252     }
10253 }
10254
10255 void
10256 break_command (char *arg, int from_tty)
10257 {
10258   break_command_1 (arg, 0, from_tty);
10259 }
10260
10261 void
10262 tbreak_command (char *arg, int from_tty)
10263 {
10264   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10265 }
10266
10267 static void
10268 hbreak_command (char *arg, int from_tty)
10269 {
10270   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10271 }
10272
10273 static void
10274 thbreak_command (char *arg, int from_tty)
10275 {
10276   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10277 }
10278
10279 static void
10280 stop_command (char *arg, int from_tty)
10281 {
10282   printf_filtered (_("Specify the type of breakpoint to set.\n\
10283 Usage: stop in <function | address>\n\
10284        stop at <line>\n"));
10285 }
10286
10287 static void
10288 stopin_command (char *arg, int from_tty)
10289 {
10290   int badInput = 0;
10291
10292   if (arg == (char *) NULL)
10293     badInput = 1;
10294   else if (*arg != '*')
10295     {
10296       char *argptr = arg;
10297       int hasColon = 0;
10298
10299       /* Look for a ':'.  If this is a line number specification, then
10300          say it is bad, otherwise, it should be an address or
10301          function/method name.  */
10302       while (*argptr && !hasColon)
10303         {
10304           hasColon = (*argptr == ':');
10305           argptr++;
10306         }
10307
10308       if (hasColon)
10309         badInput = (*argptr != ':');    /* Not a class::method */
10310       else
10311         badInput = isdigit (*arg);      /* a simple line number */
10312     }
10313
10314   if (badInput)
10315     printf_filtered (_("Usage: stop in <function | address>\n"));
10316   else
10317     break_command_1 (arg, 0, from_tty);
10318 }
10319
10320 static void
10321 stopat_command (char *arg, int from_tty)
10322 {
10323   int badInput = 0;
10324
10325   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10326     badInput = 1;
10327   else
10328     {
10329       char *argptr = arg;
10330       int hasColon = 0;
10331
10332       /* Look for a ':'.  If there is a '::' then get out, otherwise
10333          it is probably a line number.  */
10334       while (*argptr && !hasColon)
10335         {
10336           hasColon = (*argptr == ':');
10337           argptr++;
10338         }
10339
10340       if (hasColon)
10341         badInput = (*argptr == ':');    /* we have class::method */
10342       else
10343         badInput = !isdigit (*arg);     /* not a line number */
10344     }
10345
10346   if (badInput)
10347     printf_filtered (_("Usage: stop at <line>\n"));
10348   else
10349     break_command_1 (arg, 0, from_tty);
10350 }
10351
10352 /* The dynamic printf command is mostly like a regular breakpoint, but
10353    with a prewired command list consisting of a single output command,
10354    built from extra arguments supplied on the dprintf command
10355    line.  */
10356
10357 static void
10358 dprintf_command (char *arg, int from_tty)
10359 {
10360   create_breakpoint (get_current_arch (),
10361                      arg,
10362                      NULL, 0, NULL, 1 /* parse arg */,
10363                      0, bp_dprintf,
10364                      0 /* Ignore count */,
10365                      pending_break_support,
10366                      &dprintf_breakpoint_ops,
10367                      from_tty,
10368                      1 /* enabled */,
10369                      0 /* internal */,
10370                      0);
10371 }
10372
10373 static void
10374 agent_printf_command (char *arg, int from_tty)
10375 {
10376   error (_("May only run agent-printf on the target"));
10377 }
10378
10379 /* Implement the "breakpoint_hit" breakpoint_ops method for
10380    ranged breakpoints.  */
10381
10382 static int
10383 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10384                                   struct address_space *aspace,
10385                                   CORE_ADDR bp_addr,
10386                                   const struct target_waitstatus *ws)
10387 {
10388   if (ws->kind != TARGET_WAITKIND_STOPPED
10389       || ws->value.sig != GDB_SIGNAL_TRAP)
10390     return 0;
10391
10392   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10393                                          bl->length, aspace, bp_addr);
10394 }
10395
10396 /* Implement the "resources_needed" breakpoint_ops method for
10397    ranged breakpoints.  */
10398
10399 static int
10400 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10401 {
10402   return target_ranged_break_num_registers ();
10403 }
10404
10405 /* Implement the "print_it" breakpoint_ops method for
10406    ranged breakpoints.  */
10407
10408 static enum print_stop_action
10409 print_it_ranged_breakpoint (bpstat bs)
10410 {
10411   struct breakpoint *b = bs->breakpoint_at;
10412   struct bp_location *bl = b->loc;
10413   struct ui_out *uiout = current_uiout;
10414
10415   gdb_assert (b->type == bp_hardware_breakpoint);
10416
10417   /* Ranged breakpoints have only one location.  */
10418   gdb_assert (bl && bl->next == NULL);
10419
10420   annotate_breakpoint (b->number);
10421   if (b->disposition == disp_del)
10422     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10423   else
10424     ui_out_text (uiout, "\nRanged breakpoint ");
10425   if (ui_out_is_mi_like_p (uiout))
10426     {
10427       ui_out_field_string (uiout, "reason",
10428                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10429       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10430     }
10431   ui_out_field_int (uiout, "bkptno", b->number);
10432   ui_out_text (uiout, ", ");
10433
10434   return PRINT_SRC_AND_LOC;
10435 }
10436
10437 /* Implement the "print_one" breakpoint_ops method for
10438    ranged breakpoints.  */
10439
10440 static void
10441 print_one_ranged_breakpoint (struct breakpoint *b,
10442                              struct bp_location **last_loc)
10443 {
10444   struct bp_location *bl = b->loc;
10445   struct value_print_options opts;
10446   struct ui_out *uiout = current_uiout;
10447
10448   /* Ranged breakpoints have only one location.  */
10449   gdb_assert (bl && bl->next == NULL);
10450
10451   get_user_print_options (&opts);
10452
10453   if (opts.addressprint)
10454     /* We don't print the address range here, it will be printed later
10455        by print_one_detail_ranged_breakpoint.  */
10456     ui_out_field_skip (uiout, "addr");
10457   annotate_field (5);
10458   print_breakpoint_location (b, bl);
10459   *last_loc = bl;
10460 }
10461
10462 /* Implement the "print_one_detail" breakpoint_ops method for
10463    ranged breakpoints.  */
10464
10465 static void
10466 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10467                                     struct ui_out *uiout)
10468 {
10469   CORE_ADDR address_start, address_end;
10470   struct bp_location *bl = b->loc;
10471   struct ui_file *stb = mem_fileopen ();
10472   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10473
10474   gdb_assert (bl);
10475
10476   address_start = bl->address;
10477   address_end = address_start + bl->length - 1;
10478
10479   ui_out_text (uiout, "\taddress range: ");
10480   fprintf_unfiltered (stb, "[%s, %s]",
10481                       print_core_address (bl->gdbarch, address_start),
10482                       print_core_address (bl->gdbarch, address_end));
10483   ui_out_field_stream (uiout, "addr", stb);
10484   ui_out_text (uiout, "\n");
10485
10486   do_cleanups (cleanup);
10487 }
10488
10489 /* Implement the "print_mention" breakpoint_ops method for
10490    ranged breakpoints.  */
10491
10492 static void
10493 print_mention_ranged_breakpoint (struct breakpoint *b)
10494 {
10495   struct bp_location *bl = b->loc;
10496   struct ui_out *uiout = current_uiout;
10497
10498   gdb_assert (bl);
10499   gdb_assert (b->type == bp_hardware_breakpoint);
10500
10501   if (ui_out_is_mi_like_p (uiout))
10502     return;
10503
10504   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10505                    b->number, paddress (bl->gdbarch, bl->address),
10506                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10507 }
10508
10509 /* Implement the "print_recreate" breakpoint_ops method for
10510    ranged breakpoints.  */
10511
10512 static void
10513 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10514 {
10515   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10516                       b->addr_string_range_end);
10517   print_recreate_thread (b, fp);
10518 }
10519
10520 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10521
10522 static struct breakpoint_ops ranged_breakpoint_ops;
10523
10524 /* Find the address where the end of the breakpoint range should be
10525    placed, given the SAL of the end of the range.  This is so that if
10526    the user provides a line number, the end of the range is set to the
10527    last instruction of the given line.  */
10528
10529 static CORE_ADDR
10530 find_breakpoint_range_end (struct symtab_and_line sal)
10531 {
10532   CORE_ADDR end;
10533
10534   /* If the user provided a PC value, use it.  Otherwise,
10535      find the address of the end of the given location.  */
10536   if (sal.explicit_pc)
10537     end = sal.pc;
10538   else
10539     {
10540       int ret;
10541       CORE_ADDR start;
10542
10543       ret = find_line_pc_range (sal, &start, &end);
10544       if (!ret)
10545         error (_("Could not find location of the end of the range."));
10546
10547       /* find_line_pc_range returns the start of the next line.  */
10548       end--;
10549     }
10550
10551   return end;
10552 }
10553
10554 /* Implement the "break-range" CLI command.  */
10555
10556 static void
10557 break_range_command (char *arg, int from_tty)
10558 {
10559   char *arg_start, *addr_string_start, *addr_string_end;
10560   struct linespec_result canonical_start, canonical_end;
10561   int bp_count, can_use_bp, length;
10562   CORE_ADDR end;
10563   struct breakpoint *b;
10564   struct symtab_and_line sal_start, sal_end;
10565   struct cleanup *cleanup_bkpt;
10566   struct linespec_sals *lsal_start, *lsal_end;
10567
10568   /* We don't support software ranged breakpoints.  */
10569   if (target_ranged_break_num_registers () < 0)
10570     error (_("This target does not support hardware ranged breakpoints."));
10571
10572   bp_count = hw_breakpoint_used_count ();
10573   bp_count += target_ranged_break_num_registers ();
10574   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10575                                                    bp_count, 0);
10576   if (can_use_bp < 0)
10577     error (_("Hardware breakpoints used exceeds limit."));
10578
10579   arg = skip_spaces (arg);
10580   if (arg == NULL || arg[0] == '\0')
10581     error(_("No address range specified."));
10582
10583   init_linespec_result (&canonical_start);
10584
10585   arg_start = arg;
10586   parse_breakpoint_sals (&arg, &canonical_start);
10587
10588   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10589
10590   if (arg[0] != ',')
10591     error (_("Too few arguments."));
10592   else if (VEC_empty (linespec_sals, canonical_start.sals))
10593     error (_("Could not find location of the beginning of the range."));
10594
10595   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10596
10597   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10598       || lsal_start->sals.nelts != 1)
10599     error (_("Cannot create a ranged breakpoint with multiple locations."));
10600
10601   sal_start = lsal_start->sals.sals[0];
10602   addr_string_start = savestring (arg_start, arg - arg_start);
10603   make_cleanup (xfree, addr_string_start);
10604
10605   arg++;        /* Skip the comma.  */
10606   arg = skip_spaces (arg);
10607
10608   /* Parse the end location.  */
10609
10610   init_linespec_result (&canonical_end);
10611   arg_start = arg;
10612
10613   /* We call decode_line_full directly here instead of using
10614      parse_breakpoint_sals because we need to specify the start location's
10615      symtab and line as the default symtab and line for the end of the
10616      range.  This makes it possible to have ranges like "foo.c:27, +14",
10617      where +14 means 14 lines from the start location.  */
10618   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10619                     sal_start.symtab, sal_start.line,
10620                     &canonical_end, NULL, NULL);
10621
10622   make_cleanup_destroy_linespec_result (&canonical_end);
10623
10624   if (VEC_empty (linespec_sals, canonical_end.sals))
10625     error (_("Could not find location of the end of the range."));
10626
10627   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10628   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10629       || lsal_end->sals.nelts != 1)
10630     error (_("Cannot create a ranged breakpoint with multiple locations."));
10631
10632   sal_end = lsal_end->sals.sals[0];
10633   addr_string_end = savestring (arg_start, arg - arg_start);
10634   make_cleanup (xfree, addr_string_end);
10635
10636   end = find_breakpoint_range_end (sal_end);
10637   if (sal_start.pc > end)
10638     error (_("Invalid address range, end precedes start."));
10639
10640   length = end - sal_start.pc + 1;
10641   if (length < 0)
10642     /* Length overflowed.  */
10643     error (_("Address range too large."));
10644   else if (length == 1)
10645     {
10646       /* This range is simple enough to be handled by
10647          the `hbreak' command.  */
10648       hbreak_command (addr_string_start, 1);
10649
10650       do_cleanups (cleanup_bkpt);
10651
10652       return;
10653     }
10654
10655   /* Now set up the breakpoint.  */
10656   b = set_raw_breakpoint (get_current_arch (), sal_start,
10657                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10658   set_breakpoint_count (breakpoint_count + 1);
10659   b->number = breakpoint_count;
10660   b->disposition = disp_donttouch;
10661   b->addr_string = xstrdup (addr_string_start);
10662   b->addr_string_range_end = xstrdup (addr_string_end);
10663   b->loc->length = length;
10664
10665   do_cleanups (cleanup_bkpt);
10666
10667   mention (b);
10668   observer_notify_breakpoint_created (b);
10669   update_global_location_list (UGLL_MAY_INSERT);
10670 }
10671
10672 /*  Return non-zero if EXP is verified as constant.  Returned zero
10673     means EXP is variable.  Also the constant detection may fail for
10674     some constant expressions and in such case still falsely return
10675     zero.  */
10676
10677 static int
10678 watchpoint_exp_is_const (const struct expression *exp)
10679 {
10680   int i = exp->nelts;
10681
10682   while (i > 0)
10683     {
10684       int oplenp, argsp;
10685
10686       /* We are only interested in the descriptor of each element.  */
10687       operator_length (exp, i, &oplenp, &argsp);
10688       i -= oplenp;
10689
10690       switch (exp->elts[i].opcode)
10691         {
10692         case BINOP_ADD:
10693         case BINOP_SUB:
10694         case BINOP_MUL:
10695         case BINOP_DIV:
10696         case BINOP_REM:
10697         case BINOP_MOD:
10698         case BINOP_LSH:
10699         case BINOP_RSH:
10700         case BINOP_LOGICAL_AND:
10701         case BINOP_LOGICAL_OR:
10702         case BINOP_BITWISE_AND:
10703         case BINOP_BITWISE_IOR:
10704         case BINOP_BITWISE_XOR:
10705         case BINOP_EQUAL:
10706         case BINOP_NOTEQUAL:
10707         case BINOP_LESS:
10708         case BINOP_GTR:
10709         case BINOP_LEQ:
10710         case BINOP_GEQ:
10711         case BINOP_REPEAT:
10712         case BINOP_COMMA:
10713         case BINOP_EXP:
10714         case BINOP_MIN:
10715         case BINOP_MAX:
10716         case BINOP_INTDIV:
10717         case BINOP_CONCAT:
10718         case TERNOP_COND:
10719         case TERNOP_SLICE:
10720
10721         case OP_LONG:
10722         case OP_DOUBLE:
10723         case OP_DECFLOAT:
10724         case OP_LAST:
10725         case OP_COMPLEX:
10726         case OP_STRING:
10727         case OP_ARRAY:
10728         case OP_TYPE:
10729         case OP_TYPEOF:
10730         case OP_DECLTYPE:
10731         case OP_TYPEID:
10732         case OP_NAME:
10733         case OP_OBJC_NSSTRING:
10734
10735         case UNOP_NEG:
10736         case UNOP_LOGICAL_NOT:
10737         case UNOP_COMPLEMENT:
10738         case UNOP_ADDR:
10739         case UNOP_HIGH:
10740         case UNOP_CAST:
10741
10742         case UNOP_CAST_TYPE:
10743         case UNOP_REINTERPRET_CAST:
10744         case UNOP_DYNAMIC_CAST:
10745           /* Unary, binary and ternary operators: We have to check
10746              their operands.  If they are constant, then so is the
10747              result of that operation.  For instance, if A and B are
10748              determined to be constants, then so is "A + B".
10749
10750              UNOP_IND is one exception to the rule above, because the
10751              value of *ADDR is not necessarily a constant, even when
10752              ADDR is.  */
10753           break;
10754
10755         case OP_VAR_VALUE:
10756           /* Check whether the associated symbol is a constant.
10757
10758              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10759              possible that a buggy compiler could mark a variable as
10760              constant even when it is not, and TYPE_CONST would return
10761              true in this case, while SYMBOL_CLASS wouldn't.
10762
10763              We also have to check for function symbols because they
10764              are always constant.  */
10765           {
10766             struct symbol *s = exp->elts[i + 2].symbol;
10767
10768             if (SYMBOL_CLASS (s) != LOC_BLOCK
10769                 && SYMBOL_CLASS (s) != LOC_CONST
10770                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10771               return 0;
10772             break;
10773           }
10774
10775         /* The default action is to return 0 because we are using
10776            the optimistic approach here: If we don't know something,
10777            then it is not a constant.  */
10778         default:
10779           return 0;
10780         }
10781     }
10782
10783   return 1;
10784 }
10785
10786 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10787
10788 static void
10789 dtor_watchpoint (struct breakpoint *self)
10790 {
10791   struct watchpoint *w = (struct watchpoint *) self;
10792
10793   xfree (w->cond_exp);
10794   xfree (w->exp);
10795   xfree (w->exp_string);
10796   xfree (w->exp_string_reparse);
10797   value_free (w->val);
10798
10799   base_breakpoint_ops.dtor (self);
10800 }
10801
10802 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10803
10804 static void
10805 re_set_watchpoint (struct breakpoint *b)
10806 {
10807   struct watchpoint *w = (struct watchpoint *) b;
10808
10809   /* Watchpoint can be either on expression using entirely global
10810      variables, or it can be on local variables.
10811
10812      Watchpoints of the first kind are never auto-deleted, and even
10813      persist across program restarts.  Since they can use variables
10814      from shared libraries, we need to reparse expression as libraries
10815      are loaded and unloaded.
10816
10817      Watchpoints on local variables can also change meaning as result
10818      of solib event.  For example, if a watchpoint uses both a local
10819      and a global variables in expression, it's a local watchpoint,
10820      but unloading of a shared library will make the expression
10821      invalid.  This is not a very common use case, but we still
10822      re-evaluate expression, to avoid surprises to the user.
10823
10824      Note that for local watchpoints, we re-evaluate it only if
10825      watchpoints frame id is still valid.  If it's not, it means the
10826      watchpoint is out of scope and will be deleted soon.  In fact,
10827      I'm not sure we'll ever be called in this case.
10828
10829      If a local watchpoint's frame id is still valid, then
10830      w->exp_valid_block is likewise valid, and we can safely use it.
10831
10832      Don't do anything about disabled watchpoints, since they will be
10833      reevaluated again when enabled.  */
10834   update_watchpoint (w, 1 /* reparse */);
10835 }
10836
10837 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10838
10839 static int
10840 insert_watchpoint (struct bp_location *bl)
10841 {
10842   struct watchpoint *w = (struct watchpoint *) bl->owner;
10843   int length = w->exact ? 1 : bl->length;
10844
10845   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10846                                    w->cond_exp);
10847 }
10848
10849 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10850
10851 static int
10852 remove_watchpoint (struct bp_location *bl)
10853 {
10854   struct watchpoint *w = (struct watchpoint *) bl->owner;
10855   int length = w->exact ? 1 : bl->length;
10856
10857   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10858                                    w->cond_exp);
10859 }
10860
10861 static int
10862 breakpoint_hit_watchpoint (const struct bp_location *bl,
10863                            struct address_space *aspace, CORE_ADDR bp_addr,
10864                            const struct target_waitstatus *ws)
10865 {
10866   struct breakpoint *b = bl->owner;
10867   struct watchpoint *w = (struct watchpoint *) b;
10868
10869   /* Continuable hardware watchpoints are treated as non-existent if the
10870      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10871      some data address).  Otherwise gdb won't stop on a break instruction
10872      in the code (not from a breakpoint) when a hardware watchpoint has
10873      been defined.  Also skip watchpoints which we know did not trigger
10874      (did not match the data address).  */
10875   if (is_hardware_watchpoint (b)
10876       && w->watchpoint_triggered == watch_triggered_no)
10877     return 0;
10878
10879   return 1;
10880 }
10881
10882 static void
10883 check_status_watchpoint (bpstat bs)
10884 {
10885   gdb_assert (is_watchpoint (bs->breakpoint_at));
10886
10887   bpstat_check_watchpoint (bs);
10888 }
10889
10890 /* Implement the "resources_needed" breakpoint_ops method for
10891    hardware watchpoints.  */
10892
10893 static int
10894 resources_needed_watchpoint (const struct bp_location *bl)
10895 {
10896   struct watchpoint *w = (struct watchpoint *) bl->owner;
10897   int length = w->exact? 1 : bl->length;
10898
10899   return target_region_ok_for_hw_watchpoint (bl->address, length);
10900 }
10901
10902 /* Implement the "works_in_software_mode" breakpoint_ops method for
10903    hardware watchpoints.  */
10904
10905 static int
10906 works_in_software_mode_watchpoint (const struct breakpoint *b)
10907 {
10908   /* Read and access watchpoints only work with hardware support.  */
10909   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10910 }
10911
10912 static enum print_stop_action
10913 print_it_watchpoint (bpstat bs)
10914 {
10915   struct cleanup *old_chain;
10916   struct breakpoint *b;
10917   struct ui_file *stb;
10918   enum print_stop_action result;
10919   struct watchpoint *w;
10920   struct ui_out *uiout = current_uiout;
10921
10922   gdb_assert (bs->bp_location_at != NULL);
10923
10924   b = bs->breakpoint_at;
10925   w = (struct watchpoint *) b;
10926
10927   stb = mem_fileopen ();
10928   old_chain = make_cleanup_ui_file_delete (stb);
10929
10930   switch (b->type)
10931     {
10932     case bp_watchpoint:
10933     case bp_hardware_watchpoint:
10934       annotate_watchpoint (b->number);
10935       if (ui_out_is_mi_like_p (uiout))
10936         ui_out_field_string
10937           (uiout, "reason",
10938            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10939       mention (b);
10940       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10941       ui_out_text (uiout, "\nOld value = ");
10942       watchpoint_value_print (bs->old_val, stb);
10943       ui_out_field_stream (uiout, "old", stb);
10944       ui_out_text (uiout, "\nNew value = ");
10945       watchpoint_value_print (w->val, stb);
10946       ui_out_field_stream (uiout, "new", stb);
10947       ui_out_text (uiout, "\n");
10948       /* More than one watchpoint may have been triggered.  */
10949       result = PRINT_UNKNOWN;
10950       break;
10951
10952     case bp_read_watchpoint:
10953       if (ui_out_is_mi_like_p (uiout))
10954         ui_out_field_string
10955           (uiout, "reason",
10956            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10957       mention (b);
10958       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10959       ui_out_text (uiout, "\nValue = ");
10960       watchpoint_value_print (w->val, stb);
10961       ui_out_field_stream (uiout, "value", stb);
10962       ui_out_text (uiout, "\n");
10963       result = PRINT_UNKNOWN;
10964       break;
10965
10966     case bp_access_watchpoint:
10967       if (bs->old_val != NULL)
10968         {
10969           annotate_watchpoint (b->number);
10970           if (ui_out_is_mi_like_p (uiout))
10971             ui_out_field_string
10972               (uiout, "reason",
10973                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10974           mention (b);
10975           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10976           ui_out_text (uiout, "\nOld value = ");
10977           watchpoint_value_print (bs->old_val, stb);
10978           ui_out_field_stream (uiout, "old", stb);
10979           ui_out_text (uiout, "\nNew value = ");
10980         }
10981       else
10982         {
10983           mention (b);
10984           if (ui_out_is_mi_like_p (uiout))
10985             ui_out_field_string
10986               (uiout, "reason",
10987                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10988           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10989           ui_out_text (uiout, "\nValue = ");
10990         }
10991       watchpoint_value_print (w->val, stb);
10992       ui_out_field_stream (uiout, "new", stb);
10993       ui_out_text (uiout, "\n");
10994       result = PRINT_UNKNOWN;
10995       break;
10996     default:
10997       result = PRINT_UNKNOWN;
10998     }
10999
11000   do_cleanups (old_chain);
11001   return result;
11002 }
11003
11004 /* Implement the "print_mention" breakpoint_ops method for hardware
11005    watchpoints.  */
11006
11007 static void
11008 print_mention_watchpoint (struct breakpoint *b)
11009 {
11010   struct cleanup *ui_out_chain;
11011   struct watchpoint *w = (struct watchpoint *) b;
11012   struct ui_out *uiout = current_uiout;
11013
11014   switch (b->type)
11015     {
11016     case bp_watchpoint:
11017       ui_out_text (uiout, "Watchpoint ");
11018       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11019       break;
11020     case bp_hardware_watchpoint:
11021       ui_out_text (uiout, "Hardware watchpoint ");
11022       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11023       break;
11024     case bp_read_watchpoint:
11025       ui_out_text (uiout, "Hardware read watchpoint ");
11026       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11027       break;
11028     case bp_access_watchpoint:
11029       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
11030       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11031       break;
11032     default:
11033       internal_error (__FILE__, __LINE__,
11034                       _("Invalid hardware watchpoint type."));
11035     }
11036
11037   ui_out_field_int (uiout, "number", b->number);
11038   ui_out_text (uiout, ": ");
11039   ui_out_field_string (uiout, "exp", w->exp_string);
11040   do_cleanups (ui_out_chain);
11041 }
11042
11043 /* Implement the "print_recreate" breakpoint_ops method for
11044    watchpoints.  */
11045
11046 static void
11047 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
11048 {
11049   struct watchpoint *w = (struct watchpoint *) b;
11050
11051   switch (b->type)
11052     {
11053     case bp_watchpoint:
11054     case bp_hardware_watchpoint:
11055       fprintf_unfiltered (fp, "watch");
11056       break;
11057     case bp_read_watchpoint:
11058       fprintf_unfiltered (fp, "rwatch");
11059       break;
11060     case bp_access_watchpoint:
11061       fprintf_unfiltered (fp, "awatch");
11062       break;
11063     default:
11064       internal_error (__FILE__, __LINE__,
11065                       _("Invalid watchpoint type."));
11066     }
11067
11068   fprintf_unfiltered (fp, " %s", w->exp_string);
11069   print_recreate_thread (b, fp);
11070 }
11071
11072 /* Implement the "explains_signal" breakpoint_ops method for
11073    watchpoints.  */
11074
11075 static int
11076 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
11077 {
11078   /* A software watchpoint cannot cause a signal other than
11079      GDB_SIGNAL_TRAP.  */
11080   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
11081     return 0;
11082
11083   return 1;
11084 }
11085
11086 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
11087
11088 static struct breakpoint_ops watchpoint_breakpoint_ops;
11089
11090 /* Implement the "insert" breakpoint_ops method for
11091    masked hardware watchpoints.  */
11092
11093 static int
11094 insert_masked_watchpoint (struct bp_location *bl)
11095 {
11096   struct watchpoint *w = (struct watchpoint *) bl->owner;
11097
11098   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
11099                                         bl->watchpoint_type);
11100 }
11101
11102 /* Implement the "remove" breakpoint_ops method for
11103    masked hardware watchpoints.  */
11104
11105 static int
11106 remove_masked_watchpoint (struct bp_location *bl)
11107 {
11108   struct watchpoint *w = (struct watchpoint *) bl->owner;
11109
11110   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
11111                                         bl->watchpoint_type);
11112 }
11113
11114 /* Implement the "resources_needed" breakpoint_ops method for
11115    masked hardware watchpoints.  */
11116
11117 static int
11118 resources_needed_masked_watchpoint (const struct bp_location *bl)
11119 {
11120   struct watchpoint *w = (struct watchpoint *) bl->owner;
11121
11122   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11123 }
11124
11125 /* Implement the "works_in_software_mode" breakpoint_ops method for
11126    masked hardware watchpoints.  */
11127
11128 static int
11129 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11130 {
11131   return 0;
11132 }
11133
11134 /* Implement the "print_it" breakpoint_ops method for
11135    masked hardware watchpoints.  */
11136
11137 static enum print_stop_action
11138 print_it_masked_watchpoint (bpstat bs)
11139 {
11140   struct breakpoint *b = bs->breakpoint_at;
11141   struct ui_out *uiout = current_uiout;
11142
11143   /* Masked watchpoints have only one location.  */
11144   gdb_assert (b->loc && b->loc->next == NULL);
11145
11146   switch (b->type)
11147     {
11148     case bp_hardware_watchpoint:
11149       annotate_watchpoint (b->number);
11150       if (ui_out_is_mi_like_p (uiout))
11151         ui_out_field_string
11152           (uiout, "reason",
11153            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11154       break;
11155
11156     case bp_read_watchpoint:
11157       if (ui_out_is_mi_like_p (uiout))
11158         ui_out_field_string
11159           (uiout, "reason",
11160            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11161       break;
11162
11163     case bp_access_watchpoint:
11164       if (ui_out_is_mi_like_p (uiout))
11165         ui_out_field_string
11166           (uiout, "reason",
11167            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11168       break;
11169     default:
11170       internal_error (__FILE__, __LINE__,
11171                       _("Invalid hardware watchpoint type."));
11172     }
11173
11174   mention (b);
11175   ui_out_text (uiout, _("\n\
11176 Check the underlying instruction at PC for the memory\n\
11177 address and value which triggered this watchpoint.\n"));
11178   ui_out_text (uiout, "\n");
11179
11180   /* More than one watchpoint may have been triggered.  */
11181   return PRINT_UNKNOWN;
11182 }
11183
11184 /* Implement the "print_one_detail" breakpoint_ops method for
11185    masked hardware watchpoints.  */
11186
11187 static void
11188 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11189                                     struct ui_out *uiout)
11190 {
11191   struct watchpoint *w = (struct watchpoint *) b;
11192
11193   /* Masked watchpoints have only one location.  */
11194   gdb_assert (b->loc && b->loc->next == NULL);
11195
11196   ui_out_text (uiout, "\tmask ");
11197   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11198   ui_out_text (uiout, "\n");
11199 }
11200
11201 /* Implement the "print_mention" breakpoint_ops method for
11202    masked hardware watchpoints.  */
11203
11204 static void
11205 print_mention_masked_watchpoint (struct breakpoint *b)
11206 {
11207   struct watchpoint *w = (struct watchpoint *) b;
11208   struct ui_out *uiout = current_uiout;
11209   struct cleanup *ui_out_chain;
11210
11211   switch (b->type)
11212     {
11213     case bp_hardware_watchpoint:
11214       ui_out_text (uiout, "Masked hardware watchpoint ");
11215       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11216       break;
11217     case bp_read_watchpoint:
11218       ui_out_text (uiout, "Masked hardware read watchpoint ");
11219       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11220       break;
11221     case bp_access_watchpoint:
11222       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11223       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11224       break;
11225     default:
11226       internal_error (__FILE__, __LINE__,
11227                       _("Invalid hardware watchpoint type."));
11228     }
11229
11230   ui_out_field_int (uiout, "number", b->number);
11231   ui_out_text (uiout, ": ");
11232   ui_out_field_string (uiout, "exp", w->exp_string);
11233   do_cleanups (ui_out_chain);
11234 }
11235
11236 /* Implement the "print_recreate" breakpoint_ops method for
11237    masked hardware watchpoints.  */
11238
11239 static void
11240 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11241 {
11242   struct watchpoint *w = (struct watchpoint *) b;
11243   char tmp[40];
11244
11245   switch (b->type)
11246     {
11247     case bp_hardware_watchpoint:
11248       fprintf_unfiltered (fp, "watch");
11249       break;
11250     case bp_read_watchpoint:
11251       fprintf_unfiltered (fp, "rwatch");
11252       break;
11253     case bp_access_watchpoint:
11254       fprintf_unfiltered (fp, "awatch");
11255       break;
11256     default:
11257       internal_error (__FILE__, __LINE__,
11258                       _("Invalid hardware watchpoint type."));
11259     }
11260
11261   sprintf_vma (tmp, w->hw_wp_mask);
11262   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11263   print_recreate_thread (b, fp);
11264 }
11265
11266 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11267
11268 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11269
11270 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11271
11272 static int
11273 is_masked_watchpoint (const struct breakpoint *b)
11274 {
11275   return b->ops == &masked_watchpoint_breakpoint_ops;
11276 }
11277
11278 /* accessflag:  hw_write:  watch write, 
11279                 hw_read:   watch read, 
11280                 hw_access: watch access (read or write) */
11281 static void
11282 watch_command_1 (const char *arg, int accessflag, int from_tty,
11283                  int just_location, int internal)
11284 {
11285   volatile struct gdb_exception e;
11286   struct breakpoint *b, *scope_breakpoint = NULL;
11287   struct expression *exp;
11288   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11289   struct value *val, *mark, *result;
11290   int saved_bitpos = 0, saved_bitsize = 0;
11291   struct frame_info *frame;
11292   const char *exp_start = NULL;
11293   const char *exp_end = NULL;
11294   const char *tok, *end_tok;
11295   int toklen = -1;
11296   const char *cond_start = NULL;
11297   const char *cond_end = NULL;
11298   enum bptype bp_type;
11299   int thread = -1;
11300   int pc = 0;
11301   /* Flag to indicate whether we are going to use masks for
11302      the hardware watchpoint.  */
11303   int use_mask = 0;
11304   CORE_ADDR mask = 0;
11305   struct watchpoint *w;
11306   char *expression;
11307   struct cleanup *back_to;
11308
11309   /* Make sure that we actually have parameters to parse.  */
11310   if (arg != NULL && arg[0] != '\0')
11311     {
11312       const char *value_start;
11313
11314       exp_end = arg + strlen (arg);
11315
11316       /* Look for "parameter value" pairs at the end
11317          of the arguments string.  */
11318       for (tok = exp_end - 1; tok > arg; tok--)
11319         {
11320           /* Skip whitespace at the end of the argument list.  */
11321           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11322             tok--;
11323
11324           /* Find the beginning of the last token.
11325              This is the value of the parameter.  */
11326           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11327             tok--;
11328           value_start = tok + 1;
11329
11330           /* Skip whitespace.  */
11331           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11332             tok--;
11333
11334           end_tok = tok;
11335
11336           /* Find the beginning of the second to last token.
11337              This is the parameter itself.  */
11338           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11339             tok--;
11340           tok++;
11341           toklen = end_tok - tok + 1;
11342
11343           if (toklen == 6 && !strncmp (tok, "thread", 6))
11344             {
11345               /* At this point we've found a "thread" token, which means
11346                  the user is trying to set a watchpoint that triggers
11347                  only in a specific thread.  */
11348               char *endp;
11349
11350               if (thread != -1)
11351                 error(_("You can specify only one thread."));
11352
11353               /* Extract the thread ID from the next token.  */
11354               thread = strtol (value_start, &endp, 0);
11355
11356               /* Check if the user provided a valid numeric value for the
11357                  thread ID.  */
11358               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11359                 error (_("Invalid thread ID specification %s."), value_start);
11360
11361               /* Check if the thread actually exists.  */
11362               if (!valid_thread_id (thread))
11363                 invalid_thread_id_error (thread);
11364             }
11365           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11366             {
11367               /* We've found a "mask" token, which means the user wants to
11368                  create a hardware watchpoint that is going to have the mask
11369                  facility.  */
11370               struct value *mask_value, *mark;
11371
11372               if (use_mask)
11373                 error(_("You can specify only one mask."));
11374
11375               use_mask = just_location = 1;
11376
11377               mark = value_mark ();
11378               mask_value = parse_to_comma_and_eval (&value_start);
11379               mask = value_as_address (mask_value);
11380               value_free_to_mark (mark);
11381             }
11382           else
11383             /* We didn't recognize what we found.  We should stop here.  */
11384             break;
11385
11386           /* Truncate the string and get rid of the "parameter value" pair before
11387              the arguments string is parsed by the parse_exp_1 function.  */
11388           exp_end = tok;
11389         }
11390     }
11391   else
11392     exp_end = arg;
11393
11394   /* Parse the rest of the arguments.  From here on out, everything
11395      is in terms of a newly allocated string instead of the original
11396      ARG.  */
11397   innermost_block = NULL;
11398   expression = savestring (arg, exp_end - arg);
11399   back_to = make_cleanup (xfree, expression);
11400   exp_start = arg = expression;
11401   exp = parse_exp_1 (&arg, 0, 0, 0);
11402   exp_end = arg;
11403   /* Remove trailing whitespace from the expression before saving it.
11404      This makes the eventual display of the expression string a bit
11405      prettier.  */
11406   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11407     --exp_end;
11408
11409   /* Checking if the expression is not constant.  */
11410   if (watchpoint_exp_is_const (exp))
11411     {
11412       int len;
11413
11414       len = exp_end - exp_start;
11415       while (len > 0 && isspace (exp_start[len - 1]))
11416         len--;
11417       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11418     }
11419
11420   exp_valid_block = innermost_block;
11421   mark = value_mark ();
11422   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11423
11424   if (val != NULL && just_location)
11425     {
11426       saved_bitpos = value_bitpos (val);
11427       saved_bitsize = value_bitsize (val);
11428     }
11429
11430   if (just_location)
11431     {
11432       int ret;
11433
11434       exp_valid_block = NULL;
11435       val = value_addr (result);
11436       release_value (val);
11437       value_free_to_mark (mark);
11438
11439       if (use_mask)
11440         {
11441           ret = target_masked_watch_num_registers (value_as_address (val),
11442                                                    mask);
11443           if (ret == -1)
11444             error (_("This target does not support masked watchpoints."));
11445           else if (ret == -2)
11446             error (_("Invalid mask or memory region."));
11447         }
11448     }
11449   else if (val != NULL)
11450     release_value (val);
11451
11452   tok = skip_spaces_const (arg);
11453   end_tok = skip_to_space_const (tok);
11454
11455   toklen = end_tok - tok;
11456   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11457     {
11458       struct expression *cond;
11459
11460       innermost_block = NULL;
11461       tok = cond_start = end_tok + 1;
11462       cond = parse_exp_1 (&tok, 0, 0, 0);
11463
11464       /* The watchpoint expression may not be local, but the condition
11465          may still be.  E.g.: `watch global if local > 0'.  */
11466       cond_exp_valid_block = innermost_block;
11467
11468       xfree (cond);
11469       cond_end = tok;
11470     }
11471   if (*tok)
11472     error (_("Junk at end of command."));
11473
11474   frame = block_innermost_frame (exp_valid_block);
11475
11476   /* If the expression is "local", then set up a "watchpoint scope"
11477      breakpoint at the point where we've left the scope of the watchpoint
11478      expression.  Create the scope breakpoint before the watchpoint, so
11479      that we will encounter it first in bpstat_stop_status.  */
11480   if (exp_valid_block && frame)
11481     {
11482       if (frame_id_p (frame_unwind_caller_id (frame)))
11483         {
11484           scope_breakpoint
11485             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11486                                           frame_unwind_caller_pc (frame),
11487                                           bp_watchpoint_scope,
11488                                           &momentary_breakpoint_ops);
11489
11490           scope_breakpoint->enable_state = bp_enabled;
11491
11492           /* Automatically delete the breakpoint when it hits.  */
11493           scope_breakpoint->disposition = disp_del;
11494
11495           /* Only break in the proper frame (help with recursion).  */
11496           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11497
11498           /* Set the address at which we will stop.  */
11499           scope_breakpoint->loc->gdbarch
11500             = frame_unwind_caller_arch (frame);
11501           scope_breakpoint->loc->requested_address
11502             = frame_unwind_caller_pc (frame);
11503           scope_breakpoint->loc->address
11504             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11505                                          scope_breakpoint->loc->requested_address,
11506                                          scope_breakpoint->type);
11507         }
11508     }
11509
11510   /* Now set up the breakpoint.  We create all watchpoints as hardware
11511      watchpoints here even if hardware watchpoints are turned off, a call
11512      to update_watchpoint later in this function will cause the type to
11513      drop back to bp_watchpoint (software watchpoint) if required.  */
11514
11515   if (accessflag == hw_read)
11516     bp_type = bp_read_watchpoint;
11517   else if (accessflag == hw_access)
11518     bp_type = bp_access_watchpoint;
11519   else
11520     bp_type = bp_hardware_watchpoint;
11521
11522   w = XCNEW (struct watchpoint);
11523   b = &w->base;
11524   if (use_mask)
11525     init_raw_breakpoint_without_location (b, NULL, bp_type,
11526                                           &masked_watchpoint_breakpoint_ops);
11527   else
11528     init_raw_breakpoint_without_location (b, NULL, bp_type,
11529                                           &watchpoint_breakpoint_ops);
11530   b->thread = thread;
11531   b->disposition = disp_donttouch;
11532   b->pspace = current_program_space;
11533   w->exp = exp;
11534   w->exp_valid_block = exp_valid_block;
11535   w->cond_exp_valid_block = cond_exp_valid_block;
11536   if (just_location)
11537     {
11538       struct type *t = value_type (val);
11539       CORE_ADDR addr = value_as_address (val);
11540       char *name;
11541
11542       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11543       name = type_to_string (t);
11544
11545       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11546                                           core_addr_to_string (addr));
11547       xfree (name);
11548
11549       w->exp_string = xstrprintf ("-location %.*s",
11550                                   (int) (exp_end - exp_start), exp_start);
11551
11552       /* The above expression is in C.  */
11553       b->language = language_c;
11554     }
11555   else
11556     w->exp_string = savestring (exp_start, exp_end - exp_start);
11557
11558   if (use_mask)
11559     {
11560       w->hw_wp_mask = mask;
11561     }
11562   else
11563     {
11564       w->val = val;
11565       w->val_bitpos = saved_bitpos;
11566       w->val_bitsize = saved_bitsize;
11567       w->val_valid = 1;
11568     }
11569
11570   if (cond_start)
11571     b->cond_string = savestring (cond_start, cond_end - cond_start);
11572   else
11573     b->cond_string = 0;
11574
11575   if (frame)
11576     {
11577       w->watchpoint_frame = get_frame_id (frame);
11578       w->watchpoint_thread = inferior_ptid;
11579     }
11580   else
11581     {
11582       w->watchpoint_frame = null_frame_id;
11583       w->watchpoint_thread = null_ptid;
11584     }
11585
11586   if (scope_breakpoint != NULL)
11587     {
11588       /* The scope breakpoint is related to the watchpoint.  We will
11589          need to act on them together.  */
11590       b->related_breakpoint = scope_breakpoint;
11591       scope_breakpoint->related_breakpoint = b;
11592     }
11593
11594   if (!just_location)
11595     value_free_to_mark (mark);
11596
11597   TRY_CATCH (e, RETURN_MASK_ALL)
11598     {
11599       /* Finally update the new watchpoint.  This creates the locations
11600          that should be inserted.  */
11601       update_watchpoint (w, 1);
11602     }
11603   if (e.reason < 0)
11604     {
11605       delete_breakpoint (b);
11606       throw_exception (e);
11607     }
11608
11609   install_breakpoint (internal, b, 1);
11610   do_cleanups (back_to);
11611 }
11612
11613 /* Return count of debug registers needed to watch the given expression.
11614    If the watchpoint cannot be handled in hardware return zero.  */
11615
11616 static int
11617 can_use_hardware_watchpoint (struct value *v)
11618 {
11619   int found_memory_cnt = 0;
11620   struct value *head = v;
11621
11622   /* Did the user specifically forbid us to use hardware watchpoints? */
11623   if (!can_use_hw_watchpoints)
11624     return 0;
11625
11626   /* Make sure that the value of the expression depends only upon
11627      memory contents, and values computed from them within GDB.  If we
11628      find any register references or function calls, we can't use a
11629      hardware watchpoint.
11630
11631      The idea here is that evaluating an expression generates a series
11632      of values, one holding the value of every subexpression.  (The
11633      expression a*b+c has five subexpressions: a, b, a*b, c, and
11634      a*b+c.)  GDB's values hold almost enough information to establish
11635      the criteria given above --- they identify memory lvalues,
11636      register lvalues, computed values, etcetera.  So we can evaluate
11637      the expression, and then scan the chain of values that leaves
11638      behind to decide whether we can detect any possible change to the
11639      expression's final value using only hardware watchpoints.
11640
11641      However, I don't think that the values returned by inferior
11642      function calls are special in any way.  So this function may not
11643      notice that an expression involving an inferior function call
11644      can't be watched with hardware watchpoints.  FIXME.  */
11645   for (; v; v = value_next (v))
11646     {
11647       if (VALUE_LVAL (v) == lval_memory)
11648         {
11649           if (v != head && value_lazy (v))
11650             /* A lazy memory lvalue in the chain is one that GDB never
11651                needed to fetch; we either just used its address (e.g.,
11652                `a' in `a.b') or we never needed it at all (e.g., `a'
11653                in `a,b').  This doesn't apply to HEAD; if that is
11654                lazy then it was not readable, but watch it anyway.  */
11655             ;
11656           else
11657             {
11658               /* Ahh, memory we actually used!  Check if we can cover
11659                  it with hardware watchpoints.  */
11660               struct type *vtype = check_typedef (value_type (v));
11661
11662               /* We only watch structs and arrays if user asked for it
11663                  explicitly, never if they just happen to appear in a
11664                  middle of some value chain.  */
11665               if (v == head
11666                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11667                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11668                 {
11669                   CORE_ADDR vaddr = value_address (v);
11670                   int len;
11671                   int num_regs;
11672
11673                   len = (target_exact_watchpoints
11674                          && is_scalar_type_recursive (vtype))?
11675                     1 : TYPE_LENGTH (value_type (v));
11676
11677                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11678                   if (!num_regs)
11679                     return 0;
11680                   else
11681                     found_memory_cnt += num_regs;
11682                 }
11683             }
11684         }
11685       else if (VALUE_LVAL (v) != not_lval
11686                && deprecated_value_modifiable (v) == 0)
11687         return 0;       /* These are values from the history (e.g., $1).  */
11688       else if (VALUE_LVAL (v) == lval_register)
11689         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11690     }
11691
11692   /* The expression itself looks suitable for using a hardware
11693      watchpoint, but give the target machine a chance to reject it.  */
11694   return found_memory_cnt;
11695 }
11696
11697 void
11698 watch_command_wrapper (char *arg, int from_tty, int internal)
11699 {
11700   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11701 }
11702
11703 /* A helper function that looks for the "-location" argument and then
11704    calls watch_command_1.  */
11705
11706 static void
11707 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11708 {
11709   int just_location = 0;
11710
11711   if (arg
11712       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11713           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11714     {
11715       arg = skip_spaces (arg);
11716       just_location = 1;
11717     }
11718
11719   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11720 }
11721
11722 static void
11723 watch_command (char *arg, int from_tty)
11724 {
11725   watch_maybe_just_location (arg, hw_write, from_tty);
11726 }
11727
11728 void
11729 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11730 {
11731   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11732 }
11733
11734 static void
11735 rwatch_command (char *arg, int from_tty)
11736 {
11737   watch_maybe_just_location (arg, hw_read, from_tty);
11738 }
11739
11740 void
11741 awatch_command_wrapper (char *arg, int from_tty, int internal)
11742 {
11743   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11744 }
11745
11746 static void
11747 awatch_command (char *arg, int from_tty)
11748 {
11749   watch_maybe_just_location (arg, hw_access, from_tty);
11750 }
11751 \f
11752
11753 /* Helper routines for the until_command routine in infcmd.c.  Here
11754    because it uses the mechanisms of breakpoints.  */
11755
11756 struct until_break_command_continuation_args
11757 {
11758   struct breakpoint *breakpoint;
11759   struct breakpoint *breakpoint2;
11760   int thread_num;
11761 };
11762
11763 /* This function is called by fetch_inferior_event via the
11764    cmd_continuation pointer, to complete the until command.  It takes
11765    care of cleaning up the temporary breakpoints set up by the until
11766    command.  */
11767 static void
11768 until_break_command_continuation (void *arg, int err)
11769 {
11770   struct until_break_command_continuation_args *a = arg;
11771
11772   delete_breakpoint (a->breakpoint);
11773   if (a->breakpoint2)
11774     delete_breakpoint (a->breakpoint2);
11775   delete_longjmp_breakpoint (a->thread_num);
11776 }
11777
11778 void
11779 until_break_command (char *arg, int from_tty, int anywhere)
11780 {
11781   struct symtabs_and_lines sals;
11782   struct symtab_and_line sal;
11783   struct frame_info *frame;
11784   struct gdbarch *frame_gdbarch;
11785   struct frame_id stack_frame_id;
11786   struct frame_id caller_frame_id;
11787   struct breakpoint *breakpoint;
11788   struct breakpoint *breakpoint2 = NULL;
11789   struct cleanup *old_chain;
11790   int thread;
11791   struct thread_info *tp;
11792
11793   clear_proceed_status (0);
11794
11795   /* Set a breakpoint where the user wants it and at return from
11796      this function.  */
11797
11798   if (last_displayed_sal_is_valid ())
11799     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11800                           get_last_displayed_symtab (),
11801                           get_last_displayed_line ());
11802   else
11803     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11804                           (struct symtab *) NULL, 0);
11805
11806   if (sals.nelts != 1)
11807     error (_("Couldn't get information on specified line."));
11808
11809   sal = sals.sals[0];
11810   xfree (sals.sals);    /* malloc'd, so freed.  */
11811
11812   if (*arg)
11813     error (_("Junk at end of arguments."));
11814
11815   resolve_sal_pc (&sal);
11816
11817   tp = inferior_thread ();
11818   thread = tp->num;
11819
11820   old_chain = make_cleanup (null_cleanup, NULL);
11821
11822   /* Note linespec handling above invalidates the frame chain.
11823      Installing a breakpoint also invalidates the frame chain (as it
11824      may need to switch threads), so do any frame handling before
11825      that.  */
11826
11827   frame = get_selected_frame (NULL);
11828   frame_gdbarch = get_frame_arch (frame);
11829   stack_frame_id = get_stack_frame_id (frame);
11830   caller_frame_id = frame_unwind_caller_id (frame);
11831
11832   /* Keep within the current frame, or in frames called by the current
11833      one.  */
11834
11835   if (frame_id_p (caller_frame_id))
11836     {
11837       struct symtab_and_line sal2;
11838
11839       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11840       sal2.pc = frame_unwind_caller_pc (frame);
11841       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11842                                               sal2,
11843                                               caller_frame_id,
11844                                               bp_until);
11845       make_cleanup_delete_breakpoint (breakpoint2);
11846
11847       set_longjmp_breakpoint (tp, caller_frame_id);
11848       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11849     }
11850
11851   /* set_momentary_breakpoint could invalidate FRAME.  */
11852   frame = NULL;
11853
11854   if (anywhere)
11855     /* If the user told us to continue until a specified location,
11856        we don't specify a frame at which we need to stop.  */
11857     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11858                                            null_frame_id, bp_until);
11859   else
11860     /* Otherwise, specify the selected frame, because we want to stop
11861        only at the very same frame.  */
11862     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11863                                            stack_frame_id, bp_until);
11864   make_cleanup_delete_breakpoint (breakpoint);
11865
11866   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11867
11868   /* If we are running asynchronously, and proceed call above has
11869      actually managed to start the target, arrange for breakpoints to
11870      be deleted when the target stops.  Otherwise, we're already
11871      stopped and delete breakpoints via cleanup chain.  */
11872
11873   if (target_can_async_p () && is_running (inferior_ptid))
11874     {
11875       struct until_break_command_continuation_args *args;
11876       args = xmalloc (sizeof (*args));
11877
11878       args->breakpoint = breakpoint;
11879       args->breakpoint2 = breakpoint2;
11880       args->thread_num = thread;
11881
11882       discard_cleanups (old_chain);
11883       add_continuation (inferior_thread (),
11884                         until_break_command_continuation, args,
11885                         xfree);
11886     }
11887   else
11888     do_cleanups (old_chain);
11889 }
11890
11891 /* This function attempts to parse an optional "if <cond>" clause
11892    from the arg string.  If one is not found, it returns NULL.
11893
11894    Else, it returns a pointer to the condition string.  (It does not
11895    attempt to evaluate the string against a particular block.)  And,
11896    it updates arg to point to the first character following the parsed
11897    if clause in the arg string.  */
11898
11899 char *
11900 ep_parse_optional_if_clause (char **arg)
11901 {
11902   char *cond_string;
11903
11904   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11905     return NULL;
11906
11907   /* Skip the "if" keyword.  */
11908   (*arg) += 2;
11909
11910   /* Skip any extra leading whitespace, and record the start of the
11911      condition string.  */
11912   *arg = skip_spaces (*arg);
11913   cond_string = *arg;
11914
11915   /* Assume that the condition occupies the remainder of the arg
11916      string.  */
11917   (*arg) += strlen (cond_string);
11918
11919   return cond_string;
11920 }
11921
11922 /* Commands to deal with catching events, such as signals, exceptions,
11923    process start/exit, etc.  */
11924
11925 typedef enum
11926 {
11927   catch_fork_temporary, catch_vfork_temporary,
11928   catch_fork_permanent, catch_vfork_permanent
11929 }
11930 catch_fork_kind;
11931
11932 static void
11933 catch_fork_command_1 (char *arg, int from_tty, 
11934                       struct cmd_list_element *command)
11935 {
11936   struct gdbarch *gdbarch = get_current_arch ();
11937   char *cond_string = NULL;
11938   catch_fork_kind fork_kind;
11939   int tempflag;
11940
11941   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11942   tempflag = (fork_kind == catch_fork_temporary
11943               || fork_kind == catch_vfork_temporary);
11944
11945   if (!arg)
11946     arg = "";
11947   arg = skip_spaces (arg);
11948
11949   /* The allowed syntax is:
11950      catch [v]fork
11951      catch [v]fork if <cond>
11952
11953      First, check if there's an if clause.  */
11954   cond_string = ep_parse_optional_if_clause (&arg);
11955
11956   if ((*arg != '\0') && !isspace (*arg))
11957     error (_("Junk at end of arguments."));
11958
11959   /* If this target supports it, create a fork or vfork catchpoint
11960      and enable reporting of such events.  */
11961   switch (fork_kind)
11962     {
11963     case catch_fork_temporary:
11964     case catch_fork_permanent:
11965       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11966                                           &catch_fork_breakpoint_ops);
11967       break;
11968     case catch_vfork_temporary:
11969     case catch_vfork_permanent:
11970       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11971                                           &catch_vfork_breakpoint_ops);
11972       break;
11973     default:
11974       error (_("unsupported or unknown fork kind; cannot catch it"));
11975       break;
11976     }
11977 }
11978
11979 static void
11980 catch_exec_command_1 (char *arg, int from_tty, 
11981                       struct cmd_list_element *command)
11982 {
11983   struct exec_catchpoint *c;
11984   struct gdbarch *gdbarch = get_current_arch ();
11985   int tempflag;
11986   char *cond_string = NULL;
11987
11988   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11989
11990   if (!arg)
11991     arg = "";
11992   arg = skip_spaces (arg);
11993
11994   /* The allowed syntax is:
11995      catch exec
11996      catch exec if <cond>
11997
11998      First, check if there's an if clause.  */
11999   cond_string = ep_parse_optional_if_clause (&arg);
12000
12001   if ((*arg != '\0') && !isspace (*arg))
12002     error (_("Junk at end of arguments."));
12003
12004   c = XNEW (struct exec_catchpoint);
12005   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
12006                    &catch_exec_breakpoint_ops);
12007   c->exec_pathname = NULL;
12008
12009   install_breakpoint (0, &c->base, 1);
12010 }
12011
12012 void
12013 init_ada_exception_breakpoint (struct breakpoint *b,
12014                                struct gdbarch *gdbarch,
12015                                struct symtab_and_line sal,
12016                                char *addr_string,
12017                                const struct breakpoint_ops *ops,
12018                                int tempflag,
12019                                int enabled,
12020                                int from_tty)
12021 {
12022   if (from_tty)
12023     {
12024       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12025       if (!loc_gdbarch)
12026         loc_gdbarch = gdbarch;
12027
12028       describe_other_breakpoints (loc_gdbarch,
12029                                   sal.pspace, sal.pc, sal.section, -1);
12030       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12031          version for exception catchpoints, because two catchpoints
12032          used for different exception names will use the same address.
12033          In this case, a "breakpoint ... also set at..." warning is
12034          unproductive.  Besides, the warning phrasing is also a bit
12035          inappropriate, we should use the word catchpoint, and tell
12036          the user what type of catchpoint it is.  The above is good
12037          enough for now, though.  */
12038     }
12039
12040   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
12041
12042   b->enable_state = enabled ? bp_enabled : bp_disabled;
12043   b->disposition = tempflag ? disp_del : disp_donttouch;
12044   b->addr_string = addr_string;
12045   b->language = language_ada;
12046 }
12047
12048 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
12049    filter list, or NULL if no filtering is required.  */
12050 static VEC(int) *
12051 catch_syscall_split_args (char *arg)
12052 {
12053   VEC(int) *result = NULL;
12054   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
12055   struct gdbarch *gdbarch = target_gdbarch ();
12056
12057   while (*arg != '\0')
12058     {
12059       int i, syscall_number;
12060       char *endptr;
12061       char cur_name[128];
12062       struct syscall s;
12063
12064       /* Skip whitespace.  */
12065       arg = skip_spaces (arg);
12066
12067       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
12068         cur_name[i] = arg[i];
12069       cur_name[i] = '\0';
12070       arg += i;
12071
12072       /* Check if the user provided a syscall name or a number.  */
12073       syscall_number = (int) strtol (cur_name, &endptr, 0);
12074       if (*endptr == '\0')
12075         get_syscall_by_number (gdbarch, syscall_number, &s);
12076       else
12077         {
12078           /* We have a name.  Let's check if it's valid and convert it
12079              to a number.  */
12080           get_syscall_by_name (gdbarch, cur_name, &s);
12081
12082           if (s.number == UNKNOWN_SYSCALL)
12083             /* Here we have to issue an error instead of a warning,
12084                because GDB cannot do anything useful if there's no
12085                syscall number to be caught.  */
12086             error (_("Unknown syscall name '%s'."), cur_name);
12087         }
12088
12089       /* Ok, it's valid.  */
12090       VEC_safe_push (int, result, s.number);
12091     }
12092
12093   discard_cleanups (cleanup);
12094   return result;
12095 }
12096
12097 /* Implement the "catch syscall" command.  */
12098
12099 static void
12100 catch_syscall_command_1 (char *arg, int from_tty, 
12101                          struct cmd_list_element *command)
12102 {
12103   int tempflag;
12104   VEC(int) *filter;
12105   struct syscall s;
12106   struct gdbarch *gdbarch = get_current_arch ();
12107
12108   /* Checking if the feature if supported.  */
12109   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
12110     error (_("The feature 'catch syscall' is not supported on \
12111 this architecture yet."));
12112
12113   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12114
12115   arg = skip_spaces (arg);
12116
12117   /* We need to do this first "dummy" translation in order
12118      to get the syscall XML file loaded or, most important,
12119      to display a warning to the user if there's no XML file
12120      for his/her architecture.  */
12121   get_syscall_by_number (gdbarch, 0, &s);
12122
12123   /* The allowed syntax is:
12124      catch syscall
12125      catch syscall <name | number> [<name | number> ... <name | number>]
12126
12127      Let's check if there's a syscall name.  */
12128
12129   if (arg != NULL)
12130     filter = catch_syscall_split_args (arg);
12131   else
12132     filter = NULL;
12133
12134   create_syscall_event_catchpoint (tempflag, filter,
12135                                    &catch_syscall_breakpoint_ops);
12136 }
12137
12138 static void
12139 catch_command (char *arg, int from_tty)
12140 {
12141   error (_("Catch requires an event name."));
12142 }
12143 \f
12144
12145 static void
12146 tcatch_command (char *arg, int from_tty)
12147 {
12148   error (_("Catch requires an event name."));
12149 }
12150
12151 /* A qsort comparison function that sorts breakpoints in order.  */
12152
12153 static int
12154 compare_breakpoints (const void *a, const void *b)
12155 {
12156   const breakpoint_p *ba = a;
12157   uintptr_t ua = (uintptr_t) *ba;
12158   const breakpoint_p *bb = b;
12159   uintptr_t ub = (uintptr_t) *bb;
12160
12161   if ((*ba)->number < (*bb)->number)
12162     return -1;
12163   else if ((*ba)->number > (*bb)->number)
12164     return 1;
12165
12166   /* Now sort by address, in case we see, e..g, two breakpoints with
12167      the number 0.  */
12168   if (ua < ub)
12169     return -1;
12170   return ua > ub ? 1 : 0;
12171 }
12172
12173 /* Delete breakpoints by address or line.  */
12174
12175 static void
12176 clear_command (char *arg, int from_tty)
12177 {
12178   struct breakpoint *b, *prev;
12179   VEC(breakpoint_p) *found = 0;
12180   int ix;
12181   int default_match;
12182   struct symtabs_and_lines sals;
12183   struct symtab_and_line sal;
12184   int i;
12185   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12186
12187   if (arg)
12188     {
12189       sals = decode_line_with_current_source (arg,
12190                                               (DECODE_LINE_FUNFIRSTLINE
12191                                                | DECODE_LINE_LIST_MODE));
12192       make_cleanup (xfree, sals.sals);
12193       default_match = 0;
12194     }
12195   else
12196     {
12197       sals.sals = (struct symtab_and_line *)
12198         xmalloc (sizeof (struct symtab_and_line));
12199       make_cleanup (xfree, sals.sals);
12200       init_sal (&sal);          /* Initialize to zeroes.  */
12201
12202       /* Set sal's line, symtab, pc, and pspace to the values
12203          corresponding to the last call to print_frame_info.  If the
12204          codepoint is not valid, this will set all the fields to 0.  */
12205       get_last_displayed_sal (&sal);
12206       if (sal.symtab == 0)
12207         error (_("No source file specified."));
12208
12209       sals.sals[0] = sal;
12210       sals.nelts = 1;
12211
12212       default_match = 1;
12213     }
12214
12215   /* We don't call resolve_sal_pc here.  That's not as bad as it
12216      seems, because all existing breakpoints typically have both
12217      file/line and pc set.  So, if clear is given file/line, we can
12218      match this to existing breakpoint without obtaining pc at all.
12219
12220      We only support clearing given the address explicitly 
12221      present in breakpoint table.  Say, we've set breakpoint 
12222      at file:line.  There were several PC values for that file:line,
12223      due to optimization, all in one block.
12224
12225      We've picked one PC value.  If "clear" is issued with another
12226      PC corresponding to the same file:line, the breakpoint won't
12227      be cleared.  We probably can still clear the breakpoint, but 
12228      since the other PC value is never presented to user, user
12229      can only find it by guessing, and it does not seem important
12230      to support that.  */
12231
12232   /* For each line spec given, delete bps which correspond to it.  Do
12233      it in two passes, solely to preserve the current behavior that
12234      from_tty is forced true if we delete more than one
12235      breakpoint.  */
12236
12237   found = NULL;
12238   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12239   for (i = 0; i < sals.nelts; i++)
12240     {
12241       const char *sal_fullname;
12242
12243       /* If exact pc given, clear bpts at that pc.
12244          If line given (pc == 0), clear all bpts on specified line.
12245          If defaulting, clear all bpts on default line
12246          or at default pc.
12247
12248          defaulting    sal.pc != 0    tests to do
12249
12250          0              1             pc
12251          1              1             pc _and_ line
12252          0              0             line
12253          1              0             <can't happen> */
12254
12255       sal = sals.sals[i];
12256       sal_fullname = (sal.symtab == NULL
12257                       ? NULL : symtab_to_fullname (sal.symtab));
12258
12259       /* Find all matching breakpoints and add them to 'found'.  */
12260       ALL_BREAKPOINTS (b)
12261         {
12262           int match = 0;
12263           /* Are we going to delete b?  */
12264           if (b->type != bp_none && !is_watchpoint (b))
12265             {
12266               struct bp_location *loc = b->loc;
12267               for (; loc; loc = loc->next)
12268                 {
12269                   /* If the user specified file:line, don't allow a PC
12270                      match.  This matches historical gdb behavior.  */
12271                   int pc_match = (!sal.explicit_line
12272                                   && sal.pc
12273                                   && (loc->pspace == sal.pspace)
12274                                   && (loc->address == sal.pc)
12275                                   && (!section_is_overlay (loc->section)
12276                                       || loc->section == sal.section));
12277                   int line_match = 0;
12278
12279                   if ((default_match || sal.explicit_line)
12280                       && loc->symtab != NULL
12281                       && sal_fullname != NULL
12282                       && sal.pspace == loc->pspace
12283                       && loc->line_number == sal.line
12284                       && filename_cmp (symtab_to_fullname (loc->symtab),
12285                                        sal_fullname) == 0)
12286                     line_match = 1;
12287
12288                   if (pc_match || line_match)
12289                     {
12290                       match = 1;
12291                       break;
12292                     }
12293                 }
12294             }
12295
12296           if (match)
12297             VEC_safe_push(breakpoint_p, found, b);
12298         }
12299     }
12300
12301   /* Now go thru the 'found' chain and delete them.  */
12302   if (VEC_empty(breakpoint_p, found))
12303     {
12304       if (arg)
12305         error (_("No breakpoint at %s."), arg);
12306       else
12307         error (_("No breakpoint at this line."));
12308     }
12309
12310   /* Remove duplicates from the vec.  */
12311   qsort (VEC_address (breakpoint_p, found),
12312          VEC_length (breakpoint_p, found),
12313          sizeof (breakpoint_p),
12314          compare_breakpoints);
12315   prev = VEC_index (breakpoint_p, found, 0);
12316   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12317     {
12318       if (b == prev)
12319         {
12320           VEC_ordered_remove (breakpoint_p, found, ix);
12321           --ix;
12322         }
12323     }
12324
12325   if (VEC_length(breakpoint_p, found) > 1)
12326     from_tty = 1;       /* Always report if deleted more than one.  */
12327   if (from_tty)
12328     {
12329       if (VEC_length(breakpoint_p, found) == 1)
12330         printf_unfiltered (_("Deleted breakpoint "));
12331       else
12332         printf_unfiltered (_("Deleted breakpoints "));
12333     }
12334
12335   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12336     {
12337       if (from_tty)
12338         printf_unfiltered ("%d ", b->number);
12339       delete_breakpoint (b);
12340     }
12341   if (from_tty)
12342     putchar_unfiltered ('\n');
12343
12344   do_cleanups (cleanups);
12345 }
12346 \f
12347 /* Delete breakpoint in BS if they are `delete' breakpoints and
12348    all breakpoints that are marked for deletion, whether hit or not.
12349    This is called after any breakpoint is hit, or after errors.  */
12350
12351 void
12352 breakpoint_auto_delete (bpstat bs)
12353 {
12354   struct breakpoint *b, *b_tmp;
12355
12356   for (; bs; bs = bs->next)
12357     if (bs->breakpoint_at
12358         && bs->breakpoint_at->disposition == disp_del
12359         && bs->stop)
12360       delete_breakpoint (bs->breakpoint_at);
12361
12362   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12363   {
12364     if (b->disposition == disp_del_at_next_stop)
12365       delete_breakpoint (b);
12366   }
12367 }
12368
12369 /* A comparison function for bp_location AP and BP being interfaced to
12370    qsort.  Sort elements primarily by their ADDRESS (no matter what
12371    does breakpoint_address_is_meaningful say for its OWNER),
12372    secondarily by ordering first permanent elements and
12373    terciarily just ensuring the array is sorted stable way despite
12374    qsort being an unstable algorithm.  */
12375
12376 static int
12377 bp_location_compare (const void *ap, const void *bp)
12378 {
12379   struct bp_location *a = *(void **) ap;
12380   struct bp_location *b = *(void **) bp;
12381
12382   if (a->address != b->address)
12383     return (a->address > b->address) - (a->address < b->address);
12384
12385   /* Sort locations at the same address by their pspace number, keeping
12386      locations of the same inferior (in a multi-inferior environment)
12387      grouped.  */
12388
12389   if (a->pspace->num != b->pspace->num)
12390     return ((a->pspace->num > b->pspace->num)
12391             - (a->pspace->num < b->pspace->num));
12392
12393   /* Sort permanent breakpoints first.  */
12394   if (a->permanent != b->permanent)
12395     return (a->permanent < b->permanent) - (a->permanent > b->permanent);
12396
12397   /* Make the internal GDB representation stable across GDB runs
12398      where A and B memory inside GDB can differ.  Breakpoint locations of
12399      the same type at the same address can be sorted in arbitrary order.  */
12400
12401   if (a->owner->number != b->owner->number)
12402     return ((a->owner->number > b->owner->number)
12403             - (a->owner->number < b->owner->number));
12404
12405   return (a > b) - (a < b);
12406 }
12407
12408 /* Set bp_location_placed_address_before_address_max and
12409    bp_location_shadow_len_after_address_max according to the current
12410    content of the bp_location array.  */
12411
12412 static void
12413 bp_location_target_extensions_update (void)
12414 {
12415   struct bp_location *bl, **blp_tmp;
12416
12417   bp_location_placed_address_before_address_max = 0;
12418   bp_location_shadow_len_after_address_max = 0;
12419
12420   ALL_BP_LOCATIONS (bl, blp_tmp)
12421     {
12422       CORE_ADDR start, end, addr;
12423
12424       if (!bp_location_has_shadow (bl))
12425         continue;
12426
12427       start = bl->target_info.placed_address;
12428       end = start + bl->target_info.shadow_len;
12429
12430       gdb_assert (bl->address >= start);
12431       addr = bl->address - start;
12432       if (addr > bp_location_placed_address_before_address_max)
12433         bp_location_placed_address_before_address_max = addr;
12434
12435       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12436
12437       gdb_assert (bl->address < end);
12438       addr = end - bl->address;
12439       if (addr > bp_location_shadow_len_after_address_max)
12440         bp_location_shadow_len_after_address_max = addr;
12441     }
12442 }
12443
12444 /* Download tracepoint locations if they haven't been.  */
12445
12446 static void
12447 download_tracepoint_locations (void)
12448 {
12449   struct breakpoint *b;
12450   struct cleanup *old_chain;
12451
12452   if (!target_can_download_tracepoint ())
12453     return;
12454
12455   old_chain = save_current_space_and_thread ();
12456
12457   ALL_TRACEPOINTS (b)
12458     {
12459       struct bp_location *bl;
12460       struct tracepoint *t;
12461       int bp_location_downloaded = 0;
12462
12463       if ((b->type == bp_fast_tracepoint
12464            ? !may_insert_fast_tracepoints
12465            : !may_insert_tracepoints))
12466         continue;
12467
12468       for (bl = b->loc; bl; bl = bl->next)
12469         {
12470           /* In tracepoint, locations are _never_ duplicated, so
12471              should_be_inserted is equivalent to
12472              unduplicated_should_be_inserted.  */
12473           if (!should_be_inserted (bl) || bl->inserted)
12474             continue;
12475
12476           switch_to_program_space_and_thread (bl->pspace);
12477
12478           target_download_tracepoint (bl);
12479
12480           bl->inserted = 1;
12481           bp_location_downloaded = 1;
12482         }
12483       t = (struct tracepoint *) b;
12484       t->number_on_target = b->number;
12485       if (bp_location_downloaded)
12486         observer_notify_breakpoint_modified (b);
12487     }
12488
12489   do_cleanups (old_chain);
12490 }
12491
12492 /* Swap the insertion/duplication state between two locations.  */
12493
12494 static void
12495 swap_insertion (struct bp_location *left, struct bp_location *right)
12496 {
12497   const int left_inserted = left->inserted;
12498   const int left_duplicate = left->duplicate;
12499   const int left_needs_update = left->needs_update;
12500   const struct bp_target_info left_target_info = left->target_info;
12501
12502   /* Locations of tracepoints can never be duplicated.  */
12503   if (is_tracepoint (left->owner))
12504     gdb_assert (!left->duplicate);
12505   if (is_tracepoint (right->owner))
12506     gdb_assert (!right->duplicate);
12507
12508   left->inserted = right->inserted;
12509   left->duplicate = right->duplicate;
12510   left->needs_update = right->needs_update;
12511   left->target_info = right->target_info;
12512   right->inserted = left_inserted;
12513   right->duplicate = left_duplicate;
12514   right->needs_update = left_needs_update;
12515   right->target_info = left_target_info;
12516 }
12517
12518 /* Force the re-insertion of the locations at ADDRESS.  This is called
12519    once a new/deleted/modified duplicate location is found and we are evaluating
12520    conditions on the target's side.  Such conditions need to be updated on
12521    the target.  */
12522
12523 static void
12524 force_breakpoint_reinsertion (struct bp_location *bl)
12525 {
12526   struct bp_location **locp = NULL, **loc2p;
12527   struct bp_location *loc;
12528   CORE_ADDR address = 0;
12529   int pspace_num;
12530
12531   address = bl->address;
12532   pspace_num = bl->pspace->num;
12533
12534   /* This is only meaningful if the target is
12535      evaluating conditions and if the user has
12536      opted for condition evaluation on the target's
12537      side.  */
12538   if (gdb_evaluates_breakpoint_condition_p ()
12539       || !target_supports_evaluation_of_breakpoint_conditions ())
12540     return;
12541
12542   /* Flag all breakpoint locations with this address and
12543      the same program space as the location
12544      as "its condition has changed".  We need to
12545      update the conditions on the target's side.  */
12546   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12547     {
12548       loc = *loc2p;
12549
12550       if (!is_breakpoint (loc->owner)
12551           || pspace_num != loc->pspace->num)
12552         continue;
12553
12554       /* Flag the location appropriately.  We use a different state to
12555          let everyone know that we already updated the set of locations
12556          with addr bl->address and program space bl->pspace.  This is so
12557          we don't have to keep calling these functions just to mark locations
12558          that have already been marked.  */
12559       loc->condition_changed = condition_updated;
12560
12561       /* Free the agent expression bytecode as well.  We will compute
12562          it later on.  */
12563       if (loc->cond_bytecode)
12564         {
12565           free_agent_expr (loc->cond_bytecode);
12566           loc->cond_bytecode = NULL;
12567         }
12568     }
12569 }
12570 /* Called whether new breakpoints are created, or existing breakpoints
12571    deleted, to update the global location list and recompute which
12572    locations are duplicate of which.
12573
12574    The INSERT_MODE flag determines whether locations may not, may, or
12575    shall be inserted now.  See 'enum ugll_insert_mode' for more
12576    info.  */
12577
12578 static void
12579 update_global_location_list (enum ugll_insert_mode insert_mode)
12580 {
12581   struct breakpoint *b;
12582   struct bp_location **locp, *loc;
12583   struct cleanup *cleanups;
12584   /* Last breakpoint location address that was marked for update.  */
12585   CORE_ADDR last_addr = 0;
12586   /* Last breakpoint location program space that was marked for update.  */
12587   int last_pspace_num = -1;
12588
12589   /* Used in the duplicates detection below.  When iterating over all
12590      bp_locations, points to the first bp_location of a given address.
12591      Breakpoints and watchpoints of different types are never
12592      duplicates of each other.  Keep one pointer for each type of
12593      breakpoint/watchpoint, so we only need to loop over all locations
12594      once.  */
12595   struct bp_location *bp_loc_first;  /* breakpoint */
12596   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12597   struct bp_location *awp_loc_first; /* access watchpoint */
12598   struct bp_location *rwp_loc_first; /* read watchpoint */
12599
12600   /* Saved former bp_location array which we compare against the newly
12601      built bp_location from the current state of ALL_BREAKPOINTS.  */
12602   struct bp_location **old_location, **old_locp;
12603   unsigned old_location_count;
12604
12605   old_location = bp_location;
12606   old_location_count = bp_location_count;
12607   bp_location = NULL;
12608   bp_location_count = 0;
12609   cleanups = make_cleanup (xfree, old_location);
12610
12611   ALL_BREAKPOINTS (b)
12612     for (loc = b->loc; loc; loc = loc->next)
12613       bp_location_count++;
12614
12615   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12616   locp = bp_location;
12617   ALL_BREAKPOINTS (b)
12618     for (loc = b->loc; loc; loc = loc->next)
12619       *locp++ = loc;
12620   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12621          bp_location_compare);
12622
12623   bp_location_target_extensions_update ();
12624
12625   /* Identify bp_location instances that are no longer present in the
12626      new list, and therefore should be freed.  Note that it's not
12627      necessary that those locations should be removed from inferior --
12628      if there's another location at the same address (previously
12629      marked as duplicate), we don't need to remove/insert the
12630      location.
12631      
12632      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12633      and former bp_location array state respectively.  */
12634
12635   locp = bp_location;
12636   for (old_locp = old_location; old_locp < old_location + old_location_count;
12637        old_locp++)
12638     {
12639       struct bp_location *old_loc = *old_locp;
12640       struct bp_location **loc2p;
12641
12642       /* Tells if 'old_loc' is found among the new locations.  If
12643          not, we have to free it.  */
12644       int found_object = 0;
12645       /* Tells if the location should remain inserted in the target.  */
12646       int keep_in_target = 0;
12647       int removed = 0;
12648
12649       /* Skip LOCP entries which will definitely never be needed.
12650          Stop either at or being the one matching OLD_LOC.  */
12651       while (locp < bp_location + bp_location_count
12652              && (*locp)->address < old_loc->address)
12653         locp++;
12654
12655       for (loc2p = locp;
12656            (loc2p < bp_location + bp_location_count
12657             && (*loc2p)->address == old_loc->address);
12658            loc2p++)
12659         {
12660           /* Check if this is a new/duplicated location or a duplicated
12661              location that had its condition modified.  If so, we want to send
12662              its condition to the target if evaluation of conditions is taking
12663              place there.  */
12664           if ((*loc2p)->condition_changed == condition_modified
12665               && (last_addr != old_loc->address
12666                   || last_pspace_num != old_loc->pspace->num))
12667             {
12668               force_breakpoint_reinsertion (*loc2p);
12669               last_pspace_num = old_loc->pspace->num;
12670             }
12671
12672           if (*loc2p == old_loc)
12673             found_object = 1;
12674         }
12675
12676       /* We have already handled this address, update it so that we don't
12677          have to go through updates again.  */
12678       last_addr = old_loc->address;
12679
12680       /* Target-side condition evaluation: Handle deleted locations.  */
12681       if (!found_object)
12682         force_breakpoint_reinsertion (old_loc);
12683
12684       /* If this location is no longer present, and inserted, look if
12685          there's maybe a new location at the same address.  If so,
12686          mark that one inserted, and don't remove this one.  This is
12687          needed so that we don't have a time window where a breakpoint
12688          at certain location is not inserted.  */
12689
12690       if (old_loc->inserted)
12691         {
12692           /* If the location is inserted now, we might have to remove
12693              it.  */
12694
12695           if (found_object && should_be_inserted (old_loc))
12696             {
12697               /* The location is still present in the location list,
12698                  and still should be inserted.  Don't do anything.  */
12699               keep_in_target = 1;
12700             }
12701           else
12702             {
12703               /* This location still exists, but it won't be kept in the
12704                  target since it may have been disabled.  We proceed to
12705                  remove its target-side condition.  */
12706
12707               /* The location is either no longer present, or got
12708                  disabled.  See if there's another location at the
12709                  same address, in which case we don't need to remove
12710                  this one from the target.  */
12711
12712               /* OLD_LOC comes from existing struct breakpoint.  */
12713               if (breakpoint_address_is_meaningful (old_loc->owner))
12714                 {
12715                   for (loc2p = locp;
12716                        (loc2p < bp_location + bp_location_count
12717                         && (*loc2p)->address == old_loc->address);
12718                        loc2p++)
12719                     {
12720                       struct bp_location *loc2 = *loc2p;
12721
12722                       if (breakpoint_locations_match (loc2, old_loc))
12723                         {
12724                           /* Read watchpoint locations are switched to
12725                              access watchpoints, if the former are not
12726                              supported, but the latter are.  */
12727                           if (is_hardware_watchpoint (old_loc->owner))
12728                             {
12729                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12730                               loc2->watchpoint_type = old_loc->watchpoint_type;
12731                             }
12732
12733                           /* loc2 is a duplicated location. We need to check
12734                              if it should be inserted in case it will be
12735                              unduplicated.  */
12736                           if (loc2 != old_loc
12737                               && unduplicated_should_be_inserted (loc2))
12738                             {
12739                               swap_insertion (old_loc, loc2);
12740                               keep_in_target = 1;
12741                               break;
12742                             }
12743                         }
12744                     }
12745                 }
12746             }
12747
12748           if (!keep_in_target)
12749             {
12750               if (remove_breakpoint (old_loc, mark_uninserted))
12751                 {
12752                   /* This is just about all we can do.  We could keep
12753                      this location on the global list, and try to
12754                      remove it next time, but there's no particular
12755                      reason why we will succeed next time.
12756                      
12757                      Note that at this point, old_loc->owner is still
12758                      valid, as delete_breakpoint frees the breakpoint
12759                      only after calling us.  */
12760                   printf_filtered (_("warning: Error removing "
12761                                      "breakpoint %d\n"), 
12762                                    old_loc->owner->number);
12763                 }
12764               removed = 1;
12765             }
12766         }
12767
12768       if (!found_object)
12769         {
12770           if (removed && non_stop
12771               && breakpoint_address_is_meaningful (old_loc->owner)
12772               && !is_hardware_watchpoint (old_loc->owner))
12773             {
12774               /* This location was removed from the target.  In
12775                  non-stop mode, a race condition is possible where
12776                  we've removed a breakpoint, but stop events for that
12777                  breakpoint are already queued and will arrive later.
12778                  We apply an heuristic to be able to distinguish such
12779                  SIGTRAPs from other random SIGTRAPs: we keep this
12780                  breakpoint location for a bit, and will retire it
12781                  after we see some number of events.  The theory here
12782                  is that reporting of events should, "on the average",
12783                  be fair, so after a while we'll see events from all
12784                  threads that have anything of interest, and no longer
12785                  need to keep this breakpoint location around.  We
12786                  don't hold locations forever so to reduce chances of
12787                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12788                  SIGTRAP.
12789
12790                  The heuristic failing can be disastrous on
12791                  decr_pc_after_break targets.
12792
12793                  On decr_pc_after_break targets, like e.g., x86-linux,
12794                  if we fail to recognize a late breakpoint SIGTRAP,
12795                  because events_till_retirement has reached 0 too
12796                  soon, we'll fail to do the PC adjustment, and report
12797                  a random SIGTRAP to the user.  When the user resumes
12798                  the inferior, it will most likely immediately crash
12799                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12800                  corrupted, because of being resumed e.g., in the
12801                  middle of a multi-byte instruction, or skipped a
12802                  one-byte instruction.  This was actually seen happen
12803                  on native x86-linux, and should be less rare on
12804                  targets that do not support new thread events, like
12805                  remote, due to the heuristic depending on
12806                  thread_count.
12807
12808                  Mistaking a random SIGTRAP for a breakpoint trap
12809                  causes similar symptoms (PC adjustment applied when
12810                  it shouldn't), but then again, playing with SIGTRAPs
12811                  behind the debugger's back is asking for trouble.
12812
12813                  Since hardware watchpoint traps are always
12814                  distinguishable from other traps, so we don't need to
12815                  apply keep hardware watchpoint moribund locations
12816                  around.  We simply always ignore hardware watchpoint
12817                  traps we can no longer explain.  */
12818
12819               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12820               old_loc->owner = NULL;
12821
12822               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12823             }
12824           else
12825             {
12826               old_loc->owner = NULL;
12827               decref_bp_location (&old_loc);
12828             }
12829         }
12830     }
12831
12832   /* Rescan breakpoints at the same address and section, marking the
12833      first one as "first" and any others as "duplicates".  This is so
12834      that the bpt instruction is only inserted once.  If we have a
12835      permanent breakpoint at the same place as BPT, make that one the
12836      official one, and the rest as duplicates.  Permanent breakpoints
12837      are sorted first for the same address.
12838
12839      Do the same for hardware watchpoints, but also considering the
12840      watchpoint's type (regular/access/read) and length.  */
12841
12842   bp_loc_first = NULL;
12843   wp_loc_first = NULL;
12844   awp_loc_first = NULL;
12845   rwp_loc_first = NULL;
12846   ALL_BP_LOCATIONS (loc, locp)
12847     {
12848       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12849          non-NULL.  */
12850       struct bp_location **loc_first_p;
12851       b = loc->owner;
12852
12853       if (!unduplicated_should_be_inserted (loc)
12854           || !breakpoint_address_is_meaningful (b)
12855           /* Don't detect duplicate for tracepoint locations because they are
12856            never duplicated.  See the comments in field `duplicate' of
12857            `struct bp_location'.  */
12858           || is_tracepoint (b))
12859         {
12860           /* Clear the condition modification flag.  */
12861           loc->condition_changed = condition_unchanged;
12862           continue;
12863         }
12864
12865       /* Permanent breakpoint should always be inserted.  */
12866       if (loc->permanent && ! loc->inserted)
12867         internal_error (__FILE__, __LINE__,
12868                         _("allegedly permanent breakpoint is not "
12869                         "actually inserted"));
12870
12871       if (b->type == bp_hardware_watchpoint)
12872         loc_first_p = &wp_loc_first;
12873       else if (b->type == bp_read_watchpoint)
12874         loc_first_p = &rwp_loc_first;
12875       else if (b->type == bp_access_watchpoint)
12876         loc_first_p = &awp_loc_first;
12877       else
12878         loc_first_p = &bp_loc_first;
12879
12880       if (*loc_first_p == NULL
12881           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12882           || !breakpoint_locations_match (loc, *loc_first_p))
12883         {
12884           *loc_first_p = loc;
12885           loc->duplicate = 0;
12886
12887           if (is_breakpoint (loc->owner) && loc->condition_changed)
12888             {
12889               loc->needs_update = 1;
12890               /* Clear the condition modification flag.  */
12891               loc->condition_changed = condition_unchanged;
12892             }
12893           continue;
12894         }
12895
12896
12897       /* This and the above ensure the invariant that the first location
12898          is not duplicated, and is the inserted one.
12899          All following are marked as duplicated, and are not inserted.  */
12900       if (loc->inserted)
12901         swap_insertion (loc, *loc_first_p);
12902       loc->duplicate = 1;
12903
12904       /* Clear the condition modification flag.  */
12905       loc->condition_changed = condition_unchanged;
12906
12907       if (loc->inserted && !loc->permanent
12908           && (*loc_first_p)->permanent)
12909         internal_error (__FILE__, __LINE__,
12910                         _("another breakpoint was inserted on top of "
12911                         "a permanent breakpoint"));
12912     }
12913
12914   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12915     {
12916       if (insert_mode != UGLL_DONT_INSERT)
12917         insert_breakpoint_locations ();
12918       else
12919         {
12920           /* Even though the caller told us to not insert new
12921              locations, we may still need to update conditions on the
12922              target's side of breakpoints that were already inserted
12923              if the target is evaluating breakpoint conditions.  We
12924              only update conditions for locations that are marked
12925              "needs_update".  */
12926           update_inserted_breakpoint_locations ();
12927         }
12928     }
12929
12930   if (insert_mode != UGLL_DONT_INSERT)
12931     download_tracepoint_locations ();
12932
12933   do_cleanups (cleanups);
12934 }
12935
12936 void
12937 breakpoint_retire_moribund (void)
12938 {
12939   struct bp_location *loc;
12940   int ix;
12941
12942   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12943     if (--(loc->events_till_retirement) == 0)
12944       {
12945         decref_bp_location (&loc);
12946         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12947         --ix;
12948       }
12949 }
12950
12951 static void
12952 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12953 {
12954   volatile struct gdb_exception e;
12955
12956   TRY_CATCH (e, RETURN_MASK_ERROR)
12957     update_global_location_list (insert_mode);
12958 }
12959
12960 /* Clear BKP from a BPS.  */
12961
12962 static void
12963 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12964 {
12965   bpstat bs;
12966
12967   for (bs = bps; bs; bs = bs->next)
12968     if (bs->breakpoint_at == bpt)
12969       {
12970         bs->breakpoint_at = NULL;
12971         bs->old_val = NULL;
12972         /* bs->commands will be freed later.  */
12973       }
12974 }
12975
12976 /* Callback for iterate_over_threads.  */
12977 static int
12978 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12979 {
12980   struct breakpoint *bpt = data;
12981
12982   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12983   return 0;
12984 }
12985
12986 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12987    callbacks.  */
12988
12989 static void
12990 say_where (struct breakpoint *b)
12991 {
12992   struct value_print_options opts;
12993
12994   get_user_print_options (&opts);
12995
12996   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12997      single string.  */
12998   if (b->loc == NULL)
12999     {
13000       printf_filtered (_(" (%s) pending."), b->addr_string);
13001     }
13002   else
13003     {
13004       if (opts.addressprint || b->loc->symtab == NULL)
13005         {
13006           printf_filtered (" at ");
13007           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
13008                           gdb_stdout);
13009         }
13010       if (b->loc->symtab != NULL)
13011         {
13012           /* If there is a single location, we can print the location
13013              more nicely.  */
13014           if (b->loc->next == NULL)
13015             printf_filtered (": file %s, line %d.",
13016                              symtab_to_filename_for_display (b->loc->symtab),
13017                              b->loc->line_number);
13018           else
13019             /* This is not ideal, but each location may have a
13020                different file name, and this at least reflects the
13021                real situation somewhat.  */
13022             printf_filtered (": %s.", b->addr_string);
13023         }
13024
13025       if (b->loc->next)
13026         {
13027           struct bp_location *loc = b->loc;
13028           int n = 0;
13029           for (; loc; loc = loc->next)
13030             ++n;
13031           printf_filtered (" (%d locations)", n);
13032         }
13033     }
13034 }
13035
13036 /* Default bp_location_ops methods.  */
13037
13038 static void
13039 bp_location_dtor (struct bp_location *self)
13040 {
13041   xfree (self->cond);
13042   if (self->cond_bytecode)
13043     free_agent_expr (self->cond_bytecode);
13044   xfree (self->function_name);
13045
13046   VEC_free (agent_expr_p, self->target_info.conditions);
13047   VEC_free (agent_expr_p, self->target_info.tcommands);
13048 }
13049
13050 static const struct bp_location_ops bp_location_ops =
13051 {
13052   bp_location_dtor
13053 };
13054
13055 /* Default breakpoint_ops methods all breakpoint_ops ultimately
13056    inherit from.  */
13057
13058 static void
13059 base_breakpoint_dtor (struct breakpoint *self)
13060 {
13061   decref_counted_command_line (&self->commands);
13062   xfree (self->cond_string);
13063   xfree (self->extra_string);
13064   xfree (self->addr_string);
13065   xfree (self->filter);
13066   xfree (self->addr_string_range_end);
13067 }
13068
13069 static struct bp_location *
13070 base_breakpoint_allocate_location (struct breakpoint *self)
13071 {
13072   struct bp_location *loc;
13073
13074   loc = XNEW (struct bp_location);
13075   init_bp_location (loc, &bp_location_ops, self);
13076   return loc;
13077 }
13078
13079 static void
13080 base_breakpoint_re_set (struct breakpoint *b)
13081 {
13082   /* Nothing to re-set. */
13083 }
13084
13085 #define internal_error_pure_virtual_called() \
13086   gdb_assert_not_reached ("pure virtual function called")
13087
13088 static int
13089 base_breakpoint_insert_location (struct bp_location *bl)
13090 {
13091   internal_error_pure_virtual_called ();
13092 }
13093
13094 static int
13095 base_breakpoint_remove_location (struct bp_location *bl)
13096 {
13097   internal_error_pure_virtual_called ();
13098 }
13099
13100 static int
13101 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
13102                                 struct address_space *aspace,
13103                                 CORE_ADDR bp_addr,
13104                                 const struct target_waitstatus *ws)
13105 {
13106   internal_error_pure_virtual_called ();
13107 }
13108
13109 static void
13110 base_breakpoint_check_status (bpstat bs)
13111 {
13112   /* Always stop.   */
13113 }
13114
13115 /* A "works_in_software_mode" breakpoint_ops method that just internal
13116    errors.  */
13117
13118 static int
13119 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13120 {
13121   internal_error_pure_virtual_called ();
13122 }
13123
13124 /* A "resources_needed" breakpoint_ops method that just internal
13125    errors.  */
13126
13127 static int
13128 base_breakpoint_resources_needed (const struct bp_location *bl)
13129 {
13130   internal_error_pure_virtual_called ();
13131 }
13132
13133 static enum print_stop_action
13134 base_breakpoint_print_it (bpstat bs)
13135 {
13136   internal_error_pure_virtual_called ();
13137 }
13138
13139 static void
13140 base_breakpoint_print_one_detail (const struct breakpoint *self,
13141                                   struct ui_out *uiout)
13142 {
13143   /* nothing */
13144 }
13145
13146 static void
13147 base_breakpoint_print_mention (struct breakpoint *b)
13148 {
13149   internal_error_pure_virtual_called ();
13150 }
13151
13152 static void
13153 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13154 {
13155   internal_error_pure_virtual_called ();
13156 }
13157
13158 static void
13159 base_breakpoint_create_sals_from_address (char **arg,
13160                                           struct linespec_result *canonical,
13161                                           enum bptype type_wanted,
13162                                           char *addr_start,
13163                                           char **copy_arg)
13164 {
13165   internal_error_pure_virtual_called ();
13166 }
13167
13168 static void
13169 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13170                                         struct linespec_result *c,
13171                                         char *cond_string,
13172                                         char *extra_string,
13173                                         enum bptype type_wanted,
13174                                         enum bpdisp disposition,
13175                                         int thread,
13176                                         int task, int ignore_count,
13177                                         const struct breakpoint_ops *o,
13178                                         int from_tty, int enabled,
13179                                         int internal, unsigned flags)
13180 {
13181   internal_error_pure_virtual_called ();
13182 }
13183
13184 static void
13185 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13186                                  struct symtabs_and_lines *sals)
13187 {
13188   internal_error_pure_virtual_called ();
13189 }
13190
13191 /* The default 'explains_signal' method.  */
13192
13193 static int
13194 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13195 {
13196   return 1;
13197 }
13198
13199 /* The default "after_condition_true" method.  */
13200
13201 static void
13202 base_breakpoint_after_condition_true (struct bpstats *bs)
13203 {
13204   /* Nothing to do.   */
13205 }
13206
13207 struct breakpoint_ops base_breakpoint_ops =
13208 {
13209   base_breakpoint_dtor,
13210   base_breakpoint_allocate_location,
13211   base_breakpoint_re_set,
13212   base_breakpoint_insert_location,
13213   base_breakpoint_remove_location,
13214   base_breakpoint_breakpoint_hit,
13215   base_breakpoint_check_status,
13216   base_breakpoint_resources_needed,
13217   base_breakpoint_works_in_software_mode,
13218   base_breakpoint_print_it,
13219   NULL,
13220   base_breakpoint_print_one_detail,
13221   base_breakpoint_print_mention,
13222   base_breakpoint_print_recreate,
13223   base_breakpoint_create_sals_from_address,
13224   base_breakpoint_create_breakpoints_sal,
13225   base_breakpoint_decode_linespec,
13226   base_breakpoint_explains_signal,
13227   base_breakpoint_after_condition_true,
13228 };
13229
13230 /* Default breakpoint_ops methods.  */
13231
13232 static void
13233 bkpt_re_set (struct breakpoint *b)
13234 {
13235   /* FIXME: is this still reachable?  */
13236   if (b->addr_string == NULL)
13237     {
13238       /* Anything without a string can't be re-set.  */
13239       delete_breakpoint (b);
13240       return;
13241     }
13242
13243   breakpoint_re_set_default (b);
13244 }
13245
13246 static int
13247 bkpt_insert_location (struct bp_location *bl)
13248 {
13249   if (bl->loc_type == bp_loc_hardware_breakpoint)
13250     return target_insert_hw_breakpoint (bl->gdbarch, &bl->target_info);
13251   else
13252     return target_insert_breakpoint (bl->gdbarch, &bl->target_info);
13253 }
13254
13255 static int
13256 bkpt_remove_location (struct bp_location *bl)
13257 {
13258   if (bl->loc_type == bp_loc_hardware_breakpoint)
13259     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13260   else
13261     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13262 }
13263
13264 static int
13265 bkpt_breakpoint_hit (const struct bp_location *bl,
13266                      struct address_space *aspace, CORE_ADDR bp_addr,
13267                      const struct target_waitstatus *ws)
13268 {
13269   if (ws->kind != TARGET_WAITKIND_STOPPED
13270       || ws->value.sig != GDB_SIGNAL_TRAP)
13271     return 0;
13272
13273   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13274                                  aspace, bp_addr))
13275     return 0;
13276
13277   if (overlay_debugging         /* unmapped overlay section */
13278       && section_is_overlay (bl->section)
13279       && !section_is_mapped (bl->section))
13280     return 0;
13281
13282   return 1;
13283 }
13284
13285 static int
13286 dprintf_breakpoint_hit (const struct bp_location *bl,
13287                         struct address_space *aspace, CORE_ADDR bp_addr,
13288                         const struct target_waitstatus *ws)
13289 {
13290   if (dprintf_style == dprintf_style_agent
13291       && target_can_run_breakpoint_commands ())
13292     {
13293       /* An agent-style dprintf never causes a stop.  If we see a trap
13294          for this address it must be for a breakpoint that happens to
13295          be set at the same address.  */
13296       return 0;
13297     }
13298
13299   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13300 }
13301
13302 static int
13303 bkpt_resources_needed (const struct bp_location *bl)
13304 {
13305   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13306
13307   return 1;
13308 }
13309
13310 static enum print_stop_action
13311 bkpt_print_it (bpstat bs)
13312 {
13313   struct breakpoint *b;
13314   const struct bp_location *bl;
13315   int bp_temp;
13316   struct ui_out *uiout = current_uiout;
13317
13318   gdb_assert (bs->bp_location_at != NULL);
13319
13320   bl = bs->bp_location_at;
13321   b = bs->breakpoint_at;
13322
13323   bp_temp = b->disposition == disp_del;
13324   if (bl->address != bl->requested_address)
13325     breakpoint_adjustment_warning (bl->requested_address,
13326                                    bl->address,
13327                                    b->number, 1);
13328   annotate_breakpoint (b->number);
13329   if (bp_temp)
13330     ui_out_text (uiout, "\nTemporary breakpoint ");
13331   else
13332     ui_out_text (uiout, "\nBreakpoint ");
13333   if (ui_out_is_mi_like_p (uiout))
13334     {
13335       ui_out_field_string (uiout, "reason",
13336                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13337       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13338     }
13339   ui_out_field_int (uiout, "bkptno", b->number);
13340   ui_out_text (uiout, ", ");
13341
13342   return PRINT_SRC_AND_LOC;
13343 }
13344
13345 static void
13346 bkpt_print_mention (struct breakpoint *b)
13347 {
13348   if (ui_out_is_mi_like_p (current_uiout))
13349     return;
13350
13351   switch (b->type)
13352     {
13353     case bp_breakpoint:
13354     case bp_gnu_ifunc_resolver:
13355       if (b->disposition == disp_del)
13356         printf_filtered (_("Temporary breakpoint"));
13357       else
13358         printf_filtered (_("Breakpoint"));
13359       printf_filtered (_(" %d"), b->number);
13360       if (b->type == bp_gnu_ifunc_resolver)
13361         printf_filtered (_(" at gnu-indirect-function resolver"));
13362       break;
13363     case bp_hardware_breakpoint:
13364       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13365       break;
13366     case bp_dprintf:
13367       printf_filtered (_("Dprintf %d"), b->number);
13368       break;
13369     }
13370
13371   say_where (b);
13372 }
13373
13374 static void
13375 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13376 {
13377   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13378     fprintf_unfiltered (fp, "tbreak");
13379   else if (tp->type == bp_breakpoint)
13380     fprintf_unfiltered (fp, "break");
13381   else if (tp->type == bp_hardware_breakpoint
13382            && tp->disposition == disp_del)
13383     fprintf_unfiltered (fp, "thbreak");
13384   else if (tp->type == bp_hardware_breakpoint)
13385     fprintf_unfiltered (fp, "hbreak");
13386   else
13387     internal_error (__FILE__, __LINE__,
13388                     _("unhandled breakpoint type %d"), (int) tp->type);
13389
13390   fprintf_unfiltered (fp, " %s", tp->addr_string);
13391   print_recreate_thread (tp, fp);
13392 }
13393
13394 static void
13395 bkpt_create_sals_from_address (char **arg,
13396                                struct linespec_result *canonical,
13397                                enum bptype type_wanted,
13398                                char *addr_start, char **copy_arg)
13399 {
13400   create_sals_from_address_default (arg, canonical, type_wanted,
13401                                     addr_start, copy_arg);
13402 }
13403
13404 static void
13405 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13406                              struct linespec_result *canonical,
13407                              char *cond_string,
13408                              char *extra_string,
13409                              enum bptype type_wanted,
13410                              enum bpdisp disposition,
13411                              int thread,
13412                              int task, int ignore_count,
13413                              const struct breakpoint_ops *ops,
13414                              int from_tty, int enabled,
13415                              int internal, unsigned flags)
13416 {
13417   create_breakpoints_sal_default (gdbarch, canonical,
13418                                   cond_string, extra_string,
13419                                   type_wanted,
13420                                   disposition, thread, task,
13421                                   ignore_count, ops, from_tty,
13422                                   enabled, internal, flags);
13423 }
13424
13425 static void
13426 bkpt_decode_linespec (struct breakpoint *b, char **s,
13427                       struct symtabs_and_lines *sals)
13428 {
13429   decode_linespec_default (b, s, sals);
13430 }
13431
13432 /* Virtual table for internal breakpoints.  */
13433
13434 static void
13435 internal_bkpt_re_set (struct breakpoint *b)
13436 {
13437   switch (b->type)
13438     {
13439       /* Delete overlay event and longjmp master breakpoints; they
13440          will be reset later by breakpoint_re_set.  */
13441     case bp_overlay_event:
13442     case bp_longjmp_master:
13443     case bp_std_terminate_master:
13444     case bp_exception_master:
13445       delete_breakpoint (b);
13446       break;
13447
13448       /* This breakpoint is special, it's set up when the inferior
13449          starts and we really don't want to touch it.  */
13450     case bp_shlib_event:
13451
13452       /* Like bp_shlib_event, this breakpoint type is special.  Once
13453          it is set up, we do not want to touch it.  */
13454     case bp_thread_event:
13455       break;
13456     }
13457 }
13458
13459 static void
13460 internal_bkpt_check_status (bpstat bs)
13461 {
13462   if (bs->breakpoint_at->type == bp_shlib_event)
13463     {
13464       /* If requested, stop when the dynamic linker notifies GDB of
13465          events.  This allows the user to get control and place
13466          breakpoints in initializer routines for dynamically loaded
13467          objects (among other things).  */
13468       bs->stop = stop_on_solib_events;
13469       bs->print = stop_on_solib_events;
13470     }
13471   else
13472     bs->stop = 0;
13473 }
13474
13475 static enum print_stop_action
13476 internal_bkpt_print_it (bpstat bs)
13477 {
13478   struct breakpoint *b;
13479
13480   b = bs->breakpoint_at;
13481
13482   switch (b->type)
13483     {
13484     case bp_shlib_event:
13485       /* Did we stop because the user set the stop_on_solib_events
13486          variable?  (If so, we report this as a generic, "Stopped due
13487          to shlib event" message.) */
13488       print_solib_event (0);
13489       break;
13490
13491     case bp_thread_event:
13492       /* Not sure how we will get here.
13493          GDB should not stop for these breakpoints.  */
13494       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13495       break;
13496
13497     case bp_overlay_event:
13498       /* By analogy with the thread event, GDB should not stop for these.  */
13499       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13500       break;
13501
13502     case bp_longjmp_master:
13503       /* These should never be enabled.  */
13504       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13505       break;
13506
13507     case bp_std_terminate_master:
13508       /* These should never be enabled.  */
13509       printf_filtered (_("std::terminate Master Breakpoint: "
13510                          "gdb should not stop!\n"));
13511       break;
13512
13513     case bp_exception_master:
13514       /* These should never be enabled.  */
13515       printf_filtered (_("Exception Master Breakpoint: "
13516                          "gdb should not stop!\n"));
13517       break;
13518     }
13519
13520   return PRINT_NOTHING;
13521 }
13522
13523 static void
13524 internal_bkpt_print_mention (struct breakpoint *b)
13525 {
13526   /* Nothing to mention.  These breakpoints are internal.  */
13527 }
13528
13529 /* Virtual table for momentary breakpoints  */
13530
13531 static void
13532 momentary_bkpt_re_set (struct breakpoint *b)
13533 {
13534   /* Keep temporary breakpoints, which can be encountered when we step
13535      over a dlopen call and solib_add is resetting the breakpoints.
13536      Otherwise these should have been blown away via the cleanup chain
13537      or by breakpoint_init_inferior when we rerun the executable.  */
13538 }
13539
13540 static void
13541 momentary_bkpt_check_status (bpstat bs)
13542 {
13543   /* Nothing.  The point of these breakpoints is causing a stop.  */
13544 }
13545
13546 static enum print_stop_action
13547 momentary_bkpt_print_it (bpstat bs)
13548 {
13549   struct ui_out *uiout = current_uiout;
13550
13551   if (ui_out_is_mi_like_p (uiout))
13552     {
13553       struct breakpoint *b = bs->breakpoint_at;
13554
13555       switch (b->type)
13556         {
13557         case bp_finish:
13558           ui_out_field_string
13559             (uiout, "reason",
13560              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13561           break;
13562
13563         case bp_until:
13564           ui_out_field_string
13565             (uiout, "reason",
13566              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13567           break;
13568         }
13569     }
13570
13571   return PRINT_UNKNOWN;
13572 }
13573
13574 static void
13575 momentary_bkpt_print_mention (struct breakpoint *b)
13576 {
13577   /* Nothing to mention.  These breakpoints are internal.  */
13578 }
13579
13580 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13581
13582    It gets cleared already on the removal of the first one of such placed
13583    breakpoints.  This is OK as they get all removed altogether.  */
13584
13585 static void
13586 longjmp_bkpt_dtor (struct breakpoint *self)
13587 {
13588   struct thread_info *tp = find_thread_id (self->thread);
13589
13590   if (tp)
13591     tp->initiating_frame = null_frame_id;
13592
13593   momentary_breakpoint_ops.dtor (self);
13594 }
13595
13596 /* Specific methods for probe breakpoints.  */
13597
13598 static int
13599 bkpt_probe_insert_location (struct bp_location *bl)
13600 {
13601   int v = bkpt_insert_location (bl);
13602
13603   if (v == 0)
13604     {
13605       /* The insertion was successful, now let's set the probe's semaphore
13606          if needed.  */
13607       if (bl->probe.probe->pops->set_semaphore != NULL)
13608         bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13609                                               bl->probe.objfile,
13610                                               bl->gdbarch);
13611     }
13612
13613   return v;
13614 }
13615
13616 static int
13617 bkpt_probe_remove_location (struct bp_location *bl)
13618 {
13619   /* Let's clear the semaphore before removing the location.  */
13620   if (bl->probe.probe->pops->clear_semaphore != NULL)
13621     bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13622                                             bl->probe.objfile,
13623                                             bl->gdbarch);
13624
13625   return bkpt_remove_location (bl);
13626 }
13627
13628 static void
13629 bkpt_probe_create_sals_from_address (char **arg,
13630                                      struct linespec_result *canonical,
13631                                      enum bptype type_wanted,
13632                                      char *addr_start, char **copy_arg)
13633 {
13634   struct linespec_sals lsal;
13635
13636   lsal.sals = parse_probes (arg, canonical);
13637
13638   *copy_arg = xstrdup (canonical->addr_string);
13639   lsal.canonical = xstrdup (*copy_arg);
13640
13641   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13642 }
13643
13644 static void
13645 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13646                             struct symtabs_and_lines *sals)
13647 {
13648   *sals = parse_probes (s, NULL);
13649   if (!sals->sals)
13650     error (_("probe not found"));
13651 }
13652
13653 /* The breakpoint_ops structure to be used in tracepoints.  */
13654
13655 static void
13656 tracepoint_re_set (struct breakpoint *b)
13657 {
13658   breakpoint_re_set_default (b);
13659 }
13660
13661 static int
13662 tracepoint_breakpoint_hit (const struct bp_location *bl,
13663                            struct address_space *aspace, CORE_ADDR bp_addr,
13664                            const struct target_waitstatus *ws)
13665 {
13666   /* By definition, the inferior does not report stops at
13667      tracepoints.  */
13668   return 0;
13669 }
13670
13671 static void
13672 tracepoint_print_one_detail (const struct breakpoint *self,
13673                              struct ui_out *uiout)
13674 {
13675   struct tracepoint *tp = (struct tracepoint *) self;
13676   if (tp->static_trace_marker_id)
13677     {
13678       gdb_assert (self->type == bp_static_tracepoint);
13679
13680       ui_out_text (uiout, "\tmarker id is ");
13681       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13682                            tp->static_trace_marker_id);
13683       ui_out_text (uiout, "\n");
13684     }
13685 }
13686
13687 static void
13688 tracepoint_print_mention (struct breakpoint *b)
13689 {
13690   if (ui_out_is_mi_like_p (current_uiout))
13691     return;
13692
13693   switch (b->type)
13694     {
13695     case bp_tracepoint:
13696       printf_filtered (_("Tracepoint"));
13697       printf_filtered (_(" %d"), b->number);
13698       break;
13699     case bp_fast_tracepoint:
13700       printf_filtered (_("Fast tracepoint"));
13701       printf_filtered (_(" %d"), b->number);
13702       break;
13703     case bp_static_tracepoint:
13704       printf_filtered (_("Static tracepoint"));
13705       printf_filtered (_(" %d"), b->number);
13706       break;
13707     default:
13708       internal_error (__FILE__, __LINE__,
13709                       _("unhandled tracepoint type %d"), (int) b->type);
13710     }
13711
13712   say_where (b);
13713 }
13714
13715 static void
13716 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13717 {
13718   struct tracepoint *tp = (struct tracepoint *) self;
13719
13720   if (self->type == bp_fast_tracepoint)
13721     fprintf_unfiltered (fp, "ftrace");
13722   if (self->type == bp_static_tracepoint)
13723     fprintf_unfiltered (fp, "strace");
13724   else if (self->type == bp_tracepoint)
13725     fprintf_unfiltered (fp, "trace");
13726   else
13727     internal_error (__FILE__, __LINE__,
13728                     _("unhandled tracepoint type %d"), (int) self->type);
13729
13730   fprintf_unfiltered (fp, " %s", self->addr_string);
13731   print_recreate_thread (self, fp);
13732
13733   if (tp->pass_count)
13734     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13735 }
13736
13737 static void
13738 tracepoint_create_sals_from_address (char **arg,
13739                                      struct linespec_result *canonical,
13740                                      enum bptype type_wanted,
13741                                      char *addr_start, char **copy_arg)
13742 {
13743   create_sals_from_address_default (arg, canonical, type_wanted,
13744                                     addr_start, copy_arg);
13745 }
13746
13747 static void
13748 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13749                                    struct linespec_result *canonical,
13750                                    char *cond_string,
13751                                    char *extra_string,
13752                                    enum bptype type_wanted,
13753                                    enum bpdisp disposition,
13754                                    int thread,
13755                                    int task, int ignore_count,
13756                                    const struct breakpoint_ops *ops,
13757                                    int from_tty, int enabled,
13758                                    int internal, unsigned flags)
13759 {
13760   create_breakpoints_sal_default (gdbarch, canonical,
13761                                   cond_string, extra_string,
13762                                   type_wanted,
13763                                   disposition, thread, task,
13764                                   ignore_count, ops, from_tty,
13765                                   enabled, internal, flags);
13766 }
13767
13768 static void
13769 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13770                             struct symtabs_and_lines *sals)
13771 {
13772   decode_linespec_default (b, s, sals);
13773 }
13774
13775 struct breakpoint_ops tracepoint_breakpoint_ops;
13776
13777 /* The breakpoint_ops structure to be use on tracepoints placed in a
13778    static probe.  */
13779
13780 static void
13781 tracepoint_probe_create_sals_from_address (char **arg,
13782                                            struct linespec_result *canonical,
13783                                            enum bptype type_wanted,
13784                                            char *addr_start, char **copy_arg)
13785 {
13786   /* We use the same method for breakpoint on probes.  */
13787   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13788                                        addr_start, copy_arg);
13789 }
13790
13791 static void
13792 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13793                                   struct symtabs_and_lines *sals)
13794 {
13795   /* We use the same method for breakpoint on probes.  */
13796   bkpt_probe_decode_linespec (b, s, sals);
13797 }
13798
13799 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13800
13801 /* Dprintf breakpoint_ops methods.  */
13802
13803 static void
13804 dprintf_re_set (struct breakpoint *b)
13805 {
13806   breakpoint_re_set_default (b);
13807
13808   /* This breakpoint could have been pending, and be resolved now, and
13809      if so, we should now have the extra string.  If we don't, the
13810      dprintf was malformed when created, but we couldn't tell because
13811      we can't extract the extra string until the location is
13812      resolved.  */
13813   if (b->loc != NULL && b->extra_string == NULL)
13814     error (_("Format string required"));
13815
13816   /* 1 - connect to target 1, that can run breakpoint commands.
13817      2 - create a dprintf, which resolves fine.
13818      3 - disconnect from target 1
13819      4 - connect to target 2, that can NOT run breakpoint commands.
13820
13821      After steps #3/#4, you'll want the dprintf command list to
13822      be updated, because target 1 and 2 may well return different
13823      answers for target_can_run_breakpoint_commands().
13824      Given absence of finer grained resetting, we get to do
13825      it all the time.  */
13826   if (b->extra_string != NULL)
13827     update_dprintf_command_list (b);
13828 }
13829
13830 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13831
13832 static void
13833 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13834 {
13835   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13836                       tp->extra_string);
13837   print_recreate_thread (tp, fp);
13838 }
13839
13840 /* Implement the "after_condition_true" breakpoint_ops method for
13841    dprintf.
13842
13843    dprintf's are implemented with regular commands in their command
13844    list, but we run the commands here instead of before presenting the
13845    stop to the user, as dprintf's don't actually cause a stop.  This
13846    also makes it so that the commands of multiple dprintfs at the same
13847    address are all handled.  */
13848
13849 static void
13850 dprintf_after_condition_true (struct bpstats *bs)
13851 {
13852   struct cleanup *old_chain;
13853   struct bpstats tmp_bs = { NULL };
13854   struct bpstats *tmp_bs_p = &tmp_bs;
13855
13856   /* dprintf's never cause a stop.  This wasn't set in the
13857      check_status hook instead because that would make the dprintf's
13858      condition not be evaluated.  */
13859   bs->stop = 0;
13860
13861   /* Run the command list here.  Take ownership of it instead of
13862      copying.  We never want these commands to run later in
13863      bpstat_do_actions, if a breakpoint that causes a stop happens to
13864      be set at same address as this dprintf, or even if running the
13865      commands here throws.  */
13866   tmp_bs.commands = bs->commands;
13867   bs->commands = NULL;
13868   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13869
13870   bpstat_do_actions_1 (&tmp_bs_p);
13871
13872   /* 'tmp_bs.commands' will usually be NULL by now, but
13873      bpstat_do_actions_1 may return early without processing the whole
13874      list.  */
13875   do_cleanups (old_chain);
13876 }
13877
13878 /* The breakpoint_ops structure to be used on static tracepoints with
13879    markers (`-m').  */
13880
13881 static void
13882 strace_marker_create_sals_from_address (char **arg,
13883                                         struct linespec_result *canonical,
13884                                         enum bptype type_wanted,
13885                                         char *addr_start, char **copy_arg)
13886 {
13887   struct linespec_sals lsal;
13888
13889   lsal.sals = decode_static_tracepoint_spec (arg);
13890
13891   *copy_arg = savestring (addr_start, *arg - addr_start);
13892
13893   canonical->addr_string = xstrdup (*copy_arg);
13894   lsal.canonical = xstrdup (*copy_arg);
13895   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13896 }
13897
13898 static void
13899 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13900                                       struct linespec_result *canonical,
13901                                       char *cond_string,
13902                                       char *extra_string,
13903                                       enum bptype type_wanted,
13904                                       enum bpdisp disposition,
13905                                       int thread,
13906                                       int task, int ignore_count,
13907                                       const struct breakpoint_ops *ops,
13908                                       int from_tty, int enabled,
13909                                       int internal, unsigned flags)
13910 {
13911   int i;
13912   struct linespec_sals *lsal = VEC_index (linespec_sals,
13913                                           canonical->sals, 0);
13914
13915   /* If the user is creating a static tracepoint by marker id
13916      (strace -m MARKER_ID), then store the sals index, so that
13917      breakpoint_re_set can try to match up which of the newly
13918      found markers corresponds to this one, and, don't try to
13919      expand multiple locations for each sal, given than SALS
13920      already should contain all sals for MARKER_ID.  */
13921
13922   for (i = 0; i < lsal->sals.nelts; ++i)
13923     {
13924       struct symtabs_and_lines expanded;
13925       struct tracepoint *tp;
13926       struct cleanup *old_chain;
13927       char *addr_string;
13928
13929       expanded.nelts = 1;
13930       expanded.sals = &lsal->sals.sals[i];
13931
13932       addr_string = xstrdup (canonical->addr_string);
13933       old_chain = make_cleanup (xfree, addr_string);
13934
13935       tp = XCNEW (struct tracepoint);
13936       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13937                            addr_string, NULL,
13938                            cond_string, extra_string,
13939                            type_wanted, disposition,
13940                            thread, task, ignore_count, ops,
13941                            from_tty, enabled, internal, flags,
13942                            canonical->special_display);
13943       /* Given that its possible to have multiple markers with
13944          the same string id, if the user is creating a static
13945          tracepoint by marker id ("strace -m MARKER_ID"), then
13946          store the sals index, so that breakpoint_re_set can
13947          try to match up which of the newly found markers
13948          corresponds to this one  */
13949       tp->static_trace_marker_id_idx = i;
13950
13951       install_breakpoint (internal, &tp->base, 0);
13952
13953       discard_cleanups (old_chain);
13954     }
13955 }
13956
13957 static void
13958 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13959                                struct symtabs_and_lines *sals)
13960 {
13961   struct tracepoint *tp = (struct tracepoint *) b;
13962
13963   *sals = decode_static_tracepoint_spec (s);
13964   if (sals->nelts > tp->static_trace_marker_id_idx)
13965     {
13966       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13967       sals->nelts = 1;
13968     }
13969   else
13970     error (_("marker %s not found"), tp->static_trace_marker_id);
13971 }
13972
13973 static struct breakpoint_ops strace_marker_breakpoint_ops;
13974
13975 static int
13976 strace_marker_p (struct breakpoint *b)
13977 {
13978   return b->ops == &strace_marker_breakpoint_ops;
13979 }
13980
13981 /* Delete a breakpoint and clean up all traces of it in the data
13982    structures.  */
13983
13984 void
13985 delete_breakpoint (struct breakpoint *bpt)
13986 {
13987   struct breakpoint *b;
13988
13989   gdb_assert (bpt != NULL);
13990
13991   /* Has this bp already been deleted?  This can happen because
13992      multiple lists can hold pointers to bp's.  bpstat lists are
13993      especial culprits.
13994
13995      One example of this happening is a watchpoint's scope bp.  When
13996      the scope bp triggers, we notice that the watchpoint is out of
13997      scope, and delete it.  We also delete its scope bp.  But the
13998      scope bp is marked "auto-deleting", and is already on a bpstat.
13999      That bpstat is then checked for auto-deleting bp's, which are
14000      deleted.
14001
14002      A real solution to this problem might involve reference counts in
14003      bp's, and/or giving them pointers back to their referencing
14004      bpstat's, and teaching delete_breakpoint to only free a bp's
14005      storage when no more references were extent.  A cheaper bandaid
14006      was chosen.  */
14007   if (bpt->type == bp_none)
14008     return;
14009
14010   /* At least avoid this stale reference until the reference counting
14011      of breakpoints gets resolved.  */
14012   if (bpt->related_breakpoint != bpt)
14013     {
14014       struct breakpoint *related;
14015       struct watchpoint *w;
14016
14017       if (bpt->type == bp_watchpoint_scope)
14018         w = (struct watchpoint *) bpt->related_breakpoint;
14019       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
14020         w = (struct watchpoint *) bpt;
14021       else
14022         w = NULL;
14023       if (w != NULL)
14024         watchpoint_del_at_next_stop (w);
14025
14026       /* Unlink bpt from the bpt->related_breakpoint ring.  */
14027       for (related = bpt; related->related_breakpoint != bpt;
14028            related = related->related_breakpoint);
14029       related->related_breakpoint = bpt->related_breakpoint;
14030       bpt->related_breakpoint = bpt;
14031     }
14032
14033   /* watch_command_1 creates a watchpoint but only sets its number if
14034      update_watchpoint succeeds in creating its bp_locations.  If there's
14035      a problem in that process, we'll be asked to delete the half-created
14036      watchpoint.  In that case, don't announce the deletion.  */
14037   if (bpt->number)
14038     observer_notify_breakpoint_deleted (bpt);
14039
14040   if (breakpoint_chain == bpt)
14041     breakpoint_chain = bpt->next;
14042
14043   ALL_BREAKPOINTS (b)
14044     if (b->next == bpt)
14045     {
14046       b->next = bpt->next;
14047       break;
14048     }
14049
14050   /* Be sure no bpstat's are pointing at the breakpoint after it's
14051      been freed.  */
14052   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
14053      in all threads for now.  Note that we cannot just remove bpstats
14054      pointing at bpt from the stop_bpstat list entirely, as breakpoint
14055      commands are associated with the bpstat; if we remove it here,
14056      then the later call to bpstat_do_actions (&stop_bpstat); in
14057      event-top.c won't do anything, and temporary breakpoints with
14058      commands won't work.  */
14059
14060   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
14061
14062   /* Now that breakpoint is removed from breakpoint list, update the
14063      global location list.  This will remove locations that used to
14064      belong to this breakpoint.  Do this before freeing the breakpoint
14065      itself, since remove_breakpoint looks at location's owner.  It
14066      might be better design to have location completely
14067      self-contained, but it's not the case now.  */
14068   update_global_location_list (UGLL_DONT_INSERT);
14069
14070   bpt->ops->dtor (bpt);
14071   /* On the chance that someone will soon try again to delete this
14072      same bp, we mark it as deleted before freeing its storage.  */
14073   bpt->type = bp_none;
14074   xfree (bpt);
14075 }
14076
14077 static void
14078 do_delete_breakpoint_cleanup (void *b)
14079 {
14080   delete_breakpoint (b);
14081 }
14082
14083 struct cleanup *
14084 make_cleanup_delete_breakpoint (struct breakpoint *b)
14085 {
14086   return make_cleanup (do_delete_breakpoint_cleanup, b);
14087 }
14088
14089 /* Iterator function to call a user-provided callback function once
14090    for each of B and its related breakpoints.  */
14091
14092 static void
14093 iterate_over_related_breakpoints (struct breakpoint *b,
14094                                   void (*function) (struct breakpoint *,
14095                                                     void *),
14096                                   void *data)
14097 {
14098   struct breakpoint *related;
14099
14100   related = b;
14101   do
14102     {
14103       struct breakpoint *next;
14104
14105       /* FUNCTION may delete RELATED.  */
14106       next = related->related_breakpoint;
14107
14108       if (next == related)
14109         {
14110           /* RELATED is the last ring entry.  */
14111           function (related, data);
14112
14113           /* FUNCTION may have deleted it, so we'd never reach back to
14114              B.  There's nothing left to do anyway, so just break
14115              out.  */
14116           break;
14117         }
14118       else
14119         function (related, data);
14120
14121       related = next;
14122     }
14123   while (related != b);
14124 }
14125
14126 static void
14127 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14128 {
14129   delete_breakpoint (b);
14130 }
14131
14132 /* A callback for map_breakpoint_numbers that calls
14133    delete_breakpoint.  */
14134
14135 static void
14136 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14137 {
14138   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14139 }
14140
14141 void
14142 delete_command (char *arg, int from_tty)
14143 {
14144   struct breakpoint *b, *b_tmp;
14145
14146   dont_repeat ();
14147
14148   if (arg == 0)
14149     {
14150       int breaks_to_delete = 0;
14151
14152       /* Delete all breakpoints if no argument.  Do not delete
14153          internal breakpoints, these have to be deleted with an
14154          explicit breakpoint number argument.  */
14155       ALL_BREAKPOINTS (b)
14156         if (user_breakpoint_p (b))
14157           {
14158             breaks_to_delete = 1;
14159             break;
14160           }
14161
14162       /* Ask user only if there are some breakpoints to delete.  */
14163       if (!from_tty
14164           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14165         {
14166           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14167             if (user_breakpoint_p (b))
14168               delete_breakpoint (b);
14169         }
14170     }
14171   else
14172     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14173 }
14174
14175 static int
14176 all_locations_are_pending (struct bp_location *loc)
14177 {
14178   for (; loc; loc = loc->next)
14179     if (!loc->shlib_disabled
14180         && !loc->pspace->executing_startup)
14181       return 0;
14182   return 1;
14183 }
14184
14185 /* Subroutine of update_breakpoint_locations to simplify it.
14186    Return non-zero if multiple fns in list LOC have the same name.
14187    Null names are ignored.  */
14188
14189 static int
14190 ambiguous_names_p (struct bp_location *loc)
14191 {
14192   struct bp_location *l;
14193   htab_t htab = htab_create_alloc (13, htab_hash_string,
14194                                    (int (*) (const void *, 
14195                                              const void *)) streq,
14196                                    NULL, xcalloc, xfree);
14197
14198   for (l = loc; l != NULL; l = l->next)
14199     {
14200       const char **slot;
14201       const char *name = l->function_name;
14202
14203       /* Allow for some names to be NULL, ignore them.  */
14204       if (name == NULL)
14205         continue;
14206
14207       slot = (const char **) htab_find_slot (htab, (const void *) name,
14208                                              INSERT);
14209       /* NOTE: We can assume slot != NULL here because xcalloc never
14210          returns NULL.  */
14211       if (*slot != NULL)
14212         {
14213           htab_delete (htab);
14214           return 1;
14215         }
14216       *slot = name;
14217     }
14218
14219   htab_delete (htab);
14220   return 0;
14221 }
14222
14223 /* When symbols change, it probably means the sources changed as well,
14224    and it might mean the static tracepoint markers are no longer at
14225    the same address or line numbers they used to be at last we
14226    checked.  Losing your static tracepoints whenever you rebuild is
14227    undesirable.  This function tries to resync/rematch gdb static
14228    tracepoints with the markers on the target, for static tracepoints
14229    that have not been set by marker id.  Static tracepoint that have
14230    been set by marker id are reset by marker id in breakpoint_re_set.
14231    The heuristic is:
14232
14233    1) For a tracepoint set at a specific address, look for a marker at
14234    the old PC.  If one is found there, assume to be the same marker.
14235    If the name / string id of the marker found is different from the
14236    previous known name, assume that means the user renamed the marker
14237    in the sources, and output a warning.
14238
14239    2) For a tracepoint set at a given line number, look for a marker
14240    at the new address of the old line number.  If one is found there,
14241    assume to be the same marker.  If the name / string id of the
14242    marker found is different from the previous known name, assume that
14243    means the user renamed the marker in the sources, and output a
14244    warning.
14245
14246    3) If a marker is no longer found at the same address or line, it
14247    may mean the marker no longer exists.  But it may also just mean
14248    the code changed a bit.  Maybe the user added a few lines of code
14249    that made the marker move up or down (in line number terms).  Ask
14250    the target for info about the marker with the string id as we knew
14251    it.  If found, update line number and address in the matching
14252    static tracepoint.  This will get confused if there's more than one
14253    marker with the same ID (possible in UST, although unadvised
14254    precisely because it confuses tools).  */
14255
14256 static struct symtab_and_line
14257 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14258 {
14259   struct tracepoint *tp = (struct tracepoint *) b;
14260   struct static_tracepoint_marker marker;
14261   CORE_ADDR pc;
14262
14263   pc = sal.pc;
14264   if (sal.line)
14265     find_line_pc (sal.symtab, sal.line, &pc);
14266
14267   if (target_static_tracepoint_marker_at (pc, &marker))
14268     {
14269       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14270         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14271                  b->number,
14272                  tp->static_trace_marker_id, marker.str_id);
14273
14274       xfree (tp->static_trace_marker_id);
14275       tp->static_trace_marker_id = xstrdup (marker.str_id);
14276       release_static_tracepoint_marker (&marker);
14277
14278       return sal;
14279     }
14280
14281   /* Old marker wasn't found on target at lineno.  Try looking it up
14282      by string ID.  */
14283   if (!sal.explicit_pc
14284       && sal.line != 0
14285       && sal.symtab != NULL
14286       && tp->static_trace_marker_id != NULL)
14287     {
14288       VEC(static_tracepoint_marker_p) *markers;
14289
14290       markers
14291         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14292
14293       if (!VEC_empty(static_tracepoint_marker_p, markers))
14294         {
14295           struct symtab_and_line sal2;
14296           struct symbol *sym;
14297           struct static_tracepoint_marker *tpmarker;
14298           struct ui_out *uiout = current_uiout;
14299
14300           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14301
14302           xfree (tp->static_trace_marker_id);
14303           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14304
14305           warning (_("marker for static tracepoint %d (%s) not "
14306                      "found at previous line number"),
14307                    b->number, tp->static_trace_marker_id);
14308
14309           init_sal (&sal2);
14310
14311           sal2.pc = tpmarker->address;
14312
14313           sal2 = find_pc_line (tpmarker->address, 0);
14314           sym = find_pc_sect_function (tpmarker->address, NULL);
14315           ui_out_text (uiout, "Now in ");
14316           if (sym)
14317             {
14318               ui_out_field_string (uiout, "func",
14319                                    SYMBOL_PRINT_NAME (sym));
14320               ui_out_text (uiout, " at ");
14321             }
14322           ui_out_field_string (uiout, "file",
14323                                symtab_to_filename_for_display (sal2.symtab));
14324           ui_out_text (uiout, ":");
14325
14326           if (ui_out_is_mi_like_p (uiout))
14327             {
14328               const char *fullname = symtab_to_fullname (sal2.symtab);
14329
14330               ui_out_field_string (uiout, "fullname", fullname);
14331             }
14332
14333           ui_out_field_int (uiout, "line", sal2.line);
14334           ui_out_text (uiout, "\n");
14335
14336           b->loc->line_number = sal2.line;
14337           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14338
14339           xfree (b->addr_string);
14340           b->addr_string = xstrprintf ("%s:%d",
14341                                    symtab_to_filename_for_display (sal2.symtab),
14342                                        b->loc->line_number);
14343
14344           /* Might be nice to check if function changed, and warn if
14345              so.  */
14346
14347           release_static_tracepoint_marker (tpmarker);
14348         }
14349     }
14350   return sal;
14351 }
14352
14353 /* Returns 1 iff locations A and B are sufficiently same that
14354    we don't need to report breakpoint as changed.  */
14355
14356 static int
14357 locations_are_equal (struct bp_location *a, struct bp_location *b)
14358 {
14359   while (a && b)
14360     {
14361       if (a->address != b->address)
14362         return 0;
14363
14364       if (a->shlib_disabled != b->shlib_disabled)
14365         return 0;
14366
14367       if (a->enabled != b->enabled)
14368         return 0;
14369
14370       a = a->next;
14371       b = b->next;
14372     }
14373
14374   if ((a == NULL) != (b == NULL))
14375     return 0;
14376
14377   return 1;
14378 }
14379
14380 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14381    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14382    a ranged breakpoint.  */
14383
14384 void
14385 update_breakpoint_locations (struct breakpoint *b,
14386                              struct symtabs_and_lines sals,
14387                              struct symtabs_and_lines sals_end)
14388 {
14389   int i;
14390   struct bp_location *existing_locations = b->loc;
14391
14392   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14393     {
14394       /* Ranged breakpoints have only one start location and one end
14395          location.  */
14396       b->enable_state = bp_disabled;
14397       update_global_location_list (UGLL_MAY_INSERT);
14398       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14399                            "multiple locations found\n"),
14400                          b->number);
14401       return;
14402     }
14403
14404   /* If there's no new locations, and all existing locations are
14405      pending, don't do anything.  This optimizes the common case where
14406      all locations are in the same shared library, that was unloaded.
14407      We'd like to retain the location, so that when the library is
14408      loaded again, we don't loose the enabled/disabled status of the
14409      individual locations.  */
14410   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14411     return;
14412
14413   b->loc = NULL;
14414
14415   for (i = 0; i < sals.nelts; ++i)
14416     {
14417       struct bp_location *new_loc;
14418
14419       switch_to_program_space_and_thread (sals.sals[i].pspace);
14420
14421       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14422
14423       /* Reparse conditions, they might contain references to the
14424          old symtab.  */
14425       if (b->cond_string != NULL)
14426         {
14427           const char *s;
14428           volatile struct gdb_exception e;
14429
14430           s = b->cond_string;
14431           TRY_CATCH (e, RETURN_MASK_ERROR)
14432             {
14433               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14434                                            block_for_pc (sals.sals[i].pc), 
14435                                            0);
14436             }
14437           if (e.reason < 0)
14438             {
14439               warning (_("failed to reevaluate condition "
14440                          "for breakpoint %d: %s"), 
14441                        b->number, e.message);
14442               new_loc->enabled = 0;
14443             }
14444         }
14445
14446       if (sals_end.nelts)
14447         {
14448           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14449
14450           new_loc->length = end - sals.sals[0].pc + 1;
14451         }
14452     }
14453
14454   /* If possible, carry over 'disable' status from existing
14455      breakpoints.  */
14456   {
14457     struct bp_location *e = existing_locations;
14458     /* If there are multiple breakpoints with the same function name,
14459        e.g. for inline functions, comparing function names won't work.
14460        Instead compare pc addresses; this is just a heuristic as things
14461        may have moved, but in practice it gives the correct answer
14462        often enough until a better solution is found.  */
14463     int have_ambiguous_names = ambiguous_names_p (b->loc);
14464
14465     for (; e; e = e->next)
14466       {
14467         if (!e->enabled && e->function_name)
14468           {
14469             struct bp_location *l = b->loc;
14470             if (have_ambiguous_names)
14471               {
14472                 for (; l; l = l->next)
14473                   if (breakpoint_locations_match (e, l))
14474                     {
14475                       l->enabled = 0;
14476                       break;
14477                     }
14478               }
14479             else
14480               {
14481                 for (; l; l = l->next)
14482                   if (l->function_name
14483                       && strcmp (e->function_name, l->function_name) == 0)
14484                     {
14485                       l->enabled = 0;
14486                       break;
14487                     }
14488               }
14489           }
14490       }
14491   }
14492
14493   if (!locations_are_equal (existing_locations, b->loc))
14494     observer_notify_breakpoint_modified (b);
14495
14496   update_global_location_list (UGLL_MAY_INSERT);
14497 }
14498
14499 /* Find the SaL locations corresponding to the given ADDR_STRING.
14500    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14501
14502 static struct symtabs_and_lines
14503 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14504 {
14505   char *s;
14506   struct symtabs_and_lines sals = {0};
14507   volatile struct gdb_exception e;
14508
14509   gdb_assert (b->ops != NULL);
14510   s = addr_string;
14511
14512   TRY_CATCH (e, RETURN_MASK_ERROR)
14513     {
14514       b->ops->decode_linespec (b, &s, &sals);
14515     }
14516   if (e.reason < 0)
14517     {
14518       int not_found_and_ok = 0;
14519       /* For pending breakpoints, it's expected that parsing will
14520          fail until the right shared library is loaded.  User has
14521          already told to create pending breakpoints and don't need
14522          extra messages.  If breakpoint is in bp_shlib_disabled
14523          state, then user already saw the message about that
14524          breakpoint being disabled, and don't want to see more
14525          errors.  */
14526       if (e.error == NOT_FOUND_ERROR
14527           && (b->condition_not_parsed 
14528               || (b->loc && b->loc->shlib_disabled)
14529               || (b->loc && b->loc->pspace->executing_startup)
14530               || b->enable_state == bp_disabled))
14531         not_found_and_ok = 1;
14532
14533       if (!not_found_and_ok)
14534         {
14535           /* We surely don't want to warn about the same breakpoint
14536              10 times.  One solution, implemented here, is disable
14537              the breakpoint on error.  Another solution would be to
14538              have separate 'warning emitted' flag.  Since this
14539              happens only when a binary has changed, I don't know
14540              which approach is better.  */
14541           b->enable_state = bp_disabled;
14542           throw_exception (e);
14543         }
14544     }
14545
14546   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14547     {
14548       int i;
14549
14550       for (i = 0; i < sals.nelts; ++i)
14551         resolve_sal_pc (&sals.sals[i]);
14552       if (b->condition_not_parsed && s && s[0])
14553         {
14554           char *cond_string, *extra_string;
14555           int thread, task;
14556
14557           find_condition_and_thread (s, sals.sals[0].pc,
14558                                      &cond_string, &thread, &task,
14559                                      &extra_string);
14560           if (cond_string)
14561             b->cond_string = cond_string;
14562           b->thread = thread;
14563           b->task = task;
14564           if (extra_string)
14565             b->extra_string = extra_string;
14566           b->condition_not_parsed = 0;
14567         }
14568
14569       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14570         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14571
14572       *found = 1;
14573     }
14574   else
14575     *found = 0;
14576
14577   return sals;
14578 }
14579
14580 /* The default re_set method, for typical hardware or software
14581    breakpoints.  Reevaluate the breakpoint and recreate its
14582    locations.  */
14583
14584 static void
14585 breakpoint_re_set_default (struct breakpoint *b)
14586 {
14587   int found;
14588   struct symtabs_and_lines sals, sals_end;
14589   struct symtabs_and_lines expanded = {0};
14590   struct symtabs_and_lines expanded_end = {0};
14591
14592   sals = addr_string_to_sals (b, b->addr_string, &found);
14593   if (found)
14594     {
14595       make_cleanup (xfree, sals.sals);
14596       expanded = sals;
14597     }
14598
14599   if (b->addr_string_range_end)
14600     {
14601       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14602       if (found)
14603         {
14604           make_cleanup (xfree, sals_end.sals);
14605           expanded_end = sals_end;
14606         }
14607     }
14608
14609   update_breakpoint_locations (b, expanded, expanded_end);
14610 }
14611
14612 /* Default method for creating SALs from an address string.  It basically
14613    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14614
14615 static void
14616 create_sals_from_address_default (char **arg,
14617                                   struct linespec_result *canonical,
14618                                   enum bptype type_wanted,
14619                                   char *addr_start, char **copy_arg)
14620 {
14621   parse_breakpoint_sals (arg, canonical);
14622 }
14623
14624 /* Call create_breakpoints_sal for the given arguments.  This is the default
14625    function for the `create_breakpoints_sal' method of
14626    breakpoint_ops.  */
14627
14628 static void
14629 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14630                                 struct linespec_result *canonical,
14631                                 char *cond_string,
14632                                 char *extra_string,
14633                                 enum bptype type_wanted,
14634                                 enum bpdisp disposition,
14635                                 int thread,
14636                                 int task, int ignore_count,
14637                                 const struct breakpoint_ops *ops,
14638                                 int from_tty, int enabled,
14639                                 int internal, unsigned flags)
14640 {
14641   create_breakpoints_sal (gdbarch, canonical, cond_string,
14642                           extra_string,
14643                           type_wanted, disposition,
14644                           thread, task, ignore_count, ops, from_tty,
14645                           enabled, internal, flags);
14646 }
14647
14648 /* Decode the line represented by S by calling decode_line_full.  This is the
14649    default function for the `decode_linespec' method of breakpoint_ops.  */
14650
14651 static void
14652 decode_linespec_default (struct breakpoint *b, char **s,
14653                          struct symtabs_and_lines *sals)
14654 {
14655   struct linespec_result canonical;
14656
14657   init_linespec_result (&canonical);
14658   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14659                     (struct symtab *) NULL, 0,
14660                     &canonical, multiple_symbols_all,
14661                     b->filter);
14662
14663   /* We should get 0 or 1 resulting SALs.  */
14664   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14665
14666   if (VEC_length (linespec_sals, canonical.sals) > 0)
14667     {
14668       struct linespec_sals *lsal;
14669
14670       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14671       *sals = lsal->sals;
14672       /* Arrange it so the destructor does not free the
14673          contents.  */
14674       lsal->sals.sals = NULL;
14675     }
14676
14677   destroy_linespec_result (&canonical);
14678 }
14679
14680 /* Prepare the global context for a re-set of breakpoint B.  */
14681
14682 static struct cleanup *
14683 prepare_re_set_context (struct breakpoint *b)
14684 {
14685   struct cleanup *cleanups;
14686
14687   input_radix = b->input_radix;
14688   cleanups = save_current_space_and_thread ();
14689   if (b->pspace != NULL)
14690     switch_to_program_space_and_thread (b->pspace);
14691   set_language (b->language);
14692
14693   return cleanups;
14694 }
14695
14696 /* Reset a breakpoint given it's struct breakpoint * BINT.
14697    The value we return ends up being the return value from catch_errors.
14698    Unused in this case.  */
14699
14700 static int
14701 breakpoint_re_set_one (void *bint)
14702 {
14703   /* Get past catch_errs.  */
14704   struct breakpoint *b = (struct breakpoint *) bint;
14705   struct cleanup *cleanups;
14706
14707   cleanups = prepare_re_set_context (b);
14708   b->ops->re_set (b);
14709   do_cleanups (cleanups);
14710   return 0;
14711 }
14712
14713 /* Re-set all breakpoints after symbols have been re-loaded.  */
14714 void
14715 breakpoint_re_set (void)
14716 {
14717   struct breakpoint *b, *b_tmp;
14718   enum language save_language;
14719   int save_input_radix;
14720   struct cleanup *old_chain;
14721
14722   save_language = current_language->la_language;
14723   save_input_radix = input_radix;
14724   old_chain = save_current_program_space ();
14725
14726   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14727   {
14728     /* Format possible error msg.  */
14729     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14730                                 b->number);
14731     struct cleanup *cleanups = make_cleanup (xfree, message);
14732     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14733     do_cleanups (cleanups);
14734   }
14735   set_language (save_language);
14736   input_radix = save_input_radix;
14737
14738   jit_breakpoint_re_set ();
14739
14740   do_cleanups (old_chain);
14741
14742   create_overlay_event_breakpoint ();
14743   create_longjmp_master_breakpoint ();
14744   create_std_terminate_master_breakpoint ();
14745   create_exception_master_breakpoint ();
14746 }
14747 \f
14748 /* Reset the thread number of this breakpoint:
14749
14750    - If the breakpoint is for all threads, leave it as-is.
14751    - Else, reset it to the current thread for inferior_ptid.  */
14752 void
14753 breakpoint_re_set_thread (struct breakpoint *b)
14754 {
14755   if (b->thread != -1)
14756     {
14757       if (in_thread_list (inferior_ptid))
14758         b->thread = pid_to_thread_id (inferior_ptid);
14759
14760       /* We're being called after following a fork.  The new fork is
14761          selected as current, and unless this was a vfork will have a
14762          different program space from the original thread.  Reset that
14763          as well.  */
14764       b->loc->pspace = current_program_space;
14765     }
14766 }
14767
14768 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14769    If from_tty is nonzero, it prints a message to that effect,
14770    which ends with a period (no newline).  */
14771
14772 void
14773 set_ignore_count (int bptnum, int count, int from_tty)
14774 {
14775   struct breakpoint *b;
14776
14777   if (count < 0)
14778     count = 0;
14779
14780   ALL_BREAKPOINTS (b)
14781     if (b->number == bptnum)
14782     {
14783       if (is_tracepoint (b))
14784         {
14785           if (from_tty && count != 0)
14786             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14787                              bptnum);
14788           return;
14789         }
14790       
14791       b->ignore_count = count;
14792       if (from_tty)
14793         {
14794           if (count == 0)
14795             printf_filtered (_("Will stop next time "
14796                                "breakpoint %d is reached."),
14797                              bptnum);
14798           else if (count == 1)
14799             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14800                              bptnum);
14801           else
14802             printf_filtered (_("Will ignore next %d "
14803                                "crossings of breakpoint %d."),
14804                              count, bptnum);
14805         }
14806       observer_notify_breakpoint_modified (b);
14807       return;
14808     }
14809
14810   error (_("No breakpoint number %d."), bptnum);
14811 }
14812
14813 /* Command to set ignore-count of breakpoint N to COUNT.  */
14814
14815 static void
14816 ignore_command (char *args, int from_tty)
14817 {
14818   char *p = args;
14819   int num;
14820
14821   if (p == 0)
14822     error_no_arg (_("a breakpoint number"));
14823
14824   num = get_number (&p);
14825   if (num == 0)
14826     error (_("bad breakpoint number: '%s'"), args);
14827   if (*p == 0)
14828     error (_("Second argument (specified ignore-count) is missing."));
14829
14830   set_ignore_count (num,
14831                     longest_to_int (value_as_long (parse_and_eval (p))),
14832                     from_tty);
14833   if (from_tty)
14834     printf_filtered ("\n");
14835 }
14836 \f
14837 /* Call FUNCTION on each of the breakpoints
14838    whose numbers are given in ARGS.  */
14839
14840 static void
14841 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14842                                                       void *),
14843                         void *data)
14844 {
14845   int num;
14846   struct breakpoint *b, *tmp;
14847   int match;
14848   struct get_number_or_range_state state;
14849
14850   if (args == 0)
14851     error_no_arg (_("one or more breakpoint numbers"));
14852
14853   init_number_or_range (&state, args);
14854
14855   while (!state.finished)
14856     {
14857       const char *p = state.string;
14858
14859       match = 0;
14860
14861       num = get_number_or_range (&state);
14862       if (num == 0)
14863         {
14864           warning (_("bad breakpoint number at or near '%s'"), p);
14865         }
14866       else
14867         {
14868           ALL_BREAKPOINTS_SAFE (b, tmp)
14869             if (b->number == num)
14870               {
14871                 match = 1;
14872                 function (b, data);
14873                 break;
14874               }
14875           if (match == 0)
14876             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14877         }
14878     }
14879 }
14880
14881 static struct bp_location *
14882 find_location_by_number (char *number)
14883 {
14884   char *dot = strchr (number, '.');
14885   char *p1;
14886   int bp_num;
14887   int loc_num;
14888   struct breakpoint *b;
14889   struct bp_location *loc;  
14890
14891   *dot = '\0';
14892
14893   p1 = number;
14894   bp_num = get_number (&p1);
14895   if (bp_num == 0)
14896     error (_("Bad breakpoint number '%s'"), number);
14897
14898   ALL_BREAKPOINTS (b)
14899     if (b->number == bp_num)
14900       {
14901         break;
14902       }
14903
14904   if (!b || b->number != bp_num)
14905     error (_("Bad breakpoint number '%s'"), number);
14906   
14907   p1 = dot+1;
14908   loc_num = get_number (&p1);
14909   if (loc_num == 0)
14910     error (_("Bad breakpoint location number '%s'"), number);
14911
14912   --loc_num;
14913   loc = b->loc;
14914   for (;loc_num && loc; --loc_num, loc = loc->next)
14915     ;
14916   if (!loc)
14917     error (_("Bad breakpoint location number '%s'"), dot+1);
14918     
14919   return loc;  
14920 }
14921
14922
14923 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14924    If from_tty is nonzero, it prints a message to that effect,
14925    which ends with a period (no newline).  */
14926
14927 void
14928 disable_breakpoint (struct breakpoint *bpt)
14929 {
14930   /* Never disable a watchpoint scope breakpoint; we want to
14931      hit them when we leave scope so we can delete both the
14932      watchpoint and its scope breakpoint at that time.  */
14933   if (bpt->type == bp_watchpoint_scope)
14934     return;
14935
14936   bpt->enable_state = bp_disabled;
14937
14938   /* Mark breakpoint locations modified.  */
14939   mark_breakpoint_modified (bpt);
14940
14941   if (target_supports_enable_disable_tracepoint ()
14942       && current_trace_status ()->running && is_tracepoint (bpt))
14943     {
14944       struct bp_location *location;
14945      
14946       for (location = bpt->loc; location; location = location->next)
14947         target_disable_tracepoint (location);
14948     }
14949
14950   update_global_location_list (UGLL_DONT_INSERT);
14951
14952   observer_notify_breakpoint_modified (bpt);
14953 }
14954
14955 /* A callback for iterate_over_related_breakpoints.  */
14956
14957 static void
14958 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14959 {
14960   disable_breakpoint (b);
14961 }
14962
14963 /* A callback for map_breakpoint_numbers that calls
14964    disable_breakpoint.  */
14965
14966 static void
14967 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14968 {
14969   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14970 }
14971
14972 static void
14973 disable_command (char *args, int from_tty)
14974 {
14975   if (args == 0)
14976     {
14977       struct breakpoint *bpt;
14978
14979       ALL_BREAKPOINTS (bpt)
14980         if (user_breakpoint_p (bpt))
14981           disable_breakpoint (bpt);
14982     }
14983   else
14984     {
14985       char *num = extract_arg (&args);
14986
14987       while (num)
14988         {
14989           if (strchr (num, '.'))
14990             {
14991               struct bp_location *loc = find_location_by_number (num);
14992
14993               if (loc)
14994                 {
14995                   if (loc->enabled)
14996                     {
14997                       loc->enabled = 0;
14998                       mark_breakpoint_location_modified (loc);
14999                     }
15000                   if (target_supports_enable_disable_tracepoint ()
15001                       && current_trace_status ()->running && loc->owner
15002                       && is_tracepoint (loc->owner))
15003                     target_disable_tracepoint (loc);
15004                 }
15005               update_global_location_list (UGLL_DONT_INSERT);
15006             }
15007           else
15008             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
15009           num = extract_arg (&args);
15010         }
15011     }
15012 }
15013
15014 static void
15015 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
15016                         int count)
15017 {
15018   int target_resources_ok;
15019
15020   if (bpt->type == bp_hardware_breakpoint)
15021     {
15022       int i;
15023       i = hw_breakpoint_used_count ();
15024       target_resources_ok = 
15025         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
15026                                             i + 1, 0);
15027       if (target_resources_ok == 0)
15028         error (_("No hardware breakpoint support in the target."));
15029       else if (target_resources_ok < 0)
15030         error (_("Hardware breakpoints used exceeds limit."));
15031     }
15032
15033   if (is_watchpoint (bpt))
15034     {
15035       /* Initialize it just to avoid a GCC false warning.  */
15036       enum enable_state orig_enable_state = 0;
15037       volatile struct gdb_exception e;
15038
15039       TRY_CATCH (e, RETURN_MASK_ALL)
15040         {
15041           struct watchpoint *w = (struct watchpoint *) bpt;
15042
15043           orig_enable_state = bpt->enable_state;
15044           bpt->enable_state = bp_enabled;
15045           update_watchpoint (w, 1 /* reparse */);
15046         }
15047       if (e.reason < 0)
15048         {
15049           bpt->enable_state = orig_enable_state;
15050           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
15051                              bpt->number);
15052           return;
15053         }
15054     }
15055
15056   bpt->enable_state = bp_enabled;
15057
15058   /* Mark breakpoint locations modified.  */
15059   mark_breakpoint_modified (bpt);
15060
15061   if (target_supports_enable_disable_tracepoint ()
15062       && current_trace_status ()->running && is_tracepoint (bpt))
15063     {
15064       struct bp_location *location;
15065
15066       for (location = bpt->loc; location; location = location->next)
15067         target_enable_tracepoint (location);
15068     }
15069
15070   bpt->disposition = disposition;
15071   bpt->enable_count = count;
15072   update_global_location_list (UGLL_MAY_INSERT);
15073
15074   observer_notify_breakpoint_modified (bpt);
15075 }
15076
15077
15078 void
15079 enable_breakpoint (struct breakpoint *bpt)
15080 {
15081   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15082 }
15083
15084 static void
15085 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15086 {
15087   enable_breakpoint (bpt);
15088 }
15089
15090 /* A callback for map_breakpoint_numbers that calls
15091    enable_breakpoint.  */
15092
15093 static void
15094 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15095 {
15096   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15097 }
15098
15099 /* The enable command enables the specified breakpoints (or all defined
15100    breakpoints) so they once again become (or continue to be) effective
15101    in stopping the inferior.  */
15102
15103 static void
15104 enable_command (char *args, int from_tty)
15105 {
15106   if (args == 0)
15107     {
15108       struct breakpoint *bpt;
15109
15110       ALL_BREAKPOINTS (bpt)
15111         if (user_breakpoint_p (bpt))
15112           enable_breakpoint (bpt);
15113     }
15114   else
15115     {
15116       char *num = extract_arg (&args);
15117
15118       while (num)
15119         {
15120           if (strchr (num, '.'))
15121             {
15122               struct bp_location *loc = find_location_by_number (num);
15123
15124               if (loc)
15125                 {
15126                   if (!loc->enabled)
15127                     {
15128                       loc->enabled = 1;
15129                       mark_breakpoint_location_modified (loc);
15130                     }
15131                   if (target_supports_enable_disable_tracepoint ()
15132                       && current_trace_status ()->running && loc->owner
15133                       && is_tracepoint (loc->owner))
15134                     target_enable_tracepoint (loc);
15135                 }
15136               update_global_location_list (UGLL_MAY_INSERT);
15137             }
15138           else
15139             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15140           num = extract_arg (&args);
15141         }
15142     }
15143 }
15144
15145 /* This struct packages up disposition data for application to multiple
15146    breakpoints.  */
15147
15148 struct disp_data
15149 {
15150   enum bpdisp disp;
15151   int count;
15152 };
15153
15154 static void
15155 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15156 {
15157   struct disp_data disp_data = *(struct disp_data *) arg;
15158
15159   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15160 }
15161
15162 static void
15163 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15164 {
15165   struct disp_data disp = { disp_disable, 1 };
15166
15167   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15168 }
15169
15170 static void
15171 enable_once_command (char *args, int from_tty)
15172 {
15173   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15174 }
15175
15176 static void
15177 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15178 {
15179   struct disp_data disp = { disp_disable, *(int *) countptr };
15180
15181   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15182 }
15183
15184 static void
15185 enable_count_command (char *args, int from_tty)
15186 {
15187   int count = get_number (&args);
15188
15189   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15190 }
15191
15192 static void
15193 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15194 {
15195   struct disp_data disp = { disp_del, 1 };
15196
15197   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15198 }
15199
15200 static void
15201 enable_delete_command (char *args, int from_tty)
15202 {
15203   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15204 }
15205 \f
15206 static void
15207 set_breakpoint_cmd (char *args, int from_tty)
15208 {
15209 }
15210
15211 static void
15212 show_breakpoint_cmd (char *args, int from_tty)
15213 {
15214 }
15215
15216 /* Invalidate last known value of any hardware watchpoint if
15217    the memory which that value represents has been written to by
15218    GDB itself.  */
15219
15220 static void
15221 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15222                                       CORE_ADDR addr, ssize_t len,
15223                                       const bfd_byte *data)
15224 {
15225   struct breakpoint *bp;
15226
15227   ALL_BREAKPOINTS (bp)
15228     if (bp->enable_state == bp_enabled
15229         && bp->type == bp_hardware_watchpoint)
15230       {
15231         struct watchpoint *wp = (struct watchpoint *) bp;
15232
15233         if (wp->val_valid && wp->val)
15234           {
15235             struct bp_location *loc;
15236
15237             for (loc = bp->loc; loc != NULL; loc = loc->next)
15238               if (loc->loc_type == bp_loc_hardware_watchpoint
15239                   && loc->address + loc->length > addr
15240                   && addr + len > loc->address)
15241                 {
15242                   value_free (wp->val);
15243                   wp->val = NULL;
15244                   wp->val_valid = 0;
15245                 }
15246           }
15247       }
15248 }
15249
15250 /* Create and insert a breakpoint for software single step.  */
15251
15252 void
15253 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15254                                struct address_space *aspace, 
15255                                CORE_ADDR next_pc)
15256 {
15257   struct thread_info *tp = inferior_thread ();
15258   struct symtab_and_line sal;
15259   CORE_ADDR pc = next_pc;
15260
15261   if (tp->control.single_step_breakpoints == NULL)
15262     {
15263       tp->control.single_step_breakpoints
15264         = new_single_step_breakpoint (tp->num, gdbarch);
15265     }
15266
15267   sal = find_pc_line (pc, 0);
15268   sal.pc = pc;
15269   sal.section = find_pc_overlay (pc);
15270   sal.explicit_pc = 1;
15271   add_location_to_breakpoint (tp->control.single_step_breakpoints, &sal);
15272
15273   update_global_location_list (UGLL_INSERT);
15274 }
15275
15276 /* See breakpoint.h.  */
15277
15278 int
15279 breakpoint_has_location_inserted_here (struct breakpoint *bp,
15280                                        struct address_space *aspace,
15281                                        CORE_ADDR pc)
15282 {
15283   struct bp_location *loc;
15284
15285   for (loc = bp->loc; loc != NULL; loc = loc->next)
15286     if (loc->inserted
15287         && breakpoint_location_address_match (loc, aspace, pc))
15288       return 1;
15289
15290   return 0;
15291 }
15292
15293 /* Check whether a software single-step breakpoint is inserted at
15294    PC.  */
15295
15296 int
15297 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15298                                         CORE_ADDR pc)
15299 {
15300   struct breakpoint *bpt;
15301
15302   ALL_BREAKPOINTS (bpt)
15303     {
15304       if (bpt->type == bp_single_step
15305           && breakpoint_has_location_inserted_here (bpt, aspace, pc))
15306         return 1;
15307     }
15308   return 0;
15309 }
15310
15311 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15312    non-zero otherwise.  */
15313 static int
15314 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15315 {
15316   if (syscall_catchpoint_p (bp)
15317       && bp->enable_state != bp_disabled
15318       && bp->enable_state != bp_call_disabled)
15319     return 1;
15320   else
15321     return 0;
15322 }
15323
15324 int
15325 catch_syscall_enabled (void)
15326 {
15327   struct catch_syscall_inferior_data *inf_data
15328     = get_catch_syscall_inferior_data (current_inferior ());
15329
15330   return inf_data->total_syscalls_count != 0;
15331 }
15332
15333 int
15334 catching_syscall_number (int syscall_number)
15335 {
15336   struct breakpoint *bp;
15337
15338   ALL_BREAKPOINTS (bp)
15339     if (is_syscall_catchpoint_enabled (bp))
15340       {
15341         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15342
15343         if (c->syscalls_to_be_caught)
15344           {
15345             int i, iter;
15346             for (i = 0;
15347                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15348                  i++)
15349               if (syscall_number == iter)
15350                 return 1;
15351           }
15352         else
15353           return 1;
15354       }
15355
15356   return 0;
15357 }
15358
15359 /* Complete syscall names.  Used by "catch syscall".  */
15360 static VEC (char_ptr) *
15361 catch_syscall_completer (struct cmd_list_element *cmd,
15362                          const char *text, const char *word)
15363 {
15364   const char **list = get_syscall_names (get_current_arch ());
15365   VEC (char_ptr) *retlist
15366     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15367
15368   xfree (list);
15369   return retlist;
15370 }
15371
15372 /* Tracepoint-specific operations.  */
15373
15374 /* Set tracepoint count to NUM.  */
15375 static void
15376 set_tracepoint_count (int num)
15377 {
15378   tracepoint_count = num;
15379   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15380 }
15381
15382 static void
15383 trace_command (char *arg, int from_tty)
15384 {
15385   struct breakpoint_ops *ops;
15386   const char *arg_cp = arg;
15387
15388   if (arg && probe_linespec_to_ops (&arg_cp))
15389     ops = &tracepoint_probe_breakpoint_ops;
15390   else
15391     ops = &tracepoint_breakpoint_ops;
15392
15393   create_breakpoint (get_current_arch (),
15394                      arg,
15395                      NULL, 0, NULL, 1 /* parse arg */,
15396                      0 /* tempflag */,
15397                      bp_tracepoint /* type_wanted */,
15398                      0 /* Ignore count */,
15399                      pending_break_support,
15400                      ops,
15401                      from_tty,
15402                      1 /* enabled */,
15403                      0 /* internal */, 0);
15404 }
15405
15406 static void
15407 ftrace_command (char *arg, int from_tty)
15408 {
15409   create_breakpoint (get_current_arch (),
15410                      arg,
15411                      NULL, 0, NULL, 1 /* parse arg */,
15412                      0 /* tempflag */,
15413                      bp_fast_tracepoint /* type_wanted */,
15414                      0 /* Ignore count */,
15415                      pending_break_support,
15416                      &tracepoint_breakpoint_ops,
15417                      from_tty,
15418                      1 /* enabled */,
15419                      0 /* internal */, 0);
15420 }
15421
15422 /* strace command implementation.  Creates a static tracepoint.  */
15423
15424 static void
15425 strace_command (char *arg, int from_tty)
15426 {
15427   struct breakpoint_ops *ops;
15428
15429   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15430      or with a normal static tracepoint.  */
15431   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15432     ops = &strace_marker_breakpoint_ops;
15433   else
15434     ops = &tracepoint_breakpoint_ops;
15435
15436   create_breakpoint (get_current_arch (),
15437                      arg,
15438                      NULL, 0, NULL, 1 /* parse arg */,
15439                      0 /* tempflag */,
15440                      bp_static_tracepoint /* type_wanted */,
15441                      0 /* Ignore count */,
15442                      pending_break_support,
15443                      ops,
15444                      from_tty,
15445                      1 /* enabled */,
15446                      0 /* internal */, 0);
15447 }
15448
15449 /* Set up a fake reader function that gets command lines from a linked
15450    list that was acquired during tracepoint uploading.  */
15451
15452 static struct uploaded_tp *this_utp;
15453 static int next_cmd;
15454
15455 static char *
15456 read_uploaded_action (void)
15457 {
15458   char *rslt;
15459
15460   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15461
15462   next_cmd++;
15463
15464   return rslt;
15465 }
15466
15467 /* Given information about a tracepoint as recorded on a target (which
15468    can be either a live system or a trace file), attempt to create an
15469    equivalent GDB tracepoint.  This is not a reliable process, since
15470    the target does not necessarily have all the information used when
15471    the tracepoint was originally defined.  */
15472   
15473 struct tracepoint *
15474 create_tracepoint_from_upload (struct uploaded_tp *utp)
15475 {
15476   char *addr_str, small_buf[100];
15477   struct tracepoint *tp;
15478
15479   if (utp->at_string)
15480     addr_str = utp->at_string;
15481   else
15482     {
15483       /* In the absence of a source location, fall back to raw
15484          address.  Since there is no way to confirm that the address
15485          means the same thing as when the trace was started, warn the
15486          user.  */
15487       warning (_("Uploaded tracepoint %d has no "
15488                  "source location, using raw address"),
15489                utp->number);
15490       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15491       addr_str = small_buf;
15492     }
15493
15494   /* There's not much we can do with a sequence of bytecodes.  */
15495   if (utp->cond && !utp->cond_string)
15496     warning (_("Uploaded tracepoint %d condition "
15497                "has no source form, ignoring it"),
15498              utp->number);
15499
15500   if (!create_breakpoint (get_current_arch (),
15501                           addr_str,
15502                           utp->cond_string, -1, NULL,
15503                           0 /* parse cond/thread */,
15504                           0 /* tempflag */,
15505                           utp->type /* type_wanted */,
15506                           0 /* Ignore count */,
15507                           pending_break_support,
15508                           &tracepoint_breakpoint_ops,
15509                           0 /* from_tty */,
15510                           utp->enabled /* enabled */,
15511                           0 /* internal */,
15512                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15513     return NULL;
15514
15515   /* Get the tracepoint we just created.  */
15516   tp = get_tracepoint (tracepoint_count);
15517   gdb_assert (tp != NULL);
15518
15519   if (utp->pass > 0)
15520     {
15521       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15522                  tp->base.number);
15523
15524       trace_pass_command (small_buf, 0);
15525     }
15526
15527   /* If we have uploaded versions of the original commands, set up a
15528      special-purpose "reader" function and call the usual command line
15529      reader, then pass the result to the breakpoint command-setting
15530      function.  */
15531   if (!VEC_empty (char_ptr, utp->cmd_strings))
15532     {
15533       struct command_line *cmd_list;
15534
15535       this_utp = utp;
15536       next_cmd = 0;
15537
15538       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15539
15540       breakpoint_set_commands (&tp->base, cmd_list);
15541     }
15542   else if (!VEC_empty (char_ptr, utp->actions)
15543            || !VEC_empty (char_ptr, utp->step_actions))
15544     warning (_("Uploaded tracepoint %d actions "
15545                "have no source form, ignoring them"),
15546              utp->number);
15547
15548   /* Copy any status information that might be available.  */
15549   tp->base.hit_count = utp->hit_count;
15550   tp->traceframe_usage = utp->traceframe_usage;
15551
15552   return tp;
15553 }
15554   
15555 /* Print information on tracepoint number TPNUM_EXP, or all if
15556    omitted.  */
15557
15558 static void
15559 tracepoints_info (char *args, int from_tty)
15560 {
15561   struct ui_out *uiout = current_uiout;
15562   int num_printed;
15563
15564   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15565
15566   if (num_printed == 0)
15567     {
15568       if (args == NULL || *args == '\0')
15569         ui_out_message (uiout, 0, "No tracepoints.\n");
15570       else
15571         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15572     }
15573
15574   default_collect_info ();
15575 }
15576
15577 /* The 'enable trace' command enables tracepoints.
15578    Not supported by all targets.  */
15579 static void
15580 enable_trace_command (char *args, int from_tty)
15581 {
15582   enable_command (args, from_tty);
15583 }
15584
15585 /* The 'disable trace' command disables tracepoints.
15586    Not supported by all targets.  */
15587 static void
15588 disable_trace_command (char *args, int from_tty)
15589 {
15590   disable_command (args, from_tty);
15591 }
15592
15593 /* Remove a tracepoint (or all if no argument).  */
15594 static void
15595 delete_trace_command (char *arg, int from_tty)
15596 {
15597   struct breakpoint *b, *b_tmp;
15598
15599   dont_repeat ();
15600
15601   if (arg == 0)
15602     {
15603       int breaks_to_delete = 0;
15604
15605       /* Delete all breakpoints if no argument.
15606          Do not delete internal or call-dummy breakpoints, these
15607          have to be deleted with an explicit breakpoint number 
15608          argument.  */
15609       ALL_TRACEPOINTS (b)
15610         if (is_tracepoint (b) && user_breakpoint_p (b))
15611           {
15612             breaks_to_delete = 1;
15613             break;
15614           }
15615
15616       /* Ask user only if there are some breakpoints to delete.  */
15617       if (!from_tty
15618           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15619         {
15620           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15621             if (is_tracepoint (b) && user_breakpoint_p (b))
15622               delete_breakpoint (b);
15623         }
15624     }
15625   else
15626     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15627 }
15628
15629 /* Helper function for trace_pass_command.  */
15630
15631 static void
15632 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15633 {
15634   tp->pass_count = count;
15635   observer_notify_breakpoint_modified (&tp->base);
15636   if (from_tty)
15637     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15638                      tp->base.number, count);
15639 }
15640
15641 /* Set passcount for tracepoint.
15642
15643    First command argument is passcount, second is tracepoint number.
15644    If tracepoint number omitted, apply to most recently defined.
15645    Also accepts special argument "all".  */
15646
15647 static void
15648 trace_pass_command (char *args, int from_tty)
15649 {
15650   struct tracepoint *t1;
15651   unsigned int count;
15652
15653   if (args == 0 || *args == 0)
15654     error (_("passcount command requires an "
15655              "argument (count + optional TP num)"));
15656
15657   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15658
15659   args = skip_spaces (args);
15660   if (*args && strncasecmp (args, "all", 3) == 0)
15661     {
15662       struct breakpoint *b;
15663
15664       args += 3;                        /* Skip special argument "all".  */
15665       if (*args)
15666         error (_("Junk at end of arguments."));
15667
15668       ALL_TRACEPOINTS (b)
15669       {
15670         t1 = (struct tracepoint *) b;
15671         trace_pass_set_count (t1, count, from_tty);
15672       }
15673     }
15674   else if (*args == '\0')
15675     {
15676       t1 = get_tracepoint_by_number (&args, NULL);
15677       if (t1)
15678         trace_pass_set_count (t1, count, from_tty);
15679     }
15680   else
15681     {
15682       struct get_number_or_range_state state;
15683
15684       init_number_or_range (&state, args);
15685       while (!state.finished)
15686         {
15687           t1 = get_tracepoint_by_number (&args, &state);
15688           if (t1)
15689             trace_pass_set_count (t1, count, from_tty);
15690         }
15691     }
15692 }
15693
15694 struct tracepoint *
15695 get_tracepoint (int num)
15696 {
15697   struct breakpoint *t;
15698
15699   ALL_TRACEPOINTS (t)
15700     if (t->number == num)
15701       return (struct tracepoint *) t;
15702
15703   return NULL;
15704 }
15705
15706 /* Find the tracepoint with the given target-side number (which may be
15707    different from the tracepoint number after disconnecting and
15708    reconnecting).  */
15709
15710 struct tracepoint *
15711 get_tracepoint_by_number_on_target (int num)
15712 {
15713   struct breakpoint *b;
15714
15715   ALL_TRACEPOINTS (b)
15716     {
15717       struct tracepoint *t = (struct tracepoint *) b;
15718
15719       if (t->number_on_target == num)
15720         return t;
15721     }
15722
15723   return NULL;
15724 }
15725
15726 /* Utility: parse a tracepoint number and look it up in the list.
15727    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15728    If the argument is missing, the most recent tracepoint
15729    (tracepoint_count) is returned.  */
15730
15731 struct tracepoint *
15732 get_tracepoint_by_number (char **arg,
15733                           struct get_number_or_range_state *state)
15734 {
15735   struct breakpoint *t;
15736   int tpnum;
15737   char *instring = arg == NULL ? NULL : *arg;
15738
15739   if (state)
15740     {
15741       gdb_assert (!state->finished);
15742       tpnum = get_number_or_range (state);
15743     }
15744   else if (arg == NULL || *arg == NULL || ! **arg)
15745     tpnum = tracepoint_count;
15746   else
15747     tpnum = get_number (arg);
15748
15749   if (tpnum <= 0)
15750     {
15751       if (instring && *instring)
15752         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15753                          instring);
15754       else
15755         printf_filtered (_("No previous tracepoint\n"));
15756       return NULL;
15757     }
15758
15759   ALL_TRACEPOINTS (t)
15760     if (t->number == tpnum)
15761     {
15762       return (struct tracepoint *) t;
15763     }
15764
15765   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15766   return NULL;
15767 }
15768
15769 void
15770 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15771 {
15772   if (b->thread != -1)
15773     fprintf_unfiltered (fp, " thread %d", b->thread);
15774
15775   if (b->task != 0)
15776     fprintf_unfiltered (fp, " task %d", b->task);
15777
15778   fprintf_unfiltered (fp, "\n");
15779 }
15780
15781 /* Save information on user settable breakpoints (watchpoints, etc) to
15782    a new script file named FILENAME.  If FILTER is non-NULL, call it
15783    on each breakpoint and only include the ones for which it returns
15784    non-zero.  */
15785
15786 static void
15787 save_breakpoints (char *filename, int from_tty,
15788                   int (*filter) (const struct breakpoint *))
15789 {
15790   struct breakpoint *tp;
15791   int any = 0;
15792   struct cleanup *cleanup;
15793   struct ui_file *fp;
15794   int extra_trace_bits = 0;
15795
15796   if (filename == 0 || *filename == 0)
15797     error (_("Argument required (file name in which to save)"));
15798
15799   /* See if we have anything to save.  */
15800   ALL_BREAKPOINTS (tp)
15801   {
15802     /* Skip internal and momentary breakpoints.  */
15803     if (!user_breakpoint_p (tp))
15804       continue;
15805
15806     /* If we have a filter, only save the breakpoints it accepts.  */
15807     if (filter && !filter (tp))
15808       continue;
15809
15810     any = 1;
15811
15812     if (is_tracepoint (tp))
15813       {
15814         extra_trace_bits = 1;
15815
15816         /* We can stop searching.  */
15817         break;
15818       }
15819   }
15820
15821   if (!any)
15822     {
15823       warning (_("Nothing to save."));
15824       return;
15825     }
15826
15827   filename = tilde_expand (filename);
15828   cleanup = make_cleanup (xfree, filename);
15829   fp = gdb_fopen (filename, "w");
15830   if (!fp)
15831     error (_("Unable to open file '%s' for saving (%s)"),
15832            filename, safe_strerror (errno));
15833   make_cleanup_ui_file_delete (fp);
15834
15835   if (extra_trace_bits)
15836     save_trace_state_variables (fp);
15837
15838   ALL_BREAKPOINTS (tp)
15839   {
15840     /* Skip internal and momentary breakpoints.  */
15841     if (!user_breakpoint_p (tp))
15842       continue;
15843
15844     /* If we have a filter, only save the breakpoints it accepts.  */
15845     if (filter && !filter (tp))
15846       continue;
15847
15848     tp->ops->print_recreate (tp, fp);
15849
15850     /* Note, we can't rely on tp->number for anything, as we can't
15851        assume the recreated breakpoint numbers will match.  Use $bpnum
15852        instead.  */
15853
15854     if (tp->cond_string)
15855       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15856
15857     if (tp->ignore_count)
15858       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15859
15860     if (tp->type != bp_dprintf && tp->commands)
15861       {
15862         volatile struct gdb_exception ex;       
15863
15864         fprintf_unfiltered (fp, "  commands\n");
15865         
15866         ui_out_redirect (current_uiout, fp);
15867         TRY_CATCH (ex, RETURN_MASK_ALL)
15868           {
15869             print_command_lines (current_uiout, tp->commands->commands, 2);
15870           }
15871         ui_out_redirect (current_uiout, NULL);
15872
15873         if (ex.reason < 0)
15874           throw_exception (ex);
15875
15876         fprintf_unfiltered (fp, "  end\n");
15877       }
15878
15879     if (tp->enable_state == bp_disabled)
15880       fprintf_unfiltered (fp, "disable $bpnum\n");
15881
15882     /* If this is a multi-location breakpoint, check if the locations
15883        should be individually disabled.  Watchpoint locations are
15884        special, and not user visible.  */
15885     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15886       {
15887         struct bp_location *loc;
15888         int n = 1;
15889
15890         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15891           if (!loc->enabled)
15892             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15893       }
15894   }
15895
15896   if (extra_trace_bits && *default_collect)
15897     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15898
15899   if (from_tty)
15900     printf_filtered (_("Saved to file '%s'.\n"), filename);
15901   do_cleanups (cleanup);
15902 }
15903
15904 /* The `save breakpoints' command.  */
15905
15906 static void
15907 save_breakpoints_command (char *args, int from_tty)
15908 {
15909   save_breakpoints (args, from_tty, NULL);
15910 }
15911
15912 /* The `save tracepoints' command.  */
15913
15914 static void
15915 save_tracepoints_command (char *args, int from_tty)
15916 {
15917   save_breakpoints (args, from_tty, is_tracepoint);
15918 }
15919
15920 /* Create a vector of all tracepoints.  */
15921
15922 VEC(breakpoint_p) *
15923 all_tracepoints (void)
15924 {
15925   VEC(breakpoint_p) *tp_vec = 0;
15926   struct breakpoint *tp;
15927
15928   ALL_TRACEPOINTS (tp)
15929   {
15930     VEC_safe_push (breakpoint_p, tp_vec, tp);
15931   }
15932
15933   return tp_vec;
15934 }
15935
15936 \f
15937 /* This help string is used for the break, hbreak, tbreak and thbreak
15938    commands.  It is defined as a macro to prevent duplication.
15939    COMMAND should be a string constant containing the name of the
15940    command.  */
15941 #define BREAK_ARGS_HELP(command) \
15942 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15943 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15944 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15945 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15946 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15947 If a line number is specified, break at start of code for that line.\n\
15948 If a function is specified, break at start of code for that function.\n\
15949 If an address is specified, break at that exact address.\n\
15950 With no LOCATION, uses current execution address of the selected\n\
15951 stack frame.  This is useful for breaking on return to a stack frame.\n\
15952 \n\
15953 THREADNUM is the number from \"info threads\".\n\
15954 CONDITION is a boolean expression.\n\
15955 \n\
15956 Multiple breakpoints at one place are permitted, and useful if their\n\
15957 conditions are different.\n\
15958 \n\
15959 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15960
15961 /* List of subcommands for "catch".  */
15962 static struct cmd_list_element *catch_cmdlist;
15963
15964 /* List of subcommands for "tcatch".  */
15965 static struct cmd_list_element *tcatch_cmdlist;
15966
15967 void
15968 add_catch_command (char *name, char *docstring,
15969                    cmd_sfunc_ftype *sfunc,
15970                    completer_ftype *completer,
15971                    void *user_data_catch,
15972                    void *user_data_tcatch)
15973 {
15974   struct cmd_list_element *command;
15975
15976   command = add_cmd (name, class_breakpoint, NULL, docstring,
15977                      &catch_cmdlist);
15978   set_cmd_sfunc (command, sfunc);
15979   set_cmd_context (command, user_data_catch);
15980   set_cmd_completer (command, completer);
15981
15982   command = add_cmd (name, class_breakpoint, NULL, docstring,
15983                      &tcatch_cmdlist);
15984   set_cmd_sfunc (command, sfunc);
15985   set_cmd_context (command, user_data_tcatch);
15986   set_cmd_completer (command, completer);
15987 }
15988
15989 static void
15990 clear_syscall_counts (struct inferior *inf)
15991 {
15992   struct catch_syscall_inferior_data *inf_data
15993     = get_catch_syscall_inferior_data (inf);
15994
15995   inf_data->total_syscalls_count = 0;
15996   inf_data->any_syscall_count = 0;
15997   VEC_free (int, inf_data->syscalls_counts);
15998 }
15999
16000 static void
16001 save_command (char *arg, int from_tty)
16002 {
16003   printf_unfiltered (_("\"save\" must be followed by "
16004                        "the name of a save subcommand.\n"));
16005   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16006 }
16007
16008 struct breakpoint *
16009 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16010                           void *data)
16011 {
16012   struct breakpoint *b, *b_tmp;
16013
16014   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16015     {
16016       if ((*callback) (b, data))
16017         return b;
16018     }
16019
16020   return NULL;
16021 }
16022
16023 /* Zero if any of the breakpoint's locations could be a location where
16024    functions have been inlined, nonzero otherwise.  */
16025
16026 static int
16027 is_non_inline_function (struct breakpoint *b)
16028 {
16029   /* The shared library event breakpoint is set on the address of a
16030      non-inline function.  */
16031   if (b->type == bp_shlib_event)
16032     return 1;
16033
16034   return 0;
16035 }
16036
16037 /* Nonzero if the specified PC cannot be a location where functions
16038    have been inlined.  */
16039
16040 int
16041 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16042                            const struct target_waitstatus *ws)
16043 {
16044   struct breakpoint *b;
16045   struct bp_location *bl;
16046
16047   ALL_BREAKPOINTS (b)
16048     {
16049       if (!is_non_inline_function (b))
16050         continue;
16051
16052       for (bl = b->loc; bl != NULL; bl = bl->next)
16053         {
16054           if (!bl->shlib_disabled
16055               && bpstat_check_location (bl, aspace, pc, ws))
16056             return 1;
16057         }
16058     }
16059
16060   return 0;
16061 }
16062
16063 /* Remove any references to OBJFILE which is going to be freed.  */
16064
16065 void
16066 breakpoint_free_objfile (struct objfile *objfile)
16067 {
16068   struct bp_location **locp, *loc;
16069
16070   ALL_BP_LOCATIONS (loc, locp)
16071     if (loc->symtab != NULL && SYMTAB_OBJFILE (loc->symtab) == objfile)
16072       loc->symtab = NULL;
16073 }
16074
16075 void
16076 initialize_breakpoint_ops (void)
16077 {
16078   static int initialized = 0;
16079
16080   struct breakpoint_ops *ops;
16081
16082   if (initialized)
16083     return;
16084   initialized = 1;
16085
16086   /* The breakpoint_ops structure to be inherit by all kinds of
16087      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16088      internal and momentary breakpoints, etc.).  */
16089   ops = &bkpt_base_breakpoint_ops;
16090   *ops = base_breakpoint_ops;
16091   ops->re_set = bkpt_re_set;
16092   ops->insert_location = bkpt_insert_location;
16093   ops->remove_location = bkpt_remove_location;
16094   ops->breakpoint_hit = bkpt_breakpoint_hit;
16095   ops->create_sals_from_address = bkpt_create_sals_from_address;
16096   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16097   ops->decode_linespec = bkpt_decode_linespec;
16098
16099   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16100   ops = &bkpt_breakpoint_ops;
16101   *ops = bkpt_base_breakpoint_ops;
16102   ops->re_set = bkpt_re_set;
16103   ops->resources_needed = bkpt_resources_needed;
16104   ops->print_it = bkpt_print_it;
16105   ops->print_mention = bkpt_print_mention;
16106   ops->print_recreate = bkpt_print_recreate;
16107
16108   /* Ranged breakpoints.  */
16109   ops = &ranged_breakpoint_ops;
16110   *ops = bkpt_breakpoint_ops;
16111   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16112   ops->resources_needed = resources_needed_ranged_breakpoint;
16113   ops->print_it = print_it_ranged_breakpoint;
16114   ops->print_one = print_one_ranged_breakpoint;
16115   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16116   ops->print_mention = print_mention_ranged_breakpoint;
16117   ops->print_recreate = print_recreate_ranged_breakpoint;
16118
16119   /* Internal breakpoints.  */
16120   ops = &internal_breakpoint_ops;
16121   *ops = bkpt_base_breakpoint_ops;
16122   ops->re_set = internal_bkpt_re_set;
16123   ops->check_status = internal_bkpt_check_status;
16124   ops->print_it = internal_bkpt_print_it;
16125   ops->print_mention = internal_bkpt_print_mention;
16126
16127   /* Momentary breakpoints.  */
16128   ops = &momentary_breakpoint_ops;
16129   *ops = bkpt_base_breakpoint_ops;
16130   ops->re_set = momentary_bkpt_re_set;
16131   ops->check_status = momentary_bkpt_check_status;
16132   ops->print_it = momentary_bkpt_print_it;
16133   ops->print_mention = momentary_bkpt_print_mention;
16134
16135   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16136   ops = &longjmp_breakpoint_ops;
16137   *ops = momentary_breakpoint_ops;
16138   ops->dtor = longjmp_bkpt_dtor;
16139
16140   /* Probe breakpoints.  */
16141   ops = &bkpt_probe_breakpoint_ops;
16142   *ops = bkpt_breakpoint_ops;
16143   ops->insert_location = bkpt_probe_insert_location;
16144   ops->remove_location = bkpt_probe_remove_location;
16145   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16146   ops->decode_linespec = bkpt_probe_decode_linespec;
16147
16148   /* Watchpoints.  */
16149   ops = &watchpoint_breakpoint_ops;
16150   *ops = base_breakpoint_ops;
16151   ops->dtor = dtor_watchpoint;
16152   ops->re_set = re_set_watchpoint;
16153   ops->insert_location = insert_watchpoint;
16154   ops->remove_location = remove_watchpoint;
16155   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16156   ops->check_status = check_status_watchpoint;
16157   ops->resources_needed = resources_needed_watchpoint;
16158   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16159   ops->print_it = print_it_watchpoint;
16160   ops->print_mention = print_mention_watchpoint;
16161   ops->print_recreate = print_recreate_watchpoint;
16162   ops->explains_signal = explains_signal_watchpoint;
16163
16164   /* Masked watchpoints.  */
16165   ops = &masked_watchpoint_breakpoint_ops;
16166   *ops = watchpoint_breakpoint_ops;
16167   ops->insert_location = insert_masked_watchpoint;
16168   ops->remove_location = remove_masked_watchpoint;
16169   ops->resources_needed = resources_needed_masked_watchpoint;
16170   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16171   ops->print_it = print_it_masked_watchpoint;
16172   ops->print_one_detail = print_one_detail_masked_watchpoint;
16173   ops->print_mention = print_mention_masked_watchpoint;
16174   ops->print_recreate = print_recreate_masked_watchpoint;
16175
16176   /* Tracepoints.  */
16177   ops = &tracepoint_breakpoint_ops;
16178   *ops = base_breakpoint_ops;
16179   ops->re_set = tracepoint_re_set;
16180   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16181   ops->print_one_detail = tracepoint_print_one_detail;
16182   ops->print_mention = tracepoint_print_mention;
16183   ops->print_recreate = tracepoint_print_recreate;
16184   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16185   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16186   ops->decode_linespec = tracepoint_decode_linespec;
16187
16188   /* Probe tracepoints.  */
16189   ops = &tracepoint_probe_breakpoint_ops;
16190   *ops = tracepoint_breakpoint_ops;
16191   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16192   ops->decode_linespec = tracepoint_probe_decode_linespec;
16193
16194   /* Static tracepoints with marker (`-m').  */
16195   ops = &strace_marker_breakpoint_ops;
16196   *ops = tracepoint_breakpoint_ops;
16197   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16198   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16199   ops->decode_linespec = strace_marker_decode_linespec;
16200
16201   /* Fork catchpoints.  */
16202   ops = &catch_fork_breakpoint_ops;
16203   *ops = base_breakpoint_ops;
16204   ops->insert_location = insert_catch_fork;
16205   ops->remove_location = remove_catch_fork;
16206   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16207   ops->print_it = print_it_catch_fork;
16208   ops->print_one = print_one_catch_fork;
16209   ops->print_mention = print_mention_catch_fork;
16210   ops->print_recreate = print_recreate_catch_fork;
16211
16212   /* Vfork catchpoints.  */
16213   ops = &catch_vfork_breakpoint_ops;
16214   *ops = base_breakpoint_ops;
16215   ops->insert_location = insert_catch_vfork;
16216   ops->remove_location = remove_catch_vfork;
16217   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16218   ops->print_it = print_it_catch_vfork;
16219   ops->print_one = print_one_catch_vfork;
16220   ops->print_mention = print_mention_catch_vfork;
16221   ops->print_recreate = print_recreate_catch_vfork;
16222
16223   /* Exec catchpoints.  */
16224   ops = &catch_exec_breakpoint_ops;
16225   *ops = base_breakpoint_ops;
16226   ops->dtor = dtor_catch_exec;
16227   ops->insert_location = insert_catch_exec;
16228   ops->remove_location = remove_catch_exec;
16229   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16230   ops->print_it = print_it_catch_exec;
16231   ops->print_one = print_one_catch_exec;
16232   ops->print_mention = print_mention_catch_exec;
16233   ops->print_recreate = print_recreate_catch_exec;
16234
16235   /* Syscall catchpoints.  */
16236   ops = &catch_syscall_breakpoint_ops;
16237   *ops = base_breakpoint_ops;
16238   ops->dtor = dtor_catch_syscall;
16239   ops->insert_location = insert_catch_syscall;
16240   ops->remove_location = remove_catch_syscall;
16241   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16242   ops->print_it = print_it_catch_syscall;
16243   ops->print_one = print_one_catch_syscall;
16244   ops->print_mention = print_mention_catch_syscall;
16245   ops->print_recreate = print_recreate_catch_syscall;
16246
16247   /* Solib-related catchpoints.  */
16248   ops = &catch_solib_breakpoint_ops;
16249   *ops = base_breakpoint_ops;
16250   ops->dtor = dtor_catch_solib;
16251   ops->insert_location = insert_catch_solib;
16252   ops->remove_location = remove_catch_solib;
16253   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16254   ops->check_status = check_status_catch_solib;
16255   ops->print_it = print_it_catch_solib;
16256   ops->print_one = print_one_catch_solib;
16257   ops->print_mention = print_mention_catch_solib;
16258   ops->print_recreate = print_recreate_catch_solib;
16259
16260   ops = &dprintf_breakpoint_ops;
16261   *ops = bkpt_base_breakpoint_ops;
16262   ops->re_set = dprintf_re_set;
16263   ops->resources_needed = bkpt_resources_needed;
16264   ops->print_it = bkpt_print_it;
16265   ops->print_mention = bkpt_print_mention;
16266   ops->print_recreate = dprintf_print_recreate;
16267   ops->after_condition_true = dprintf_after_condition_true;
16268   ops->breakpoint_hit = dprintf_breakpoint_hit;
16269 }
16270
16271 /* Chain containing all defined "enable breakpoint" subcommands.  */
16272
16273 static struct cmd_list_element *enablebreaklist = NULL;
16274
16275 void
16276 _initialize_breakpoint (void)
16277 {
16278   struct cmd_list_element *c;
16279
16280   initialize_breakpoint_ops ();
16281
16282   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16283   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16284   observer_attach_inferior_exit (clear_syscall_counts);
16285   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16286
16287   breakpoint_objfile_key
16288     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16289
16290   catch_syscall_inferior_data
16291     = register_inferior_data_with_cleanup (NULL,
16292                                            catch_syscall_inferior_data_cleanup);
16293
16294   breakpoint_chain = 0;
16295   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16296      before a breakpoint is set.  */
16297   breakpoint_count = 0;
16298
16299   tracepoint_count = 0;
16300
16301   add_com ("ignore", class_breakpoint, ignore_command, _("\
16302 Set ignore-count of breakpoint number N to COUNT.\n\
16303 Usage is `ignore N COUNT'."));
16304   if (xdb_commands)
16305     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16306
16307   add_com ("commands", class_breakpoint, commands_command, _("\
16308 Set commands to be executed when a breakpoint is hit.\n\
16309 Give breakpoint number as argument after \"commands\".\n\
16310 With no argument, the targeted breakpoint is the last one set.\n\
16311 The commands themselves follow starting on the next line.\n\
16312 Type a line containing \"end\" to indicate the end of them.\n\
16313 Give \"silent\" as the first line to make the breakpoint silent;\n\
16314 then no output is printed when it is hit, except what the commands print."));
16315
16316   c = add_com ("condition", class_breakpoint, condition_command, _("\
16317 Specify breakpoint number N to break only if COND is true.\n\
16318 Usage is `condition N COND', where N is an integer and COND is an\n\
16319 expression to be evaluated whenever breakpoint N is reached."));
16320   set_cmd_completer (c, condition_completer);
16321
16322   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16323 Set a temporary breakpoint.\n\
16324 Like \"break\" except the breakpoint is only temporary,\n\
16325 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16326 by using \"enable delete\" on the breakpoint number.\n\
16327 \n"
16328 BREAK_ARGS_HELP ("tbreak")));
16329   set_cmd_completer (c, location_completer);
16330
16331   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16332 Set a hardware assisted breakpoint.\n\
16333 Like \"break\" except the breakpoint requires hardware support,\n\
16334 some target hardware may not have this support.\n\
16335 \n"
16336 BREAK_ARGS_HELP ("hbreak")));
16337   set_cmd_completer (c, location_completer);
16338
16339   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16340 Set a temporary hardware assisted breakpoint.\n\
16341 Like \"hbreak\" except the breakpoint is only temporary,\n\
16342 so it will be deleted when hit.\n\
16343 \n"
16344 BREAK_ARGS_HELP ("thbreak")));
16345   set_cmd_completer (c, location_completer);
16346
16347   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16348 Enable some breakpoints.\n\
16349 Give breakpoint numbers (separated by spaces) as arguments.\n\
16350 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16351 This is used to cancel the effect of the \"disable\" command.\n\
16352 With a subcommand you can enable temporarily."),
16353                   &enablelist, "enable ", 1, &cmdlist);
16354   if (xdb_commands)
16355     add_com ("ab", class_breakpoint, enable_command, _("\
16356 Enable some breakpoints.\n\
16357 Give breakpoint numbers (separated by spaces) as arguments.\n\
16358 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16359 This is used to cancel the effect of the \"disable\" command.\n\
16360 With a subcommand you can enable temporarily."));
16361
16362   add_com_alias ("en", "enable", class_breakpoint, 1);
16363
16364   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16365 Enable some breakpoints.\n\
16366 Give breakpoint numbers (separated by spaces) as arguments.\n\
16367 This is used to cancel the effect of the \"disable\" command.\n\
16368 May be abbreviated to simply \"enable\".\n"),
16369                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16370
16371   add_cmd ("once", no_class, enable_once_command, _("\
16372 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16373 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16374            &enablebreaklist);
16375
16376   add_cmd ("delete", no_class, enable_delete_command, _("\
16377 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16378 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16379            &enablebreaklist);
16380
16381   add_cmd ("count", no_class, enable_count_command, _("\
16382 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16383 If a breakpoint is hit while enabled in this fashion,\n\
16384 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16385            &enablebreaklist);
16386
16387   add_cmd ("delete", no_class, enable_delete_command, _("\
16388 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16389 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16390            &enablelist);
16391
16392   add_cmd ("once", no_class, enable_once_command, _("\
16393 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16394 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16395            &enablelist);
16396
16397   add_cmd ("count", no_class, enable_count_command, _("\
16398 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16399 If a breakpoint is hit while enabled in this fashion,\n\
16400 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16401            &enablelist);
16402
16403   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16404 Disable some breakpoints.\n\
16405 Arguments are breakpoint numbers with spaces in between.\n\
16406 To disable all breakpoints, give no argument.\n\
16407 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16408                   &disablelist, "disable ", 1, &cmdlist);
16409   add_com_alias ("dis", "disable", class_breakpoint, 1);
16410   add_com_alias ("disa", "disable", class_breakpoint, 1);
16411   if (xdb_commands)
16412     add_com ("sb", class_breakpoint, disable_command, _("\
16413 Disable some breakpoints.\n\
16414 Arguments are breakpoint numbers with spaces in between.\n\
16415 To disable all breakpoints, give no argument.\n\
16416 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16417
16418   add_cmd ("breakpoints", class_alias, disable_command, _("\
16419 Disable some breakpoints.\n\
16420 Arguments are breakpoint numbers with spaces in between.\n\
16421 To disable all breakpoints, give no argument.\n\
16422 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16423 This command may be abbreviated \"disable\"."),
16424            &disablelist);
16425
16426   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16427 Delete some breakpoints or auto-display expressions.\n\
16428 Arguments are breakpoint numbers with spaces in between.\n\
16429 To delete all breakpoints, give no argument.\n\
16430 \n\
16431 Also a prefix command for deletion of other GDB objects.\n\
16432 The \"unset\" command is also an alias for \"delete\"."),
16433                   &deletelist, "delete ", 1, &cmdlist);
16434   add_com_alias ("d", "delete", class_breakpoint, 1);
16435   add_com_alias ("del", "delete", class_breakpoint, 1);
16436   if (xdb_commands)
16437     add_com ("db", class_breakpoint, delete_command, _("\
16438 Delete some breakpoints.\n\
16439 Arguments are breakpoint numbers with spaces in between.\n\
16440 To delete all breakpoints, give no argument.\n"));
16441
16442   add_cmd ("breakpoints", class_alias, delete_command, _("\
16443 Delete some breakpoints or auto-display expressions.\n\
16444 Arguments are breakpoint numbers with spaces in between.\n\
16445 To delete all breakpoints, give no argument.\n\
16446 This command may be abbreviated \"delete\"."),
16447            &deletelist);
16448
16449   add_com ("clear", class_breakpoint, clear_command, _("\
16450 Clear breakpoint at specified line or function.\n\
16451 Argument may be line number, function name, or \"*\" and an address.\n\
16452 If line number is specified, all breakpoints in that line are cleared.\n\
16453 If function is specified, breakpoints at beginning of function are cleared.\n\
16454 If an address is specified, breakpoints at that address are cleared.\n\
16455 \n\
16456 With no argument, clears all breakpoints in the line that the selected frame\n\
16457 is executing in.\n\
16458 \n\
16459 See also the \"delete\" command which clears breakpoints by number."));
16460   add_com_alias ("cl", "clear", class_breakpoint, 1);
16461
16462   c = add_com ("break", class_breakpoint, break_command, _("\
16463 Set breakpoint at specified line or function.\n"
16464 BREAK_ARGS_HELP ("break")));
16465   set_cmd_completer (c, location_completer);
16466
16467   add_com_alias ("b", "break", class_run, 1);
16468   add_com_alias ("br", "break", class_run, 1);
16469   add_com_alias ("bre", "break", class_run, 1);
16470   add_com_alias ("brea", "break", class_run, 1);
16471
16472   if (xdb_commands)
16473    add_com_alias ("ba", "break", class_breakpoint, 1);
16474
16475   if (dbx_commands)
16476     {
16477       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16478 Break in function/address or break at a line in the current file."),
16479                              &stoplist, "stop ", 1, &cmdlist);
16480       add_cmd ("in", class_breakpoint, stopin_command,
16481                _("Break in function or address."), &stoplist);
16482       add_cmd ("at", class_breakpoint, stopat_command,
16483                _("Break at a line in the current file."), &stoplist);
16484       add_com ("status", class_info, breakpoints_info, _("\
16485 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16486 The \"Type\" column indicates one of:\n\
16487 \tbreakpoint     - normal breakpoint\n\
16488 \twatchpoint     - watchpoint\n\
16489 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16490 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16491 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16492 address and file/line number respectively.\n\
16493 \n\
16494 Convenience variable \"$_\" and default examine address for \"x\"\n\
16495 are set to the address of the last breakpoint listed unless the command\n\
16496 is prefixed with \"server \".\n\n\
16497 Convenience variable \"$bpnum\" contains the number of the last\n\
16498 breakpoint set."));
16499     }
16500
16501   add_info ("breakpoints", breakpoints_info, _("\
16502 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16503 The \"Type\" column indicates one of:\n\
16504 \tbreakpoint     - normal breakpoint\n\
16505 \twatchpoint     - watchpoint\n\
16506 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16507 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16508 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16509 address and file/line number respectively.\n\
16510 \n\
16511 Convenience variable \"$_\" and default examine address for \"x\"\n\
16512 are set to the address of the last breakpoint listed unless the command\n\
16513 is prefixed with \"server \".\n\n\
16514 Convenience variable \"$bpnum\" contains the number of the last\n\
16515 breakpoint set."));
16516
16517   add_info_alias ("b", "breakpoints", 1);
16518
16519   if (xdb_commands)
16520     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16521 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16522 The \"Type\" column indicates one of:\n\
16523 \tbreakpoint     - normal breakpoint\n\
16524 \twatchpoint     - watchpoint\n\
16525 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16526 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16527 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16528 address and file/line number respectively.\n\
16529 \n\
16530 Convenience variable \"$_\" and default examine address for \"x\"\n\
16531 are set to the address of the last breakpoint listed unless the command\n\
16532 is prefixed with \"server \".\n\n\
16533 Convenience variable \"$bpnum\" contains the number of the last\n\
16534 breakpoint set."));
16535
16536   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16537 Status of all breakpoints, or breakpoint number NUMBER.\n\
16538 The \"Type\" column indicates one of:\n\
16539 \tbreakpoint     - normal breakpoint\n\
16540 \twatchpoint     - watchpoint\n\
16541 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16542 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16543 \tuntil          - internal breakpoint used by the \"until\" command\n\
16544 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16545 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16546 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16547 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16548 address and file/line number respectively.\n\
16549 \n\
16550 Convenience variable \"$_\" and default examine address for \"x\"\n\
16551 are set to the address of the last breakpoint listed unless the command\n\
16552 is prefixed with \"server \".\n\n\
16553 Convenience variable \"$bpnum\" contains the number of the last\n\
16554 breakpoint set."),
16555            &maintenanceinfolist);
16556
16557   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16558 Set catchpoints to catch events."),
16559                   &catch_cmdlist, "catch ",
16560                   0/*allow-unknown*/, &cmdlist);
16561
16562   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16563 Set temporary catchpoints to catch events."),
16564                   &tcatch_cmdlist, "tcatch ",
16565                   0/*allow-unknown*/, &cmdlist);
16566
16567   add_catch_command ("fork", _("Catch calls to fork."),
16568                      catch_fork_command_1,
16569                      NULL,
16570                      (void *) (uintptr_t) catch_fork_permanent,
16571                      (void *) (uintptr_t) catch_fork_temporary);
16572   add_catch_command ("vfork", _("Catch calls to vfork."),
16573                      catch_fork_command_1,
16574                      NULL,
16575                      (void *) (uintptr_t) catch_vfork_permanent,
16576                      (void *) (uintptr_t) catch_vfork_temporary);
16577   add_catch_command ("exec", _("Catch calls to exec."),
16578                      catch_exec_command_1,
16579                      NULL,
16580                      CATCH_PERMANENT,
16581                      CATCH_TEMPORARY);
16582   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16583 Usage: catch load [REGEX]\n\
16584 If REGEX is given, only stop for libraries matching the regular expression."),
16585                      catch_load_command_1,
16586                      NULL,
16587                      CATCH_PERMANENT,
16588                      CATCH_TEMPORARY);
16589   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16590 Usage: catch unload [REGEX]\n\
16591 If REGEX is given, only stop for libraries matching the regular expression."),
16592                      catch_unload_command_1,
16593                      NULL,
16594                      CATCH_PERMANENT,
16595                      CATCH_TEMPORARY);
16596   add_catch_command ("syscall", _("\
16597 Catch system calls by their names and/or numbers.\n\
16598 Arguments say which system calls to catch.  If no arguments\n\
16599 are given, every system call will be caught.\n\
16600 Arguments, if given, should be one or more system call names\n\
16601 (if your system supports that), or system call numbers."),
16602                      catch_syscall_command_1,
16603                      catch_syscall_completer,
16604                      CATCH_PERMANENT,
16605                      CATCH_TEMPORARY);
16606
16607   c = add_com ("watch", class_breakpoint, watch_command, _("\
16608 Set a watchpoint for an expression.\n\
16609 Usage: watch [-l|-location] EXPRESSION\n\
16610 A watchpoint stops execution of your program whenever the value of\n\
16611 an expression changes.\n\
16612 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16613 the memory to which it refers."));
16614   set_cmd_completer (c, expression_completer);
16615
16616   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16617 Set a read watchpoint for an expression.\n\
16618 Usage: rwatch [-l|-location] EXPRESSION\n\
16619 A watchpoint stops execution of your program whenever the value of\n\
16620 an expression is read.\n\
16621 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16622 the memory to which it refers."));
16623   set_cmd_completer (c, expression_completer);
16624
16625   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16626 Set a watchpoint for an expression.\n\
16627 Usage: awatch [-l|-location] EXPRESSION\n\
16628 A watchpoint stops execution of your program whenever the value of\n\
16629 an expression is either read or written.\n\
16630 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16631 the memory to which it refers."));
16632   set_cmd_completer (c, expression_completer);
16633
16634   add_info ("watchpoints", watchpoints_info, _("\
16635 Status of specified watchpoints (all watchpoints if no argument)."));
16636
16637   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16638      respond to changes - contrary to the description.  */
16639   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16640                             &can_use_hw_watchpoints, _("\
16641 Set debugger's willingness to use watchpoint hardware."), _("\
16642 Show debugger's willingness to use watchpoint hardware."), _("\
16643 If zero, gdb will not use hardware for new watchpoints, even if\n\
16644 such is available.  (However, any hardware watchpoints that were\n\
16645 created before setting this to nonzero, will continue to use watchpoint\n\
16646 hardware.)"),
16647                             NULL,
16648                             show_can_use_hw_watchpoints,
16649                             &setlist, &showlist);
16650
16651   can_use_hw_watchpoints = 1;
16652
16653   /* Tracepoint manipulation commands.  */
16654
16655   c = add_com ("trace", class_breakpoint, trace_command, _("\
16656 Set a tracepoint at specified line or function.\n\
16657 \n"
16658 BREAK_ARGS_HELP ("trace") "\n\
16659 Do \"help tracepoints\" for info on other tracepoint commands."));
16660   set_cmd_completer (c, location_completer);
16661
16662   add_com_alias ("tp", "trace", class_alias, 0);
16663   add_com_alias ("tr", "trace", class_alias, 1);
16664   add_com_alias ("tra", "trace", class_alias, 1);
16665   add_com_alias ("trac", "trace", class_alias, 1);
16666
16667   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16668 Set a fast tracepoint at specified line or function.\n\
16669 \n"
16670 BREAK_ARGS_HELP ("ftrace") "\n\
16671 Do \"help tracepoints\" for info on other tracepoint commands."));
16672   set_cmd_completer (c, location_completer);
16673
16674   c = add_com ("strace", class_breakpoint, strace_command, _("\
16675 Set a static tracepoint at specified line, function or marker.\n\
16676 \n\
16677 strace [LOCATION] [if CONDITION]\n\
16678 LOCATION may be a line number, function name, \"*\" and an address,\n\
16679 or -m MARKER_ID.\n\
16680 If a line number is specified, probe the marker at start of code\n\
16681 for that line.  If a function is specified, probe the marker at start\n\
16682 of code for that function.  If an address is specified, probe the marker\n\
16683 at that exact address.  If a marker id is specified, probe the marker\n\
16684 with that name.  With no LOCATION, uses current execution address of\n\
16685 the selected stack frame.\n\
16686 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16687 This collects arbitrary user data passed in the probe point call to the\n\
16688 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16689 by printing the $_sdata variable like any other convenience variable.\n\
16690 \n\
16691 CONDITION is a boolean expression.\n\
16692 \n\
16693 Multiple tracepoints at one place are permitted, and useful if their\n\
16694 conditions are different.\n\
16695 \n\
16696 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16697 Do \"help tracepoints\" for info on other tracepoint commands."));
16698   set_cmd_completer (c, location_completer);
16699
16700   add_info ("tracepoints", tracepoints_info, _("\
16701 Status of specified tracepoints (all tracepoints if no argument).\n\
16702 Convenience variable \"$tpnum\" contains the number of the\n\
16703 last tracepoint set."));
16704
16705   add_info_alias ("tp", "tracepoints", 1);
16706
16707   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16708 Delete specified tracepoints.\n\
16709 Arguments are tracepoint numbers, separated by spaces.\n\
16710 No argument means delete all tracepoints."),
16711            &deletelist);
16712   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16713
16714   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16715 Disable specified tracepoints.\n\
16716 Arguments are tracepoint numbers, separated by spaces.\n\
16717 No argument means disable all tracepoints."),
16718            &disablelist);
16719   deprecate_cmd (c, "disable");
16720
16721   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16722 Enable specified tracepoints.\n\
16723 Arguments are tracepoint numbers, separated by spaces.\n\
16724 No argument means enable all tracepoints."),
16725            &enablelist);
16726   deprecate_cmd (c, "enable");
16727
16728   add_com ("passcount", class_trace, trace_pass_command, _("\
16729 Set the passcount for a tracepoint.\n\
16730 The trace will end when the tracepoint has been passed 'count' times.\n\
16731 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16732 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16733
16734   add_prefix_cmd ("save", class_breakpoint, save_command,
16735                   _("Save breakpoint definitions as a script."),
16736                   &save_cmdlist, "save ",
16737                   0/*allow-unknown*/, &cmdlist);
16738
16739   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16740 Save current breakpoint definitions as a script.\n\
16741 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16742 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16743 session to restore them."),
16744                &save_cmdlist);
16745   set_cmd_completer (c, filename_completer);
16746
16747   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16748 Save current tracepoint definitions as a script.\n\
16749 Use the 'source' command in another debug session to restore them."),
16750                &save_cmdlist);
16751   set_cmd_completer (c, filename_completer);
16752
16753   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16754   deprecate_cmd (c, "save tracepoints");
16755
16756   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16757 Breakpoint specific settings\n\
16758 Configure various breakpoint-specific variables such as\n\
16759 pending breakpoint behavior"),
16760                   &breakpoint_set_cmdlist, "set breakpoint ",
16761                   0/*allow-unknown*/, &setlist);
16762   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16763 Breakpoint specific settings\n\
16764 Configure various breakpoint-specific variables such as\n\
16765 pending breakpoint behavior"),
16766                   &breakpoint_show_cmdlist, "show breakpoint ",
16767                   0/*allow-unknown*/, &showlist);
16768
16769   add_setshow_auto_boolean_cmd ("pending", no_class,
16770                                 &pending_break_support, _("\
16771 Set debugger's behavior regarding pending breakpoints."), _("\
16772 Show debugger's behavior regarding pending breakpoints."), _("\
16773 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16774 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16775 an error.  If auto, an unrecognized breakpoint location results in a\n\
16776 user-query to see if a pending breakpoint should be created."),
16777                                 NULL,
16778                                 show_pending_break_support,
16779                                 &breakpoint_set_cmdlist,
16780                                 &breakpoint_show_cmdlist);
16781
16782   pending_break_support = AUTO_BOOLEAN_AUTO;
16783
16784   add_setshow_boolean_cmd ("auto-hw", no_class,
16785                            &automatic_hardware_breakpoints, _("\
16786 Set automatic usage of hardware breakpoints."), _("\
16787 Show automatic usage of hardware breakpoints."), _("\
16788 If set, the debugger will automatically use hardware breakpoints for\n\
16789 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16790 a warning will be emitted for such breakpoints."),
16791                            NULL,
16792                            show_automatic_hardware_breakpoints,
16793                            &breakpoint_set_cmdlist,
16794                            &breakpoint_show_cmdlist);
16795
16796   add_setshow_boolean_cmd ("always-inserted", class_support,
16797                            &always_inserted_mode, _("\
16798 Set mode for inserting breakpoints."), _("\
16799 Show mode for inserting breakpoints."), _("\
16800 When this mode is on, breakpoints are inserted immediately as soon as\n\
16801 they're created, kept inserted even when execution stops, and removed\n\
16802 only when the user deletes them.  When this mode is off (the default),\n\
16803 breakpoints are inserted only when execution continues, and removed\n\
16804 when execution stops."),
16805                                 NULL,
16806                                 &show_always_inserted_mode,
16807                                 &breakpoint_set_cmdlist,
16808                                 &breakpoint_show_cmdlist);
16809
16810   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16811                         condition_evaluation_enums,
16812                         &condition_evaluation_mode_1, _("\
16813 Set mode of breakpoint condition evaluation."), _("\
16814 Show mode of breakpoint condition evaluation."), _("\
16815 When this is set to \"host\", breakpoint conditions will be\n\
16816 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16817 breakpoint conditions will be downloaded to the target (if the target\n\
16818 supports such feature) and conditions will be evaluated on the target's side.\n\
16819 If this is set to \"auto\" (default), this will be automatically set to\n\
16820 \"target\" if it supports condition evaluation, otherwise it will\n\
16821 be set to \"gdb\""),
16822                            &set_condition_evaluation_mode,
16823                            &show_condition_evaluation_mode,
16824                            &breakpoint_set_cmdlist,
16825                            &breakpoint_show_cmdlist);
16826
16827   add_com ("break-range", class_breakpoint, break_range_command, _("\
16828 Set a breakpoint for an address range.\n\
16829 break-range START-LOCATION, END-LOCATION\n\
16830 where START-LOCATION and END-LOCATION can be one of the following:\n\
16831   LINENUM, for that line in the current file,\n\
16832   FILE:LINENUM, for that line in that file,\n\
16833   +OFFSET, for that number of lines after the current line\n\
16834            or the start of the range\n\
16835   FUNCTION, for the first line in that function,\n\
16836   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16837   *ADDRESS, for the instruction at that address.\n\
16838 \n\
16839 The breakpoint will stop execution of the inferior whenever it executes\n\
16840 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16841 range (including START-LOCATION and END-LOCATION)."));
16842
16843   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16844 Set a dynamic printf at specified line or function.\n\
16845 dprintf location,format string,arg1,arg2,...\n\
16846 location may be a line number, function name, or \"*\" and an address.\n\
16847 If a line number is specified, break at start of code for that line.\n\
16848 If a function is specified, break at start of code for that function."));
16849   set_cmd_completer (c, location_completer);
16850
16851   add_setshow_enum_cmd ("dprintf-style", class_support,
16852                         dprintf_style_enums, &dprintf_style, _("\
16853 Set the style of usage for dynamic printf."), _("\
16854 Show the style of usage for dynamic printf."), _("\
16855 This setting chooses how GDB will do a dynamic printf.\n\
16856 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16857 console, as with the \"printf\" command.\n\
16858 If the value is \"call\", the print is done by calling a function in your\n\
16859 program; by default printf(), but you can choose a different function or\n\
16860 output stream by setting dprintf-function and dprintf-channel."),
16861                         update_dprintf_commands, NULL,
16862                         &setlist, &showlist);
16863
16864   dprintf_function = xstrdup ("printf");
16865   add_setshow_string_cmd ("dprintf-function", class_support,
16866                           &dprintf_function, _("\
16867 Set the function to use for dynamic printf"), _("\
16868 Show the function to use for dynamic printf"), NULL,
16869                           update_dprintf_commands, NULL,
16870                           &setlist, &showlist);
16871
16872   dprintf_channel = xstrdup ("");
16873   add_setshow_string_cmd ("dprintf-channel", class_support,
16874                           &dprintf_channel, _("\
16875 Set the channel to use for dynamic printf"), _("\
16876 Show the channel to use for dynamic printf"), NULL,
16877                           update_dprintf_commands, NULL,
16878                           &setlist, &showlist);
16879
16880   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16881                            &disconnected_dprintf, _("\
16882 Set whether dprintf continues after GDB disconnects."), _("\
16883 Show whether dprintf continues after GDB disconnects."), _("\
16884 Use this to let dprintf commands continue to hit and produce output\n\
16885 even if GDB disconnects or detaches from the target."),
16886                            NULL,
16887                            NULL,
16888                            &setlist, &showlist);
16889
16890   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16891 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16892 (target agent only) This is useful for formatted output in user-defined commands."));
16893
16894   automatic_hardware_breakpoints = 1;
16895
16896   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16897   observer_attach_thread_exit (remove_threaded_breakpoints);
16898 }