Hardware watchpoints turned off, inferior not yet started.
[platform/upstream/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2013 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "gdb_regex.h"
64 #include "probe.h"
65 #include "cli/cli-utils.h"
66 #include "continuations.h"
67 #include "stack.h"
68 #include "skip.h"
69 #include "gdb_regex.h"
70 #include "ax-gdb.h"
71 #include "dummy-frame.h"
72
73 #include "format.h"
74
75 /* readline include files */
76 #include "readline/readline.h"
77 #include "readline/history.h"
78
79 /* readline defines this.  */
80 #undef savestring
81
82 #include "mi/mi-common.h"
83 #include "python/python.h"
84
85 /* Enums for exception-handling support.  */
86 enum exception_event_kind
87 {
88   EX_EVENT_THROW,
89   EX_EVENT_RETHROW,
90   EX_EVENT_CATCH
91 };
92
93 /* Prototypes for local functions.  */
94
95 static void enable_delete_command (char *, int);
96
97 static void enable_once_command (char *, int);
98
99 static void enable_count_command (char *, int);
100
101 static void disable_command (char *, int);
102
103 static void enable_command (char *, int);
104
105 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
106                                                       void *),
107                                     void *);
108
109 static void ignore_command (char *, int);
110
111 static int breakpoint_re_set_one (void *);
112
113 static void breakpoint_re_set_default (struct breakpoint *);
114
115 static void create_sals_from_address_default (char **,
116                                               struct linespec_result *,
117                                               enum bptype, char *,
118                                               char **);
119
120 static void create_breakpoints_sal_default (struct gdbarch *,
121                                             struct linespec_result *,
122                                             char *, char *, enum bptype,
123                                             enum bpdisp, int, int,
124                                             int,
125                                             const struct breakpoint_ops *,
126                                             int, int, int, unsigned);
127
128 static void decode_linespec_default (struct breakpoint *, char **,
129                                      struct symtabs_and_lines *);
130
131 static void clear_command (char *, int);
132
133 static void catch_command (char *, int);
134
135 static int can_use_hardware_watchpoint (struct value *);
136
137 static void break_command_1 (char *, int, int);
138
139 static void mention (struct breakpoint *);
140
141 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
142                                                                enum bptype,
143                                                                const struct breakpoint_ops *);
144 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
145                                                        const struct symtab_and_line *);
146
147 /* This function is used in gdbtk sources and thus can not be made
148    static.  */
149 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
150                                        struct symtab_and_line,
151                                        enum bptype,
152                                        const struct breakpoint_ops *);
153
154 static struct breakpoint *
155   momentary_breakpoint_from_master (struct breakpoint *orig,
156                                     enum bptype type,
157                                     const struct breakpoint_ops *ops);
158
159 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
160
161 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
162                                             CORE_ADDR bpaddr,
163                                             enum bptype bptype);
164
165 static void describe_other_breakpoints (struct gdbarch *,
166                                         struct program_space *, CORE_ADDR,
167                                         struct obj_section *, int);
168
169 static int breakpoint_address_match (struct address_space *aspace1,
170                                      CORE_ADDR addr1,
171                                      struct address_space *aspace2,
172                                      CORE_ADDR addr2);
173
174 static int watchpoint_locations_match (struct bp_location *loc1,
175                                        struct bp_location *loc2);
176
177 static int breakpoint_location_address_match (struct bp_location *bl,
178                                               struct address_space *aspace,
179                                               CORE_ADDR addr);
180
181 static void breakpoints_info (char *, int);
182
183 static void watchpoints_info (char *, int);
184
185 static int breakpoint_1 (char *, int, 
186                          int (*) (const struct breakpoint *));
187
188 static int breakpoint_cond_eval (void *);
189
190 static void cleanup_executing_breakpoints (void *);
191
192 static void commands_command (char *, int);
193
194 static void condition_command (char *, int);
195
196 typedef enum
197   {
198     mark_inserted,
199     mark_uninserted
200   }
201 insertion_state_t;
202
203 static int remove_breakpoint (struct bp_location *, insertion_state_t);
204 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
205
206 static enum print_stop_action print_bp_stop_message (bpstat bs);
207
208 static int watchpoint_check (void *);
209
210 static void maintenance_info_breakpoints (char *, int);
211
212 static int hw_breakpoint_used_count (void);
213
214 static int hw_watchpoint_use_count (struct breakpoint *);
215
216 static int hw_watchpoint_used_count_others (struct breakpoint *except,
217                                             enum bptype type,
218                                             int *other_type_used);
219
220 static void hbreak_command (char *, int);
221
222 static void thbreak_command (char *, int);
223
224 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
225                                     int count);
226
227 static void stop_command (char *arg, int from_tty);
228
229 static void stopin_command (char *arg, int from_tty);
230
231 static void stopat_command (char *arg, int from_tty);
232
233 static void tcatch_command (char *arg, int from_tty);
234
235 static void detach_single_step_breakpoints (void);
236
237 static int single_step_breakpoint_inserted_here_p (struct address_space *,
238                                                    CORE_ADDR pc);
239
240 static void free_bp_location (struct bp_location *loc);
241 static void incref_bp_location (struct bp_location *loc);
242 static void decref_bp_location (struct bp_location **loc);
243
244 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
245
246 static void update_global_location_list (int);
247
248 static void update_global_location_list_nothrow (int);
249
250 static int is_hardware_watchpoint (const struct breakpoint *bpt);
251
252 static void insert_breakpoint_locations (void);
253
254 static int syscall_catchpoint_p (struct breakpoint *b);
255
256 static void tracepoints_info (char *, int);
257
258 static void delete_trace_command (char *, int);
259
260 static void enable_trace_command (char *, int);
261
262 static void disable_trace_command (char *, int);
263
264 static void trace_pass_command (char *, int);
265
266 static void set_tracepoint_count (int num);
267
268 static int is_masked_watchpoint (const struct breakpoint *b);
269
270 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
271
272 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
273    otherwise.  */
274
275 static int strace_marker_p (struct breakpoint *b);
276
277 /* The abstract base class all breakpoint_ops structures inherit
278    from.  */
279 struct breakpoint_ops base_breakpoint_ops;
280
281 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
282    that are implemented on top of software or hardware breakpoints
283    (user breakpoints, internal and momentary breakpoints, etc.).  */
284 static struct breakpoint_ops bkpt_base_breakpoint_ops;
285
286 /* Internal breakpoints class type.  */
287 static struct breakpoint_ops internal_breakpoint_ops;
288
289 /* Momentary breakpoints class type.  */
290 static struct breakpoint_ops momentary_breakpoint_ops;
291
292 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
293 static struct breakpoint_ops longjmp_breakpoint_ops;
294
295 /* The breakpoint_ops structure to be used in regular user created
296    breakpoints.  */
297 struct breakpoint_ops bkpt_breakpoint_ops;
298
299 /* Breakpoints set on probes.  */
300 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
301
302 /* Dynamic printf class type.  */
303 struct breakpoint_ops dprintf_breakpoint_ops;
304
305 /* The style in which to perform a dynamic printf.  This is a user
306    option because different output options have different tradeoffs;
307    if GDB does the printing, there is better error handling if there
308    is a problem with any of the arguments, but using an inferior
309    function lets you have special-purpose printers and sending of
310    output to the same place as compiled-in print functions.  */
311
312 static const char dprintf_style_gdb[] = "gdb";
313 static const char dprintf_style_call[] = "call";
314 static const char dprintf_style_agent[] = "agent";
315 static const char *const dprintf_style_enums[] = {
316   dprintf_style_gdb,
317   dprintf_style_call,
318   dprintf_style_agent,
319   NULL
320 };
321 static const char *dprintf_style = dprintf_style_gdb;
322
323 /* The function to use for dynamic printf if the preferred style is to
324    call into the inferior.  The value is simply a string that is
325    copied into the command, so it can be anything that GDB can
326    evaluate to a callable address, not necessarily a function name.  */
327
328 static char *dprintf_function = "";
329
330 /* The channel to use for dynamic printf if the preferred style is to
331    call into the inferior; if a nonempty string, it will be passed to
332    the call as the first argument, with the format string as the
333    second.  As with the dprintf function, this can be anything that
334    GDB knows how to evaluate, so in addition to common choices like
335    "stderr", this could be an app-specific expression like
336    "mystreams[curlogger]".  */
337
338 static char *dprintf_channel = "";
339
340 /* True if dprintf commands should continue to operate even if GDB
341    has disconnected.  */
342 static int disconnected_dprintf = 1;
343
344 /* A reference-counted struct command_line.  This lets multiple
345    breakpoints share a single command list.  */
346 struct counted_command_line
347 {
348   /* The reference count.  */
349   int refc;
350
351   /* The command list.  */
352   struct command_line *commands;
353 };
354
355 struct command_line *
356 breakpoint_commands (struct breakpoint *b)
357 {
358   return b->commands ? b->commands->commands : NULL;
359 }
360
361 /* Flag indicating that a command has proceeded the inferior past the
362    current breakpoint.  */
363
364 static int breakpoint_proceeded;
365
366 const char *
367 bpdisp_text (enum bpdisp disp)
368 {
369   /* NOTE: the following values are a part of MI protocol and
370      represent values of 'disp' field returned when inferior stops at
371      a breakpoint.  */
372   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
373
374   return bpdisps[(int) disp];
375 }
376
377 /* Prototypes for exported functions.  */
378 /* If FALSE, gdb will not use hardware support for watchpoints, even
379    if such is available.  */
380 static int can_use_hw_watchpoints;
381
382 static void
383 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
384                              struct cmd_list_element *c,
385                              const char *value)
386 {
387   fprintf_filtered (file,
388                     _("Debugger's willingness to use "
389                       "watchpoint hardware is %s.\n"),
390                     value);
391 }
392
393 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
394    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
395    for unrecognized breakpoint locations.
396    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
397 static enum auto_boolean pending_break_support;
398 static void
399 show_pending_break_support (struct ui_file *file, int from_tty,
400                             struct cmd_list_element *c,
401                             const char *value)
402 {
403   fprintf_filtered (file,
404                     _("Debugger's behavior regarding "
405                       "pending breakpoints is %s.\n"),
406                     value);
407 }
408
409 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
410    set with "break" but falling in read-only memory.
411    If 0, gdb will warn about such breakpoints, but won't automatically
412    use hardware breakpoints.  */
413 static int automatic_hardware_breakpoints;
414 static void
415 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
416                                      struct cmd_list_element *c,
417                                      const char *value)
418 {
419   fprintf_filtered (file,
420                     _("Automatic usage of hardware breakpoints is %s.\n"),
421                     value);
422 }
423
424 /* If on, gdb will keep breakpoints inserted even as inferior is
425    stopped, and immediately insert any new breakpoints.  If off, gdb
426    will insert breakpoints into inferior only when resuming it, and
427    will remove breakpoints upon stop.  If auto, GDB will behave as ON
428    if in non-stop mode, and as OFF if all-stop mode.*/
429
430 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
431
432 static void
433 show_always_inserted_mode (struct ui_file *file, int from_tty,
434                      struct cmd_list_element *c, const char *value)
435 {
436   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
437     fprintf_filtered (file,
438                       _("Always inserted breakpoint "
439                         "mode is %s (currently %s).\n"),
440                       value,
441                       breakpoints_always_inserted_mode () ? "on" : "off");
442   else
443     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
444                       value);
445 }
446
447 int
448 breakpoints_always_inserted_mode (void)
449 {
450   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
451           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
452 }
453
454 static const char condition_evaluation_both[] = "host or target";
455
456 /* Modes for breakpoint condition evaluation.  */
457 static const char condition_evaluation_auto[] = "auto";
458 static const char condition_evaluation_host[] = "host";
459 static const char condition_evaluation_target[] = "target";
460 static const char *const condition_evaluation_enums[] = {
461   condition_evaluation_auto,
462   condition_evaluation_host,
463   condition_evaluation_target,
464   NULL
465 };
466
467 /* Global that holds the current mode for breakpoint condition evaluation.  */
468 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
469
470 /* Global that we use to display information to the user (gets its value from
471    condition_evaluation_mode_1.  */
472 static const char *condition_evaluation_mode = condition_evaluation_auto;
473
474 /* Translate a condition evaluation mode MODE into either "host"
475    or "target".  This is used mostly to translate from "auto" to the
476    real setting that is being used.  It returns the translated
477    evaluation mode.  */
478
479 static const char *
480 translate_condition_evaluation_mode (const char *mode)
481 {
482   if (mode == condition_evaluation_auto)
483     {
484       if (target_supports_evaluation_of_breakpoint_conditions ())
485         return condition_evaluation_target;
486       else
487         return condition_evaluation_host;
488     }
489   else
490     return mode;
491 }
492
493 /* Discovers what condition_evaluation_auto translates to.  */
494
495 static const char *
496 breakpoint_condition_evaluation_mode (void)
497 {
498   return translate_condition_evaluation_mode (condition_evaluation_mode);
499 }
500
501 /* Return true if GDB should evaluate breakpoint conditions or false
502    otherwise.  */
503
504 static int
505 gdb_evaluates_breakpoint_condition_p (void)
506 {
507   const char *mode = breakpoint_condition_evaluation_mode ();
508
509   return (mode == condition_evaluation_host);
510 }
511
512 void _initialize_breakpoint (void);
513
514 /* Are we executing breakpoint commands?  */
515 static int executing_breakpoint_commands;
516
517 /* Are overlay event breakpoints enabled? */
518 static int overlay_events_enabled;
519
520 /* See description in breakpoint.h. */
521 int target_exact_watchpoints = 0;
522
523 /* Walk the following statement or block through all breakpoints.
524    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
525    current breakpoint.  */
526
527 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
528
529 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
530         for (B = breakpoint_chain;      \
531              B ? (TMP=B->next, 1): 0;   \
532              B = TMP)
533
534 /* Similar iterator for the low-level breakpoints.  SAFE variant is
535    not provided so update_global_location_list must not be called
536    while executing the block of ALL_BP_LOCATIONS.  */
537
538 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
539         for (BP_TMP = bp_location;                                      \
540              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
541              BP_TMP++)
542
543 /* Iterates through locations with address ADDRESS for the currently selected
544    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
545    to where the loop should start from.
546    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
547    appropriate location to start with.  */
548
549 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
550         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
551              BP_LOCP_TMP = BP_LOCP_START;                               \
552              BP_LOCP_START                                              \
553              && (BP_LOCP_TMP < bp_location + bp_location_count          \
554              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
555              BP_LOCP_TMP++)
556
557 /* Iterator for tracepoints only.  */
558
559 #define ALL_TRACEPOINTS(B)  \
560   for (B = breakpoint_chain; B; B = B->next)  \
561     if (is_tracepoint (B))
562
563 /* Chains of all breakpoints defined.  */
564
565 struct breakpoint *breakpoint_chain;
566
567 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
568
569 static struct bp_location **bp_location;
570
571 /* Number of elements of BP_LOCATION.  */
572
573 static unsigned bp_location_count;
574
575 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
576    ADDRESS for the current elements of BP_LOCATION which get a valid
577    result from bp_location_has_shadow.  You can use it for roughly
578    limiting the subrange of BP_LOCATION to scan for shadow bytes for
579    an address you need to read.  */
580
581 static CORE_ADDR bp_location_placed_address_before_address_max;
582
583 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
584    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
585    BP_LOCATION which get a valid result from bp_location_has_shadow.
586    You can use it for roughly limiting the subrange of BP_LOCATION to
587    scan for shadow bytes for an address you need to read.  */
588
589 static CORE_ADDR bp_location_shadow_len_after_address_max;
590
591 /* The locations that no longer correspond to any breakpoint, unlinked
592    from bp_location array, but for which a hit may still be reported
593    by a target.  */
594 VEC(bp_location_p) *moribund_locations = NULL;
595
596 /* Number of last breakpoint made.  */
597
598 static int breakpoint_count;
599
600 /* The value of `breakpoint_count' before the last command that
601    created breakpoints.  If the last (break-like) command created more
602    than one breakpoint, then the difference between BREAKPOINT_COUNT
603    and PREV_BREAKPOINT_COUNT is more than one.  */
604 static int prev_breakpoint_count;
605
606 /* Number of last tracepoint made.  */
607
608 static int tracepoint_count;
609
610 static struct cmd_list_element *breakpoint_set_cmdlist;
611 static struct cmd_list_element *breakpoint_show_cmdlist;
612 struct cmd_list_element *save_cmdlist;
613
614 /* Return whether a breakpoint is an active enabled breakpoint.  */
615 static int
616 breakpoint_enabled (struct breakpoint *b)
617 {
618   return (b->enable_state == bp_enabled);
619 }
620
621 /* Set breakpoint count to NUM.  */
622
623 static void
624 set_breakpoint_count (int num)
625 {
626   prev_breakpoint_count = breakpoint_count;
627   breakpoint_count = num;
628   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
629 }
630
631 /* Used by `start_rbreak_breakpoints' below, to record the current
632    breakpoint count before "rbreak" creates any breakpoint.  */
633 static int rbreak_start_breakpoint_count;
634
635 /* Called at the start an "rbreak" command to record the first
636    breakpoint made.  */
637
638 void
639 start_rbreak_breakpoints (void)
640 {
641   rbreak_start_breakpoint_count = breakpoint_count;
642 }
643
644 /* Called at the end of an "rbreak" command to record the last
645    breakpoint made.  */
646
647 void
648 end_rbreak_breakpoints (void)
649 {
650   prev_breakpoint_count = rbreak_start_breakpoint_count;
651 }
652
653 /* Used in run_command to zero the hit count when a new run starts.  */
654
655 void
656 clear_breakpoint_hit_counts (void)
657 {
658   struct breakpoint *b;
659
660   ALL_BREAKPOINTS (b)
661     b->hit_count = 0;
662 }
663
664 /* Allocate a new counted_command_line with reference count of 1.
665    The new structure owns COMMANDS.  */
666
667 static struct counted_command_line *
668 alloc_counted_command_line (struct command_line *commands)
669 {
670   struct counted_command_line *result
671     = xmalloc (sizeof (struct counted_command_line));
672
673   result->refc = 1;
674   result->commands = commands;
675   return result;
676 }
677
678 /* Increment reference count.  This does nothing if CMD is NULL.  */
679
680 static void
681 incref_counted_command_line (struct counted_command_line *cmd)
682 {
683   if (cmd)
684     ++cmd->refc;
685 }
686
687 /* Decrement reference count.  If the reference count reaches 0,
688    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
689    nothing if *CMDP is NULL.  */
690
691 static void
692 decref_counted_command_line (struct counted_command_line **cmdp)
693 {
694   if (*cmdp)
695     {
696       if (--(*cmdp)->refc == 0)
697         {
698           free_command_lines (&(*cmdp)->commands);
699           xfree (*cmdp);
700         }
701       *cmdp = NULL;
702     }
703 }
704
705 /* A cleanup function that calls decref_counted_command_line.  */
706
707 static void
708 do_cleanup_counted_command_line (void *arg)
709 {
710   decref_counted_command_line (arg);
711 }
712
713 /* Create a cleanup that calls decref_counted_command_line on the
714    argument.  */
715
716 static struct cleanup *
717 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
718 {
719   return make_cleanup (do_cleanup_counted_command_line, cmdp);
720 }
721
722 \f
723 /* Return the breakpoint with the specified number, or NULL
724    if the number does not refer to an existing breakpoint.  */
725
726 struct breakpoint *
727 get_breakpoint (int num)
728 {
729   struct breakpoint *b;
730
731   ALL_BREAKPOINTS (b)
732     if (b->number == num)
733       return b;
734   
735   return NULL;
736 }
737
738 \f
739
740 /* Mark locations as "conditions have changed" in case the target supports
741    evaluating conditions on its side.  */
742
743 static void
744 mark_breakpoint_modified (struct breakpoint *b)
745 {
746   struct bp_location *loc;
747
748   /* This is only meaningful if the target is
749      evaluating conditions and if the user has
750      opted for condition evaluation on the target's
751      side.  */
752   if (gdb_evaluates_breakpoint_condition_p ()
753       || !target_supports_evaluation_of_breakpoint_conditions ())
754     return;
755
756   if (!is_breakpoint (b))
757     return;
758
759   for (loc = b->loc; loc; loc = loc->next)
760     loc->condition_changed = condition_modified;
761 }
762
763 /* Mark location as "conditions have changed" in case the target supports
764    evaluating conditions on its side.  */
765
766 static void
767 mark_breakpoint_location_modified (struct bp_location *loc)
768 {
769   /* This is only meaningful if the target is
770      evaluating conditions and if the user has
771      opted for condition evaluation on the target's
772      side.  */
773   if (gdb_evaluates_breakpoint_condition_p ()
774       || !target_supports_evaluation_of_breakpoint_conditions ())
775
776     return;
777
778   if (!is_breakpoint (loc->owner))
779     return;
780
781   loc->condition_changed = condition_modified;
782 }
783
784 /* Sets the condition-evaluation mode using the static global
785    condition_evaluation_mode.  */
786
787 static void
788 set_condition_evaluation_mode (char *args, int from_tty,
789                                struct cmd_list_element *c)
790 {
791   const char *old_mode, *new_mode;
792
793   if ((condition_evaluation_mode_1 == condition_evaluation_target)
794       && !target_supports_evaluation_of_breakpoint_conditions ())
795     {
796       condition_evaluation_mode_1 = condition_evaluation_mode;
797       warning (_("Target does not support breakpoint condition evaluation.\n"
798                  "Using host evaluation mode instead."));
799       return;
800     }
801
802   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
803   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
804
805   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
806      settings was "auto".  */
807   condition_evaluation_mode = condition_evaluation_mode_1;
808
809   /* Only update the mode if the user picked a different one.  */
810   if (new_mode != old_mode)
811     {
812       struct bp_location *loc, **loc_tmp;
813       /* If the user switched to a different evaluation mode, we
814          need to synch the changes with the target as follows:
815
816          "host" -> "target": Send all (valid) conditions to the target.
817          "target" -> "host": Remove all the conditions from the target.
818       */
819
820       if (new_mode == condition_evaluation_target)
821         {
822           /* Mark everything modified and synch conditions with the
823              target.  */
824           ALL_BP_LOCATIONS (loc, loc_tmp)
825             mark_breakpoint_location_modified (loc);
826         }
827       else
828         {
829           /* Manually mark non-duplicate locations to synch conditions
830              with the target.  We do this to remove all the conditions the
831              target knows about.  */
832           ALL_BP_LOCATIONS (loc, loc_tmp)
833             if (is_breakpoint (loc->owner) && loc->inserted)
834               loc->needs_update = 1;
835         }
836
837       /* Do the update.  */
838       update_global_location_list (1);
839     }
840
841   return;
842 }
843
844 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
845    what "auto" is translating to.  */
846
847 static void
848 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
849                                 struct cmd_list_element *c, const char *value)
850 {
851   if (condition_evaluation_mode == condition_evaluation_auto)
852     fprintf_filtered (file,
853                       _("Breakpoint condition evaluation "
854                         "mode is %s (currently %s).\n"),
855                       value,
856                       breakpoint_condition_evaluation_mode ());
857   else
858     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
859                       value);
860 }
861
862 /* A comparison function for bp_location AP and BP that is used by
863    bsearch.  This comparison function only cares about addresses, unlike
864    the more general bp_location_compare function.  */
865
866 static int
867 bp_location_compare_addrs (const void *ap, const void *bp)
868 {
869   struct bp_location *a = *(void **) ap;
870   struct bp_location *b = *(void **) bp;
871
872   if (a->address == b->address)
873     return 0;
874   else
875     return ((a->address > b->address) - (a->address < b->address));
876 }
877
878 /* Helper function to skip all bp_locations with addresses
879    less than ADDRESS.  It returns the first bp_location that
880    is greater than or equal to ADDRESS.  If none is found, just
881    return NULL.  */
882
883 static struct bp_location **
884 get_first_locp_gte_addr (CORE_ADDR address)
885 {
886   struct bp_location dummy_loc;
887   struct bp_location *dummy_locp = &dummy_loc;
888   struct bp_location **locp_found = NULL;
889
890   /* Initialize the dummy location's address field.  */
891   memset (&dummy_loc, 0, sizeof (struct bp_location));
892   dummy_loc.address = address;
893
894   /* Find a close match to the first location at ADDRESS.  */
895   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
896                         sizeof (struct bp_location **),
897                         bp_location_compare_addrs);
898
899   /* Nothing was found, nothing left to do.  */
900   if (locp_found == NULL)
901     return NULL;
902
903   /* We may have found a location that is at ADDRESS but is not the first in the
904      location's list.  Go backwards (if possible) and locate the first one.  */
905   while ((locp_found - 1) >= bp_location
906          && (*(locp_found - 1))->address == address)
907     locp_found--;
908
909   return locp_found;
910 }
911
912 void
913 set_breakpoint_condition (struct breakpoint *b, char *exp,
914                           int from_tty)
915 {
916   xfree (b->cond_string);
917   b->cond_string = NULL;
918
919   if (is_watchpoint (b))
920     {
921       struct watchpoint *w = (struct watchpoint *) b;
922
923       xfree (w->cond_exp);
924       w->cond_exp = NULL;
925     }
926   else
927     {
928       struct bp_location *loc;
929
930       for (loc = b->loc; loc; loc = loc->next)
931         {
932           xfree (loc->cond);
933           loc->cond = NULL;
934
935           /* No need to free the condition agent expression
936              bytecode (if we have one).  We will handle this
937              when we go through update_global_location_list.  */
938         }
939     }
940
941   if (*exp == 0)
942     {
943       if (from_tty)
944         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
945     }
946   else
947     {
948       const char *arg = exp;
949
950       /* I don't know if it matters whether this is the string the user
951          typed in or the decompiled expression.  */
952       b->cond_string = xstrdup (arg);
953       b->condition_not_parsed = 0;
954
955       if (is_watchpoint (b))
956         {
957           struct watchpoint *w = (struct watchpoint *) b;
958
959           innermost_block = NULL;
960           arg = exp;
961           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
962           if (*arg)
963             error (_("Junk at end of expression"));
964           w->cond_exp_valid_block = innermost_block;
965         }
966       else
967         {
968           struct bp_location *loc;
969
970           for (loc = b->loc; loc; loc = loc->next)
971             {
972               arg = exp;
973               loc->cond =
974                 parse_exp_1 (&arg, loc->address,
975                              block_for_pc (loc->address), 0);
976               if (*arg)
977                 error (_("Junk at end of expression"));
978             }
979         }
980     }
981   mark_breakpoint_modified (b);
982
983   observer_notify_breakpoint_modified (b);
984 }
985
986 /* Completion for the "condition" command.  */
987
988 static VEC (char_ptr) *
989 condition_completer (struct cmd_list_element *cmd,
990                      const char *text, const char *word)
991 {
992   const char *space;
993
994   text = skip_spaces_const (text);
995   space = skip_to_space_const (text);
996   if (*space == '\0')
997     {
998       int len;
999       struct breakpoint *b;
1000       VEC (char_ptr) *result = NULL;
1001
1002       if (text[0] == '$')
1003         {
1004           /* We don't support completion of history indices.  */
1005           if (isdigit (text[1]))
1006             return NULL;
1007           return complete_internalvar (&text[1]);
1008         }
1009
1010       /* We're completing the breakpoint number.  */
1011       len = strlen (text);
1012
1013       ALL_BREAKPOINTS (b)
1014         {
1015           char number[50];
1016
1017           xsnprintf (number, sizeof (number), "%d", b->number);
1018
1019           if (strncmp (number, text, len) == 0)
1020             VEC_safe_push (char_ptr, result, xstrdup (number));
1021         }
1022
1023       return result;
1024     }
1025
1026   /* We're completing the expression part.  */
1027   text = skip_spaces_const (space);
1028   return expression_completer (cmd, text, word);
1029 }
1030
1031 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1032
1033 static void
1034 condition_command (char *arg, int from_tty)
1035 {
1036   struct breakpoint *b;
1037   char *p;
1038   int bnum;
1039
1040   if (arg == 0)
1041     error_no_arg (_("breakpoint number"));
1042
1043   p = arg;
1044   bnum = get_number (&p);
1045   if (bnum == 0)
1046     error (_("Bad breakpoint argument: '%s'"), arg);
1047
1048   ALL_BREAKPOINTS (b)
1049     if (b->number == bnum)
1050       {
1051         /* Check if this breakpoint has a Python object assigned to
1052            it, and if it has a definition of the "stop"
1053            method.  This method and conditions entered into GDB from
1054            the CLI are mutually exclusive.  */
1055         if (b->py_bp_object
1056             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
1057           error (_("Cannot set a condition where a Python 'stop' "
1058                    "method has been defined in the breakpoint."));
1059         set_breakpoint_condition (b, p, from_tty);
1060
1061         if (is_breakpoint (b))
1062           update_global_location_list (1);
1063
1064         return;
1065       }
1066
1067   error (_("No breakpoint number %d."), bnum);
1068 }
1069
1070 /* Check that COMMAND do not contain commands that are suitable
1071    only for tracepoints and not suitable for ordinary breakpoints.
1072    Throw if any such commands is found.  */
1073
1074 static void
1075 check_no_tracepoint_commands (struct command_line *commands)
1076 {
1077   struct command_line *c;
1078
1079   for (c = commands; c; c = c->next)
1080     {
1081       int i;
1082
1083       if (c->control_type == while_stepping_control)
1084         error (_("The 'while-stepping' command can "
1085                  "only be used for tracepoints"));
1086
1087       for (i = 0; i < c->body_count; ++i)
1088         check_no_tracepoint_commands ((c->body_list)[i]);
1089
1090       /* Not that command parsing removes leading whitespace and comment
1091          lines and also empty lines.  So, we only need to check for
1092          command directly.  */
1093       if (strstr (c->line, "collect ") == c->line)
1094         error (_("The 'collect' command can only be used for tracepoints"));
1095
1096       if (strstr (c->line, "teval ") == c->line)
1097         error (_("The 'teval' command can only be used for tracepoints"));
1098     }
1099 }
1100
1101 /* Encapsulate tests for different types of tracepoints.  */
1102
1103 static int
1104 is_tracepoint_type (enum bptype type)
1105 {
1106   return (type == bp_tracepoint
1107           || type == bp_fast_tracepoint
1108           || type == bp_static_tracepoint);
1109 }
1110
1111 int
1112 is_tracepoint (const struct breakpoint *b)
1113 {
1114   return is_tracepoint_type (b->type);
1115 }
1116
1117 /* A helper function that validates that COMMANDS are valid for a
1118    breakpoint.  This function will throw an exception if a problem is
1119    found.  */
1120
1121 static void
1122 validate_commands_for_breakpoint (struct breakpoint *b,
1123                                   struct command_line *commands)
1124 {
1125   if (is_tracepoint (b))
1126     {
1127       struct tracepoint *t = (struct tracepoint *) b;
1128       struct command_line *c;
1129       struct command_line *while_stepping = 0;
1130
1131       /* Reset the while-stepping step count.  The previous commands
1132          might have included a while-stepping action, while the new
1133          ones might not.  */
1134       t->step_count = 0;
1135
1136       /* We need to verify that each top-level element of commands is
1137          valid for tracepoints, that there's at most one
1138          while-stepping element, and that the while-stepping's body
1139          has valid tracing commands excluding nested while-stepping.
1140          We also need to validate the tracepoint action line in the
1141          context of the tracepoint --- validate_actionline actually
1142          has side effects, like setting the tracepoint's
1143          while-stepping STEP_COUNT, in addition to checking if the
1144          collect/teval actions parse and make sense in the
1145          tracepoint's context.  */
1146       for (c = commands; c; c = c->next)
1147         {
1148           if (c->control_type == while_stepping_control)
1149             {
1150               if (b->type == bp_fast_tracepoint)
1151                 error (_("The 'while-stepping' command "
1152                          "cannot be used for fast tracepoint"));
1153               else if (b->type == bp_static_tracepoint)
1154                 error (_("The 'while-stepping' command "
1155                          "cannot be used for static tracepoint"));
1156
1157               if (while_stepping)
1158                 error (_("The 'while-stepping' command "
1159                          "can be used only once"));
1160               else
1161                 while_stepping = c;
1162             }
1163
1164           validate_actionline (c->line, b);
1165         }
1166       if (while_stepping)
1167         {
1168           struct command_line *c2;
1169
1170           gdb_assert (while_stepping->body_count == 1);
1171           c2 = while_stepping->body_list[0];
1172           for (; c2; c2 = c2->next)
1173             {
1174               if (c2->control_type == while_stepping_control)
1175                 error (_("The 'while-stepping' command cannot be nested"));
1176             }
1177         }
1178     }
1179   else
1180     {
1181       check_no_tracepoint_commands (commands);
1182     }
1183 }
1184
1185 /* Return a vector of all the static tracepoints set at ADDR.  The
1186    caller is responsible for releasing the vector.  */
1187
1188 VEC(breakpoint_p) *
1189 static_tracepoints_here (CORE_ADDR addr)
1190 {
1191   struct breakpoint *b;
1192   VEC(breakpoint_p) *found = 0;
1193   struct bp_location *loc;
1194
1195   ALL_BREAKPOINTS (b)
1196     if (b->type == bp_static_tracepoint)
1197       {
1198         for (loc = b->loc; loc; loc = loc->next)
1199           if (loc->address == addr)
1200             VEC_safe_push(breakpoint_p, found, b);
1201       }
1202
1203   return found;
1204 }
1205
1206 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1207    validate that only allowed commands are included.  */
1208
1209 void
1210 breakpoint_set_commands (struct breakpoint *b, 
1211                          struct command_line *commands)
1212 {
1213   validate_commands_for_breakpoint (b, commands);
1214
1215   decref_counted_command_line (&b->commands);
1216   b->commands = alloc_counted_command_line (commands);
1217   observer_notify_breakpoint_modified (b);
1218 }
1219
1220 /* Set the internal `silent' flag on the breakpoint.  Note that this
1221    is not the same as the "silent" that may appear in the breakpoint's
1222    commands.  */
1223
1224 void
1225 breakpoint_set_silent (struct breakpoint *b, int silent)
1226 {
1227   int old_silent = b->silent;
1228
1229   b->silent = silent;
1230   if (old_silent != silent)
1231     observer_notify_breakpoint_modified (b);
1232 }
1233
1234 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1235    breakpoint work for any thread.  */
1236
1237 void
1238 breakpoint_set_thread (struct breakpoint *b, int thread)
1239 {
1240   int old_thread = b->thread;
1241
1242   b->thread = thread;
1243   if (old_thread != thread)
1244     observer_notify_breakpoint_modified (b);
1245 }
1246
1247 /* Set the task for this breakpoint.  If TASK is 0, make the
1248    breakpoint work for any task.  */
1249
1250 void
1251 breakpoint_set_task (struct breakpoint *b, int task)
1252 {
1253   int old_task = b->task;
1254
1255   b->task = task;
1256   if (old_task != task)
1257     observer_notify_breakpoint_modified (b);
1258 }
1259
1260 void
1261 check_tracepoint_command (char *line, void *closure)
1262 {
1263   struct breakpoint *b = closure;
1264
1265   validate_actionline (line, b);
1266 }
1267
1268 /* A structure used to pass information through
1269    map_breakpoint_numbers.  */
1270
1271 struct commands_info
1272 {
1273   /* True if the command was typed at a tty.  */
1274   int from_tty;
1275
1276   /* The breakpoint range spec.  */
1277   char *arg;
1278
1279   /* Non-NULL if the body of the commands are being read from this
1280      already-parsed command.  */
1281   struct command_line *control;
1282
1283   /* The command lines read from the user, or NULL if they have not
1284      yet been read.  */
1285   struct counted_command_line *cmd;
1286 };
1287
1288 /* A callback for map_breakpoint_numbers that sets the commands for
1289    commands_command.  */
1290
1291 static void
1292 do_map_commands_command (struct breakpoint *b, void *data)
1293 {
1294   struct commands_info *info = data;
1295
1296   if (info->cmd == NULL)
1297     {
1298       struct command_line *l;
1299
1300       if (info->control != NULL)
1301         l = copy_command_lines (info->control->body_list[0]);
1302       else
1303         {
1304           struct cleanup *old_chain;
1305           char *str;
1306
1307           str = xstrprintf (_("Type commands for breakpoint(s) "
1308                               "%s, one per line."),
1309                             info->arg);
1310
1311           old_chain = make_cleanup (xfree, str);
1312
1313           l = read_command_lines (str,
1314                                   info->from_tty, 1,
1315                                   (is_tracepoint (b)
1316                                    ? check_tracepoint_command : 0),
1317                                   b);
1318
1319           do_cleanups (old_chain);
1320         }
1321
1322       info->cmd = alloc_counted_command_line (l);
1323     }
1324
1325   /* If a breakpoint was on the list more than once, we don't need to
1326      do anything.  */
1327   if (b->commands != info->cmd)
1328     {
1329       validate_commands_for_breakpoint (b, info->cmd->commands);
1330       incref_counted_command_line (info->cmd);
1331       decref_counted_command_line (&b->commands);
1332       b->commands = info->cmd;
1333       observer_notify_breakpoint_modified (b);
1334     }
1335 }
1336
1337 static void
1338 commands_command_1 (char *arg, int from_tty, 
1339                     struct command_line *control)
1340 {
1341   struct cleanup *cleanups;
1342   struct commands_info info;
1343
1344   info.from_tty = from_tty;
1345   info.control = control;
1346   info.cmd = NULL;
1347   /* If we read command lines from the user, then `info' will hold an
1348      extra reference to the commands that we must clean up.  */
1349   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1350
1351   if (arg == NULL || !*arg)
1352     {
1353       if (breakpoint_count - prev_breakpoint_count > 1)
1354         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1355                           breakpoint_count);
1356       else if (breakpoint_count > 0)
1357         arg = xstrprintf ("%d", breakpoint_count);
1358       else
1359         {
1360           /* So that we don't try to free the incoming non-NULL
1361              argument in the cleanup below.  Mapping breakpoint
1362              numbers will fail in this case.  */
1363           arg = NULL;
1364         }
1365     }
1366   else
1367     /* The command loop has some static state, so we need to preserve
1368        our argument.  */
1369     arg = xstrdup (arg);
1370
1371   if (arg != NULL)
1372     make_cleanup (xfree, arg);
1373
1374   info.arg = arg;
1375
1376   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1377
1378   if (info.cmd == NULL)
1379     error (_("No breakpoints specified."));
1380
1381   do_cleanups (cleanups);
1382 }
1383
1384 static void
1385 commands_command (char *arg, int from_tty)
1386 {
1387   commands_command_1 (arg, from_tty, NULL);
1388 }
1389
1390 /* Like commands_command, but instead of reading the commands from
1391    input stream, takes them from an already parsed command structure.
1392
1393    This is used by cli-script.c to DTRT with breakpoint commands
1394    that are part of if and while bodies.  */
1395 enum command_control_type
1396 commands_from_control_command (char *arg, struct command_line *cmd)
1397 {
1398   commands_command_1 (arg, 0, cmd);
1399   return simple_control;
1400 }
1401
1402 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1403
1404 static int
1405 bp_location_has_shadow (struct bp_location *bl)
1406 {
1407   if (bl->loc_type != bp_loc_software_breakpoint)
1408     return 0;
1409   if (!bl->inserted)
1410     return 0;
1411   if (bl->target_info.shadow_len == 0)
1412     /* BL isn't valid, or doesn't shadow memory.  */
1413     return 0;
1414   return 1;
1415 }
1416
1417 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1418    by replacing any memory breakpoints with their shadowed contents.
1419
1420    If READBUF is not NULL, this buffer must not overlap with any of
1421    the breakpoint location's shadow_contents buffers.  Otherwise,
1422    a failed assertion internal error will be raised.
1423
1424    The range of shadowed area by each bp_location is:
1425      bl->address - bp_location_placed_address_before_address_max
1426      up to bl->address + bp_location_shadow_len_after_address_max
1427    The range we were requested to resolve shadows for is:
1428      memaddr ... memaddr + len
1429    Thus the safe cutoff boundaries for performance optimization are
1430      memaddr + len <= (bl->address
1431                        - bp_location_placed_address_before_address_max)
1432    and:
1433      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1434
1435 void
1436 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1437                         const gdb_byte *writebuf_org,
1438                         ULONGEST memaddr, LONGEST len)
1439 {
1440   /* Left boundary, right boundary and median element of our binary
1441      search.  */
1442   unsigned bc_l, bc_r, bc;
1443
1444   /* Find BC_L which is a leftmost element which may affect BUF
1445      content.  It is safe to report lower value but a failure to
1446      report higher one.  */
1447
1448   bc_l = 0;
1449   bc_r = bp_location_count;
1450   while (bc_l + 1 < bc_r)
1451     {
1452       struct bp_location *bl;
1453
1454       bc = (bc_l + bc_r) / 2;
1455       bl = bp_location[bc];
1456
1457       /* Check first BL->ADDRESS will not overflow due to the added
1458          constant.  Then advance the left boundary only if we are sure
1459          the BC element can in no way affect the BUF content (MEMADDR
1460          to MEMADDR + LEN range).
1461
1462          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1463          offset so that we cannot miss a breakpoint with its shadow
1464          range tail still reaching MEMADDR.  */
1465
1466       if ((bl->address + bp_location_shadow_len_after_address_max
1467            >= bl->address)
1468           && (bl->address + bp_location_shadow_len_after_address_max
1469               <= memaddr))
1470         bc_l = bc;
1471       else
1472         bc_r = bc;
1473     }
1474
1475   /* Due to the binary search above, we need to make sure we pick the
1476      first location that's at BC_L's address.  E.g., if there are
1477      multiple locations at the same address, BC_L may end up pointing
1478      at a duplicate location, and miss the "master"/"inserted"
1479      location.  Say, given locations L1, L2 and L3 at addresses A and
1480      B:
1481
1482       L1@A, L2@A, L3@B, ...
1483
1484      BC_L could end up pointing at location L2, while the "master"
1485      location could be L1.  Since the `loc->inserted' flag is only set
1486      on "master" locations, we'd forget to restore the shadow of L1
1487      and L2.  */
1488   while (bc_l > 0
1489          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1490     bc_l--;
1491
1492   /* Now do full processing of the found relevant range of elements.  */
1493
1494   for (bc = bc_l; bc < bp_location_count; bc++)
1495   {
1496     struct bp_location *bl = bp_location[bc];
1497     CORE_ADDR bp_addr = 0;
1498     int bp_size = 0;
1499     int bptoffset = 0;
1500
1501     /* bp_location array has BL->OWNER always non-NULL.  */
1502     if (bl->owner->type == bp_none)
1503       warning (_("reading through apparently deleted breakpoint #%d?"),
1504                bl->owner->number);
1505
1506     /* Performance optimization: any further element can no longer affect BUF
1507        content.  */
1508
1509     if (bl->address >= bp_location_placed_address_before_address_max
1510         && memaddr + len <= (bl->address
1511                              - bp_location_placed_address_before_address_max))
1512       break;
1513
1514     if (!bp_location_has_shadow (bl))
1515       continue;
1516     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1517                                    current_program_space->aspace, 0))
1518       continue;
1519
1520     /* Addresses and length of the part of the breakpoint that
1521        we need to copy.  */
1522     bp_addr = bl->target_info.placed_address;
1523     bp_size = bl->target_info.shadow_len;
1524
1525     if (bp_addr + bp_size <= memaddr)
1526       /* The breakpoint is entirely before the chunk of memory we
1527          are reading.  */
1528       continue;
1529
1530     if (bp_addr >= memaddr + len)
1531       /* The breakpoint is entirely after the chunk of memory we are
1532          reading.  */
1533       continue;
1534
1535     /* Offset within shadow_contents.  */
1536     if (bp_addr < memaddr)
1537       {
1538         /* Only copy the second part of the breakpoint.  */
1539         bp_size -= memaddr - bp_addr;
1540         bptoffset = memaddr - bp_addr;
1541         bp_addr = memaddr;
1542       }
1543
1544     if (bp_addr + bp_size > memaddr + len)
1545       {
1546         /* Only copy the first part of the breakpoint.  */
1547         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1548       }
1549
1550     if (readbuf != NULL)
1551       {
1552         /* Verify that the readbuf buffer does not overlap with
1553            the shadow_contents buffer.  */
1554         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1555                     || readbuf >= (bl->target_info.shadow_contents
1556                                    + bl->target_info.shadow_len));
1557
1558         /* Update the read buffer with this inserted breakpoint's
1559            shadow.  */
1560         memcpy (readbuf + bp_addr - memaddr,
1561                 bl->target_info.shadow_contents + bptoffset, bp_size);
1562       }
1563     else
1564       {
1565         struct gdbarch *gdbarch = bl->gdbarch;
1566         const unsigned char *bp;
1567         CORE_ADDR placed_address = bl->target_info.placed_address;
1568         int placed_size = bl->target_info.placed_size;
1569
1570         /* Update the shadow with what we want to write to memory.  */
1571         memcpy (bl->target_info.shadow_contents + bptoffset,
1572                 writebuf_org + bp_addr - memaddr, bp_size);
1573
1574         /* Determine appropriate breakpoint contents and size for this
1575            address.  */
1576         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1577
1578         /* Update the final write buffer with this inserted
1579            breakpoint's INSN.  */
1580         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1581       }
1582   }
1583 }
1584 \f
1585
1586 /* Return true if BPT is either a software breakpoint or a hardware
1587    breakpoint.  */
1588
1589 int
1590 is_breakpoint (const struct breakpoint *bpt)
1591 {
1592   return (bpt->type == bp_breakpoint
1593           || bpt->type == bp_hardware_breakpoint
1594           || bpt->type == bp_dprintf);
1595 }
1596
1597 /* Return true if BPT is of any hardware watchpoint kind.  */
1598
1599 static int
1600 is_hardware_watchpoint (const struct breakpoint *bpt)
1601 {
1602   return (bpt->type == bp_hardware_watchpoint
1603           || bpt->type == bp_read_watchpoint
1604           || bpt->type == bp_access_watchpoint);
1605 }
1606
1607 /* Return true if BPT is of any watchpoint kind, hardware or
1608    software.  */
1609
1610 int
1611 is_watchpoint (const struct breakpoint *bpt)
1612 {
1613   return (is_hardware_watchpoint (bpt)
1614           || bpt->type == bp_watchpoint);
1615 }
1616
1617 /* Returns true if the current thread and its running state are safe
1618    to evaluate or update watchpoint B.  Watchpoints on local
1619    expressions need to be evaluated in the context of the thread that
1620    was current when the watchpoint was created, and, that thread needs
1621    to be stopped to be able to select the correct frame context.
1622    Watchpoints on global expressions can be evaluated on any thread,
1623    and in any state.  It is presently left to the target allowing
1624    memory accesses when threads are running.  */
1625
1626 static int
1627 watchpoint_in_thread_scope (struct watchpoint *b)
1628 {
1629   return (b->base.pspace == current_program_space
1630           && (ptid_equal (b->watchpoint_thread, null_ptid)
1631               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1632                   && !is_executing (inferior_ptid))));
1633 }
1634
1635 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1636    associated bp_watchpoint_scope breakpoint.  */
1637
1638 static void
1639 watchpoint_del_at_next_stop (struct watchpoint *w)
1640 {
1641   struct breakpoint *b = &w->base;
1642
1643   if (b->related_breakpoint != b)
1644     {
1645       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1646       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1647       b->related_breakpoint->disposition = disp_del_at_next_stop;
1648       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1649       b->related_breakpoint = b;
1650     }
1651   b->disposition = disp_del_at_next_stop;
1652 }
1653
1654 /* Assuming that B is a watchpoint:
1655    - Reparse watchpoint expression, if REPARSE is non-zero
1656    - Evaluate expression and store the result in B->val
1657    - Evaluate the condition if there is one, and store the result
1658      in b->loc->cond.
1659    - Update the list of values that must be watched in B->loc.
1660
1661    If the watchpoint disposition is disp_del_at_next_stop, then do
1662    nothing.  If this is local watchpoint that is out of scope, delete
1663    it.
1664
1665    Even with `set breakpoint always-inserted on' the watchpoints are
1666    removed + inserted on each stop here.  Normal breakpoints must
1667    never be removed because they might be missed by a running thread
1668    when debugging in non-stop mode.  On the other hand, hardware
1669    watchpoints (is_hardware_watchpoint; processed here) are specific
1670    to each LWP since they are stored in each LWP's hardware debug
1671    registers.  Therefore, such LWP must be stopped first in order to
1672    be able to modify its hardware watchpoints.
1673
1674    Hardware watchpoints must be reset exactly once after being
1675    presented to the user.  It cannot be done sooner, because it would
1676    reset the data used to present the watchpoint hit to the user.  And
1677    it must not be done later because it could display the same single
1678    watchpoint hit during multiple GDB stops.  Note that the latter is
1679    relevant only to the hardware watchpoint types bp_read_watchpoint
1680    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1681    not user-visible - its hit is suppressed if the memory content has
1682    not changed.
1683
1684    The following constraints influence the location where we can reset
1685    hardware watchpoints:
1686
1687    * target_stopped_by_watchpoint and target_stopped_data_address are
1688      called several times when GDB stops.
1689
1690    [linux] 
1691    * Multiple hardware watchpoints can be hit at the same time,
1692      causing GDB to stop.  GDB only presents one hardware watchpoint
1693      hit at a time as the reason for stopping, and all the other hits
1694      are presented later, one after the other, each time the user
1695      requests the execution to be resumed.  Execution is not resumed
1696      for the threads still having pending hit event stored in
1697      LWP_INFO->STATUS.  While the watchpoint is already removed from
1698      the inferior on the first stop the thread hit event is kept being
1699      reported from its cached value by linux_nat_stopped_data_address
1700      until the real thread resume happens after the watchpoint gets
1701      presented and thus its LWP_INFO->STATUS gets reset.
1702
1703    Therefore the hardware watchpoint hit can get safely reset on the
1704    watchpoint removal from inferior.  */
1705
1706 static void
1707 update_watchpoint (struct watchpoint *b, int reparse)
1708 {
1709   int within_current_scope;
1710   struct frame_id saved_frame_id;
1711   int frame_saved;
1712
1713   /* If this is a local watchpoint, we only want to check if the
1714      watchpoint frame is in scope if the current thread is the thread
1715      that was used to create the watchpoint.  */
1716   if (!watchpoint_in_thread_scope (b))
1717     return;
1718
1719   if (b->base.disposition == disp_del_at_next_stop)
1720     return;
1721  
1722   frame_saved = 0;
1723
1724   /* Determine if the watchpoint is within scope.  */
1725   if (b->exp_valid_block == NULL)
1726     within_current_scope = 1;
1727   else
1728     {
1729       struct frame_info *fi = get_current_frame ();
1730       struct gdbarch *frame_arch = get_frame_arch (fi);
1731       CORE_ADDR frame_pc = get_frame_pc (fi);
1732
1733       /* If we're in a function epilogue, unwinding may not work
1734          properly, so do not attempt to recreate locations at this
1735          point.  See similar comments in watchpoint_check.  */
1736       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1737         return;
1738
1739       /* Save the current frame's ID so we can restore it after
1740          evaluating the watchpoint expression on its own frame.  */
1741       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1742          took a frame parameter, so that we didn't have to change the
1743          selected frame.  */
1744       frame_saved = 1;
1745       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1746
1747       fi = frame_find_by_id (b->watchpoint_frame);
1748       within_current_scope = (fi != NULL);
1749       if (within_current_scope)
1750         select_frame (fi);
1751     }
1752
1753   /* We don't free locations.  They are stored in the bp_location array
1754      and update_global_location_list will eventually delete them and
1755      remove breakpoints if needed.  */
1756   b->base.loc = NULL;
1757
1758   if (within_current_scope && reparse)
1759     {
1760       const char *s;
1761
1762       if (b->exp)
1763         {
1764           xfree (b->exp);
1765           b->exp = NULL;
1766         }
1767       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1768       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1769       /* If the meaning of expression itself changed, the old value is
1770          no longer relevant.  We don't want to report a watchpoint hit
1771          to the user when the old value and the new value may actually
1772          be completely different objects.  */
1773       value_free (b->val);
1774       b->val = NULL;
1775       b->val_valid = 0;
1776
1777       /* Note that unlike with breakpoints, the watchpoint's condition
1778          expression is stored in the breakpoint object, not in the
1779          locations (re)created below.  */
1780       if (b->base.cond_string != NULL)
1781         {
1782           if (b->cond_exp != NULL)
1783             {
1784               xfree (b->cond_exp);
1785               b->cond_exp = NULL;
1786             }
1787
1788           s = b->base.cond_string;
1789           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1790         }
1791     }
1792
1793   /* If we failed to parse the expression, for example because
1794      it refers to a global variable in a not-yet-loaded shared library,
1795      don't try to insert watchpoint.  We don't automatically delete
1796      such watchpoint, though, since failure to parse expression
1797      is different from out-of-scope watchpoint.  */
1798   if (!target_has_execution)
1799     {
1800       /* Without execution, memory can't change.  No use to try and
1801          set watchpoint locations.  The watchpoint will be reset when
1802          the target gains execution, through breakpoint_re_set.  */
1803       if (!can_use_hw_watchpoints)
1804         {
1805           if (b->base.ops->works_in_software_mode (&b->base))
1806             b->base.type = bp_watchpoint;
1807           else
1808             error (_("Software read/access watchpoints not supported."));
1809         }
1810     }
1811   else if (within_current_scope && b->exp)
1812     {
1813       int pc = 0;
1814       struct value *val_chain, *v, *result, *next;
1815       struct program_space *frame_pspace;
1816
1817       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1818
1819       /* Avoid setting b->val if it's already set.  The meaning of
1820          b->val is 'the last value' user saw, and we should update
1821          it only if we reported that last value to user.  As it
1822          happens, the code that reports it updates b->val directly.
1823          We don't keep track of the memory value for masked
1824          watchpoints.  */
1825       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1826         {
1827           b->val = v;
1828           b->val_valid = 1;
1829         }
1830
1831       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1832
1833       /* Look at each value on the value chain.  */
1834       for (v = val_chain; v; v = value_next (v))
1835         {
1836           /* If it's a memory location, and GDB actually needed
1837              its contents to evaluate the expression, then we
1838              must watch it.  If the first value returned is
1839              still lazy, that means an error occurred reading it;
1840              watch it anyway in case it becomes readable.  */
1841           if (VALUE_LVAL (v) == lval_memory
1842               && (v == val_chain || ! value_lazy (v)))
1843             {
1844               struct type *vtype = check_typedef (value_type (v));
1845
1846               /* We only watch structs and arrays if user asked
1847                  for it explicitly, never if they just happen to
1848                  appear in the middle of some value chain.  */
1849               if (v == result
1850                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1851                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1852                 {
1853                   CORE_ADDR addr;
1854                   int type;
1855                   struct bp_location *loc, **tmp;
1856
1857                   addr = value_address (v);
1858                   type = hw_write;
1859                   if (b->base.type == bp_read_watchpoint)
1860                     type = hw_read;
1861                   else if (b->base.type == bp_access_watchpoint)
1862                     type = hw_access;
1863
1864                   loc = allocate_bp_location (&b->base);
1865                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1866                     ;
1867                   *tmp = loc;
1868                   loc->gdbarch = get_type_arch (value_type (v));
1869
1870                   loc->pspace = frame_pspace;
1871                   loc->address = addr;
1872                   loc->length = TYPE_LENGTH (value_type (v));
1873                   loc->watchpoint_type = type;
1874                 }
1875             }
1876         }
1877
1878       /* Change the type of breakpoint between hardware assisted or
1879          an ordinary watchpoint depending on the hardware support
1880          and free hardware slots.  REPARSE is set when the inferior
1881          is started.  */
1882       if (reparse)
1883         {
1884           int reg_cnt;
1885           enum bp_loc_type loc_type;
1886           struct bp_location *bl;
1887
1888           reg_cnt = can_use_hardware_watchpoint (val_chain);
1889
1890           if (reg_cnt)
1891             {
1892               int i, target_resources_ok, other_type_used;
1893               enum bptype type;
1894
1895               /* Use an exact watchpoint when there's only one memory region to be
1896                  watched, and only one debug register is needed to watch it.  */
1897               b->exact = target_exact_watchpoints && reg_cnt == 1;
1898
1899               /* We need to determine how many resources are already
1900                  used for all other hardware watchpoints plus this one
1901                  to see if we still have enough resources to also fit
1902                  this watchpoint in as well.  */
1903
1904               /* If this is a software watchpoint, we try to turn it
1905                  to a hardware one -- count resources as if B was of
1906                  hardware watchpoint type.  */
1907               type = b->base.type;
1908               if (type == bp_watchpoint)
1909                 type = bp_hardware_watchpoint;
1910
1911               /* This watchpoint may or may not have been placed on
1912                  the list yet at this point (it won't be in the list
1913                  if we're trying to create it for the first time,
1914                  through watch_command), so always account for it
1915                  manually.  */
1916
1917               /* Count resources used by all watchpoints except B.  */
1918               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1919
1920               /* Add in the resources needed for B.  */
1921               i += hw_watchpoint_use_count (&b->base);
1922
1923               target_resources_ok
1924                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1925               if (target_resources_ok <= 0)
1926                 {
1927                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1928
1929                   if (target_resources_ok == 0 && !sw_mode)
1930                     error (_("Target does not support this type of "
1931                              "hardware watchpoint."));
1932                   else if (target_resources_ok < 0 && !sw_mode)
1933                     error (_("There are not enough available hardware "
1934                              "resources for this watchpoint."));
1935
1936                   /* Downgrade to software watchpoint.  */
1937                   b->base.type = bp_watchpoint;
1938                 }
1939               else
1940                 {
1941                   /* If this was a software watchpoint, we've just
1942                      found we have enough resources to turn it to a
1943                      hardware watchpoint.  Otherwise, this is a
1944                      nop.  */
1945                   b->base.type = type;
1946                 }
1947             }
1948           else if (!b->base.ops->works_in_software_mode (&b->base))
1949             error (_("Expression cannot be implemented with "
1950                      "read/access watchpoint."));
1951           else
1952             b->base.type = bp_watchpoint;
1953
1954           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1955                       : bp_loc_hardware_watchpoint);
1956           for (bl = b->base.loc; bl; bl = bl->next)
1957             bl->loc_type = loc_type;
1958         }
1959
1960       for (v = val_chain; v; v = next)
1961         {
1962           next = value_next (v);
1963           if (v != b->val)
1964             value_free (v);
1965         }
1966
1967       /* If a software watchpoint is not watching any memory, then the
1968          above left it without any location set up.  But,
1969          bpstat_stop_status requires a location to be able to report
1970          stops, so make sure there's at least a dummy one.  */
1971       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1972         {
1973           struct breakpoint *base = &b->base;
1974           base->loc = allocate_bp_location (base);
1975           base->loc->pspace = frame_pspace;
1976           base->loc->address = -1;
1977           base->loc->length = -1;
1978           base->loc->watchpoint_type = -1;
1979         }
1980     }
1981   else if (!within_current_scope)
1982     {
1983       printf_filtered (_("\
1984 Watchpoint %d deleted because the program has left the block\n\
1985 in which its expression is valid.\n"),
1986                        b->base.number);
1987       watchpoint_del_at_next_stop (b);
1988     }
1989
1990   /* Restore the selected frame.  */
1991   if (frame_saved)
1992     select_frame (frame_find_by_id (saved_frame_id));
1993 }
1994
1995
1996 /* Returns 1 iff breakpoint location should be
1997    inserted in the inferior.  We don't differentiate the type of BL's owner
1998    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1999    breakpoint_ops is not defined, because in insert_bp_location,
2000    tracepoint's insert_location will not be called.  */
2001 static int
2002 should_be_inserted (struct bp_location *bl)
2003 {
2004   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2005     return 0;
2006
2007   if (bl->owner->disposition == disp_del_at_next_stop)
2008     return 0;
2009
2010   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2011     return 0;
2012
2013   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2014     return 0;
2015
2016   /* This is set for example, when we're attached to the parent of a
2017      vfork, and have detached from the child.  The child is running
2018      free, and we expect it to do an exec or exit, at which point the
2019      OS makes the parent schedulable again (and the target reports
2020      that the vfork is done).  Until the child is done with the shared
2021      memory region, do not insert breakpoints in the parent, otherwise
2022      the child could still trip on the parent's breakpoints.  Since
2023      the parent is blocked anyway, it won't miss any breakpoint.  */
2024   if (bl->pspace->breakpoints_not_allowed)
2025     return 0;
2026
2027   return 1;
2028 }
2029
2030 /* Same as should_be_inserted but does the check assuming
2031    that the location is not duplicated.  */
2032
2033 static int
2034 unduplicated_should_be_inserted (struct bp_location *bl)
2035 {
2036   int result;
2037   const int save_duplicate = bl->duplicate;
2038
2039   bl->duplicate = 0;
2040   result = should_be_inserted (bl);
2041   bl->duplicate = save_duplicate;
2042   return result;
2043 }
2044
2045 /* Parses a conditional described by an expression COND into an
2046    agent expression bytecode suitable for evaluation
2047    by the bytecode interpreter.  Return NULL if there was
2048    any error during parsing.  */
2049
2050 static struct agent_expr *
2051 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2052 {
2053   struct agent_expr *aexpr = NULL;
2054   volatile struct gdb_exception ex;
2055
2056   if (!cond)
2057     return NULL;
2058
2059   /* We don't want to stop processing, so catch any errors
2060      that may show up.  */
2061   TRY_CATCH (ex, RETURN_MASK_ERROR)
2062     {
2063       aexpr = gen_eval_for_expr (scope, cond);
2064     }
2065
2066   if (ex.reason < 0)
2067     {
2068       /* If we got here, it means the condition could not be parsed to a valid
2069          bytecode expression and thus can't be evaluated on the target's side.
2070          It's no use iterating through the conditions.  */
2071       return NULL;
2072     }
2073
2074   /* We have a valid agent expression.  */
2075   return aexpr;
2076 }
2077
2078 /* Based on location BL, create a list of breakpoint conditions to be
2079    passed on to the target.  If we have duplicated locations with different
2080    conditions, we will add such conditions to the list.  The idea is that the
2081    target will evaluate the list of conditions and will only notify GDB when
2082    one of them is true.  */
2083
2084 static void
2085 build_target_condition_list (struct bp_location *bl)
2086 {
2087   struct bp_location **locp = NULL, **loc2p;
2088   int null_condition_or_parse_error = 0;
2089   int modified = bl->needs_update;
2090   struct bp_location *loc;
2091
2092   /* This is only meaningful if the target is
2093      evaluating conditions and if the user has
2094      opted for condition evaluation on the target's
2095      side.  */
2096   if (gdb_evaluates_breakpoint_condition_p ()
2097       || !target_supports_evaluation_of_breakpoint_conditions ())
2098     return;
2099
2100   /* Do a first pass to check for locations with no assigned
2101      conditions or conditions that fail to parse to a valid agent expression
2102      bytecode.  If any of these happen, then it's no use to send conditions
2103      to the target since this location will always trigger and generate a
2104      response back to GDB.  */
2105   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2106     {
2107       loc = (*loc2p);
2108       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2109         {
2110           if (modified)
2111             {
2112               struct agent_expr *aexpr;
2113
2114               /* Re-parse the conditions since something changed.  In that
2115                  case we already freed the condition bytecodes (see
2116                  force_breakpoint_reinsertion).  We just
2117                  need to parse the condition to bytecodes again.  */
2118               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2119               loc->cond_bytecode = aexpr;
2120
2121               /* Check if we managed to parse the conditional expression
2122                  correctly.  If not, we will not send this condition
2123                  to the target.  */
2124               if (aexpr)
2125                 continue;
2126             }
2127
2128           /* If we have a NULL bytecode expression, it means something
2129              went wrong or we have a null condition expression.  */
2130           if (!loc->cond_bytecode)
2131             {
2132               null_condition_or_parse_error = 1;
2133               break;
2134             }
2135         }
2136     }
2137
2138   /* If any of these happened, it means we will have to evaluate the conditions
2139      for the location's address on gdb's side.  It is no use keeping bytecodes
2140      for all the other duplicate locations, thus we free all of them here.
2141
2142      This is so we have a finer control over which locations' conditions are
2143      being evaluated by GDB or the remote stub.  */
2144   if (null_condition_or_parse_error)
2145     {
2146       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2147         {
2148           loc = (*loc2p);
2149           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2150             {
2151               /* Only go as far as the first NULL bytecode is
2152                  located.  */
2153               if (!loc->cond_bytecode)
2154                 return;
2155
2156               free_agent_expr (loc->cond_bytecode);
2157               loc->cond_bytecode = NULL;
2158             }
2159         }
2160     }
2161
2162   /* No NULL conditions or failed bytecode generation.  Build a condition list
2163      for this location's address.  */
2164   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2165     {
2166       loc = (*loc2p);
2167       if (loc->cond
2168           && is_breakpoint (loc->owner)
2169           && loc->pspace->num == bl->pspace->num
2170           && loc->owner->enable_state == bp_enabled
2171           && loc->enabled)
2172         /* Add the condition to the vector.  This will be used later to send the
2173            conditions to the target.  */
2174         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2175                        loc->cond_bytecode);
2176     }
2177
2178   return;
2179 }
2180
2181 /* Parses a command described by string CMD into an agent expression
2182    bytecode suitable for evaluation by the bytecode interpreter.
2183    Return NULL if there was any error during parsing.  */
2184
2185 static struct agent_expr *
2186 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2187 {
2188   struct cleanup *old_cleanups = 0;
2189   struct expression *expr, **argvec;
2190   struct agent_expr *aexpr = NULL;
2191   volatile struct gdb_exception ex;
2192   const char *cmdrest;
2193   const char *format_start, *format_end;
2194   struct format_piece *fpieces;
2195   int nargs;
2196   struct gdbarch *gdbarch = get_current_arch ();
2197
2198   if (!cmd)
2199     return NULL;
2200
2201   cmdrest = cmd;
2202
2203   if (*cmdrest == ',')
2204     ++cmdrest;
2205   cmdrest = skip_spaces_const (cmdrest);
2206
2207   if (*cmdrest++ != '"')
2208     error (_("No format string following the location"));
2209
2210   format_start = cmdrest;
2211
2212   fpieces = parse_format_string (&cmdrest);
2213
2214   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2215
2216   format_end = cmdrest;
2217
2218   if (*cmdrest++ != '"')
2219     error (_("Bad format string, non-terminated '\"'."));
2220   
2221   cmdrest = skip_spaces_const (cmdrest);
2222
2223   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2224     error (_("Invalid argument syntax"));
2225
2226   if (*cmdrest == ',')
2227     cmdrest++;
2228   cmdrest = skip_spaces_const (cmdrest);
2229
2230   /* For each argument, make an expression.  */
2231
2232   argvec = (struct expression **) alloca (strlen (cmd)
2233                                          * sizeof (struct expression *));
2234
2235   nargs = 0;
2236   while (*cmdrest != '\0')
2237     {
2238       const char *cmd1;
2239
2240       cmd1 = cmdrest;
2241       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2242       argvec[nargs++] = expr;
2243       cmdrest = cmd1;
2244       if (*cmdrest == ',')
2245         ++cmdrest;
2246     }
2247
2248   /* We don't want to stop processing, so catch any errors
2249      that may show up.  */
2250   TRY_CATCH (ex, RETURN_MASK_ERROR)
2251     {
2252       aexpr = gen_printf (scope, gdbarch, 0, 0,
2253                           format_start, format_end - format_start,
2254                           fpieces, nargs, argvec);
2255     }
2256
2257   do_cleanups (old_cleanups);
2258
2259   if (ex.reason < 0)
2260     {
2261       /* If we got here, it means the command could not be parsed to a valid
2262          bytecode expression and thus can't be evaluated on the target's side.
2263          It's no use iterating through the other commands.  */
2264       return NULL;
2265     }
2266
2267   /* We have a valid agent expression, return it.  */
2268   return aexpr;
2269 }
2270
2271 /* Based on location BL, create a list of breakpoint commands to be
2272    passed on to the target.  If we have duplicated locations with
2273    different commands, we will add any such to the list.  */
2274
2275 static void
2276 build_target_command_list (struct bp_location *bl)
2277 {
2278   struct bp_location **locp = NULL, **loc2p;
2279   int null_command_or_parse_error = 0;
2280   int modified = bl->needs_update;
2281   struct bp_location *loc;
2282
2283   /* For now, limit to agent-style dprintf breakpoints.  */
2284   if (bl->owner->type != bp_dprintf
2285       || strcmp (dprintf_style, dprintf_style_agent) != 0)
2286     return;
2287
2288   if (!target_can_run_breakpoint_commands ())
2289     return;
2290
2291   /* Do a first pass to check for locations with no assigned
2292      conditions or conditions that fail to parse to a valid agent expression
2293      bytecode.  If any of these happen, then it's no use to send conditions
2294      to the target since this location will always trigger and generate a
2295      response back to GDB.  */
2296   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2297     {
2298       loc = (*loc2p);
2299       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2300         {
2301           if (modified)
2302             {
2303               struct agent_expr *aexpr;
2304
2305               /* Re-parse the commands since something changed.  In that
2306                  case we already freed the command bytecodes (see
2307                  force_breakpoint_reinsertion).  We just
2308                  need to parse the command to bytecodes again.  */
2309               aexpr = parse_cmd_to_aexpr (bl->address,
2310                                           loc->owner->extra_string);
2311               loc->cmd_bytecode = aexpr;
2312
2313               if (!aexpr)
2314                 continue;
2315             }
2316
2317           /* If we have a NULL bytecode expression, it means something
2318              went wrong or we have a null command expression.  */
2319           if (!loc->cmd_bytecode)
2320             {
2321               null_command_or_parse_error = 1;
2322               break;
2323             }
2324         }
2325     }
2326
2327   /* If anything failed, then we're not doing target-side commands,
2328      and so clean up.  */
2329   if (null_command_or_parse_error)
2330     {
2331       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2332         {
2333           loc = (*loc2p);
2334           if (is_breakpoint (loc->owner)
2335               && loc->pspace->num == bl->pspace->num)
2336             {
2337               /* Only go as far as the first NULL bytecode is
2338                  located.  */
2339               if (loc->cmd_bytecode == NULL)
2340                 return;
2341
2342               free_agent_expr (loc->cmd_bytecode);
2343               loc->cmd_bytecode = NULL;
2344             }
2345         }
2346     }
2347
2348   /* No NULL commands or failed bytecode generation.  Build a command list
2349      for this location's address.  */
2350   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2351     {
2352       loc = (*loc2p);
2353       if (loc->owner->extra_string
2354           && is_breakpoint (loc->owner)
2355           && loc->pspace->num == bl->pspace->num
2356           && loc->owner->enable_state == bp_enabled
2357           && loc->enabled)
2358         /* Add the command to the vector.  This will be used later
2359            to send the commands to the target.  */
2360         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2361                        loc->cmd_bytecode);
2362     }
2363
2364   bl->target_info.persist = 0;
2365   /* Maybe flag this location as persistent.  */
2366   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2367     bl->target_info.persist = 1;
2368 }
2369
2370 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2371    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2372    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2373    Returns 0 for success, 1 if the bp_location type is not supported or
2374    -1 for failure.
2375
2376    NOTE drow/2003-09-09: This routine could be broken down to an
2377    object-style method for each breakpoint or catchpoint type.  */
2378 static int
2379 insert_bp_location (struct bp_location *bl,
2380                     struct ui_file *tmp_error_stream,
2381                     int *disabled_breaks,
2382                     int *hw_breakpoint_error,
2383                     int *hw_bp_error_explained_already)
2384 {
2385   int val = 0;
2386   char *hw_bp_err_string = NULL;
2387   struct gdb_exception e;
2388
2389   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2390     return 0;
2391
2392   /* Note we don't initialize bl->target_info, as that wipes out
2393      the breakpoint location's shadow_contents if the breakpoint
2394      is still inserted at that location.  This in turn breaks
2395      target_read_memory which depends on these buffers when
2396      a memory read is requested at the breakpoint location:
2397      Once the target_info has been wiped, we fail to see that
2398      we have a breakpoint inserted at that address and thus
2399      read the breakpoint instead of returning the data saved in
2400      the breakpoint location's shadow contents.  */
2401   bl->target_info.placed_address = bl->address;
2402   bl->target_info.placed_address_space = bl->pspace->aspace;
2403   bl->target_info.length = bl->length;
2404
2405   /* When working with target-side conditions, we must pass all the conditions
2406      for the same breakpoint address down to the target since GDB will not
2407      insert those locations.  With a list of breakpoint conditions, the target
2408      can decide when to stop and notify GDB.  */
2409
2410   if (is_breakpoint (bl->owner))
2411     {
2412       build_target_condition_list (bl);
2413       build_target_command_list (bl);
2414       /* Reset the modification marker.  */
2415       bl->needs_update = 0;
2416     }
2417
2418   if (bl->loc_type == bp_loc_software_breakpoint
2419       || bl->loc_type == bp_loc_hardware_breakpoint)
2420     {
2421       if (bl->owner->type != bp_hardware_breakpoint)
2422         {
2423           /* If the explicitly specified breakpoint type
2424              is not hardware breakpoint, check the memory map to see
2425              if the breakpoint address is in read only memory or not.
2426
2427              Two important cases are:
2428              - location type is not hardware breakpoint, memory
2429              is readonly.  We change the type of the location to
2430              hardware breakpoint.
2431              - location type is hardware breakpoint, memory is
2432              read-write.  This means we've previously made the
2433              location hardware one, but then the memory map changed,
2434              so we undo.
2435              
2436              When breakpoints are removed, remove_breakpoints will use
2437              location types we've just set here, the only possible
2438              problem is that memory map has changed during running
2439              program, but it's not going to work anyway with current
2440              gdb.  */
2441           struct mem_region *mr 
2442             = lookup_mem_region (bl->target_info.placed_address);
2443           
2444           if (mr)
2445             {
2446               if (automatic_hardware_breakpoints)
2447                 {
2448                   enum bp_loc_type new_type;
2449                   
2450                   if (mr->attrib.mode != MEM_RW)
2451                     new_type = bp_loc_hardware_breakpoint;
2452                   else 
2453                     new_type = bp_loc_software_breakpoint;
2454                   
2455                   if (new_type != bl->loc_type)
2456                     {
2457                       static int said = 0;
2458
2459                       bl->loc_type = new_type;
2460                       if (!said)
2461                         {
2462                           fprintf_filtered (gdb_stdout,
2463                                             _("Note: automatically using "
2464                                               "hardware breakpoints for "
2465                                               "read-only addresses.\n"));
2466                           said = 1;
2467                         }
2468                     }
2469                 }
2470               else if (bl->loc_type == bp_loc_software_breakpoint
2471                        && mr->attrib.mode != MEM_RW)        
2472                 warning (_("cannot set software breakpoint "
2473                            "at readonly address %s"),
2474                          paddress (bl->gdbarch, bl->address));
2475             }
2476         }
2477         
2478       /* First check to see if we have to handle an overlay.  */
2479       if (overlay_debugging == ovly_off
2480           || bl->section == NULL
2481           || !(section_is_overlay (bl->section)))
2482         {
2483           /* No overlay handling: just set the breakpoint.  */
2484           TRY_CATCH (e, RETURN_MASK_ALL)
2485             {
2486               val = bl->owner->ops->insert_location (bl);
2487             }
2488           if (e.reason < 0)
2489             {
2490               val = 1;
2491               hw_bp_err_string = (char *) e.message;
2492             }
2493         }
2494       else
2495         {
2496           /* This breakpoint is in an overlay section.
2497              Shall we set a breakpoint at the LMA?  */
2498           if (!overlay_events_enabled)
2499             {
2500               /* Yes -- overlay event support is not active, 
2501                  so we must try to set a breakpoint at the LMA.
2502                  This will not work for a hardware breakpoint.  */
2503               if (bl->loc_type == bp_loc_hardware_breakpoint)
2504                 warning (_("hardware breakpoint %d not supported in overlay!"),
2505                          bl->owner->number);
2506               else
2507                 {
2508                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2509                                                              bl->section);
2510                   /* Set a software (trap) breakpoint at the LMA.  */
2511                   bl->overlay_target_info = bl->target_info;
2512                   bl->overlay_target_info.placed_address = addr;
2513                   val = target_insert_breakpoint (bl->gdbarch,
2514                                                   &bl->overlay_target_info);
2515                   if (val != 0)
2516                     fprintf_unfiltered (tmp_error_stream,
2517                                         "Overlay breakpoint %d "
2518                                         "failed: in ROM?\n",
2519                                         bl->owner->number);
2520                 }
2521             }
2522           /* Shall we set a breakpoint at the VMA? */
2523           if (section_is_mapped (bl->section))
2524             {
2525               /* Yes.  This overlay section is mapped into memory.  */
2526               TRY_CATCH (e, RETURN_MASK_ALL)
2527                 {
2528                   val = bl->owner->ops->insert_location (bl);
2529                 }
2530               if (e.reason < 0)
2531                 {
2532                   val = 1;
2533                   hw_bp_err_string = (char *) e.message;
2534                 }
2535             }
2536           else
2537             {
2538               /* No.  This breakpoint will not be inserted.  
2539                  No error, but do not mark the bp as 'inserted'.  */
2540               return 0;
2541             }
2542         }
2543
2544       if (val)
2545         {
2546           /* Can't set the breakpoint.  */
2547           if (solib_name_from_address (bl->pspace, bl->address))
2548             {
2549               /* See also: disable_breakpoints_in_shlibs.  */
2550               val = 0;
2551               bl->shlib_disabled = 1;
2552               observer_notify_breakpoint_modified (bl->owner);
2553               if (!*disabled_breaks)
2554                 {
2555                   fprintf_unfiltered (tmp_error_stream, 
2556                                       "Cannot insert breakpoint %d.\n", 
2557                                       bl->owner->number);
2558                   fprintf_unfiltered (tmp_error_stream, 
2559                                       "Temporarily disabling shared "
2560                                       "library breakpoints:\n");
2561                 }
2562               *disabled_breaks = 1;
2563               fprintf_unfiltered (tmp_error_stream,
2564                                   "breakpoint #%d\n", bl->owner->number);
2565             }
2566           else
2567             {
2568               if (bl->loc_type == bp_loc_hardware_breakpoint)
2569                 {
2570                   *hw_breakpoint_error = 1;
2571                   *hw_bp_error_explained_already = hw_bp_err_string != NULL;
2572                   fprintf_unfiltered (tmp_error_stream,
2573                                       "Cannot insert hardware breakpoint %d%s",
2574                                       bl->owner->number, hw_bp_err_string ? ":" : ".\n");
2575                   if (hw_bp_err_string)
2576                     fprintf_unfiltered (tmp_error_stream, "%s.\n", hw_bp_err_string);
2577                 }
2578               else
2579                 {
2580                   char *message = memory_error_message (TARGET_XFER_E_IO,
2581                                                         bl->gdbarch, bl->address);
2582                   struct cleanup *old_chain = make_cleanup (xfree, message);
2583
2584                   fprintf_unfiltered (tmp_error_stream, 
2585                                       "Cannot insert breakpoint %d.\n"
2586                                       "%s\n",
2587                                       bl->owner->number, message);
2588
2589                   do_cleanups (old_chain);
2590                 }
2591
2592             }
2593         }
2594       else
2595         bl->inserted = 1;
2596
2597       return val;
2598     }
2599
2600   else if (bl->loc_type == bp_loc_hardware_watchpoint
2601            /* NOTE drow/2003-09-08: This state only exists for removing
2602               watchpoints.  It's not clear that it's necessary...  */
2603            && bl->owner->disposition != disp_del_at_next_stop)
2604     {
2605       gdb_assert (bl->owner->ops != NULL
2606                   && bl->owner->ops->insert_location != NULL);
2607
2608       val = bl->owner->ops->insert_location (bl);
2609
2610       /* If trying to set a read-watchpoint, and it turns out it's not
2611          supported, try emulating one with an access watchpoint.  */
2612       if (val == 1 && bl->watchpoint_type == hw_read)
2613         {
2614           struct bp_location *loc, **loc_temp;
2615
2616           /* But don't try to insert it, if there's already another
2617              hw_access location that would be considered a duplicate
2618              of this one.  */
2619           ALL_BP_LOCATIONS (loc, loc_temp)
2620             if (loc != bl
2621                 && loc->watchpoint_type == hw_access
2622                 && watchpoint_locations_match (bl, loc))
2623               {
2624                 bl->duplicate = 1;
2625                 bl->inserted = 1;
2626                 bl->target_info = loc->target_info;
2627                 bl->watchpoint_type = hw_access;
2628                 val = 0;
2629                 break;
2630               }
2631
2632           if (val == 1)
2633             {
2634               bl->watchpoint_type = hw_access;
2635               val = bl->owner->ops->insert_location (bl);
2636
2637               if (val)
2638                 /* Back to the original value.  */
2639                 bl->watchpoint_type = hw_read;
2640             }
2641         }
2642
2643       bl->inserted = (val == 0);
2644     }
2645
2646   else if (bl->owner->type == bp_catchpoint)
2647     {
2648       gdb_assert (bl->owner->ops != NULL
2649                   && bl->owner->ops->insert_location != NULL);
2650
2651       val = bl->owner->ops->insert_location (bl);
2652       if (val)
2653         {
2654           bl->owner->enable_state = bp_disabled;
2655
2656           if (val == 1)
2657             warning (_("\
2658 Error inserting catchpoint %d: Your system does not support this type\n\
2659 of catchpoint."), bl->owner->number);
2660           else
2661             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2662         }
2663
2664       bl->inserted = (val == 0);
2665
2666       /* We've already printed an error message if there was a problem
2667          inserting this catchpoint, and we've disabled the catchpoint,
2668          so just return success.  */
2669       return 0;
2670     }
2671
2672   return 0;
2673 }
2674
2675 /* This function is called when program space PSPACE is about to be
2676    deleted.  It takes care of updating breakpoints to not reference
2677    PSPACE anymore.  */
2678
2679 void
2680 breakpoint_program_space_exit (struct program_space *pspace)
2681 {
2682   struct breakpoint *b, *b_temp;
2683   struct bp_location *loc, **loc_temp;
2684
2685   /* Remove any breakpoint that was set through this program space.  */
2686   ALL_BREAKPOINTS_SAFE (b, b_temp)
2687     {
2688       if (b->pspace == pspace)
2689         delete_breakpoint (b);
2690     }
2691
2692   /* Breakpoints set through other program spaces could have locations
2693      bound to PSPACE as well.  Remove those.  */
2694   ALL_BP_LOCATIONS (loc, loc_temp)
2695     {
2696       struct bp_location *tmp;
2697
2698       if (loc->pspace == pspace)
2699         {
2700           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2701           if (loc->owner->loc == loc)
2702             loc->owner->loc = loc->next;
2703           else
2704             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2705               if (tmp->next == loc)
2706                 {
2707                   tmp->next = loc->next;
2708                   break;
2709                 }
2710         }
2711     }
2712
2713   /* Now update the global location list to permanently delete the
2714      removed locations above.  */
2715   update_global_location_list (0);
2716 }
2717
2718 /* Make sure all breakpoints are inserted in inferior.
2719    Throws exception on any error.
2720    A breakpoint that is already inserted won't be inserted
2721    again, so calling this function twice is safe.  */
2722 void
2723 insert_breakpoints (void)
2724 {
2725   struct breakpoint *bpt;
2726
2727   ALL_BREAKPOINTS (bpt)
2728     if (is_hardware_watchpoint (bpt))
2729       {
2730         struct watchpoint *w = (struct watchpoint *) bpt;
2731
2732         update_watchpoint (w, 0 /* don't reparse.  */);
2733       }
2734
2735   update_global_location_list (1);
2736
2737   /* update_global_location_list does not insert breakpoints when
2738      always_inserted_mode is not enabled.  Explicitly insert them
2739      now.  */
2740   if (!breakpoints_always_inserted_mode ())
2741     insert_breakpoint_locations ();
2742 }
2743
2744 /* Invoke CALLBACK for each of bp_location.  */
2745
2746 void
2747 iterate_over_bp_locations (walk_bp_location_callback callback)
2748 {
2749   struct bp_location *loc, **loc_tmp;
2750
2751   ALL_BP_LOCATIONS (loc, loc_tmp)
2752     {
2753       callback (loc, NULL);
2754     }
2755 }
2756
2757 /* This is used when we need to synch breakpoint conditions between GDB and the
2758    target.  It is the case with deleting and disabling of breakpoints when using
2759    always-inserted mode.  */
2760
2761 static void
2762 update_inserted_breakpoint_locations (void)
2763 {
2764   struct bp_location *bl, **blp_tmp;
2765   int error_flag = 0;
2766   int val = 0;
2767   int disabled_breaks = 0;
2768   int hw_breakpoint_error = 0;
2769   int hw_bp_details_reported = 0;
2770
2771   struct ui_file *tmp_error_stream = mem_fileopen ();
2772   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2773
2774   /* Explicitly mark the warning -- this will only be printed if
2775      there was an error.  */
2776   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2777
2778   save_current_space_and_thread ();
2779
2780   ALL_BP_LOCATIONS (bl, blp_tmp)
2781     {
2782       /* We only want to update software breakpoints and hardware
2783          breakpoints.  */
2784       if (!is_breakpoint (bl->owner))
2785         continue;
2786
2787       /* We only want to update locations that are already inserted
2788          and need updating.  This is to avoid unwanted insertion during
2789          deletion of breakpoints.  */
2790       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2791         continue;
2792
2793       switch_to_program_space_and_thread (bl->pspace);
2794
2795       /* For targets that support global breakpoints, there's no need
2796          to select an inferior to insert breakpoint to.  In fact, even
2797          if we aren't attached to any process yet, we should still
2798          insert breakpoints.  */
2799       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2800           && ptid_equal (inferior_ptid, null_ptid))
2801         continue;
2802
2803       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2804                                     &hw_breakpoint_error, &hw_bp_details_reported);
2805       if (val)
2806         error_flag = val;
2807     }
2808
2809   if (error_flag)
2810     {
2811       target_terminal_ours_for_output ();
2812       error_stream (tmp_error_stream);
2813     }
2814
2815   do_cleanups (cleanups);
2816 }
2817
2818 /* Used when starting or continuing the program.  */
2819
2820 static void
2821 insert_breakpoint_locations (void)
2822 {
2823   struct breakpoint *bpt;
2824   struct bp_location *bl, **blp_tmp;
2825   int error_flag = 0;
2826   int val = 0;
2827   int disabled_breaks = 0;
2828   int hw_breakpoint_error = 0;
2829   int hw_bp_error_explained_already = 0;
2830
2831   struct ui_file *tmp_error_stream = mem_fileopen ();
2832   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2833   
2834   /* Explicitly mark the warning -- this will only be printed if
2835      there was an error.  */
2836   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2837
2838   save_current_space_and_thread ();
2839
2840   ALL_BP_LOCATIONS (bl, blp_tmp)
2841     {
2842       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2843         continue;
2844
2845       /* There is no point inserting thread-specific breakpoints if
2846          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2847          has BL->OWNER always non-NULL.  */
2848       if (bl->owner->thread != -1
2849           && !valid_thread_id (bl->owner->thread))
2850         continue;
2851
2852       switch_to_program_space_and_thread (bl->pspace);
2853
2854       /* For targets that support global breakpoints, there's no need
2855          to select an inferior to insert breakpoint to.  In fact, even
2856          if we aren't attached to any process yet, we should still
2857          insert breakpoints.  */
2858       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2859           && ptid_equal (inferior_ptid, null_ptid))
2860         continue;
2861
2862       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2863                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2864       if (val)
2865         error_flag = val;
2866     }
2867
2868   /* If we failed to insert all locations of a watchpoint, remove
2869      them, as half-inserted watchpoint is of limited use.  */
2870   ALL_BREAKPOINTS (bpt)  
2871     {
2872       int some_failed = 0;
2873       struct bp_location *loc;
2874
2875       if (!is_hardware_watchpoint (bpt))
2876         continue;
2877
2878       if (!breakpoint_enabled (bpt))
2879         continue;
2880
2881       if (bpt->disposition == disp_del_at_next_stop)
2882         continue;
2883       
2884       for (loc = bpt->loc; loc; loc = loc->next)
2885         if (!loc->inserted && should_be_inserted (loc))
2886           {
2887             some_failed = 1;
2888             break;
2889           }
2890       if (some_failed)
2891         {
2892           for (loc = bpt->loc; loc; loc = loc->next)
2893             if (loc->inserted)
2894               remove_breakpoint (loc, mark_uninserted);
2895
2896           hw_breakpoint_error = 1;
2897           fprintf_unfiltered (tmp_error_stream,
2898                               "Could not insert hardware watchpoint %d.\n", 
2899                               bpt->number);
2900           error_flag = -1;
2901         }
2902     }
2903
2904   if (error_flag)
2905     {
2906       /* If a hardware breakpoint or watchpoint was inserted, add a
2907          message about possibly exhausted resources.  */
2908       if (hw_breakpoint_error && !hw_bp_error_explained_already)
2909         {
2910           fprintf_unfiltered (tmp_error_stream, 
2911                               "Could not insert hardware breakpoints:\n\
2912 You may have requested too many hardware breakpoints/watchpoints.\n");
2913         }
2914       target_terminal_ours_for_output ();
2915       error_stream (tmp_error_stream);
2916     }
2917
2918   do_cleanups (cleanups);
2919 }
2920
2921 /* Used when the program stops.
2922    Returns zero if successful, or non-zero if there was a problem
2923    removing a breakpoint location.  */
2924
2925 int
2926 remove_breakpoints (void)
2927 {
2928   struct bp_location *bl, **blp_tmp;
2929   int val = 0;
2930
2931   ALL_BP_LOCATIONS (bl, blp_tmp)
2932   {
2933     if (bl->inserted && !is_tracepoint (bl->owner))
2934       val |= remove_breakpoint (bl, mark_uninserted);
2935   }
2936   return val;
2937 }
2938
2939 /* When a thread exits, remove breakpoints that are related to
2940    that thread.  */
2941
2942 static void
2943 remove_threaded_breakpoints (struct thread_info *tp, int silent)
2944 {
2945   struct breakpoint *b, *b_tmp;
2946
2947   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2948     {
2949       if (b->thread == tp->num && user_breakpoint_p (b))
2950         {
2951           b->disposition = disp_del_at_next_stop;
2952
2953           printf_filtered (_("\
2954 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
2955                           b->number, tp->num);
2956
2957           /* Hide it from the user.  */
2958           b->number = 0;
2959        }
2960     }
2961 }
2962
2963 /* Remove breakpoints of process PID.  */
2964
2965 int
2966 remove_breakpoints_pid (int pid)
2967 {
2968   struct bp_location *bl, **blp_tmp;
2969   int val;
2970   struct inferior *inf = find_inferior_pid (pid);
2971
2972   ALL_BP_LOCATIONS (bl, blp_tmp)
2973   {
2974     if (bl->pspace != inf->pspace)
2975       continue;
2976
2977     if (bl->owner->type == bp_dprintf)
2978       continue;
2979
2980     if (bl->inserted)
2981       {
2982         val = remove_breakpoint (bl, mark_uninserted);
2983         if (val != 0)
2984           return val;
2985       }
2986   }
2987   return 0;
2988 }
2989
2990 int
2991 reattach_breakpoints (int pid)
2992 {
2993   struct cleanup *old_chain;
2994   struct bp_location *bl, **blp_tmp;
2995   int val;
2996   struct ui_file *tmp_error_stream;
2997   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
2998   struct inferior *inf;
2999   struct thread_info *tp;
3000
3001   tp = any_live_thread_of_process (pid);
3002   if (tp == NULL)
3003     return 1;
3004
3005   inf = find_inferior_pid (pid);
3006   old_chain = save_inferior_ptid ();
3007
3008   inferior_ptid = tp->ptid;
3009
3010   tmp_error_stream = mem_fileopen ();
3011   make_cleanup_ui_file_delete (tmp_error_stream);
3012
3013   ALL_BP_LOCATIONS (bl, blp_tmp)
3014   {
3015     if (bl->pspace != inf->pspace)
3016       continue;
3017
3018     if (bl->inserted)
3019       {
3020         bl->inserted = 0;
3021         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3022         if (val != 0)
3023           {
3024             do_cleanups (old_chain);
3025             return val;
3026           }
3027       }
3028   }
3029   do_cleanups (old_chain);
3030   return 0;
3031 }
3032
3033 static int internal_breakpoint_number = -1;
3034
3035 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3036    If INTERNAL is non-zero, the breakpoint number will be populated
3037    from internal_breakpoint_number and that variable decremented.
3038    Otherwise the breakpoint number will be populated from
3039    breakpoint_count and that value incremented.  Internal breakpoints
3040    do not set the internal var bpnum.  */
3041 static void
3042 set_breakpoint_number (int internal, struct breakpoint *b)
3043 {
3044   if (internal)
3045     b->number = internal_breakpoint_number--;
3046   else
3047     {
3048       set_breakpoint_count (breakpoint_count + 1);
3049       b->number = breakpoint_count;
3050     }
3051 }
3052
3053 static struct breakpoint *
3054 create_internal_breakpoint (struct gdbarch *gdbarch,
3055                             CORE_ADDR address, enum bptype type,
3056                             const struct breakpoint_ops *ops)
3057 {
3058   struct symtab_and_line sal;
3059   struct breakpoint *b;
3060
3061   init_sal (&sal);              /* Initialize to zeroes.  */
3062
3063   sal.pc = address;
3064   sal.section = find_pc_overlay (sal.pc);
3065   sal.pspace = current_program_space;
3066
3067   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3068   b->number = internal_breakpoint_number--;
3069   b->disposition = disp_donttouch;
3070
3071   return b;
3072 }
3073
3074 static const char *const longjmp_names[] =
3075   {
3076     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3077   };
3078 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3079
3080 /* Per-objfile data private to breakpoint.c.  */
3081 struct breakpoint_objfile_data
3082 {
3083   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3084   struct minimal_symbol *overlay_msym;
3085
3086   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3087   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
3088
3089   /* True if we have looked for longjmp probes.  */
3090   int longjmp_searched;
3091
3092   /* SystemTap probe points for longjmp (if any).  */
3093   VEC (probe_p) *longjmp_probes;
3094
3095   /* Minimal symbol for "std::terminate()" (if any).  */
3096   struct minimal_symbol *terminate_msym;
3097
3098   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3099   struct minimal_symbol *exception_msym;
3100
3101   /* True if we have looked for exception probes.  */
3102   int exception_searched;
3103
3104   /* SystemTap probe points for unwinding (if any).  */
3105   VEC (probe_p) *exception_probes;
3106 };
3107
3108 static const struct objfile_data *breakpoint_objfile_key;
3109
3110 /* Minimal symbol not found sentinel.  */
3111 static struct minimal_symbol msym_not_found;
3112
3113 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3114
3115 static int
3116 msym_not_found_p (const struct minimal_symbol *msym)
3117 {
3118   return msym == &msym_not_found;
3119 }
3120
3121 /* Return per-objfile data needed by breakpoint.c.
3122    Allocate the data if necessary.  */
3123
3124 static struct breakpoint_objfile_data *
3125 get_breakpoint_objfile_data (struct objfile *objfile)
3126 {
3127   struct breakpoint_objfile_data *bp_objfile_data;
3128
3129   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3130   if (bp_objfile_data == NULL)
3131     {
3132       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3133                                        sizeof (*bp_objfile_data));
3134
3135       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3136       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3137     }
3138   return bp_objfile_data;
3139 }
3140
3141 static void
3142 free_breakpoint_probes (struct objfile *obj, void *data)
3143 {
3144   struct breakpoint_objfile_data *bp_objfile_data = data;
3145
3146   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3147   VEC_free (probe_p, bp_objfile_data->exception_probes);
3148 }
3149
3150 static void
3151 create_overlay_event_breakpoint (void)
3152 {
3153   struct objfile *objfile;
3154   const char *const func_name = "_ovly_debug_event";
3155
3156   ALL_OBJFILES (objfile)
3157     {
3158       struct breakpoint *b;
3159       struct breakpoint_objfile_data *bp_objfile_data;
3160       CORE_ADDR addr;
3161
3162       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3163
3164       if (msym_not_found_p (bp_objfile_data->overlay_msym))
3165         continue;
3166
3167       if (bp_objfile_data->overlay_msym == NULL)
3168         {
3169           struct minimal_symbol *m;
3170
3171           m = lookup_minimal_symbol_text (func_name, objfile);
3172           if (m == NULL)
3173             {
3174               /* Avoid future lookups in this objfile.  */
3175               bp_objfile_data->overlay_msym = &msym_not_found;
3176               continue;
3177             }
3178           bp_objfile_data->overlay_msym = m;
3179         }
3180
3181       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3182       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3183                                       bp_overlay_event,
3184                                       &internal_breakpoint_ops);
3185       b->addr_string = xstrdup (func_name);
3186
3187       if (overlay_debugging == ovly_auto)
3188         {
3189           b->enable_state = bp_enabled;
3190           overlay_events_enabled = 1;
3191         }
3192       else
3193        {
3194          b->enable_state = bp_disabled;
3195          overlay_events_enabled = 0;
3196        }
3197     }
3198   update_global_location_list (1);
3199 }
3200
3201 static void
3202 create_longjmp_master_breakpoint (void)
3203 {
3204   struct program_space *pspace;
3205   struct cleanup *old_chain;
3206
3207   old_chain = save_current_program_space ();
3208
3209   ALL_PSPACES (pspace)
3210   {
3211     struct objfile *objfile;
3212
3213     set_current_program_space (pspace);
3214
3215     ALL_OBJFILES (objfile)
3216     {
3217       int i;
3218       struct gdbarch *gdbarch;
3219       struct breakpoint_objfile_data *bp_objfile_data;
3220
3221       gdbarch = get_objfile_arch (objfile);
3222       if (!gdbarch_get_longjmp_target_p (gdbarch))
3223         continue;
3224
3225       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3226
3227       if (!bp_objfile_data->longjmp_searched)
3228         {
3229           VEC (probe_p) *ret;
3230
3231           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3232           if (ret != NULL)
3233             {
3234               /* We are only interested in checking one element.  */
3235               struct probe *p = VEC_index (probe_p, ret, 0);
3236
3237               if (!can_evaluate_probe_arguments (p))
3238                 {
3239                   /* We cannot use the probe interface here, because it does
3240                      not know how to evaluate arguments.  */
3241                   VEC_free (probe_p, ret);
3242                   ret = NULL;
3243                 }
3244             }
3245           bp_objfile_data->longjmp_probes = ret;
3246           bp_objfile_data->longjmp_searched = 1;
3247         }
3248
3249       if (bp_objfile_data->longjmp_probes != NULL)
3250         {
3251           int i;
3252           struct probe *probe;
3253           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3254
3255           for (i = 0;
3256                VEC_iterate (probe_p,
3257                             bp_objfile_data->longjmp_probes,
3258                             i, probe);
3259                ++i)
3260             {
3261               struct breakpoint *b;
3262
3263               b = create_internal_breakpoint (gdbarch, probe->address,
3264                                               bp_longjmp_master,
3265                                               &internal_breakpoint_ops);
3266               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3267               b->enable_state = bp_disabled;
3268             }
3269
3270           continue;
3271         }
3272
3273       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3274         {
3275           struct breakpoint *b;
3276           const char *func_name;
3277           CORE_ADDR addr;
3278
3279           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
3280             continue;
3281
3282           func_name = longjmp_names[i];
3283           if (bp_objfile_data->longjmp_msym[i] == NULL)
3284             {
3285               struct minimal_symbol *m;
3286
3287               m = lookup_minimal_symbol_text (func_name, objfile);
3288               if (m == NULL)
3289                 {
3290                   /* Prevent future lookups in this objfile.  */
3291                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
3292                   continue;
3293                 }
3294               bp_objfile_data->longjmp_msym[i] = m;
3295             }
3296
3297           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3298           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3299                                           &internal_breakpoint_ops);
3300           b->addr_string = xstrdup (func_name);
3301           b->enable_state = bp_disabled;
3302         }
3303     }
3304   }
3305   update_global_location_list (1);
3306
3307   do_cleanups (old_chain);
3308 }
3309
3310 /* Create a master std::terminate breakpoint.  */
3311 static void
3312 create_std_terminate_master_breakpoint (void)
3313 {
3314   struct program_space *pspace;
3315   struct cleanup *old_chain;
3316   const char *const func_name = "std::terminate()";
3317
3318   old_chain = save_current_program_space ();
3319
3320   ALL_PSPACES (pspace)
3321   {
3322     struct objfile *objfile;
3323     CORE_ADDR addr;
3324
3325     set_current_program_space (pspace);
3326
3327     ALL_OBJFILES (objfile)
3328     {
3329       struct breakpoint *b;
3330       struct breakpoint_objfile_data *bp_objfile_data;
3331
3332       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3333
3334       if (msym_not_found_p (bp_objfile_data->terminate_msym))
3335         continue;
3336
3337       if (bp_objfile_data->terminate_msym == NULL)
3338         {
3339           struct minimal_symbol *m;
3340
3341           m = lookup_minimal_symbol (func_name, NULL, objfile);
3342           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
3343                             && MSYMBOL_TYPE (m) != mst_file_text))
3344             {
3345               /* Prevent future lookups in this objfile.  */
3346               bp_objfile_data->terminate_msym = &msym_not_found;
3347               continue;
3348             }
3349           bp_objfile_data->terminate_msym = m;
3350         }
3351
3352       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3353       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3354                                       bp_std_terminate_master,
3355                                       &internal_breakpoint_ops);
3356       b->addr_string = xstrdup (func_name);
3357       b->enable_state = bp_disabled;
3358     }
3359   }
3360
3361   update_global_location_list (1);
3362
3363   do_cleanups (old_chain);
3364 }
3365
3366 /* Install a master breakpoint on the unwinder's debug hook.  */
3367
3368 static void
3369 create_exception_master_breakpoint (void)
3370 {
3371   struct objfile *objfile;
3372   const char *const func_name = "_Unwind_DebugHook";
3373
3374   ALL_OBJFILES (objfile)
3375     {
3376       struct breakpoint *b;
3377       struct gdbarch *gdbarch;
3378       struct breakpoint_objfile_data *bp_objfile_data;
3379       CORE_ADDR addr;
3380
3381       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3382
3383       /* We prefer the SystemTap probe point if it exists.  */
3384       if (!bp_objfile_data->exception_searched)
3385         {
3386           VEC (probe_p) *ret;
3387
3388           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3389
3390           if (ret != NULL)
3391             {
3392               /* We are only interested in checking one element.  */
3393               struct probe *p = VEC_index (probe_p, ret, 0);
3394
3395               if (!can_evaluate_probe_arguments (p))
3396                 {
3397                   /* We cannot use the probe interface here, because it does
3398                      not know how to evaluate arguments.  */
3399                   VEC_free (probe_p, ret);
3400                   ret = NULL;
3401                 }
3402             }
3403           bp_objfile_data->exception_probes = ret;
3404           bp_objfile_data->exception_searched = 1;
3405         }
3406
3407       if (bp_objfile_data->exception_probes != NULL)
3408         {
3409           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3410           int i;
3411           struct probe *probe;
3412
3413           for (i = 0;
3414                VEC_iterate (probe_p,
3415                             bp_objfile_data->exception_probes,
3416                             i, probe);
3417                ++i)
3418             {
3419               struct breakpoint *b;
3420
3421               b = create_internal_breakpoint (gdbarch, probe->address,
3422                                               bp_exception_master,
3423                                               &internal_breakpoint_ops);
3424               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3425               b->enable_state = bp_disabled;
3426             }
3427
3428           continue;
3429         }
3430
3431       /* Otherwise, try the hook function.  */
3432
3433       if (msym_not_found_p (bp_objfile_data->exception_msym))
3434         continue;
3435
3436       gdbarch = get_objfile_arch (objfile);
3437
3438       if (bp_objfile_data->exception_msym == NULL)
3439         {
3440           struct minimal_symbol *debug_hook;
3441
3442           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3443           if (debug_hook == NULL)
3444             {
3445               bp_objfile_data->exception_msym = &msym_not_found;
3446               continue;
3447             }
3448
3449           bp_objfile_data->exception_msym = debug_hook;
3450         }
3451
3452       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3453       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3454                                                  &current_target);
3455       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3456                                       &internal_breakpoint_ops);
3457       b->addr_string = xstrdup (func_name);
3458       b->enable_state = bp_disabled;
3459     }
3460
3461   update_global_location_list (1);
3462 }
3463
3464 void
3465 update_breakpoints_after_exec (void)
3466 {
3467   struct breakpoint *b, *b_tmp;
3468   struct bp_location *bploc, **bplocp_tmp;
3469
3470   /* We're about to delete breakpoints from GDB's lists.  If the
3471      INSERTED flag is true, GDB will try to lift the breakpoints by
3472      writing the breakpoints' "shadow contents" back into memory.  The
3473      "shadow contents" are NOT valid after an exec, so GDB should not
3474      do that.  Instead, the target is responsible from marking
3475      breakpoints out as soon as it detects an exec.  We don't do that
3476      here instead, because there may be other attempts to delete
3477      breakpoints after detecting an exec and before reaching here.  */
3478   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3479     if (bploc->pspace == current_program_space)
3480       gdb_assert (!bploc->inserted);
3481
3482   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3483   {
3484     if (b->pspace != current_program_space)
3485       continue;
3486
3487     /* Solib breakpoints must be explicitly reset after an exec().  */
3488     if (b->type == bp_shlib_event)
3489       {
3490         delete_breakpoint (b);
3491         continue;
3492       }
3493
3494     /* JIT breakpoints must be explicitly reset after an exec().  */
3495     if (b->type == bp_jit_event)
3496       {
3497         delete_breakpoint (b);
3498         continue;
3499       }
3500
3501     /* Thread event breakpoints must be set anew after an exec(),
3502        as must overlay event and longjmp master breakpoints.  */
3503     if (b->type == bp_thread_event || b->type == bp_overlay_event
3504         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3505         || b->type == bp_exception_master)
3506       {
3507         delete_breakpoint (b);
3508         continue;
3509       }
3510
3511     /* Step-resume breakpoints are meaningless after an exec().  */
3512     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3513       {
3514         delete_breakpoint (b);
3515         continue;
3516       }
3517
3518     /* Longjmp and longjmp-resume breakpoints are also meaningless
3519        after an exec.  */
3520     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3521         || b->type == bp_longjmp_call_dummy
3522         || b->type == bp_exception || b->type == bp_exception_resume)
3523       {
3524         delete_breakpoint (b);
3525         continue;
3526       }
3527
3528     if (b->type == bp_catchpoint)
3529       {
3530         /* For now, none of the bp_catchpoint breakpoints need to
3531            do anything at this point.  In the future, if some of
3532            the catchpoints need to something, we will need to add
3533            a new method, and call this method from here.  */
3534         continue;
3535       }
3536
3537     /* bp_finish is a special case.  The only way we ought to be able
3538        to see one of these when an exec() has happened, is if the user
3539        caught a vfork, and then said "finish".  Ordinarily a finish just
3540        carries them to the call-site of the current callee, by setting
3541        a temporary bp there and resuming.  But in this case, the finish
3542        will carry them entirely through the vfork & exec.
3543
3544        We don't want to allow a bp_finish to remain inserted now.  But
3545        we can't safely delete it, 'cause finish_command has a handle to
3546        the bp on a bpstat, and will later want to delete it.  There's a
3547        chance (and I've seen it happen) that if we delete the bp_finish
3548        here, that its storage will get reused by the time finish_command
3549        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3550        We really must allow finish_command to delete a bp_finish.
3551
3552        In the absence of a general solution for the "how do we know
3553        it's safe to delete something others may have handles to?"
3554        problem, what we'll do here is just uninsert the bp_finish, and
3555        let finish_command delete it.
3556
3557        (We know the bp_finish is "doomed" in the sense that it's
3558        momentary, and will be deleted as soon as finish_command sees
3559        the inferior stopped.  So it doesn't matter that the bp's
3560        address is probably bogus in the new a.out, unlike e.g., the
3561        solib breakpoints.)  */
3562
3563     if (b->type == bp_finish)
3564       {
3565         continue;
3566       }
3567
3568     /* Without a symbolic address, we have little hope of the
3569        pre-exec() address meaning the same thing in the post-exec()
3570        a.out.  */
3571     if (b->addr_string == NULL)
3572       {
3573         delete_breakpoint (b);
3574         continue;
3575       }
3576   }
3577   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3578   create_overlay_event_breakpoint ();
3579   create_longjmp_master_breakpoint ();
3580   create_std_terminate_master_breakpoint ();
3581   create_exception_master_breakpoint ();
3582 }
3583
3584 int
3585 detach_breakpoints (ptid_t ptid)
3586 {
3587   struct bp_location *bl, **blp_tmp;
3588   int val = 0;
3589   struct cleanup *old_chain = save_inferior_ptid ();
3590   struct inferior *inf = current_inferior ();
3591
3592   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3593     error (_("Cannot detach breakpoints of inferior_ptid"));
3594
3595   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3596   inferior_ptid = ptid;
3597   ALL_BP_LOCATIONS (bl, blp_tmp)
3598   {
3599     if (bl->pspace != inf->pspace)
3600       continue;
3601
3602     /* This function must physically remove breakpoints locations
3603        from the specified ptid, without modifying the breakpoint
3604        package's state.  Locations of type bp_loc_other are only
3605        maintained at GDB side.  So, there is no need to remove
3606        these bp_loc_other locations.  Moreover, removing these
3607        would modify the breakpoint package's state.  */
3608     if (bl->loc_type == bp_loc_other)
3609       continue;
3610
3611     if (bl->inserted)
3612       val |= remove_breakpoint_1 (bl, mark_inserted);
3613   }
3614
3615   /* Detach single-step breakpoints as well.  */
3616   detach_single_step_breakpoints ();
3617
3618   do_cleanups (old_chain);
3619   return val;
3620 }
3621
3622 /* Remove the breakpoint location BL from the current address space.
3623    Note that this is used to detach breakpoints from a child fork.
3624    When we get here, the child isn't in the inferior list, and neither
3625    do we have objects to represent its address space --- we should
3626    *not* look at bl->pspace->aspace here.  */
3627
3628 static int
3629 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3630 {
3631   int val;
3632
3633   /* BL is never in moribund_locations by our callers.  */
3634   gdb_assert (bl->owner != NULL);
3635
3636   if (bl->owner->enable_state == bp_permanent)
3637     /* Permanent breakpoints cannot be inserted or removed.  */
3638     return 0;
3639
3640   /* The type of none suggests that owner is actually deleted.
3641      This should not ever happen.  */
3642   gdb_assert (bl->owner->type != bp_none);
3643
3644   if (bl->loc_type == bp_loc_software_breakpoint
3645       || bl->loc_type == bp_loc_hardware_breakpoint)
3646     {
3647       /* "Normal" instruction breakpoint: either the standard
3648          trap-instruction bp (bp_breakpoint), or a
3649          bp_hardware_breakpoint.  */
3650
3651       /* First check to see if we have to handle an overlay.  */
3652       if (overlay_debugging == ovly_off
3653           || bl->section == NULL
3654           || !(section_is_overlay (bl->section)))
3655         {
3656           /* No overlay handling: just remove the breakpoint.  */
3657           val = bl->owner->ops->remove_location (bl);
3658         }
3659       else
3660         {
3661           /* This breakpoint is in an overlay section.
3662              Did we set a breakpoint at the LMA?  */
3663           if (!overlay_events_enabled)
3664               {
3665                 /* Yes -- overlay event support is not active, so we
3666                    should have set a breakpoint at the LMA.  Remove it.  
3667                 */
3668                 /* Ignore any failures: if the LMA is in ROM, we will
3669                    have already warned when we failed to insert it.  */
3670                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3671                   target_remove_hw_breakpoint (bl->gdbarch,
3672                                                &bl->overlay_target_info);
3673                 else
3674                   target_remove_breakpoint (bl->gdbarch,
3675                                             &bl->overlay_target_info);
3676               }
3677           /* Did we set a breakpoint at the VMA? 
3678              If so, we will have marked the breakpoint 'inserted'.  */
3679           if (bl->inserted)
3680             {
3681               /* Yes -- remove it.  Previously we did not bother to
3682                  remove the breakpoint if the section had been
3683                  unmapped, but let's not rely on that being safe.  We
3684                  don't know what the overlay manager might do.  */
3685
3686               /* However, we should remove *software* breakpoints only
3687                  if the section is still mapped, or else we overwrite
3688                  wrong code with the saved shadow contents.  */
3689               if (bl->loc_type == bp_loc_hardware_breakpoint
3690                   || section_is_mapped (bl->section))
3691                 val = bl->owner->ops->remove_location (bl);
3692               else
3693                 val = 0;
3694             }
3695           else
3696             {
3697               /* No -- not inserted, so no need to remove.  No error.  */
3698               val = 0;
3699             }
3700         }
3701
3702       /* In some cases, we might not be able to remove a breakpoint
3703          in a shared library that has already been removed, but we
3704          have not yet processed the shlib unload event.  */
3705       if (val && solib_name_from_address (bl->pspace, bl->address))
3706         val = 0;
3707
3708       if (val)
3709         return val;
3710       bl->inserted = (is == mark_inserted);
3711     }
3712   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3713     {
3714       gdb_assert (bl->owner->ops != NULL
3715                   && bl->owner->ops->remove_location != NULL);
3716
3717       bl->inserted = (is == mark_inserted);
3718       bl->owner->ops->remove_location (bl);
3719
3720       /* Failure to remove any of the hardware watchpoints comes here.  */
3721       if ((is == mark_uninserted) && (bl->inserted))
3722         warning (_("Could not remove hardware watchpoint %d."),
3723                  bl->owner->number);
3724     }
3725   else if (bl->owner->type == bp_catchpoint
3726            && breakpoint_enabled (bl->owner)
3727            && !bl->duplicate)
3728     {
3729       gdb_assert (bl->owner->ops != NULL
3730                   && bl->owner->ops->remove_location != NULL);
3731
3732       val = bl->owner->ops->remove_location (bl);
3733       if (val)
3734         return val;
3735
3736       bl->inserted = (is == mark_inserted);
3737     }
3738
3739   return 0;
3740 }
3741
3742 static int
3743 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3744 {
3745   int ret;
3746   struct cleanup *old_chain;
3747
3748   /* BL is never in moribund_locations by our callers.  */
3749   gdb_assert (bl->owner != NULL);
3750
3751   if (bl->owner->enable_state == bp_permanent)
3752     /* Permanent breakpoints cannot be inserted or removed.  */
3753     return 0;
3754
3755   /* The type of none suggests that owner is actually deleted.
3756      This should not ever happen.  */
3757   gdb_assert (bl->owner->type != bp_none);
3758
3759   old_chain = save_current_space_and_thread ();
3760
3761   switch_to_program_space_and_thread (bl->pspace);
3762
3763   ret = remove_breakpoint_1 (bl, is);
3764
3765   do_cleanups (old_chain);
3766   return ret;
3767 }
3768
3769 /* Clear the "inserted" flag in all breakpoints.  */
3770
3771 void
3772 mark_breakpoints_out (void)
3773 {
3774   struct bp_location *bl, **blp_tmp;
3775
3776   ALL_BP_LOCATIONS (bl, blp_tmp)
3777     if (bl->pspace == current_program_space)
3778       bl->inserted = 0;
3779 }
3780
3781 /* Clear the "inserted" flag in all breakpoints and delete any
3782    breakpoints which should go away between runs of the program.
3783
3784    Plus other such housekeeping that has to be done for breakpoints
3785    between runs.
3786
3787    Note: this function gets called at the end of a run (by
3788    generic_mourn_inferior) and when a run begins (by
3789    init_wait_for_inferior).  */
3790
3791
3792
3793 void
3794 breakpoint_init_inferior (enum inf_context context)
3795 {
3796   struct breakpoint *b, *b_tmp;
3797   struct bp_location *bl, **blp_tmp;
3798   int ix;
3799   struct program_space *pspace = current_program_space;
3800
3801   /* If breakpoint locations are shared across processes, then there's
3802      nothing to do.  */
3803   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3804     return;
3805
3806   ALL_BP_LOCATIONS (bl, blp_tmp)
3807   {
3808     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3809     if (bl->pspace == pspace
3810         && bl->owner->enable_state != bp_permanent)
3811       bl->inserted = 0;
3812   }
3813
3814   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3815   {
3816     if (b->loc && b->loc->pspace != pspace)
3817       continue;
3818
3819     switch (b->type)
3820       {
3821       case bp_call_dummy:
3822       case bp_longjmp_call_dummy:
3823
3824         /* If the call dummy breakpoint is at the entry point it will
3825            cause problems when the inferior is rerun, so we better get
3826            rid of it.  */
3827
3828       case bp_watchpoint_scope:
3829
3830         /* Also get rid of scope breakpoints.  */
3831
3832       case bp_shlib_event:
3833
3834         /* Also remove solib event breakpoints.  Their addresses may
3835            have changed since the last time we ran the program.
3836            Actually we may now be debugging against different target;
3837            and so the solib backend that installed this breakpoint may
3838            not be used in by the target.  E.g.,
3839
3840            (gdb) file prog-linux
3841            (gdb) run               # native linux target
3842            ...
3843            (gdb) kill
3844            (gdb) file prog-win.exe
3845            (gdb) tar rem :9999     # remote Windows gdbserver.
3846         */
3847
3848       case bp_step_resume:
3849
3850         /* Also remove step-resume breakpoints.  */
3851
3852         delete_breakpoint (b);
3853         break;
3854
3855       case bp_watchpoint:
3856       case bp_hardware_watchpoint:
3857       case bp_read_watchpoint:
3858       case bp_access_watchpoint:
3859         {
3860           struct watchpoint *w = (struct watchpoint *) b;
3861
3862           /* Likewise for watchpoints on local expressions.  */
3863           if (w->exp_valid_block != NULL)
3864             delete_breakpoint (b);
3865           else if (context == inf_starting)
3866             {
3867               /* Reset val field to force reread of starting value in
3868                  insert_breakpoints.  */
3869               if (w->val)
3870                 value_free (w->val);
3871               w->val = NULL;
3872               w->val_valid = 0;
3873           }
3874         }
3875         break;
3876       default:
3877         break;
3878       }
3879   }
3880
3881   /* Get rid of the moribund locations.  */
3882   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3883     decref_bp_location (&bl);
3884   VEC_free (bp_location_p, moribund_locations);
3885 }
3886
3887 /* These functions concern about actual breakpoints inserted in the
3888    target --- to e.g. check if we need to do decr_pc adjustment or if
3889    we need to hop over the bkpt --- so we check for address space
3890    match, not program space.  */
3891
3892 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3893    exists at PC.  It returns ordinary_breakpoint_here if it's an
3894    ordinary breakpoint, or permanent_breakpoint_here if it's a
3895    permanent breakpoint.
3896    - When continuing from a location with an ordinary breakpoint, we
3897      actually single step once before calling insert_breakpoints.
3898    - When continuing from a location with a permanent breakpoint, we
3899      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3900      the target, to advance the PC past the breakpoint.  */
3901
3902 enum breakpoint_here
3903 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3904 {
3905   struct bp_location *bl, **blp_tmp;
3906   int any_breakpoint_here = 0;
3907
3908   ALL_BP_LOCATIONS (bl, blp_tmp)
3909     {
3910       if (bl->loc_type != bp_loc_software_breakpoint
3911           && bl->loc_type != bp_loc_hardware_breakpoint)
3912         continue;
3913
3914       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3915       if ((breakpoint_enabled (bl->owner)
3916            || bl->owner->enable_state == bp_permanent)
3917           && breakpoint_location_address_match (bl, aspace, pc))
3918         {
3919           if (overlay_debugging 
3920               && section_is_overlay (bl->section)
3921               && !section_is_mapped (bl->section))
3922             continue;           /* unmapped overlay -- can't be a match */
3923           else if (bl->owner->enable_state == bp_permanent)
3924             return permanent_breakpoint_here;
3925           else
3926             any_breakpoint_here = 1;
3927         }
3928     }
3929
3930   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3931 }
3932
3933 /* Return true if there's a moribund breakpoint at PC.  */
3934
3935 int
3936 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3937 {
3938   struct bp_location *loc;
3939   int ix;
3940
3941   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3942     if (breakpoint_location_address_match (loc, aspace, pc))
3943       return 1;
3944
3945   return 0;
3946 }
3947
3948 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3949    inserted using regular breakpoint_chain / bp_location array
3950    mechanism.  This does not check for single-step breakpoints, which
3951    are inserted and removed using direct target manipulation.  */
3952
3953 int
3954 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3955                                     CORE_ADDR pc)
3956 {
3957   struct bp_location *bl, **blp_tmp;
3958
3959   ALL_BP_LOCATIONS (bl, blp_tmp)
3960     {
3961       if (bl->loc_type != bp_loc_software_breakpoint
3962           && bl->loc_type != bp_loc_hardware_breakpoint)
3963         continue;
3964
3965       if (bl->inserted
3966           && breakpoint_location_address_match (bl, aspace, pc))
3967         {
3968           if (overlay_debugging 
3969               && section_is_overlay (bl->section)
3970               && !section_is_mapped (bl->section))
3971             continue;           /* unmapped overlay -- can't be a match */
3972           else
3973             return 1;
3974         }
3975     }
3976   return 0;
3977 }
3978
3979 /* Returns non-zero iff there's either regular breakpoint
3980    or a single step breakpoint inserted at PC.  */
3981
3982 int
3983 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3984 {
3985   if (regular_breakpoint_inserted_here_p (aspace, pc))
3986     return 1;
3987
3988   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3989     return 1;
3990
3991   return 0;
3992 }
3993
3994 /* This function returns non-zero iff there is a software breakpoint
3995    inserted at PC.  */
3996
3997 int
3998 software_breakpoint_inserted_here_p (struct address_space *aspace,
3999                                      CORE_ADDR pc)
4000 {
4001   struct bp_location *bl, **blp_tmp;
4002
4003   ALL_BP_LOCATIONS (bl, blp_tmp)
4004     {
4005       if (bl->loc_type != bp_loc_software_breakpoint)
4006         continue;
4007
4008       if (bl->inserted
4009           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4010                                        aspace, pc))
4011         {
4012           if (overlay_debugging 
4013               && section_is_overlay (bl->section)
4014               && !section_is_mapped (bl->section))
4015             continue;           /* unmapped overlay -- can't be a match */
4016           else
4017             return 1;
4018         }
4019     }
4020
4021   /* Also check for software single-step breakpoints.  */
4022   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4023     return 1;
4024
4025   return 0;
4026 }
4027
4028 int
4029 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4030                                        CORE_ADDR addr, ULONGEST len)
4031 {
4032   struct breakpoint *bpt;
4033
4034   ALL_BREAKPOINTS (bpt)
4035     {
4036       struct bp_location *loc;
4037
4038       if (bpt->type != bp_hardware_watchpoint
4039           && bpt->type != bp_access_watchpoint)
4040         continue;
4041
4042       if (!breakpoint_enabled (bpt))
4043         continue;
4044
4045       for (loc = bpt->loc; loc; loc = loc->next)
4046         if (loc->pspace->aspace == aspace && loc->inserted)
4047           {
4048             CORE_ADDR l, h;
4049
4050             /* Check for intersection.  */
4051             l = max (loc->address, addr);
4052             h = min (loc->address + loc->length, addr + len);
4053             if (l < h)
4054               return 1;
4055           }
4056     }
4057   return 0;
4058 }
4059
4060 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4061    PC is valid for process/thread PTID.  */
4062
4063 int
4064 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4065                          ptid_t ptid)
4066 {
4067   struct bp_location *bl, **blp_tmp;
4068   /* The thread and task IDs associated to PTID, computed lazily.  */
4069   int thread = -1;
4070   int task = 0;
4071   
4072   ALL_BP_LOCATIONS (bl, blp_tmp)
4073     {
4074       if (bl->loc_type != bp_loc_software_breakpoint
4075           && bl->loc_type != bp_loc_hardware_breakpoint)
4076         continue;
4077
4078       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4079       if (!breakpoint_enabled (bl->owner)
4080           && bl->owner->enable_state != bp_permanent)
4081         continue;
4082
4083       if (!breakpoint_location_address_match (bl, aspace, pc))
4084         continue;
4085
4086       if (bl->owner->thread != -1)
4087         {
4088           /* This is a thread-specific breakpoint.  Check that ptid
4089              matches that thread.  If thread hasn't been computed yet,
4090              it is now time to do so.  */
4091           if (thread == -1)
4092             thread = pid_to_thread_id (ptid);
4093           if (bl->owner->thread != thread)
4094             continue;
4095         }
4096
4097       if (bl->owner->task != 0)
4098         {
4099           /* This is a task-specific breakpoint.  Check that ptid
4100              matches that task.  If task hasn't been computed yet,
4101              it is now time to do so.  */
4102           if (task == 0)
4103             task = ada_get_task_number (ptid);
4104           if (bl->owner->task != task)
4105             continue;
4106         }
4107
4108       if (overlay_debugging 
4109           && section_is_overlay (bl->section)
4110           && !section_is_mapped (bl->section))
4111         continue;           /* unmapped overlay -- can't be a match */
4112
4113       return 1;
4114     }
4115
4116   return 0;
4117 }
4118 \f
4119
4120 /* bpstat stuff.  External routines' interfaces are documented
4121    in breakpoint.h.  */
4122
4123 int
4124 is_catchpoint (struct breakpoint *ep)
4125 {
4126   return (ep->type == bp_catchpoint);
4127 }
4128
4129 /* Frees any storage that is part of a bpstat.  Does not walk the
4130    'next' chain.  */
4131
4132 static void
4133 bpstat_free (bpstat bs)
4134 {
4135   if (bs->old_val != NULL)
4136     value_free (bs->old_val);
4137   decref_counted_command_line (&bs->commands);
4138   decref_bp_location (&bs->bp_location_at);
4139   xfree (bs);
4140 }
4141
4142 /* Clear a bpstat so that it says we are not at any breakpoint.
4143    Also free any storage that is part of a bpstat.  */
4144
4145 void
4146 bpstat_clear (bpstat *bsp)
4147 {
4148   bpstat p;
4149   bpstat q;
4150
4151   if (bsp == 0)
4152     return;
4153   p = *bsp;
4154   while (p != NULL)
4155     {
4156       q = p->next;
4157       bpstat_free (p);
4158       p = q;
4159     }
4160   *bsp = NULL;
4161 }
4162
4163 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4164    is part of the bpstat is copied as well.  */
4165
4166 bpstat
4167 bpstat_copy (bpstat bs)
4168 {
4169   bpstat p = NULL;
4170   bpstat tmp;
4171   bpstat retval = NULL;
4172
4173   if (bs == NULL)
4174     return bs;
4175
4176   for (; bs != NULL; bs = bs->next)
4177     {
4178       tmp = (bpstat) xmalloc (sizeof (*tmp));
4179       memcpy (tmp, bs, sizeof (*tmp));
4180       incref_counted_command_line (tmp->commands);
4181       incref_bp_location (tmp->bp_location_at);
4182       if (bs->old_val != NULL)
4183         {
4184           tmp->old_val = value_copy (bs->old_val);
4185           release_value (tmp->old_val);
4186         }
4187
4188       if (p == NULL)
4189         /* This is the first thing in the chain.  */
4190         retval = tmp;
4191       else
4192         p->next = tmp;
4193       p = tmp;
4194     }
4195   p->next = NULL;
4196   return retval;
4197 }
4198
4199 /* Find the bpstat associated with this breakpoint.  */
4200
4201 bpstat
4202 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4203 {
4204   if (bsp == NULL)
4205     return NULL;
4206
4207   for (; bsp != NULL; bsp = bsp->next)
4208     {
4209       if (bsp->breakpoint_at == breakpoint)
4210         return bsp;
4211     }
4212   return NULL;
4213 }
4214
4215 /* See breakpoint.h.  */
4216
4217 enum bpstat_signal_value
4218 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4219 {
4220   enum bpstat_signal_value result = BPSTAT_SIGNAL_NO;
4221
4222   for (; bsp != NULL; bsp = bsp->next)
4223     {
4224       /* Ensure that, if we ever entered this loop, then we at least
4225          return BPSTAT_SIGNAL_HIDE.  */
4226       enum bpstat_signal_value newval;
4227
4228       if (bsp->breakpoint_at == NULL)
4229         {
4230           /* A moribund location can never explain a signal other than
4231              GDB_SIGNAL_TRAP.  */
4232           if (sig == GDB_SIGNAL_TRAP)
4233             newval = BPSTAT_SIGNAL_HIDE;
4234           else
4235             newval = BPSTAT_SIGNAL_NO;
4236         }
4237       else
4238         newval = bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4239                                                            sig);
4240
4241       if (newval > result)
4242         result = newval;
4243     }
4244
4245   return result;
4246 }
4247
4248 /* Put in *NUM the breakpoint number of the first breakpoint we are
4249    stopped at.  *BSP upon return is a bpstat which points to the
4250    remaining breakpoints stopped at (but which is not guaranteed to be
4251    good for anything but further calls to bpstat_num).
4252
4253    Return 0 if passed a bpstat which does not indicate any breakpoints.
4254    Return -1 if stopped at a breakpoint that has been deleted since
4255    we set it.
4256    Return 1 otherwise.  */
4257
4258 int
4259 bpstat_num (bpstat *bsp, int *num)
4260 {
4261   struct breakpoint *b;
4262
4263   if ((*bsp) == NULL)
4264     return 0;                   /* No more breakpoint values */
4265
4266   /* We assume we'll never have several bpstats that correspond to a
4267      single breakpoint -- otherwise, this function might return the
4268      same number more than once and this will look ugly.  */
4269   b = (*bsp)->breakpoint_at;
4270   *bsp = (*bsp)->next;
4271   if (b == NULL)
4272     return -1;                  /* breakpoint that's been deleted since */
4273
4274   *num = b->number;             /* We have its number */
4275   return 1;
4276 }
4277
4278 /* See breakpoint.h.  */
4279
4280 void
4281 bpstat_clear_actions (void)
4282 {
4283   struct thread_info *tp;
4284   bpstat bs;
4285
4286   if (ptid_equal (inferior_ptid, null_ptid))
4287     return;
4288
4289   tp = find_thread_ptid (inferior_ptid);
4290   if (tp == NULL)
4291     return;
4292
4293   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4294     {
4295       decref_counted_command_line (&bs->commands);
4296
4297       if (bs->old_val != NULL)
4298         {
4299           value_free (bs->old_val);
4300           bs->old_val = NULL;
4301         }
4302     }
4303 }
4304
4305 /* Called when a command is about to proceed the inferior.  */
4306
4307 static void
4308 breakpoint_about_to_proceed (void)
4309 {
4310   if (!ptid_equal (inferior_ptid, null_ptid))
4311     {
4312       struct thread_info *tp = inferior_thread ();
4313
4314       /* Allow inferior function calls in breakpoint commands to not
4315          interrupt the command list.  When the call finishes
4316          successfully, the inferior will be standing at the same
4317          breakpoint as if nothing happened.  */
4318       if (tp->control.in_infcall)
4319         return;
4320     }
4321
4322   breakpoint_proceeded = 1;
4323 }
4324
4325 /* Stub for cleaning up our state if we error-out of a breakpoint
4326    command.  */
4327 static void
4328 cleanup_executing_breakpoints (void *ignore)
4329 {
4330   executing_breakpoint_commands = 0;
4331 }
4332
4333 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4334    or its equivalent.  */
4335
4336 static int
4337 command_line_is_silent (struct command_line *cmd)
4338 {
4339   return cmd && (strcmp ("silent", cmd->line) == 0
4340                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4341 }
4342
4343 /* Execute all the commands associated with all the breakpoints at
4344    this location.  Any of these commands could cause the process to
4345    proceed beyond this point, etc.  We look out for such changes by
4346    checking the global "breakpoint_proceeded" after each command.
4347
4348    Returns true if a breakpoint command resumed the inferior.  In that
4349    case, it is the caller's responsibility to recall it again with the
4350    bpstat of the current thread.  */
4351
4352 static int
4353 bpstat_do_actions_1 (bpstat *bsp)
4354 {
4355   bpstat bs;
4356   struct cleanup *old_chain;
4357   int again = 0;
4358
4359   /* Avoid endless recursion if a `source' command is contained
4360      in bs->commands.  */
4361   if (executing_breakpoint_commands)
4362     return 0;
4363
4364   executing_breakpoint_commands = 1;
4365   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4366
4367   prevent_dont_repeat ();
4368
4369   /* This pointer will iterate over the list of bpstat's.  */
4370   bs = *bsp;
4371
4372   breakpoint_proceeded = 0;
4373   for (; bs != NULL; bs = bs->next)
4374     {
4375       struct counted_command_line *ccmd;
4376       struct command_line *cmd;
4377       struct cleanup *this_cmd_tree_chain;
4378
4379       /* Take ownership of the BSP's command tree, if it has one.
4380
4381          The command tree could legitimately contain commands like
4382          'step' and 'next', which call clear_proceed_status, which
4383          frees stop_bpstat's command tree.  To make sure this doesn't
4384          free the tree we're executing out from under us, we need to
4385          take ownership of the tree ourselves.  Since a given bpstat's
4386          commands are only executed once, we don't need to copy it; we
4387          can clear the pointer in the bpstat, and make sure we free
4388          the tree when we're done.  */
4389       ccmd = bs->commands;
4390       bs->commands = NULL;
4391       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4392       cmd = ccmd ? ccmd->commands : NULL;
4393       if (command_line_is_silent (cmd))
4394         {
4395           /* The action has been already done by bpstat_stop_status.  */
4396           cmd = cmd->next;
4397         }
4398
4399       while (cmd != NULL)
4400         {
4401           execute_control_command (cmd);
4402
4403           if (breakpoint_proceeded)
4404             break;
4405           else
4406             cmd = cmd->next;
4407         }
4408
4409       /* We can free this command tree now.  */
4410       do_cleanups (this_cmd_tree_chain);
4411
4412       if (breakpoint_proceeded)
4413         {
4414           if (target_can_async_p ())
4415             /* If we are in async mode, then the target might be still
4416                running, not stopped at any breakpoint, so nothing for
4417                us to do here -- just return to the event loop.  */
4418             ;
4419           else
4420             /* In sync mode, when execute_control_command returns
4421                we're already standing on the next breakpoint.
4422                Breakpoint commands for that stop were not run, since
4423                execute_command does not run breakpoint commands --
4424                only command_line_handler does, but that one is not
4425                involved in execution of breakpoint commands.  So, we
4426                can now execute breakpoint commands.  It should be
4427                noted that making execute_command do bpstat actions is
4428                not an option -- in this case we'll have recursive
4429                invocation of bpstat for each breakpoint with a
4430                command, and can easily blow up GDB stack.  Instead, we
4431                return true, which will trigger the caller to recall us
4432                with the new stop_bpstat.  */
4433             again = 1;
4434           break;
4435         }
4436     }
4437   do_cleanups (old_chain);
4438   return again;
4439 }
4440
4441 void
4442 bpstat_do_actions (void)
4443 {
4444   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4445
4446   /* Do any commands attached to breakpoint we are stopped at.  */
4447   while (!ptid_equal (inferior_ptid, null_ptid)
4448          && target_has_execution
4449          && !is_exited (inferior_ptid)
4450          && !is_executing (inferior_ptid))
4451     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4452        and only return when it is stopped at the next breakpoint, we
4453        keep doing breakpoint actions until it returns false to
4454        indicate the inferior was not resumed.  */
4455     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4456       break;
4457
4458   discard_cleanups (cleanup_if_error);
4459 }
4460
4461 /* Print out the (old or new) value associated with a watchpoint.  */
4462
4463 static void
4464 watchpoint_value_print (struct value *val, struct ui_file *stream)
4465 {
4466   if (val == NULL)
4467     fprintf_unfiltered (stream, _("<unreadable>"));
4468   else
4469     {
4470       struct value_print_options opts;
4471       get_user_print_options (&opts);
4472       value_print (val, stream, &opts);
4473     }
4474 }
4475
4476 /* Generic routine for printing messages indicating why we
4477    stopped.  The behavior of this function depends on the value
4478    'print_it' in the bpstat structure.  Under some circumstances we
4479    may decide not to print anything here and delegate the task to
4480    normal_stop().  */
4481
4482 static enum print_stop_action
4483 print_bp_stop_message (bpstat bs)
4484 {
4485   switch (bs->print_it)
4486     {
4487     case print_it_noop:
4488       /* Nothing should be printed for this bpstat entry.  */
4489       return PRINT_UNKNOWN;
4490       break;
4491
4492     case print_it_done:
4493       /* We still want to print the frame, but we already printed the
4494          relevant messages.  */
4495       return PRINT_SRC_AND_LOC;
4496       break;
4497
4498     case print_it_normal:
4499       {
4500         struct breakpoint *b = bs->breakpoint_at;
4501
4502         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4503            which has since been deleted.  */
4504         if (b == NULL)
4505           return PRINT_UNKNOWN;
4506
4507         /* Normal case.  Call the breakpoint's print_it method.  */
4508         return b->ops->print_it (bs);
4509       }
4510       break;
4511
4512     default:
4513       internal_error (__FILE__, __LINE__,
4514                       _("print_bp_stop_message: unrecognized enum value"));
4515       break;
4516     }
4517 }
4518
4519 /* A helper function that prints a shared library stopped event.  */
4520
4521 static void
4522 print_solib_event (int is_catchpoint)
4523 {
4524   int any_deleted
4525     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4526   int any_added
4527     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4528
4529   if (!is_catchpoint)
4530     {
4531       if (any_added || any_deleted)
4532         ui_out_text (current_uiout,
4533                      _("Stopped due to shared library event:\n"));
4534       else
4535         ui_out_text (current_uiout,
4536                      _("Stopped due to shared library event (no "
4537                        "libraries added or removed)\n"));
4538     }
4539
4540   if (ui_out_is_mi_like_p (current_uiout))
4541     ui_out_field_string (current_uiout, "reason",
4542                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4543
4544   if (any_deleted)
4545     {
4546       struct cleanup *cleanup;
4547       char *name;
4548       int ix;
4549
4550       ui_out_text (current_uiout, _("  Inferior unloaded "));
4551       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4552                                                     "removed");
4553       for (ix = 0;
4554            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4555                         ix, name);
4556            ++ix)
4557         {
4558           if (ix > 0)
4559             ui_out_text (current_uiout, "    ");
4560           ui_out_field_string (current_uiout, "library", name);
4561           ui_out_text (current_uiout, "\n");
4562         }
4563
4564       do_cleanups (cleanup);
4565     }
4566
4567   if (any_added)
4568     {
4569       struct so_list *iter;
4570       int ix;
4571       struct cleanup *cleanup;
4572
4573       ui_out_text (current_uiout, _("  Inferior loaded "));
4574       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4575                                                     "added");
4576       for (ix = 0;
4577            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4578                         ix, iter);
4579            ++ix)
4580         {
4581           if (ix > 0)
4582             ui_out_text (current_uiout, "    ");
4583           ui_out_field_string (current_uiout, "library", iter->so_name);
4584           ui_out_text (current_uiout, "\n");
4585         }
4586
4587       do_cleanups (cleanup);
4588     }
4589 }
4590
4591 /* Print a message indicating what happened.  This is called from
4592    normal_stop().  The input to this routine is the head of the bpstat
4593    list - a list of the eventpoints that caused this stop.  KIND is
4594    the target_waitkind for the stopping event.  This
4595    routine calls the generic print routine for printing a message
4596    about reasons for stopping.  This will print (for example) the
4597    "Breakpoint n," part of the output.  The return value of this
4598    routine is one of:
4599
4600    PRINT_UNKNOWN: Means we printed nothing.
4601    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4602    code to print the location.  An example is 
4603    "Breakpoint 1, " which should be followed by
4604    the location.
4605    PRINT_SRC_ONLY: Means we printed something, but there is no need
4606    to also print the location part of the message.
4607    An example is the catch/throw messages, which
4608    don't require a location appended to the end.
4609    PRINT_NOTHING: We have done some printing and we don't need any 
4610    further info to be printed.  */
4611
4612 enum print_stop_action
4613 bpstat_print (bpstat bs, int kind)
4614 {
4615   int val;
4616
4617   /* Maybe another breakpoint in the chain caused us to stop.
4618      (Currently all watchpoints go on the bpstat whether hit or not.
4619      That probably could (should) be changed, provided care is taken
4620      with respect to bpstat_explains_signal).  */
4621   for (; bs; bs = bs->next)
4622     {
4623       val = print_bp_stop_message (bs);
4624       if (val == PRINT_SRC_ONLY 
4625           || val == PRINT_SRC_AND_LOC 
4626           || val == PRINT_NOTHING)
4627         return val;
4628     }
4629
4630   /* If we had hit a shared library event breakpoint,
4631      print_bp_stop_message would print out this message.  If we hit an
4632      OS-level shared library event, do the same thing.  */
4633   if (kind == TARGET_WAITKIND_LOADED)
4634     {
4635       print_solib_event (0);
4636       return PRINT_NOTHING;
4637     }
4638
4639   /* We reached the end of the chain, or we got a null BS to start
4640      with and nothing was printed.  */
4641   return PRINT_UNKNOWN;
4642 }
4643
4644 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4645    used inside a catch_errors to evaluate the breakpoint condition.
4646    The argument is a "struct expression *" that has been cast to a
4647    "char *" to make it pass through catch_errors.  */
4648
4649 static int
4650 breakpoint_cond_eval (void *exp)
4651 {
4652   struct value *mark = value_mark ();
4653   int i = !value_true (evaluate_expression ((struct expression *) exp));
4654
4655   value_free_to_mark (mark);
4656   return i;
4657 }
4658
4659 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4660
4661 static bpstat
4662 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4663 {
4664   bpstat bs;
4665
4666   bs = (bpstat) xmalloc (sizeof (*bs));
4667   bs->next = NULL;
4668   **bs_link_pointer = bs;
4669   *bs_link_pointer = &bs->next;
4670   bs->breakpoint_at = bl->owner;
4671   bs->bp_location_at = bl;
4672   incref_bp_location (bl);
4673   /* If the condition is false, etc., don't do the commands.  */
4674   bs->commands = NULL;
4675   bs->old_val = NULL;
4676   bs->print_it = print_it_normal;
4677   return bs;
4678 }
4679 \f
4680 /* The target has stopped with waitstatus WS.  Check if any hardware
4681    watchpoints have triggered, according to the target.  */
4682
4683 int
4684 watchpoints_triggered (struct target_waitstatus *ws)
4685 {
4686   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4687   CORE_ADDR addr;
4688   struct breakpoint *b;
4689
4690   if (!stopped_by_watchpoint)
4691     {
4692       /* We were not stopped by a watchpoint.  Mark all watchpoints
4693          as not triggered.  */
4694       ALL_BREAKPOINTS (b)
4695         if (is_hardware_watchpoint (b))
4696           {
4697             struct watchpoint *w = (struct watchpoint *) b;
4698
4699             w->watchpoint_triggered = watch_triggered_no;
4700           }
4701
4702       return 0;
4703     }
4704
4705   if (!target_stopped_data_address (&current_target, &addr))
4706     {
4707       /* We were stopped by a watchpoint, but we don't know where.
4708          Mark all watchpoints as unknown.  */
4709       ALL_BREAKPOINTS (b)
4710         if (is_hardware_watchpoint (b))
4711           {
4712             struct watchpoint *w = (struct watchpoint *) b;
4713
4714             w->watchpoint_triggered = watch_triggered_unknown;
4715           }
4716
4717       return stopped_by_watchpoint;
4718     }
4719
4720   /* The target could report the data address.  Mark watchpoints
4721      affected by this data address as triggered, and all others as not
4722      triggered.  */
4723
4724   ALL_BREAKPOINTS (b)
4725     if (is_hardware_watchpoint (b))
4726       {
4727         struct watchpoint *w = (struct watchpoint *) b;
4728         struct bp_location *loc;
4729
4730         w->watchpoint_triggered = watch_triggered_no;
4731         for (loc = b->loc; loc; loc = loc->next)
4732           {
4733             if (is_masked_watchpoint (b))
4734               {
4735                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4736                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4737
4738                 if (newaddr == start)
4739                   {
4740                     w->watchpoint_triggered = watch_triggered_yes;
4741                     break;
4742                   }
4743               }
4744             /* Exact match not required.  Within range is sufficient.  */
4745             else if (target_watchpoint_addr_within_range (&current_target,
4746                                                          addr, loc->address,
4747                                                          loc->length))
4748               {
4749                 w->watchpoint_triggered = watch_triggered_yes;
4750                 break;
4751               }
4752           }
4753       }
4754
4755   return 1;
4756 }
4757
4758 /* Possible return values for watchpoint_check (this can't be an enum
4759    because of check_errors).  */
4760 /* The watchpoint has been deleted.  */
4761 #define WP_DELETED 1
4762 /* The value has changed.  */
4763 #define WP_VALUE_CHANGED 2
4764 /* The value has not changed.  */
4765 #define WP_VALUE_NOT_CHANGED 3
4766 /* Ignore this watchpoint, no matter if the value changed or not.  */
4767 #define WP_IGNORE 4
4768
4769 #define BP_TEMPFLAG 1
4770 #define BP_HARDWAREFLAG 2
4771
4772 /* Evaluate watchpoint condition expression and check if its value
4773    changed.
4774
4775    P should be a pointer to struct bpstat, but is defined as a void *
4776    in order for this function to be usable with catch_errors.  */
4777
4778 static int
4779 watchpoint_check (void *p)
4780 {
4781   bpstat bs = (bpstat) p;
4782   struct watchpoint *b;
4783   struct frame_info *fr;
4784   int within_current_scope;
4785
4786   /* BS is built from an existing struct breakpoint.  */
4787   gdb_assert (bs->breakpoint_at != NULL);
4788   b = (struct watchpoint *) bs->breakpoint_at;
4789
4790   /* If this is a local watchpoint, we only want to check if the
4791      watchpoint frame is in scope if the current thread is the thread
4792      that was used to create the watchpoint.  */
4793   if (!watchpoint_in_thread_scope (b))
4794     return WP_IGNORE;
4795
4796   if (b->exp_valid_block == NULL)
4797     within_current_scope = 1;
4798   else
4799     {
4800       struct frame_info *frame = get_current_frame ();
4801       struct gdbarch *frame_arch = get_frame_arch (frame);
4802       CORE_ADDR frame_pc = get_frame_pc (frame);
4803
4804       /* in_function_epilogue_p() returns a non-zero value if we're
4805          still in the function but the stack frame has already been
4806          invalidated.  Since we can't rely on the values of local
4807          variables after the stack has been destroyed, we are treating
4808          the watchpoint in that state as `not changed' without further
4809          checking.  Don't mark watchpoints as changed if the current
4810          frame is in an epilogue - even if they are in some other
4811          frame, our view of the stack is likely to be wrong and
4812          frame_find_by_id could error out.  */
4813       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4814         return WP_IGNORE;
4815
4816       fr = frame_find_by_id (b->watchpoint_frame);
4817       within_current_scope = (fr != NULL);
4818
4819       /* If we've gotten confused in the unwinder, we might have
4820          returned a frame that can't describe this variable.  */
4821       if (within_current_scope)
4822         {
4823           struct symbol *function;
4824
4825           function = get_frame_function (fr);
4826           if (function == NULL
4827               || !contained_in (b->exp_valid_block,
4828                                 SYMBOL_BLOCK_VALUE (function)))
4829             within_current_scope = 0;
4830         }
4831
4832       if (within_current_scope)
4833         /* If we end up stopping, the current frame will get selected
4834            in normal_stop.  So this call to select_frame won't affect
4835            the user.  */
4836         select_frame (fr);
4837     }
4838
4839   if (within_current_scope)
4840     {
4841       /* We use value_{,free_to_}mark because it could be a *long*
4842          time before we return to the command level and call
4843          free_all_values.  We can't call free_all_values because we
4844          might be in the middle of evaluating a function call.  */
4845
4846       int pc = 0;
4847       struct value *mark;
4848       struct value *new_val;
4849
4850       if (is_masked_watchpoint (&b->base))
4851         /* Since we don't know the exact trigger address (from
4852            stopped_data_address), just tell the user we've triggered
4853            a mask watchpoint.  */
4854         return WP_VALUE_CHANGED;
4855
4856       mark = value_mark ();
4857       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
4858
4859       /* We use value_equal_contents instead of value_equal because
4860          the latter coerces an array to a pointer, thus comparing just
4861          the address of the array instead of its contents.  This is
4862          not what we want.  */
4863       if ((b->val != NULL) != (new_val != NULL)
4864           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4865         {
4866           if (new_val != NULL)
4867             {
4868               release_value (new_val);
4869               value_free_to_mark (mark);
4870             }
4871           bs->old_val = b->val;
4872           b->val = new_val;
4873           b->val_valid = 1;
4874           return WP_VALUE_CHANGED;
4875         }
4876       else
4877         {
4878           /* Nothing changed.  */
4879           value_free_to_mark (mark);
4880           return WP_VALUE_NOT_CHANGED;
4881         }
4882     }
4883   else
4884     {
4885       struct ui_out *uiout = current_uiout;
4886
4887       /* This seems like the only logical thing to do because
4888          if we temporarily ignored the watchpoint, then when
4889          we reenter the block in which it is valid it contains
4890          garbage (in the case of a function, it may have two
4891          garbage values, one before and one after the prologue).
4892          So we can't even detect the first assignment to it and
4893          watch after that (since the garbage may or may not equal
4894          the first value assigned).  */
4895       /* We print all the stop information in
4896          breakpoint_ops->print_it, but in this case, by the time we
4897          call breakpoint_ops->print_it this bp will be deleted
4898          already.  So we have no choice but print the information
4899          here.  */
4900       if (ui_out_is_mi_like_p (uiout))
4901         ui_out_field_string
4902           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4903       ui_out_text (uiout, "\nWatchpoint ");
4904       ui_out_field_int (uiout, "wpnum", b->base.number);
4905       ui_out_text (uiout,
4906                    " deleted because the program has left the block in\n\
4907 which its expression is valid.\n");     
4908
4909       /* Make sure the watchpoint's commands aren't executed.  */
4910       decref_counted_command_line (&b->base.commands);
4911       watchpoint_del_at_next_stop (b);
4912
4913       return WP_DELETED;
4914     }
4915 }
4916
4917 /* Return true if it looks like target has stopped due to hitting
4918    breakpoint location BL.  This function does not check if we should
4919    stop, only if BL explains the stop.  */
4920
4921 static int
4922 bpstat_check_location (const struct bp_location *bl,
4923                        struct address_space *aspace, CORE_ADDR bp_addr,
4924                        const struct target_waitstatus *ws)
4925 {
4926   struct breakpoint *b = bl->owner;
4927
4928   /* BL is from an existing breakpoint.  */
4929   gdb_assert (b != NULL);
4930
4931   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4932 }
4933
4934 /* Determine if the watched values have actually changed, and we
4935    should stop.  If not, set BS->stop to 0.  */
4936
4937 static void
4938 bpstat_check_watchpoint (bpstat bs)
4939 {
4940   const struct bp_location *bl;
4941   struct watchpoint *b;
4942
4943   /* BS is built for existing struct breakpoint.  */
4944   bl = bs->bp_location_at;
4945   gdb_assert (bl != NULL);
4946   b = (struct watchpoint *) bs->breakpoint_at;
4947   gdb_assert (b != NULL);
4948
4949     {
4950       int must_check_value = 0;
4951       
4952       if (b->base.type == bp_watchpoint)
4953         /* For a software watchpoint, we must always check the
4954            watched value.  */
4955         must_check_value = 1;
4956       else if (b->watchpoint_triggered == watch_triggered_yes)
4957         /* We have a hardware watchpoint (read, write, or access)
4958            and the target earlier reported an address watched by
4959            this watchpoint.  */
4960         must_check_value = 1;
4961       else if (b->watchpoint_triggered == watch_triggered_unknown
4962                && b->base.type == bp_hardware_watchpoint)
4963         /* We were stopped by a hardware watchpoint, but the target could
4964            not report the data address.  We must check the watchpoint's
4965            value.  Access and read watchpoints are out of luck; without
4966            a data address, we can't figure it out.  */
4967         must_check_value = 1;
4968
4969       if (must_check_value)
4970         {
4971           char *message
4972             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4973                           b->base.number);
4974           struct cleanup *cleanups = make_cleanup (xfree, message);
4975           int e = catch_errors (watchpoint_check, bs, message,
4976                                 RETURN_MASK_ALL);
4977           do_cleanups (cleanups);
4978           switch (e)
4979             {
4980             case WP_DELETED:
4981               /* We've already printed what needs to be printed.  */
4982               bs->print_it = print_it_done;
4983               /* Stop.  */
4984               break;
4985             case WP_IGNORE:
4986               bs->print_it = print_it_noop;
4987               bs->stop = 0;
4988               break;
4989             case WP_VALUE_CHANGED:
4990               if (b->base.type == bp_read_watchpoint)
4991                 {
4992                   /* There are two cases to consider here:
4993
4994                      1. We're watching the triggered memory for reads.
4995                      In that case, trust the target, and always report
4996                      the watchpoint hit to the user.  Even though
4997                      reads don't cause value changes, the value may
4998                      have changed since the last time it was read, and
4999                      since we're not trapping writes, we will not see
5000                      those, and as such we should ignore our notion of
5001                      old value.
5002
5003                      2. We're watching the triggered memory for both
5004                      reads and writes.  There are two ways this may
5005                      happen:
5006
5007                      2.1. This is a target that can't break on data
5008                      reads only, but can break on accesses (reads or
5009                      writes), such as e.g., x86.  We detect this case
5010                      at the time we try to insert read watchpoints.
5011
5012                      2.2. Otherwise, the target supports read
5013                      watchpoints, but, the user set an access or write
5014                      watchpoint watching the same memory as this read
5015                      watchpoint.
5016
5017                      If we're watching memory writes as well as reads,
5018                      ignore watchpoint hits when we find that the
5019                      value hasn't changed, as reads don't cause
5020                      changes.  This still gives false positives when
5021                      the program writes the same value to memory as
5022                      what there was already in memory (we will confuse
5023                      it for a read), but it's much better than
5024                      nothing.  */
5025
5026                   int other_write_watchpoint = 0;
5027
5028                   if (bl->watchpoint_type == hw_read)
5029                     {
5030                       struct breakpoint *other_b;
5031
5032                       ALL_BREAKPOINTS (other_b)
5033                         if (other_b->type == bp_hardware_watchpoint
5034                             || other_b->type == bp_access_watchpoint)
5035                           {
5036                             struct watchpoint *other_w =
5037                               (struct watchpoint *) other_b;
5038
5039                             if (other_w->watchpoint_triggered
5040                                 == watch_triggered_yes)
5041                               {
5042                                 other_write_watchpoint = 1;
5043                                 break;
5044                               }
5045                           }
5046                     }
5047
5048                   if (other_write_watchpoint
5049                       || bl->watchpoint_type == hw_access)
5050                     {
5051                       /* We're watching the same memory for writes,
5052                          and the value changed since the last time we
5053                          updated it, so this trap must be for a write.
5054                          Ignore it.  */
5055                       bs->print_it = print_it_noop;
5056                       bs->stop = 0;
5057                     }
5058                 }
5059               break;
5060             case WP_VALUE_NOT_CHANGED:
5061               if (b->base.type == bp_hardware_watchpoint
5062                   || b->base.type == bp_watchpoint)
5063                 {
5064                   /* Don't stop: write watchpoints shouldn't fire if
5065                      the value hasn't changed.  */
5066                   bs->print_it = print_it_noop;
5067                   bs->stop = 0;
5068                 }
5069               /* Stop.  */
5070               break;
5071             default:
5072               /* Can't happen.  */
5073             case 0:
5074               /* Error from catch_errors.  */
5075               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5076               watchpoint_del_at_next_stop (b);
5077               /* We've already printed what needs to be printed.  */
5078               bs->print_it = print_it_done;
5079               break;
5080             }
5081         }
5082       else      /* must_check_value == 0 */
5083         {
5084           /* This is a case where some watchpoint(s) triggered, but
5085              not at the address of this watchpoint, or else no
5086              watchpoint triggered after all.  So don't print
5087              anything for this watchpoint.  */
5088           bs->print_it = print_it_noop;
5089           bs->stop = 0;
5090         }
5091     }
5092 }
5093
5094
5095 /* Check conditions (condition proper, frame, thread and ignore count)
5096    of breakpoint referred to by BS.  If we should not stop for this
5097    breakpoint, set BS->stop to 0.  */
5098
5099 static void
5100 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5101 {
5102   int thread_id = pid_to_thread_id (ptid);
5103   const struct bp_location *bl;
5104   struct breakpoint *b;
5105
5106   /* BS is built for existing struct breakpoint.  */
5107   bl = bs->bp_location_at;
5108   gdb_assert (bl != NULL);
5109   b = bs->breakpoint_at;
5110   gdb_assert (b != NULL);
5111
5112   /* Even if the target evaluated the condition on its end and notified GDB, we
5113      need to do so again since GDB does not know if we stopped due to a
5114      breakpoint or a single step breakpoint.  */
5115
5116   if (frame_id_p (b->frame_id)
5117       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5118     bs->stop = 0;
5119   else if (bs->stop)
5120     {
5121       int value_is_zero = 0;
5122       struct expression *cond;
5123
5124       /* Evaluate Python breakpoints that have a "stop"
5125          method implemented.  */
5126       if (b->py_bp_object)
5127         bs->stop = gdbpy_should_stop (b->py_bp_object);
5128
5129       if (is_watchpoint (b))
5130         {
5131           struct watchpoint *w = (struct watchpoint *) b;
5132
5133           cond = w->cond_exp;
5134         }
5135       else
5136         cond = bl->cond;
5137
5138       if (cond && b->disposition != disp_del_at_next_stop)
5139         {
5140           int within_current_scope = 1;
5141           struct watchpoint * w;
5142
5143           /* We use value_mark and value_free_to_mark because it could
5144              be a long time before we return to the command level and
5145              call free_all_values.  We can't call free_all_values
5146              because we might be in the middle of evaluating a
5147              function call.  */
5148           struct value *mark = value_mark ();
5149
5150           if (is_watchpoint (b))
5151             w = (struct watchpoint *) b;
5152           else
5153             w = NULL;
5154
5155           /* Need to select the frame, with all that implies so that
5156              the conditions will have the right context.  Because we
5157              use the frame, we will not see an inlined function's
5158              variables when we arrive at a breakpoint at the start
5159              of the inlined function; the current frame will be the
5160              call site.  */
5161           if (w == NULL || w->cond_exp_valid_block == NULL)
5162             select_frame (get_current_frame ());
5163           else
5164             {
5165               struct frame_info *frame;
5166
5167               /* For local watchpoint expressions, which particular
5168                  instance of a local is being watched matters, so we
5169                  keep track of the frame to evaluate the expression
5170                  in.  To evaluate the condition however, it doesn't
5171                  really matter which instantiation of the function
5172                  where the condition makes sense triggers the
5173                  watchpoint.  This allows an expression like "watch
5174                  global if q > 10" set in `func', catch writes to
5175                  global on all threads that call `func', or catch
5176                  writes on all recursive calls of `func' by a single
5177                  thread.  We simply always evaluate the condition in
5178                  the innermost frame that's executing where it makes
5179                  sense to evaluate the condition.  It seems
5180                  intuitive.  */
5181               frame = block_innermost_frame (w->cond_exp_valid_block);
5182               if (frame != NULL)
5183                 select_frame (frame);
5184               else
5185                 within_current_scope = 0;
5186             }
5187           if (within_current_scope)
5188             value_is_zero
5189               = catch_errors (breakpoint_cond_eval, cond,
5190                               "Error in testing breakpoint condition:\n",
5191                               RETURN_MASK_ALL);
5192           else
5193             {
5194               warning (_("Watchpoint condition cannot be tested "
5195                          "in the current scope"));
5196               /* If we failed to set the right context for this
5197                  watchpoint, unconditionally report it.  */
5198               value_is_zero = 0;
5199             }
5200           /* FIXME-someday, should give breakpoint #.  */
5201           value_free_to_mark (mark);
5202         }
5203
5204       if (cond && value_is_zero)
5205         {
5206           bs->stop = 0;
5207         }
5208       else if (b->thread != -1 && b->thread != thread_id)
5209         {
5210           bs->stop = 0;
5211         }
5212       else if (b->ignore_count > 0)
5213         {
5214           b->ignore_count--;
5215           bs->stop = 0;
5216           /* Increase the hit count even though we don't stop.  */
5217           ++(b->hit_count);
5218           observer_notify_breakpoint_modified (b);
5219         }       
5220     }
5221 }
5222
5223
5224 /* Get a bpstat associated with having just stopped at address
5225    BP_ADDR in thread PTID.
5226
5227    Determine whether we stopped at a breakpoint, etc, or whether we
5228    don't understand this stop.  Result is a chain of bpstat's such
5229    that:
5230
5231    if we don't understand the stop, the result is a null pointer.
5232
5233    if we understand why we stopped, the result is not null.
5234
5235    Each element of the chain refers to a particular breakpoint or
5236    watchpoint at which we have stopped.  (We may have stopped for
5237    several reasons concurrently.)
5238
5239    Each element of the chain has valid next, breakpoint_at,
5240    commands, FIXME??? fields.  */
5241
5242 bpstat
5243 bpstat_stop_status (struct address_space *aspace,
5244                     CORE_ADDR bp_addr, ptid_t ptid,
5245                     const struct target_waitstatus *ws)
5246 {
5247   struct breakpoint *b = NULL;
5248   struct bp_location *bl;
5249   struct bp_location *loc;
5250   /* First item of allocated bpstat's.  */
5251   bpstat bs_head = NULL, *bs_link = &bs_head;
5252   /* Pointer to the last thing in the chain currently.  */
5253   bpstat bs;
5254   int ix;
5255   int need_remove_insert;
5256   int removed_any;
5257
5258   /* First, build the bpstat chain with locations that explain a
5259      target stop, while being careful to not set the target running,
5260      as that may invalidate locations (in particular watchpoint
5261      locations are recreated).  Resuming will happen here with
5262      breakpoint conditions or watchpoint expressions that include
5263      inferior function calls.  */
5264
5265   ALL_BREAKPOINTS (b)
5266     {
5267       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5268         continue;
5269
5270       for (bl = b->loc; bl != NULL; bl = bl->next)
5271         {
5272           /* For hardware watchpoints, we look only at the first
5273              location.  The watchpoint_check function will work on the
5274              entire expression, not the individual locations.  For
5275              read watchpoints, the watchpoints_triggered function has
5276              checked all locations already.  */
5277           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5278             break;
5279
5280           if (!bl->enabled || bl->shlib_disabled)
5281             continue;
5282
5283           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5284             continue;
5285
5286           /* Come here if it's a watchpoint, or if the break address
5287              matches.  */
5288
5289           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5290                                                    explain stop.  */
5291
5292           /* Assume we stop.  Should we find a watchpoint that is not
5293              actually triggered, or if the condition of the breakpoint
5294              evaluates as false, we'll reset 'stop' to 0.  */
5295           bs->stop = 1;
5296           bs->print = 1;
5297
5298           /* If this is a scope breakpoint, mark the associated
5299              watchpoint as triggered so that we will handle the
5300              out-of-scope event.  We'll get to the watchpoint next
5301              iteration.  */
5302           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5303             {
5304               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5305
5306               w->watchpoint_triggered = watch_triggered_yes;
5307             }
5308         }
5309     }
5310
5311   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5312     {
5313       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5314         {
5315           bs = bpstat_alloc (loc, &bs_link);
5316           /* For hits of moribund locations, we should just proceed.  */
5317           bs->stop = 0;
5318           bs->print = 0;
5319           bs->print_it = print_it_noop;
5320         }
5321     }
5322
5323   /* A bit of special processing for shlib breakpoints.  We need to
5324      process solib loading here, so that the lists of loaded and
5325      unloaded libraries are correct before we handle "catch load" and
5326      "catch unload".  */
5327   for (bs = bs_head; bs != NULL; bs = bs->next)
5328     {
5329       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5330         {
5331           handle_solib_event ();
5332           break;
5333         }
5334     }
5335
5336   /* Now go through the locations that caused the target to stop, and
5337      check whether we're interested in reporting this stop to higher
5338      layers, or whether we should resume the target transparently.  */
5339
5340   removed_any = 0;
5341
5342   for (bs = bs_head; bs != NULL; bs = bs->next)
5343     {
5344       if (!bs->stop)
5345         continue;
5346
5347       b = bs->breakpoint_at;
5348       b->ops->check_status (bs);
5349       if (bs->stop)
5350         {
5351           bpstat_check_breakpoint_conditions (bs, ptid);
5352
5353           if (bs->stop)
5354             {
5355               ++(b->hit_count);
5356               observer_notify_breakpoint_modified (b);
5357
5358               /* We will stop here.  */
5359               if (b->disposition == disp_disable)
5360                 {
5361                   --(b->enable_count);
5362                   if (b->enable_count <= 0
5363                       && b->enable_state != bp_permanent)
5364                     b->enable_state = bp_disabled;
5365                   removed_any = 1;
5366                 }
5367               if (b->silent)
5368                 bs->print = 0;
5369               bs->commands = b->commands;
5370               incref_counted_command_line (bs->commands);
5371               if (command_line_is_silent (bs->commands
5372                                           ? bs->commands->commands : NULL))
5373                 bs->print = 0;
5374
5375               b->ops->after_condition_true (bs);
5376             }
5377
5378         }
5379
5380       /* Print nothing for this entry if we don't stop or don't
5381          print.  */
5382       if (!bs->stop || !bs->print)
5383         bs->print_it = print_it_noop;
5384     }
5385
5386   /* If we aren't stopping, the value of some hardware watchpoint may
5387      not have changed, but the intermediate memory locations we are
5388      watching may have.  Don't bother if we're stopping; this will get
5389      done later.  */
5390   need_remove_insert = 0;
5391   if (! bpstat_causes_stop (bs_head))
5392     for (bs = bs_head; bs != NULL; bs = bs->next)
5393       if (!bs->stop
5394           && bs->breakpoint_at
5395           && is_hardware_watchpoint (bs->breakpoint_at))
5396         {
5397           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5398
5399           update_watchpoint (w, 0 /* don't reparse.  */);
5400           need_remove_insert = 1;
5401         }
5402
5403   if (need_remove_insert)
5404     update_global_location_list (1);
5405   else if (removed_any)
5406     update_global_location_list (0);
5407
5408   return bs_head;
5409 }
5410
5411 static void
5412 handle_jit_event (void)
5413 {
5414   struct frame_info *frame;
5415   struct gdbarch *gdbarch;
5416
5417   /* Switch terminal for any messages produced by
5418      breakpoint_re_set.  */
5419   target_terminal_ours_for_output ();
5420
5421   frame = get_current_frame ();
5422   gdbarch = get_frame_arch (frame);
5423
5424   jit_event_handler (gdbarch);
5425
5426   target_terminal_inferior ();
5427 }
5428
5429 /* Prepare WHAT final decision for infrun.  */
5430
5431 /* Decide what infrun needs to do with this bpstat.  */
5432
5433 struct bpstat_what
5434 bpstat_what (bpstat bs_head)
5435 {
5436   struct bpstat_what retval;
5437   int jit_event = 0;
5438   bpstat bs;
5439
5440   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5441   retval.call_dummy = STOP_NONE;
5442   retval.is_longjmp = 0;
5443
5444   for (bs = bs_head; bs != NULL; bs = bs->next)
5445     {
5446       /* Extract this BS's action.  After processing each BS, we check
5447          if its action overrides all we've seem so far.  */
5448       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5449       enum bptype bptype;
5450
5451       if (bs->breakpoint_at == NULL)
5452         {
5453           /* I suspect this can happen if it was a momentary
5454              breakpoint which has since been deleted.  */
5455           bptype = bp_none;
5456         }
5457       else
5458         bptype = bs->breakpoint_at->type;
5459
5460       switch (bptype)
5461         {
5462         case bp_none:
5463           break;
5464         case bp_breakpoint:
5465         case bp_hardware_breakpoint:
5466         case bp_until:
5467         case bp_finish:
5468         case bp_shlib_event:
5469           if (bs->stop)
5470             {
5471               if (bs->print)
5472                 this_action = BPSTAT_WHAT_STOP_NOISY;
5473               else
5474                 this_action = BPSTAT_WHAT_STOP_SILENT;
5475             }
5476           else
5477             this_action = BPSTAT_WHAT_SINGLE;
5478           break;
5479         case bp_watchpoint:
5480         case bp_hardware_watchpoint:
5481         case bp_read_watchpoint:
5482         case bp_access_watchpoint:
5483           if (bs->stop)
5484             {
5485               if (bs->print)
5486                 this_action = BPSTAT_WHAT_STOP_NOISY;
5487               else
5488                 this_action = BPSTAT_WHAT_STOP_SILENT;
5489             }
5490           else
5491             {
5492               /* There was a watchpoint, but we're not stopping.
5493                  This requires no further action.  */
5494             }
5495           break;
5496         case bp_longjmp:
5497         case bp_longjmp_call_dummy:
5498         case bp_exception:
5499           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5500           retval.is_longjmp = bptype != bp_exception;
5501           break;
5502         case bp_longjmp_resume:
5503         case bp_exception_resume:
5504           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5505           retval.is_longjmp = bptype == bp_longjmp_resume;
5506           break;
5507         case bp_step_resume:
5508           if (bs->stop)
5509             this_action = BPSTAT_WHAT_STEP_RESUME;
5510           else
5511             {
5512               /* It is for the wrong frame.  */
5513               this_action = BPSTAT_WHAT_SINGLE;
5514             }
5515           break;
5516         case bp_hp_step_resume:
5517           if (bs->stop)
5518             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5519           else
5520             {
5521               /* It is for the wrong frame.  */
5522               this_action = BPSTAT_WHAT_SINGLE;
5523             }
5524           break;
5525         case bp_watchpoint_scope:
5526         case bp_thread_event:
5527         case bp_overlay_event:
5528         case bp_longjmp_master:
5529         case bp_std_terminate_master:
5530         case bp_exception_master:
5531           this_action = BPSTAT_WHAT_SINGLE;
5532           break;
5533         case bp_catchpoint:
5534           if (bs->stop)
5535             {
5536               if (bs->print)
5537                 this_action = BPSTAT_WHAT_STOP_NOISY;
5538               else
5539                 this_action = BPSTAT_WHAT_STOP_SILENT;
5540             }
5541           else
5542             {
5543               /* There was a catchpoint, but we're not stopping.
5544                  This requires no further action.  */
5545             }
5546           break;
5547         case bp_jit_event:
5548           jit_event = 1;
5549           this_action = BPSTAT_WHAT_SINGLE;
5550           break;
5551         case bp_call_dummy:
5552           /* Make sure the action is stop (silent or noisy),
5553              so infrun.c pops the dummy frame.  */
5554           retval.call_dummy = STOP_STACK_DUMMY;
5555           this_action = BPSTAT_WHAT_STOP_SILENT;
5556           break;
5557         case bp_std_terminate:
5558           /* Make sure the action is stop (silent or noisy),
5559              so infrun.c pops the dummy frame.  */
5560           retval.call_dummy = STOP_STD_TERMINATE;
5561           this_action = BPSTAT_WHAT_STOP_SILENT;
5562           break;
5563         case bp_tracepoint:
5564         case bp_fast_tracepoint:
5565         case bp_static_tracepoint:
5566           /* Tracepoint hits should not be reported back to GDB, and
5567              if one got through somehow, it should have been filtered
5568              out already.  */
5569           internal_error (__FILE__, __LINE__,
5570                           _("bpstat_what: tracepoint encountered"));
5571           break;
5572         case bp_gnu_ifunc_resolver:
5573           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5574           this_action = BPSTAT_WHAT_SINGLE;
5575           break;
5576         case bp_gnu_ifunc_resolver_return:
5577           /* The breakpoint will be removed, execution will restart from the
5578              PC of the former breakpoint.  */
5579           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5580           break;
5581
5582         case bp_dprintf:
5583           if (bs->stop)
5584             this_action = BPSTAT_WHAT_STOP_SILENT;
5585           else
5586             this_action = BPSTAT_WHAT_SINGLE;
5587           break;
5588
5589         default:
5590           internal_error (__FILE__, __LINE__,
5591                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5592         }
5593
5594       retval.main_action = max (retval.main_action, this_action);
5595     }
5596
5597   /* These operations may affect the bs->breakpoint_at state so they are
5598      delayed after MAIN_ACTION is decided above.  */
5599
5600   if (jit_event)
5601     {
5602       if (debug_infrun)
5603         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5604
5605       handle_jit_event ();
5606     }
5607
5608   for (bs = bs_head; bs != NULL; bs = bs->next)
5609     {
5610       struct breakpoint *b = bs->breakpoint_at;
5611
5612       if (b == NULL)
5613         continue;
5614       switch (b->type)
5615         {
5616         case bp_gnu_ifunc_resolver:
5617           gnu_ifunc_resolver_stop (b);
5618           break;
5619         case bp_gnu_ifunc_resolver_return:
5620           gnu_ifunc_resolver_return_stop (b);
5621           break;
5622         }
5623     }
5624
5625   return retval;
5626 }
5627
5628 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5629    without hardware support).  This isn't related to a specific bpstat,
5630    just to things like whether watchpoints are set.  */
5631
5632 int
5633 bpstat_should_step (void)
5634 {
5635   struct breakpoint *b;
5636
5637   ALL_BREAKPOINTS (b)
5638     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5639       return 1;
5640   return 0;
5641 }
5642
5643 int
5644 bpstat_causes_stop (bpstat bs)
5645 {
5646   for (; bs != NULL; bs = bs->next)
5647     if (bs->stop)
5648       return 1;
5649
5650   return 0;
5651 }
5652
5653 \f
5654
5655 /* Compute a string of spaces suitable to indent the next line
5656    so it starts at the position corresponding to the table column
5657    named COL_NAME in the currently active table of UIOUT.  */
5658
5659 static char *
5660 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5661 {
5662   static char wrap_indent[80];
5663   int i, total_width, width, align;
5664   char *text;
5665
5666   total_width = 0;
5667   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5668     {
5669       if (strcmp (text, col_name) == 0)
5670         {
5671           gdb_assert (total_width < sizeof wrap_indent);
5672           memset (wrap_indent, ' ', total_width);
5673           wrap_indent[total_width] = 0;
5674
5675           return wrap_indent;
5676         }
5677
5678       total_width += width + 1;
5679     }
5680
5681   return NULL;
5682 }
5683
5684 /* Determine if the locations of this breakpoint will have their conditions
5685    evaluated by the target, host or a mix of both.  Returns the following:
5686
5687     "host": Host evals condition.
5688     "host or target": Host or Target evals condition.
5689     "target": Target evals condition.
5690 */
5691
5692 static const char *
5693 bp_condition_evaluator (struct breakpoint *b)
5694 {
5695   struct bp_location *bl;
5696   char host_evals = 0;
5697   char target_evals = 0;
5698
5699   if (!b)
5700     return NULL;
5701
5702   if (!is_breakpoint (b))
5703     return NULL;
5704
5705   if (gdb_evaluates_breakpoint_condition_p ()
5706       || !target_supports_evaluation_of_breakpoint_conditions ())
5707     return condition_evaluation_host;
5708
5709   for (bl = b->loc; bl; bl = bl->next)
5710     {
5711       if (bl->cond_bytecode)
5712         target_evals++;
5713       else
5714         host_evals++;
5715     }
5716
5717   if (host_evals && target_evals)
5718     return condition_evaluation_both;
5719   else if (target_evals)
5720     return condition_evaluation_target;
5721   else
5722     return condition_evaluation_host;
5723 }
5724
5725 /* Determine the breakpoint location's condition evaluator.  This is
5726    similar to bp_condition_evaluator, but for locations.  */
5727
5728 static const char *
5729 bp_location_condition_evaluator (struct bp_location *bl)
5730 {
5731   if (bl && !is_breakpoint (bl->owner))
5732     return NULL;
5733
5734   if (gdb_evaluates_breakpoint_condition_p ()
5735       || !target_supports_evaluation_of_breakpoint_conditions ())
5736     return condition_evaluation_host;
5737
5738   if (bl && bl->cond_bytecode)
5739     return condition_evaluation_target;
5740   else
5741     return condition_evaluation_host;
5742 }
5743
5744 /* Print the LOC location out of the list of B->LOC locations.  */
5745
5746 static void
5747 print_breakpoint_location (struct breakpoint *b,
5748                            struct bp_location *loc)
5749 {
5750   struct ui_out *uiout = current_uiout;
5751   struct cleanup *old_chain = save_current_program_space ();
5752
5753   if (loc != NULL && loc->shlib_disabled)
5754     loc = NULL;
5755
5756   if (loc != NULL)
5757     set_current_program_space (loc->pspace);
5758
5759   if (b->display_canonical)
5760     ui_out_field_string (uiout, "what", b->addr_string);
5761   else if (loc && loc->symtab)
5762     {
5763       struct symbol *sym 
5764         = find_pc_sect_function (loc->address, loc->section);
5765       if (sym)
5766         {
5767           ui_out_text (uiout, "in ");
5768           ui_out_field_string (uiout, "func",
5769                                SYMBOL_PRINT_NAME (sym));
5770           ui_out_text (uiout, " ");
5771           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5772           ui_out_text (uiout, "at ");
5773         }
5774       ui_out_field_string (uiout, "file",
5775                            symtab_to_filename_for_display (loc->symtab));
5776       ui_out_text (uiout, ":");
5777
5778       if (ui_out_is_mi_like_p (uiout))
5779         ui_out_field_string (uiout, "fullname",
5780                              symtab_to_fullname (loc->symtab));
5781       
5782       ui_out_field_int (uiout, "line", loc->line_number);
5783     }
5784   else if (loc)
5785     {
5786       struct ui_file *stb = mem_fileopen ();
5787       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5788
5789       print_address_symbolic (loc->gdbarch, loc->address, stb,
5790                               demangle, "");
5791       ui_out_field_stream (uiout, "at", stb);
5792
5793       do_cleanups (stb_chain);
5794     }
5795   else
5796     ui_out_field_string (uiout, "pending", b->addr_string);
5797
5798   if (loc && is_breakpoint (b)
5799       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5800       && bp_condition_evaluator (b) == condition_evaluation_both)
5801     {
5802       ui_out_text (uiout, " (");
5803       ui_out_field_string (uiout, "evaluated-by",
5804                            bp_location_condition_evaluator (loc));
5805       ui_out_text (uiout, ")");
5806     }
5807
5808   do_cleanups (old_chain);
5809 }
5810
5811 static const char *
5812 bptype_string (enum bptype type)
5813 {
5814   struct ep_type_description
5815     {
5816       enum bptype type;
5817       char *description;
5818     };
5819   static struct ep_type_description bptypes[] =
5820   {
5821     {bp_none, "?deleted?"},
5822     {bp_breakpoint, "breakpoint"},
5823     {bp_hardware_breakpoint, "hw breakpoint"},
5824     {bp_until, "until"},
5825     {bp_finish, "finish"},
5826     {bp_watchpoint, "watchpoint"},
5827     {bp_hardware_watchpoint, "hw watchpoint"},
5828     {bp_read_watchpoint, "read watchpoint"},
5829     {bp_access_watchpoint, "acc watchpoint"},
5830     {bp_longjmp, "longjmp"},
5831     {bp_longjmp_resume, "longjmp resume"},
5832     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5833     {bp_exception, "exception"},
5834     {bp_exception_resume, "exception resume"},
5835     {bp_step_resume, "step resume"},
5836     {bp_hp_step_resume, "high-priority step resume"},
5837     {bp_watchpoint_scope, "watchpoint scope"},
5838     {bp_call_dummy, "call dummy"},
5839     {bp_std_terminate, "std::terminate"},
5840     {bp_shlib_event, "shlib events"},
5841     {bp_thread_event, "thread events"},
5842     {bp_overlay_event, "overlay events"},
5843     {bp_longjmp_master, "longjmp master"},
5844     {bp_std_terminate_master, "std::terminate master"},
5845     {bp_exception_master, "exception master"},
5846     {bp_catchpoint, "catchpoint"},
5847     {bp_tracepoint, "tracepoint"},
5848     {bp_fast_tracepoint, "fast tracepoint"},
5849     {bp_static_tracepoint, "static tracepoint"},
5850     {bp_dprintf, "dprintf"},
5851     {bp_jit_event, "jit events"},
5852     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5853     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5854   };
5855
5856   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5857       || ((int) type != bptypes[(int) type].type))
5858     internal_error (__FILE__, __LINE__,
5859                     _("bptypes table does not describe type #%d."),
5860                     (int) type);
5861
5862   return bptypes[(int) type].description;
5863 }
5864
5865 /* For MI, output a field named 'thread-groups' with a list as the value.
5866    For CLI, prefix the list with the string 'inf'. */
5867
5868 static void
5869 output_thread_groups (struct ui_out *uiout,
5870                       const char *field_name,
5871                       VEC(int) *inf_num,
5872                       int mi_only)
5873 {
5874   struct cleanup *back_to;
5875   int is_mi = ui_out_is_mi_like_p (uiout);
5876   int inf;
5877   int i;
5878
5879   /* For backward compatibility, don't display inferiors in CLI unless
5880      there are several.  Always display them for MI. */
5881   if (!is_mi && mi_only)
5882     return;
5883
5884   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
5885
5886   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
5887     {
5888       if (is_mi)
5889         {
5890           char mi_group[10];
5891
5892           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
5893           ui_out_field_string (uiout, NULL, mi_group);
5894         }
5895       else
5896         {
5897           if (i == 0)
5898             ui_out_text (uiout, " inf ");
5899           else
5900             ui_out_text (uiout, ", ");
5901         
5902           ui_out_text (uiout, plongest (inf));
5903         }
5904     }
5905
5906   do_cleanups (back_to);
5907 }
5908
5909 /* Print B to gdb_stdout.  */
5910
5911 static void
5912 print_one_breakpoint_location (struct breakpoint *b,
5913                                struct bp_location *loc,
5914                                int loc_number,
5915                                struct bp_location **last_loc,
5916                                int allflag)
5917 {
5918   struct command_line *l;
5919   static char bpenables[] = "nynny";
5920
5921   struct ui_out *uiout = current_uiout;
5922   int header_of_multiple = 0;
5923   int part_of_multiple = (loc != NULL);
5924   struct value_print_options opts;
5925
5926   get_user_print_options (&opts);
5927
5928   gdb_assert (!loc || loc_number != 0);
5929   /* See comment in print_one_breakpoint concerning treatment of
5930      breakpoints with single disabled location.  */
5931   if (loc == NULL 
5932       && (b->loc != NULL 
5933           && (b->loc->next != NULL || !b->loc->enabled)))
5934     header_of_multiple = 1;
5935   if (loc == NULL)
5936     loc = b->loc;
5937
5938   annotate_record ();
5939
5940   /* 1 */
5941   annotate_field (0);
5942   if (part_of_multiple)
5943     {
5944       char *formatted;
5945       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5946       ui_out_field_string (uiout, "number", formatted);
5947       xfree (formatted);
5948     }
5949   else
5950     {
5951       ui_out_field_int (uiout, "number", b->number);
5952     }
5953
5954   /* 2 */
5955   annotate_field (1);
5956   if (part_of_multiple)
5957     ui_out_field_skip (uiout, "type");
5958   else
5959     ui_out_field_string (uiout, "type", bptype_string (b->type));
5960
5961   /* 3 */
5962   annotate_field (2);
5963   if (part_of_multiple)
5964     ui_out_field_skip (uiout, "disp");
5965   else
5966     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5967
5968
5969   /* 4 */
5970   annotate_field (3);
5971   if (part_of_multiple)
5972     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5973   else
5974     ui_out_field_fmt (uiout, "enabled", "%c", 
5975                       bpenables[(int) b->enable_state]);
5976   ui_out_spaces (uiout, 2);
5977
5978   
5979   /* 5 and 6 */
5980   if (b->ops != NULL && b->ops->print_one != NULL)
5981     {
5982       /* Although the print_one can possibly print all locations,
5983          calling it here is not likely to get any nice result.  So,
5984          make sure there's just one location.  */
5985       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5986       b->ops->print_one (b, last_loc);
5987     }
5988   else
5989     switch (b->type)
5990       {
5991       case bp_none:
5992         internal_error (__FILE__, __LINE__,
5993                         _("print_one_breakpoint: bp_none encountered\n"));
5994         break;
5995
5996       case bp_watchpoint:
5997       case bp_hardware_watchpoint:
5998       case bp_read_watchpoint:
5999       case bp_access_watchpoint:
6000         {
6001           struct watchpoint *w = (struct watchpoint *) b;
6002
6003           /* Field 4, the address, is omitted (which makes the columns
6004              not line up too nicely with the headers, but the effect
6005              is relatively readable).  */
6006           if (opts.addressprint)
6007             ui_out_field_skip (uiout, "addr");
6008           annotate_field (5);
6009           ui_out_field_string (uiout, "what", w->exp_string);
6010         }
6011         break;
6012
6013       case bp_breakpoint:
6014       case bp_hardware_breakpoint:
6015       case bp_until:
6016       case bp_finish:
6017       case bp_longjmp:
6018       case bp_longjmp_resume:
6019       case bp_longjmp_call_dummy:
6020       case bp_exception:
6021       case bp_exception_resume:
6022       case bp_step_resume:
6023       case bp_hp_step_resume:
6024       case bp_watchpoint_scope:
6025       case bp_call_dummy:
6026       case bp_std_terminate:
6027       case bp_shlib_event:
6028       case bp_thread_event:
6029       case bp_overlay_event:
6030       case bp_longjmp_master:
6031       case bp_std_terminate_master:
6032       case bp_exception_master:
6033       case bp_tracepoint:
6034       case bp_fast_tracepoint:
6035       case bp_static_tracepoint:
6036       case bp_dprintf:
6037       case bp_jit_event:
6038       case bp_gnu_ifunc_resolver:
6039       case bp_gnu_ifunc_resolver_return:
6040         if (opts.addressprint)
6041           {
6042             annotate_field (4);
6043             if (header_of_multiple)
6044               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6045             else if (b->loc == NULL || loc->shlib_disabled)
6046               ui_out_field_string (uiout, "addr", "<PENDING>");
6047             else
6048               ui_out_field_core_addr (uiout, "addr",
6049                                       loc->gdbarch, loc->address);
6050           }
6051         annotate_field (5);
6052         if (!header_of_multiple)
6053           print_breakpoint_location (b, loc);
6054         if (b->loc)
6055           *last_loc = b->loc;
6056         break;
6057       }
6058
6059
6060   if (loc != NULL && !header_of_multiple)
6061     {
6062       struct inferior *inf;
6063       VEC(int) *inf_num = NULL;
6064       int mi_only = 1;
6065
6066       ALL_INFERIORS (inf)
6067         {
6068           if (inf->pspace == loc->pspace)
6069             VEC_safe_push (int, inf_num, inf->num);
6070         }
6071
6072         /* For backward compatibility, don't display inferiors in CLI unless
6073            there are several.  Always display for MI. */
6074         if (allflag
6075             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6076                 && (number_of_program_spaces () > 1
6077                     || number_of_inferiors () > 1)
6078                 /* LOC is for existing B, it cannot be in
6079                    moribund_locations and thus having NULL OWNER.  */
6080                 && loc->owner->type != bp_catchpoint))
6081         mi_only = 0;
6082       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6083       VEC_free (int, inf_num);
6084     }
6085
6086   if (!part_of_multiple)
6087     {
6088       if (b->thread != -1)
6089         {
6090           /* FIXME: This seems to be redundant and lost here; see the
6091              "stop only in" line a little further down.  */
6092           ui_out_text (uiout, " thread ");
6093           ui_out_field_int (uiout, "thread", b->thread);
6094         }
6095       else if (b->task != 0)
6096         {
6097           ui_out_text (uiout, " task ");
6098           ui_out_field_int (uiout, "task", b->task);
6099         }
6100     }
6101
6102   ui_out_text (uiout, "\n");
6103
6104   if (!part_of_multiple)
6105     b->ops->print_one_detail (b, uiout);
6106
6107   if (part_of_multiple && frame_id_p (b->frame_id))
6108     {
6109       annotate_field (6);
6110       ui_out_text (uiout, "\tstop only in stack frame at ");
6111       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6112          the frame ID.  */
6113       ui_out_field_core_addr (uiout, "frame",
6114                               b->gdbarch, b->frame_id.stack_addr);
6115       ui_out_text (uiout, "\n");
6116     }
6117   
6118   if (!part_of_multiple && b->cond_string)
6119     {
6120       annotate_field (7);
6121       if (is_tracepoint (b))
6122         ui_out_text (uiout, "\ttrace only if ");
6123       else
6124         ui_out_text (uiout, "\tstop only if ");
6125       ui_out_field_string (uiout, "cond", b->cond_string);
6126
6127       /* Print whether the target is doing the breakpoint's condition
6128          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6129       if (is_breakpoint (b)
6130           && breakpoint_condition_evaluation_mode ()
6131           == condition_evaluation_target)
6132         {
6133           ui_out_text (uiout, " (");
6134           ui_out_field_string (uiout, "evaluated-by",
6135                                bp_condition_evaluator (b));
6136           ui_out_text (uiout, " evals)");
6137         }
6138       ui_out_text (uiout, "\n");
6139     }
6140
6141   if (!part_of_multiple && b->thread != -1)
6142     {
6143       /* FIXME should make an annotation for this.  */
6144       ui_out_text (uiout, "\tstop only in thread ");
6145       ui_out_field_int (uiout, "thread", b->thread);
6146       ui_out_text (uiout, "\n");
6147     }
6148   
6149   if (!part_of_multiple)
6150     {
6151       if (b->hit_count)
6152         {
6153           /* FIXME should make an annotation for this.  */
6154           if (is_catchpoint (b))
6155             ui_out_text (uiout, "\tcatchpoint");
6156           else if (is_tracepoint (b))
6157             ui_out_text (uiout, "\ttracepoint");
6158           else
6159             ui_out_text (uiout, "\tbreakpoint");
6160           ui_out_text (uiout, " already hit ");
6161           ui_out_field_int (uiout, "times", b->hit_count);
6162           if (b->hit_count == 1)
6163             ui_out_text (uiout, " time\n");
6164           else
6165             ui_out_text (uiout, " times\n");
6166         }
6167       else
6168         {
6169           /* Output the count also if it is zero, but only if this is mi.  */
6170           if (ui_out_is_mi_like_p (uiout))
6171             ui_out_field_int (uiout, "times", b->hit_count);
6172         }
6173     }
6174
6175   if (!part_of_multiple && b->ignore_count)
6176     {
6177       annotate_field (8);
6178       ui_out_text (uiout, "\tignore next ");
6179       ui_out_field_int (uiout, "ignore", b->ignore_count);
6180       ui_out_text (uiout, " hits\n");
6181     }
6182
6183   /* Note that an enable count of 1 corresponds to "enable once"
6184      behavior, which is reported by the combination of enablement and
6185      disposition, so we don't need to mention it here.  */
6186   if (!part_of_multiple && b->enable_count > 1)
6187     {
6188       annotate_field (8);
6189       ui_out_text (uiout, "\tdisable after ");
6190       /* Tweak the wording to clarify that ignore and enable counts
6191          are distinct, and have additive effect.  */
6192       if (b->ignore_count)
6193         ui_out_text (uiout, "additional ");
6194       else
6195         ui_out_text (uiout, "next ");
6196       ui_out_field_int (uiout, "enable", b->enable_count);
6197       ui_out_text (uiout, " hits\n");
6198     }
6199
6200   if (!part_of_multiple && is_tracepoint (b))
6201     {
6202       struct tracepoint *tp = (struct tracepoint *) b;
6203
6204       if (tp->traceframe_usage)
6205         {
6206           ui_out_text (uiout, "\ttrace buffer usage ");
6207           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6208           ui_out_text (uiout, " bytes\n");
6209         }
6210     }
6211
6212   l = b->commands ? b->commands->commands : NULL;
6213   if (!part_of_multiple && l)
6214     {
6215       struct cleanup *script_chain;
6216
6217       annotate_field (9);
6218       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6219       print_command_lines (uiout, l, 4);
6220       do_cleanups (script_chain);
6221     }
6222
6223   if (is_tracepoint (b))
6224     {
6225       struct tracepoint *t = (struct tracepoint *) b;
6226
6227       if (!part_of_multiple && t->pass_count)
6228         {
6229           annotate_field (10);
6230           ui_out_text (uiout, "\tpass count ");
6231           ui_out_field_int (uiout, "pass", t->pass_count);
6232           ui_out_text (uiout, " \n");
6233         }
6234
6235       /* Don't display it when tracepoint or tracepoint location is
6236          pending.   */
6237       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6238         {
6239           annotate_field (11);
6240
6241           if (ui_out_is_mi_like_p (uiout))
6242             ui_out_field_string (uiout, "installed",
6243                                  loc->inserted ? "y" : "n");
6244           else
6245             {
6246               if (loc->inserted)
6247                 ui_out_text (uiout, "\t");
6248               else
6249                 ui_out_text (uiout, "\tnot ");
6250               ui_out_text (uiout, "installed on target\n");
6251             }
6252         }
6253     }
6254
6255   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6256     {
6257       if (is_watchpoint (b))
6258         {
6259           struct watchpoint *w = (struct watchpoint *) b;
6260
6261           ui_out_field_string (uiout, "original-location", w->exp_string);
6262         }
6263       else if (b->addr_string)
6264         ui_out_field_string (uiout, "original-location", b->addr_string);
6265     }
6266 }
6267
6268 static void
6269 print_one_breakpoint (struct breakpoint *b,
6270                       struct bp_location **last_loc, 
6271                       int allflag)
6272 {
6273   struct cleanup *bkpt_chain;
6274   struct ui_out *uiout = current_uiout;
6275
6276   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6277
6278   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6279   do_cleanups (bkpt_chain);
6280
6281   /* If this breakpoint has custom print function,
6282      it's already printed.  Otherwise, print individual
6283      locations, if any.  */
6284   if (b->ops == NULL || b->ops->print_one == NULL)
6285     {
6286       /* If breakpoint has a single location that is disabled, we
6287          print it as if it had several locations, since otherwise it's
6288          hard to represent "breakpoint enabled, location disabled"
6289          situation.
6290
6291          Note that while hardware watchpoints have several locations
6292          internally, that's not a property exposed to user.  */
6293       if (b->loc 
6294           && !is_hardware_watchpoint (b)
6295           && (b->loc->next || !b->loc->enabled))
6296         {
6297           struct bp_location *loc;
6298           int n = 1;
6299
6300           for (loc = b->loc; loc; loc = loc->next, ++n)
6301             {
6302               struct cleanup *inner2 =
6303                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6304               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6305               do_cleanups (inner2);
6306             }
6307         }
6308     }
6309 }
6310
6311 static int
6312 breakpoint_address_bits (struct breakpoint *b)
6313 {
6314   int print_address_bits = 0;
6315   struct bp_location *loc;
6316
6317   for (loc = b->loc; loc; loc = loc->next)
6318     {
6319       int addr_bit;
6320
6321       /* Software watchpoints that aren't watching memory don't have
6322          an address to print.  */
6323       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6324         continue;
6325
6326       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6327       if (addr_bit > print_address_bits)
6328         print_address_bits = addr_bit;
6329     }
6330
6331   return print_address_bits;
6332 }
6333
6334 struct captured_breakpoint_query_args
6335   {
6336     int bnum;
6337   };
6338
6339 static int
6340 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6341 {
6342   struct captured_breakpoint_query_args *args = data;
6343   struct breakpoint *b;
6344   struct bp_location *dummy_loc = NULL;
6345
6346   ALL_BREAKPOINTS (b)
6347     {
6348       if (args->bnum == b->number)
6349         {
6350           print_one_breakpoint (b, &dummy_loc, 0);
6351           return GDB_RC_OK;
6352         }
6353     }
6354   return GDB_RC_NONE;
6355 }
6356
6357 enum gdb_rc
6358 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6359                       char **error_message)
6360 {
6361   struct captured_breakpoint_query_args args;
6362
6363   args.bnum = bnum;
6364   /* For the moment we don't trust print_one_breakpoint() to not throw
6365      an error.  */
6366   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6367                                  error_message, RETURN_MASK_ALL) < 0)
6368     return GDB_RC_FAIL;
6369   else
6370     return GDB_RC_OK;
6371 }
6372
6373 /* Return true if this breakpoint was set by the user, false if it is
6374    internal or momentary.  */
6375
6376 int
6377 user_breakpoint_p (struct breakpoint *b)
6378 {
6379   return b->number > 0;
6380 }
6381
6382 /* Print information on user settable breakpoint (watchpoint, etc)
6383    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6384    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6385    FILTER is non-NULL, call it on each breakpoint and only include the
6386    ones for which it returns non-zero.  Return the total number of
6387    breakpoints listed.  */
6388
6389 static int
6390 breakpoint_1 (char *args, int allflag, 
6391               int (*filter) (const struct breakpoint *))
6392 {
6393   struct breakpoint *b;
6394   struct bp_location *last_loc = NULL;
6395   int nr_printable_breakpoints;
6396   struct cleanup *bkpttbl_chain;
6397   struct value_print_options opts;
6398   int print_address_bits = 0;
6399   int print_type_col_width = 14;
6400   struct ui_out *uiout = current_uiout;
6401
6402   get_user_print_options (&opts);
6403
6404   /* Compute the number of rows in the table, as well as the size
6405      required for address fields.  */
6406   nr_printable_breakpoints = 0;
6407   ALL_BREAKPOINTS (b)
6408     {
6409       /* If we have a filter, only list the breakpoints it accepts.  */
6410       if (filter && !filter (b))
6411         continue;
6412
6413       /* If we have an "args" string, it is a list of breakpoints to 
6414          accept.  Skip the others.  */
6415       if (args != NULL && *args != '\0')
6416         {
6417           if (allflag && parse_and_eval_long (args) != b->number)
6418             continue;
6419           if (!allflag && !number_is_in_list (args, b->number))
6420             continue;
6421         }
6422
6423       if (allflag || user_breakpoint_p (b))
6424         {
6425           int addr_bit, type_len;
6426
6427           addr_bit = breakpoint_address_bits (b);
6428           if (addr_bit > print_address_bits)
6429             print_address_bits = addr_bit;
6430
6431           type_len = strlen (bptype_string (b->type));
6432           if (type_len > print_type_col_width)
6433             print_type_col_width = type_len;
6434
6435           nr_printable_breakpoints++;
6436         }
6437     }
6438
6439   if (opts.addressprint)
6440     bkpttbl_chain 
6441       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6442                                              nr_printable_breakpoints,
6443                                              "BreakpointTable");
6444   else
6445     bkpttbl_chain 
6446       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6447                                              nr_printable_breakpoints,
6448                                              "BreakpointTable");
6449
6450   if (nr_printable_breakpoints > 0)
6451     annotate_breakpoints_headers ();
6452   if (nr_printable_breakpoints > 0)
6453     annotate_field (0);
6454   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6455   if (nr_printable_breakpoints > 0)
6456     annotate_field (1);
6457   ui_out_table_header (uiout, print_type_col_width, ui_left,
6458                        "type", "Type");                         /* 2 */
6459   if (nr_printable_breakpoints > 0)
6460     annotate_field (2);
6461   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6462   if (nr_printable_breakpoints > 0)
6463     annotate_field (3);
6464   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6465   if (opts.addressprint)
6466     {
6467       if (nr_printable_breakpoints > 0)
6468         annotate_field (4);
6469       if (print_address_bits <= 32)
6470         ui_out_table_header (uiout, 10, ui_left, 
6471                              "addr", "Address");                /* 5 */
6472       else
6473         ui_out_table_header (uiout, 18, ui_left, 
6474                              "addr", "Address");                /* 5 */
6475     }
6476   if (nr_printable_breakpoints > 0)
6477     annotate_field (5);
6478   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6479   ui_out_table_body (uiout);
6480   if (nr_printable_breakpoints > 0)
6481     annotate_breakpoints_table ();
6482
6483   ALL_BREAKPOINTS (b)
6484     {
6485       QUIT;
6486       /* If we have a filter, only list the breakpoints it accepts.  */
6487       if (filter && !filter (b))
6488         continue;
6489
6490       /* If we have an "args" string, it is a list of breakpoints to 
6491          accept.  Skip the others.  */
6492
6493       if (args != NULL && *args != '\0')
6494         {
6495           if (allflag)  /* maintenance info breakpoint */
6496             {
6497               if (parse_and_eval_long (args) != b->number)
6498                 continue;
6499             }
6500           else          /* all others */
6501             {
6502               if (!number_is_in_list (args, b->number))
6503                 continue;
6504             }
6505         }
6506       /* We only print out user settable breakpoints unless the
6507          allflag is set.  */
6508       if (allflag || user_breakpoint_p (b))
6509         print_one_breakpoint (b, &last_loc, allflag);
6510     }
6511
6512   do_cleanups (bkpttbl_chain);
6513
6514   if (nr_printable_breakpoints == 0)
6515     {
6516       /* If there's a filter, let the caller decide how to report
6517          empty list.  */
6518       if (!filter)
6519         {
6520           if (args == NULL || *args == '\0')
6521             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6522           else
6523             ui_out_message (uiout, 0, 
6524                             "No breakpoint or watchpoint matching '%s'.\n",
6525                             args);
6526         }
6527     }
6528   else
6529     {
6530       if (last_loc && !server_command)
6531         set_next_address (last_loc->gdbarch, last_loc->address);
6532     }
6533
6534   /* FIXME?  Should this be moved up so that it is only called when
6535      there have been breakpoints? */
6536   annotate_breakpoints_table_end ();
6537
6538   return nr_printable_breakpoints;
6539 }
6540
6541 /* Display the value of default-collect in a way that is generally
6542    compatible with the breakpoint list.  */
6543
6544 static void
6545 default_collect_info (void)
6546 {
6547   struct ui_out *uiout = current_uiout;
6548
6549   /* If it has no value (which is frequently the case), say nothing; a
6550      message like "No default-collect." gets in user's face when it's
6551      not wanted.  */
6552   if (!*default_collect)
6553     return;
6554
6555   /* The following phrase lines up nicely with per-tracepoint collect
6556      actions.  */
6557   ui_out_text (uiout, "default collect ");
6558   ui_out_field_string (uiout, "default-collect", default_collect);
6559   ui_out_text (uiout, " \n");
6560 }
6561   
6562 static void
6563 breakpoints_info (char *args, int from_tty)
6564 {
6565   breakpoint_1 (args, 0, NULL);
6566
6567   default_collect_info ();
6568 }
6569
6570 static void
6571 watchpoints_info (char *args, int from_tty)
6572 {
6573   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6574   struct ui_out *uiout = current_uiout;
6575
6576   if (num_printed == 0)
6577     {
6578       if (args == NULL || *args == '\0')
6579         ui_out_message (uiout, 0, "No watchpoints.\n");
6580       else
6581         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6582     }
6583 }
6584
6585 static void
6586 maintenance_info_breakpoints (char *args, int from_tty)
6587 {
6588   breakpoint_1 (args, 1, NULL);
6589
6590   default_collect_info ();
6591 }
6592
6593 static int
6594 breakpoint_has_pc (struct breakpoint *b,
6595                    struct program_space *pspace,
6596                    CORE_ADDR pc, struct obj_section *section)
6597 {
6598   struct bp_location *bl = b->loc;
6599
6600   for (; bl; bl = bl->next)
6601     {
6602       if (bl->pspace == pspace
6603           && bl->address == pc
6604           && (!overlay_debugging || bl->section == section))
6605         return 1;         
6606     }
6607   return 0;
6608 }
6609
6610 /* Print a message describing any user-breakpoints set at PC.  This
6611    concerns with logical breakpoints, so we match program spaces, not
6612    address spaces.  */
6613
6614 static void
6615 describe_other_breakpoints (struct gdbarch *gdbarch,
6616                             struct program_space *pspace, CORE_ADDR pc,
6617                             struct obj_section *section, int thread)
6618 {
6619   int others = 0;
6620   struct breakpoint *b;
6621
6622   ALL_BREAKPOINTS (b)
6623     others += (user_breakpoint_p (b)
6624                && breakpoint_has_pc (b, pspace, pc, section));
6625   if (others > 0)
6626     {
6627       if (others == 1)
6628         printf_filtered (_("Note: breakpoint "));
6629       else /* if (others == ???) */
6630         printf_filtered (_("Note: breakpoints "));
6631       ALL_BREAKPOINTS (b)
6632         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6633           {
6634             others--;
6635             printf_filtered ("%d", b->number);
6636             if (b->thread == -1 && thread != -1)
6637               printf_filtered (" (all threads)");
6638             else if (b->thread != -1)
6639               printf_filtered (" (thread %d)", b->thread);
6640             printf_filtered ("%s%s ",
6641                              ((b->enable_state == bp_disabled
6642                                || b->enable_state == bp_call_disabled)
6643                               ? " (disabled)"
6644                               : b->enable_state == bp_permanent 
6645                               ? " (permanent)"
6646                               : ""),
6647                              (others > 1) ? "," 
6648                              : ((others == 1) ? " and" : ""));
6649           }
6650       printf_filtered (_("also set at pc "));
6651       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6652       printf_filtered (".\n");
6653     }
6654 }
6655 \f
6656
6657 /* Return true iff it is meaningful to use the address member of
6658    BPT.  For some breakpoint types, the address member is irrelevant
6659    and it makes no sense to attempt to compare it to other addresses
6660    (or use it for any other purpose either).
6661
6662    More specifically, each of the following breakpoint types will
6663    always have a zero valued address and we don't want to mark
6664    breakpoints of any of these types to be a duplicate of an actual
6665    breakpoint at address zero:
6666
6667       bp_watchpoint
6668       bp_catchpoint
6669
6670 */
6671
6672 static int
6673 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6674 {
6675   enum bptype type = bpt->type;
6676
6677   return (type != bp_watchpoint && type != bp_catchpoint);
6678 }
6679
6680 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6681    true if LOC1 and LOC2 represent the same watchpoint location.  */
6682
6683 static int
6684 watchpoint_locations_match (struct bp_location *loc1, 
6685                             struct bp_location *loc2)
6686 {
6687   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6688   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6689
6690   /* Both of them must exist.  */
6691   gdb_assert (w1 != NULL);
6692   gdb_assert (w2 != NULL);
6693
6694   /* If the target can evaluate the condition expression in hardware,
6695      then we we need to insert both watchpoints even if they are at
6696      the same place.  Otherwise the watchpoint will only trigger when
6697      the condition of whichever watchpoint was inserted evaluates to
6698      true, not giving a chance for GDB to check the condition of the
6699      other watchpoint.  */
6700   if ((w1->cond_exp
6701        && target_can_accel_watchpoint_condition (loc1->address, 
6702                                                  loc1->length,
6703                                                  loc1->watchpoint_type,
6704                                                  w1->cond_exp))
6705       || (w2->cond_exp
6706           && target_can_accel_watchpoint_condition (loc2->address, 
6707                                                     loc2->length,
6708                                                     loc2->watchpoint_type,
6709                                                     w2->cond_exp)))
6710     return 0;
6711
6712   /* Note that this checks the owner's type, not the location's.  In
6713      case the target does not support read watchpoints, but does
6714      support access watchpoints, we'll have bp_read_watchpoint
6715      watchpoints with hw_access locations.  Those should be considered
6716      duplicates of hw_read locations.  The hw_read locations will
6717      become hw_access locations later.  */
6718   return (loc1->owner->type == loc2->owner->type
6719           && loc1->pspace->aspace == loc2->pspace->aspace
6720           && loc1->address == loc2->address
6721           && loc1->length == loc2->length);
6722 }
6723
6724 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6725    same breakpoint location.  In most targets, this can only be true
6726    if ASPACE1 matches ASPACE2.  On targets that have global
6727    breakpoints, the address space doesn't really matter.  */
6728
6729 static int
6730 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6731                           struct address_space *aspace2, CORE_ADDR addr2)
6732 {
6733   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6734            || aspace1 == aspace2)
6735           && addr1 == addr2);
6736 }
6737
6738 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6739    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6740    matches ASPACE2.  On targets that have global breakpoints, the address
6741    space doesn't really matter.  */
6742
6743 static int
6744 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6745                                 int len1, struct address_space *aspace2,
6746                                 CORE_ADDR addr2)
6747 {
6748   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6749            || aspace1 == aspace2)
6750           && addr2 >= addr1 && addr2 < addr1 + len1);
6751 }
6752
6753 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6754    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6755    matches the breakpoint's address space.  On targets that have global
6756    breakpoints, the address space doesn't really matter.  */
6757
6758 static int
6759 breakpoint_location_address_match (struct bp_location *bl,
6760                                    struct address_space *aspace,
6761                                    CORE_ADDR addr)
6762 {
6763   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6764                                     aspace, addr)
6765           || (bl->length
6766               && breakpoint_address_match_range (bl->pspace->aspace,
6767                                                  bl->address, bl->length,
6768                                                  aspace, addr)));
6769 }
6770
6771 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6772    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6773    true, otherwise returns false.  */
6774
6775 static int
6776 tracepoint_locations_match (struct bp_location *loc1,
6777                             struct bp_location *loc2)
6778 {
6779   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6780     /* Since tracepoint locations are never duplicated with others', tracepoint
6781        locations at the same address of different tracepoints are regarded as
6782        different locations.  */
6783     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6784   else
6785     return 0;
6786 }
6787
6788 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6789    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6790    represent the same location.  */
6791
6792 static int
6793 breakpoint_locations_match (struct bp_location *loc1, 
6794                             struct bp_location *loc2)
6795 {
6796   int hw_point1, hw_point2;
6797
6798   /* Both of them must not be in moribund_locations.  */
6799   gdb_assert (loc1->owner != NULL);
6800   gdb_assert (loc2->owner != NULL);
6801
6802   hw_point1 = is_hardware_watchpoint (loc1->owner);
6803   hw_point2 = is_hardware_watchpoint (loc2->owner);
6804
6805   if (hw_point1 != hw_point2)
6806     return 0;
6807   else if (hw_point1)
6808     return watchpoint_locations_match (loc1, loc2);
6809   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6810     return tracepoint_locations_match (loc1, loc2);
6811   else
6812     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6813     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6814                                      loc2->pspace->aspace, loc2->address)
6815             && loc1->length == loc2->length);
6816 }
6817
6818 static void
6819 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6820                                int bnum, int have_bnum)
6821 {
6822   /* The longest string possibly returned by hex_string_custom
6823      is 50 chars.  These must be at least that big for safety.  */
6824   char astr1[64];
6825   char astr2[64];
6826
6827   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6828   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6829   if (have_bnum)
6830     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6831              bnum, astr1, astr2);
6832   else
6833     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6834 }
6835
6836 /* Adjust a breakpoint's address to account for architectural
6837    constraints on breakpoint placement.  Return the adjusted address.
6838    Note: Very few targets require this kind of adjustment.  For most
6839    targets, this function is simply the identity function.  */
6840
6841 static CORE_ADDR
6842 adjust_breakpoint_address (struct gdbarch *gdbarch,
6843                            CORE_ADDR bpaddr, enum bptype bptype)
6844 {
6845   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6846     {
6847       /* Very few targets need any kind of breakpoint adjustment.  */
6848       return bpaddr;
6849     }
6850   else if (bptype == bp_watchpoint
6851            || bptype == bp_hardware_watchpoint
6852            || bptype == bp_read_watchpoint
6853            || bptype == bp_access_watchpoint
6854            || bptype == bp_catchpoint)
6855     {
6856       /* Watchpoints and the various bp_catch_* eventpoints should not
6857          have their addresses modified.  */
6858       return bpaddr;
6859     }
6860   else
6861     {
6862       CORE_ADDR adjusted_bpaddr;
6863
6864       /* Some targets have architectural constraints on the placement
6865          of breakpoint instructions.  Obtain the adjusted address.  */
6866       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6867
6868       /* An adjusted breakpoint address can significantly alter
6869          a user's expectations.  Print a warning if an adjustment
6870          is required.  */
6871       if (adjusted_bpaddr != bpaddr)
6872         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6873
6874       return adjusted_bpaddr;
6875     }
6876 }
6877
6878 void
6879 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6880                   struct breakpoint *owner)
6881 {
6882   memset (loc, 0, sizeof (*loc));
6883
6884   gdb_assert (ops != NULL);
6885
6886   loc->ops = ops;
6887   loc->owner = owner;
6888   loc->cond = NULL;
6889   loc->cond_bytecode = NULL;
6890   loc->shlib_disabled = 0;
6891   loc->enabled = 1;
6892
6893   switch (owner->type)
6894     {
6895     case bp_breakpoint:
6896     case bp_until:
6897     case bp_finish:
6898     case bp_longjmp:
6899     case bp_longjmp_resume:
6900     case bp_longjmp_call_dummy:
6901     case bp_exception:
6902     case bp_exception_resume:
6903     case bp_step_resume:
6904     case bp_hp_step_resume:
6905     case bp_watchpoint_scope:
6906     case bp_call_dummy:
6907     case bp_std_terminate:
6908     case bp_shlib_event:
6909     case bp_thread_event:
6910     case bp_overlay_event:
6911     case bp_jit_event:
6912     case bp_longjmp_master:
6913     case bp_std_terminate_master:
6914     case bp_exception_master:
6915     case bp_gnu_ifunc_resolver:
6916     case bp_gnu_ifunc_resolver_return:
6917     case bp_dprintf:
6918       loc->loc_type = bp_loc_software_breakpoint;
6919       mark_breakpoint_location_modified (loc);
6920       break;
6921     case bp_hardware_breakpoint:
6922       loc->loc_type = bp_loc_hardware_breakpoint;
6923       mark_breakpoint_location_modified (loc);
6924       break;
6925     case bp_hardware_watchpoint:
6926     case bp_read_watchpoint:
6927     case bp_access_watchpoint:
6928       loc->loc_type = bp_loc_hardware_watchpoint;
6929       break;
6930     case bp_watchpoint:
6931     case bp_catchpoint:
6932     case bp_tracepoint:
6933     case bp_fast_tracepoint:
6934     case bp_static_tracepoint:
6935       loc->loc_type = bp_loc_other;
6936       break;
6937     default:
6938       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6939     }
6940
6941   loc->refc = 1;
6942 }
6943
6944 /* Allocate a struct bp_location.  */
6945
6946 static struct bp_location *
6947 allocate_bp_location (struct breakpoint *bpt)
6948 {
6949   return bpt->ops->allocate_location (bpt);
6950 }
6951
6952 static void
6953 free_bp_location (struct bp_location *loc)
6954 {
6955   loc->ops->dtor (loc);
6956   xfree (loc);
6957 }
6958
6959 /* Increment reference count.  */
6960
6961 static void
6962 incref_bp_location (struct bp_location *bl)
6963 {
6964   ++bl->refc;
6965 }
6966
6967 /* Decrement reference count.  If the reference count reaches 0,
6968    destroy the bp_location.  Sets *BLP to NULL.  */
6969
6970 static void
6971 decref_bp_location (struct bp_location **blp)
6972 {
6973   gdb_assert ((*blp)->refc > 0);
6974
6975   if (--(*blp)->refc == 0)
6976     free_bp_location (*blp);
6977   *blp = NULL;
6978 }
6979
6980 /* Add breakpoint B at the end of the global breakpoint chain.  */
6981
6982 static void
6983 add_to_breakpoint_chain (struct breakpoint *b)
6984 {
6985   struct breakpoint *b1;
6986
6987   /* Add this breakpoint to the end of the chain so that a list of
6988      breakpoints will come out in order of increasing numbers.  */
6989
6990   b1 = breakpoint_chain;
6991   if (b1 == 0)
6992     breakpoint_chain = b;
6993   else
6994     {
6995       while (b1->next)
6996         b1 = b1->next;
6997       b1->next = b;
6998     }
6999 }
7000
7001 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7002
7003 static void
7004 init_raw_breakpoint_without_location (struct breakpoint *b,
7005                                       struct gdbarch *gdbarch,
7006                                       enum bptype bptype,
7007                                       const struct breakpoint_ops *ops)
7008 {
7009   memset (b, 0, sizeof (*b));
7010
7011   gdb_assert (ops != NULL);
7012
7013   b->ops = ops;
7014   b->type = bptype;
7015   b->gdbarch = gdbarch;
7016   b->language = current_language->la_language;
7017   b->input_radix = input_radix;
7018   b->thread = -1;
7019   b->enable_state = bp_enabled;
7020   b->next = 0;
7021   b->silent = 0;
7022   b->ignore_count = 0;
7023   b->commands = NULL;
7024   b->frame_id = null_frame_id;
7025   b->condition_not_parsed = 0;
7026   b->py_bp_object = NULL;
7027   b->related_breakpoint = b;
7028 }
7029
7030 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7031    that has type BPTYPE and has no locations as yet.  */
7032
7033 static struct breakpoint *
7034 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7035                                      enum bptype bptype,
7036                                      const struct breakpoint_ops *ops)
7037 {
7038   struct breakpoint *b = XNEW (struct breakpoint);
7039
7040   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7041   add_to_breakpoint_chain (b);
7042   return b;
7043 }
7044
7045 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7046    resolutions should be made as the user specified the location explicitly
7047    enough.  */
7048
7049 static void
7050 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7051 {
7052   gdb_assert (loc->owner != NULL);
7053
7054   if (loc->owner->type == bp_breakpoint
7055       || loc->owner->type == bp_hardware_breakpoint
7056       || is_tracepoint (loc->owner))
7057     {
7058       int is_gnu_ifunc;
7059       const char *function_name;
7060       CORE_ADDR func_addr;
7061
7062       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7063                                           &func_addr, NULL, &is_gnu_ifunc);
7064
7065       if (is_gnu_ifunc && !explicit_loc)
7066         {
7067           struct breakpoint *b = loc->owner;
7068
7069           gdb_assert (loc->pspace == current_program_space);
7070           if (gnu_ifunc_resolve_name (function_name,
7071                                       &loc->requested_address))
7072             {
7073               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7074               loc->address = adjust_breakpoint_address (loc->gdbarch,
7075                                                         loc->requested_address,
7076                                                         b->type);
7077             }
7078           else if (b->type == bp_breakpoint && b->loc == loc
7079                    && loc->next == NULL && b->related_breakpoint == b)
7080             {
7081               /* Create only the whole new breakpoint of this type but do not
7082                  mess more complicated breakpoints with multiple locations.  */
7083               b->type = bp_gnu_ifunc_resolver;
7084               /* Remember the resolver's address for use by the return
7085                  breakpoint.  */
7086               loc->related_address = func_addr;
7087             }
7088         }
7089
7090       if (function_name)
7091         loc->function_name = xstrdup (function_name);
7092     }
7093 }
7094
7095 /* Attempt to determine architecture of location identified by SAL.  */
7096 struct gdbarch *
7097 get_sal_arch (struct symtab_and_line sal)
7098 {
7099   if (sal.section)
7100     return get_objfile_arch (sal.section->objfile);
7101   if (sal.symtab)
7102     return get_objfile_arch (sal.symtab->objfile);
7103
7104   return NULL;
7105 }
7106
7107 /* Low level routine for partially initializing a breakpoint of type
7108    BPTYPE.  The newly created breakpoint's address, section, source
7109    file name, and line number are provided by SAL.
7110
7111    It is expected that the caller will complete the initialization of
7112    the newly created breakpoint struct as well as output any status
7113    information regarding the creation of a new breakpoint.  */
7114
7115 static void
7116 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7117                      struct symtab_and_line sal, enum bptype bptype,
7118                      const struct breakpoint_ops *ops)
7119 {
7120   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7121
7122   add_location_to_breakpoint (b, &sal);
7123
7124   if (bptype != bp_catchpoint)
7125     gdb_assert (sal.pspace != NULL);
7126
7127   /* Store the program space that was used to set the breakpoint,
7128      except for ordinary breakpoints, which are independent of the
7129      program space.  */
7130   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7131     b->pspace = sal.pspace;
7132 }
7133
7134 /* set_raw_breakpoint is a low level routine for allocating and
7135    partially initializing a breakpoint of type BPTYPE.  The newly
7136    created breakpoint's address, section, source file name, and line
7137    number are provided by SAL.  The newly created and partially
7138    initialized breakpoint is added to the breakpoint chain and
7139    is also returned as the value of this function.
7140
7141    It is expected that the caller will complete the initialization of
7142    the newly created breakpoint struct as well as output any status
7143    information regarding the creation of a new breakpoint.  In
7144    particular, set_raw_breakpoint does NOT set the breakpoint
7145    number!  Care should be taken to not allow an error to occur
7146    prior to completing the initialization of the breakpoint.  If this
7147    should happen, a bogus breakpoint will be left on the chain.  */
7148
7149 struct breakpoint *
7150 set_raw_breakpoint (struct gdbarch *gdbarch,
7151                     struct symtab_and_line sal, enum bptype bptype,
7152                     const struct breakpoint_ops *ops)
7153 {
7154   struct breakpoint *b = XNEW (struct breakpoint);
7155
7156   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7157   add_to_breakpoint_chain (b);
7158   return b;
7159 }
7160
7161
7162 /* Note that the breakpoint object B describes a permanent breakpoint
7163    instruction, hard-wired into the inferior's code.  */
7164 void
7165 make_breakpoint_permanent (struct breakpoint *b)
7166 {
7167   struct bp_location *bl;
7168
7169   b->enable_state = bp_permanent;
7170
7171   /* By definition, permanent breakpoints are already present in the
7172      code.  Mark all locations as inserted.  For now,
7173      make_breakpoint_permanent is called in just one place, so it's
7174      hard to say if it's reasonable to have permanent breakpoint with
7175      multiple locations or not, but it's easy to implement.  */
7176   for (bl = b->loc; bl; bl = bl->next)
7177     bl->inserted = 1;
7178 }
7179
7180 /* Call this routine when stepping and nexting to enable a breakpoint
7181    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7182    initiated the operation.  */
7183
7184 void
7185 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7186 {
7187   struct breakpoint *b, *b_tmp;
7188   int thread = tp->num;
7189
7190   /* To avoid having to rescan all objfile symbols at every step,
7191      we maintain a list of continually-inserted but always disabled
7192      longjmp "master" breakpoints.  Here, we simply create momentary
7193      clones of those and enable them for the requested thread.  */
7194   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7195     if (b->pspace == current_program_space
7196         && (b->type == bp_longjmp_master
7197             || b->type == bp_exception_master))
7198       {
7199         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7200         struct breakpoint *clone;
7201
7202         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7203            after their removal.  */
7204         clone = momentary_breakpoint_from_master (b, type,
7205                                                   &longjmp_breakpoint_ops);
7206         clone->thread = thread;
7207       }
7208
7209   tp->initiating_frame = frame;
7210 }
7211
7212 /* Delete all longjmp breakpoints from THREAD.  */
7213 void
7214 delete_longjmp_breakpoint (int thread)
7215 {
7216   struct breakpoint *b, *b_tmp;
7217
7218   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7219     if (b->type == bp_longjmp || b->type == bp_exception)
7220       {
7221         if (b->thread == thread)
7222           delete_breakpoint (b);
7223       }
7224 }
7225
7226 void
7227 delete_longjmp_breakpoint_at_next_stop (int thread)
7228 {
7229   struct breakpoint *b, *b_tmp;
7230
7231   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7232     if (b->type == bp_longjmp || b->type == bp_exception)
7233       {
7234         if (b->thread == thread)
7235           b->disposition = disp_del_at_next_stop;
7236       }
7237 }
7238
7239 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7240    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7241    pointer to any of them.  Return NULL if this system cannot place longjmp
7242    breakpoints.  */
7243
7244 struct breakpoint *
7245 set_longjmp_breakpoint_for_call_dummy (void)
7246 {
7247   struct breakpoint *b, *retval = NULL;
7248
7249   ALL_BREAKPOINTS (b)
7250     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7251       {
7252         struct breakpoint *new_b;
7253
7254         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7255                                                   &momentary_breakpoint_ops);
7256         new_b->thread = pid_to_thread_id (inferior_ptid);
7257
7258         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7259
7260         gdb_assert (new_b->related_breakpoint == new_b);
7261         if (retval == NULL)
7262           retval = new_b;
7263         new_b->related_breakpoint = retval;
7264         while (retval->related_breakpoint != new_b->related_breakpoint)
7265           retval = retval->related_breakpoint;
7266         retval->related_breakpoint = new_b;
7267       }
7268
7269   return retval;
7270 }
7271
7272 /* Verify all existing dummy frames and their associated breakpoints for
7273    THREAD.  Remove those which can no longer be found in the current frame
7274    stack.
7275
7276    You should call this function only at places where it is safe to currently
7277    unwind the whole stack.  Failed stack unwind would discard live dummy
7278    frames.  */
7279
7280 void
7281 check_longjmp_breakpoint_for_call_dummy (int thread)
7282 {
7283   struct breakpoint *b, *b_tmp;
7284
7285   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7286     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7287       {
7288         struct breakpoint *dummy_b = b->related_breakpoint;
7289
7290         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7291           dummy_b = dummy_b->related_breakpoint;
7292         if (dummy_b->type != bp_call_dummy
7293             || frame_find_by_id (dummy_b->frame_id) != NULL)
7294           continue;
7295         
7296         dummy_frame_discard (dummy_b->frame_id);
7297
7298         while (b->related_breakpoint != b)
7299           {
7300             if (b_tmp == b->related_breakpoint)
7301               b_tmp = b->related_breakpoint->next;
7302             delete_breakpoint (b->related_breakpoint);
7303           }
7304         delete_breakpoint (b);
7305       }
7306 }
7307
7308 void
7309 enable_overlay_breakpoints (void)
7310 {
7311   struct breakpoint *b;
7312
7313   ALL_BREAKPOINTS (b)
7314     if (b->type == bp_overlay_event)
7315     {
7316       b->enable_state = bp_enabled;
7317       update_global_location_list (1);
7318       overlay_events_enabled = 1;
7319     }
7320 }
7321
7322 void
7323 disable_overlay_breakpoints (void)
7324 {
7325   struct breakpoint *b;
7326
7327   ALL_BREAKPOINTS (b)
7328     if (b->type == bp_overlay_event)
7329     {
7330       b->enable_state = bp_disabled;
7331       update_global_location_list (0);
7332       overlay_events_enabled = 0;
7333     }
7334 }
7335
7336 /* Set an active std::terminate breakpoint for each std::terminate
7337    master breakpoint.  */
7338 void
7339 set_std_terminate_breakpoint (void)
7340 {
7341   struct breakpoint *b, *b_tmp;
7342
7343   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7344     if (b->pspace == current_program_space
7345         && b->type == bp_std_terminate_master)
7346       {
7347         momentary_breakpoint_from_master (b, bp_std_terminate,
7348                                           &momentary_breakpoint_ops);
7349       }
7350 }
7351
7352 /* Delete all the std::terminate breakpoints.  */
7353 void
7354 delete_std_terminate_breakpoint (void)
7355 {
7356   struct breakpoint *b, *b_tmp;
7357
7358   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7359     if (b->type == bp_std_terminate)
7360       delete_breakpoint (b);
7361 }
7362
7363 struct breakpoint *
7364 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7365 {
7366   struct breakpoint *b;
7367
7368   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7369                                   &internal_breakpoint_ops);
7370
7371   b->enable_state = bp_enabled;
7372   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7373   b->addr_string
7374     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7375
7376   update_global_location_list_nothrow (1);
7377
7378   return b;
7379 }
7380
7381 void
7382 remove_thread_event_breakpoints (void)
7383 {
7384   struct breakpoint *b, *b_tmp;
7385
7386   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7387     if (b->type == bp_thread_event
7388         && b->loc->pspace == current_program_space)
7389       delete_breakpoint (b);
7390 }
7391
7392 struct lang_and_radix
7393   {
7394     enum language lang;
7395     int radix;
7396   };
7397
7398 /* Create a breakpoint for JIT code registration and unregistration.  */
7399
7400 struct breakpoint *
7401 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7402 {
7403   struct breakpoint *b;
7404
7405   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7406                                   &internal_breakpoint_ops);
7407   update_global_location_list_nothrow (1);
7408   return b;
7409 }
7410
7411 /* Remove JIT code registration and unregistration breakpoint(s).  */
7412
7413 void
7414 remove_jit_event_breakpoints (void)
7415 {
7416   struct breakpoint *b, *b_tmp;
7417
7418   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7419     if (b->type == bp_jit_event
7420         && b->loc->pspace == current_program_space)
7421       delete_breakpoint (b);
7422 }
7423
7424 void
7425 remove_solib_event_breakpoints (void)
7426 {
7427   struct breakpoint *b, *b_tmp;
7428
7429   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7430     if (b->type == bp_shlib_event
7431         && b->loc->pspace == current_program_space)
7432       delete_breakpoint (b);
7433 }
7434
7435 struct breakpoint *
7436 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7437 {
7438   struct breakpoint *b;
7439
7440   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7441                                   &internal_breakpoint_ops);
7442   update_global_location_list_nothrow (1);
7443   return b;
7444 }
7445
7446 /* Disable any breakpoints that are on code in shared libraries.  Only
7447    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7448
7449 void
7450 disable_breakpoints_in_shlibs (void)
7451 {
7452   struct bp_location *loc, **locp_tmp;
7453
7454   ALL_BP_LOCATIONS (loc, locp_tmp)
7455   {
7456     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7457     struct breakpoint *b = loc->owner;
7458
7459     /* We apply the check to all breakpoints, including disabled for
7460        those with loc->duplicate set.  This is so that when breakpoint
7461        becomes enabled, or the duplicate is removed, gdb will try to
7462        insert all breakpoints.  If we don't set shlib_disabled here,
7463        we'll try to insert those breakpoints and fail.  */
7464     if (((b->type == bp_breakpoint)
7465          || (b->type == bp_jit_event)
7466          || (b->type == bp_hardware_breakpoint)
7467          || (is_tracepoint (b)))
7468         && loc->pspace == current_program_space
7469         && !loc->shlib_disabled
7470         && solib_name_from_address (loc->pspace, loc->address)
7471         )
7472       {
7473         loc->shlib_disabled = 1;
7474       }
7475   }
7476 }
7477
7478 /* Disable any breakpoints and tracepoints that are in an unloaded shared
7479    library.  Only apply to enabled breakpoints, disabled ones can just stay
7480    disabled.  */
7481
7482 static void
7483 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7484 {
7485   struct bp_location *loc, **locp_tmp;
7486   int disabled_shlib_breaks = 0;
7487
7488   /* SunOS a.out shared libraries are always mapped, so do not
7489      disable breakpoints; they will only be reported as unloaded
7490      through clear_solib when GDB discards its shared library
7491      list.  See clear_solib for more information.  */
7492   if (exec_bfd != NULL
7493       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7494     return;
7495
7496   ALL_BP_LOCATIONS (loc, locp_tmp)
7497   {
7498     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7499     struct breakpoint *b = loc->owner;
7500
7501     if (solib->pspace == loc->pspace
7502         && !loc->shlib_disabled
7503         && (((b->type == bp_breakpoint
7504               || b->type == bp_jit_event
7505               || b->type == bp_hardware_breakpoint)
7506              && (loc->loc_type == bp_loc_hardware_breakpoint
7507                  || loc->loc_type == bp_loc_software_breakpoint))
7508             || is_tracepoint (b))
7509         && solib_contains_address_p (solib, loc->address))
7510       {
7511         loc->shlib_disabled = 1;
7512         /* At this point, we cannot rely on remove_breakpoint
7513            succeeding so we must mark the breakpoint as not inserted
7514            to prevent future errors occurring in remove_breakpoints.  */
7515         loc->inserted = 0;
7516
7517         /* This may cause duplicate notifications for the same breakpoint.  */
7518         observer_notify_breakpoint_modified (b);
7519
7520         if (!disabled_shlib_breaks)
7521           {
7522             target_terminal_ours_for_output ();
7523             warning (_("Temporarily disabling breakpoints "
7524                        "for unloaded shared library \"%s\""),
7525                      solib->so_name);
7526           }
7527         disabled_shlib_breaks = 1;
7528       }
7529   }
7530 }
7531
7532 /* FORK & VFORK catchpoints.  */
7533
7534 /* An instance of this type is used to represent a fork or vfork
7535    catchpoint.  It includes a "struct breakpoint" as a kind of base
7536    class; users downcast to "struct breakpoint *" when needed.  A
7537    breakpoint is really of this type iff its ops pointer points to
7538    CATCH_FORK_BREAKPOINT_OPS.  */
7539
7540 struct fork_catchpoint
7541 {
7542   /* The base class.  */
7543   struct breakpoint base;
7544
7545   /* Process id of a child process whose forking triggered this
7546      catchpoint.  This field is only valid immediately after this
7547      catchpoint has triggered.  */
7548   ptid_t forked_inferior_pid;
7549 };
7550
7551 /* Implement the "insert" breakpoint_ops method for fork
7552    catchpoints.  */
7553
7554 static int
7555 insert_catch_fork (struct bp_location *bl)
7556 {
7557   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7558 }
7559
7560 /* Implement the "remove" breakpoint_ops method for fork
7561    catchpoints.  */
7562
7563 static int
7564 remove_catch_fork (struct bp_location *bl)
7565 {
7566   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7567 }
7568
7569 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7570    catchpoints.  */
7571
7572 static int
7573 breakpoint_hit_catch_fork (const struct bp_location *bl,
7574                            struct address_space *aspace, CORE_ADDR bp_addr,
7575                            const struct target_waitstatus *ws)
7576 {
7577   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7578
7579   if (ws->kind != TARGET_WAITKIND_FORKED)
7580     return 0;
7581
7582   c->forked_inferior_pid = ws->value.related_pid;
7583   return 1;
7584 }
7585
7586 /* Implement the "print_it" breakpoint_ops method for fork
7587    catchpoints.  */
7588
7589 static enum print_stop_action
7590 print_it_catch_fork (bpstat bs)
7591 {
7592   struct ui_out *uiout = current_uiout;
7593   struct breakpoint *b = bs->breakpoint_at;
7594   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7595
7596   annotate_catchpoint (b->number);
7597   if (b->disposition == disp_del)
7598     ui_out_text (uiout, "\nTemporary catchpoint ");
7599   else
7600     ui_out_text (uiout, "\nCatchpoint ");
7601   if (ui_out_is_mi_like_p (uiout))
7602     {
7603       ui_out_field_string (uiout, "reason",
7604                            async_reason_lookup (EXEC_ASYNC_FORK));
7605       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7606     }
7607   ui_out_field_int (uiout, "bkptno", b->number);
7608   ui_out_text (uiout, " (forked process ");
7609   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7610   ui_out_text (uiout, "), ");
7611   return PRINT_SRC_AND_LOC;
7612 }
7613
7614 /* Implement the "print_one" breakpoint_ops method for fork
7615    catchpoints.  */
7616
7617 static void
7618 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7619 {
7620   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7621   struct value_print_options opts;
7622   struct ui_out *uiout = current_uiout;
7623
7624   get_user_print_options (&opts);
7625
7626   /* Field 4, the address, is omitted (which makes the columns not
7627      line up too nicely with the headers, but the effect is relatively
7628      readable).  */
7629   if (opts.addressprint)
7630     ui_out_field_skip (uiout, "addr");
7631   annotate_field (5);
7632   ui_out_text (uiout, "fork");
7633   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7634     {
7635       ui_out_text (uiout, ", process ");
7636       ui_out_field_int (uiout, "what",
7637                         ptid_get_pid (c->forked_inferior_pid));
7638       ui_out_spaces (uiout, 1);
7639     }
7640
7641   if (ui_out_is_mi_like_p (uiout))
7642     ui_out_field_string (uiout, "catch-type", "fork");
7643 }
7644
7645 /* Implement the "print_mention" breakpoint_ops method for fork
7646    catchpoints.  */
7647
7648 static void
7649 print_mention_catch_fork (struct breakpoint *b)
7650 {
7651   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7652 }
7653
7654 /* Implement the "print_recreate" breakpoint_ops method for fork
7655    catchpoints.  */
7656
7657 static void
7658 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7659 {
7660   fprintf_unfiltered (fp, "catch fork");
7661   print_recreate_thread (b, fp);
7662 }
7663
7664 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7665
7666 static struct breakpoint_ops catch_fork_breakpoint_ops;
7667
7668 /* Implement the "insert" breakpoint_ops method for vfork
7669    catchpoints.  */
7670
7671 static int
7672 insert_catch_vfork (struct bp_location *bl)
7673 {
7674   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7675 }
7676
7677 /* Implement the "remove" breakpoint_ops method for vfork
7678    catchpoints.  */
7679
7680 static int
7681 remove_catch_vfork (struct bp_location *bl)
7682 {
7683   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7684 }
7685
7686 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7687    catchpoints.  */
7688
7689 static int
7690 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7691                             struct address_space *aspace, CORE_ADDR bp_addr,
7692                             const struct target_waitstatus *ws)
7693 {
7694   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7695
7696   if (ws->kind != TARGET_WAITKIND_VFORKED)
7697     return 0;
7698
7699   c->forked_inferior_pid = ws->value.related_pid;
7700   return 1;
7701 }
7702
7703 /* Implement the "print_it" breakpoint_ops method for vfork
7704    catchpoints.  */
7705
7706 static enum print_stop_action
7707 print_it_catch_vfork (bpstat bs)
7708 {
7709   struct ui_out *uiout = current_uiout;
7710   struct breakpoint *b = bs->breakpoint_at;
7711   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7712
7713   annotate_catchpoint (b->number);
7714   if (b->disposition == disp_del)
7715     ui_out_text (uiout, "\nTemporary catchpoint ");
7716   else
7717     ui_out_text (uiout, "\nCatchpoint ");
7718   if (ui_out_is_mi_like_p (uiout))
7719     {
7720       ui_out_field_string (uiout, "reason",
7721                            async_reason_lookup (EXEC_ASYNC_VFORK));
7722       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7723     }
7724   ui_out_field_int (uiout, "bkptno", b->number);
7725   ui_out_text (uiout, " (vforked process ");
7726   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7727   ui_out_text (uiout, "), ");
7728   return PRINT_SRC_AND_LOC;
7729 }
7730
7731 /* Implement the "print_one" breakpoint_ops method for vfork
7732    catchpoints.  */
7733
7734 static void
7735 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7736 {
7737   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7738   struct value_print_options opts;
7739   struct ui_out *uiout = current_uiout;
7740
7741   get_user_print_options (&opts);
7742   /* Field 4, the address, is omitted (which makes the columns not
7743      line up too nicely with the headers, but the effect is relatively
7744      readable).  */
7745   if (opts.addressprint)
7746     ui_out_field_skip (uiout, "addr");
7747   annotate_field (5);
7748   ui_out_text (uiout, "vfork");
7749   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7750     {
7751       ui_out_text (uiout, ", process ");
7752       ui_out_field_int (uiout, "what",
7753                         ptid_get_pid (c->forked_inferior_pid));
7754       ui_out_spaces (uiout, 1);
7755     }
7756
7757   if (ui_out_is_mi_like_p (uiout))
7758     ui_out_field_string (uiout, "catch-type", "vfork");
7759 }
7760
7761 /* Implement the "print_mention" breakpoint_ops method for vfork
7762    catchpoints.  */
7763
7764 static void
7765 print_mention_catch_vfork (struct breakpoint *b)
7766 {
7767   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7768 }
7769
7770 /* Implement the "print_recreate" breakpoint_ops method for vfork
7771    catchpoints.  */
7772
7773 static void
7774 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7775 {
7776   fprintf_unfiltered (fp, "catch vfork");
7777   print_recreate_thread (b, fp);
7778 }
7779
7780 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7781
7782 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7783
7784 /* An instance of this type is used to represent an solib catchpoint.
7785    It includes a "struct breakpoint" as a kind of base class; users
7786    downcast to "struct breakpoint *" when needed.  A breakpoint is
7787    really of this type iff its ops pointer points to
7788    CATCH_SOLIB_BREAKPOINT_OPS.  */
7789
7790 struct solib_catchpoint
7791 {
7792   /* The base class.  */
7793   struct breakpoint base;
7794
7795   /* True for "catch load", false for "catch unload".  */
7796   unsigned char is_load;
7797
7798   /* Regular expression to match, if any.  COMPILED is only valid when
7799      REGEX is non-NULL.  */
7800   char *regex;
7801   regex_t compiled;
7802 };
7803
7804 static void
7805 dtor_catch_solib (struct breakpoint *b)
7806 {
7807   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7808
7809   if (self->regex)
7810     regfree (&self->compiled);
7811   xfree (self->regex);
7812
7813   base_breakpoint_ops.dtor (b);
7814 }
7815
7816 static int
7817 insert_catch_solib (struct bp_location *ignore)
7818 {
7819   return 0;
7820 }
7821
7822 static int
7823 remove_catch_solib (struct bp_location *ignore)
7824 {
7825   return 0;
7826 }
7827
7828 static int
7829 breakpoint_hit_catch_solib (const struct bp_location *bl,
7830                             struct address_space *aspace,
7831                             CORE_ADDR bp_addr,
7832                             const struct target_waitstatus *ws)
7833 {
7834   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7835   struct breakpoint *other;
7836
7837   if (ws->kind == TARGET_WAITKIND_LOADED)
7838     return 1;
7839
7840   ALL_BREAKPOINTS (other)
7841   {
7842     struct bp_location *other_bl;
7843
7844     if (other == bl->owner)
7845       continue;
7846
7847     if (other->type != bp_shlib_event)
7848       continue;
7849
7850     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7851       continue;
7852
7853     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7854       {
7855         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7856           return 1;
7857       }
7858   }
7859
7860   return 0;
7861 }
7862
7863 static void
7864 check_status_catch_solib (struct bpstats *bs)
7865 {
7866   struct solib_catchpoint *self
7867     = (struct solib_catchpoint *) bs->breakpoint_at;
7868   int ix;
7869
7870   if (self->is_load)
7871     {
7872       struct so_list *iter;
7873
7874       for (ix = 0;
7875            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7876                         ix, iter);
7877            ++ix)
7878         {
7879           if (!self->regex
7880               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7881             return;
7882         }
7883     }
7884   else
7885     {
7886       char *iter;
7887
7888       for (ix = 0;
7889            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7890                         ix, iter);
7891            ++ix)
7892         {
7893           if (!self->regex
7894               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7895             return;
7896         }
7897     }
7898
7899   bs->stop = 0;
7900   bs->print_it = print_it_noop;
7901 }
7902
7903 static enum print_stop_action
7904 print_it_catch_solib (bpstat bs)
7905 {
7906   struct breakpoint *b = bs->breakpoint_at;
7907   struct ui_out *uiout = current_uiout;
7908
7909   annotate_catchpoint (b->number);
7910   if (b->disposition == disp_del)
7911     ui_out_text (uiout, "\nTemporary catchpoint ");
7912   else
7913     ui_out_text (uiout, "\nCatchpoint ");
7914   ui_out_field_int (uiout, "bkptno", b->number);
7915   ui_out_text (uiout, "\n");
7916   if (ui_out_is_mi_like_p (uiout))
7917     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7918   print_solib_event (1);
7919   return PRINT_SRC_AND_LOC;
7920 }
7921
7922 static void
7923 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7924 {
7925   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7926   struct value_print_options opts;
7927   struct ui_out *uiout = current_uiout;
7928   char *msg;
7929
7930   get_user_print_options (&opts);
7931   /* Field 4, the address, is omitted (which makes the columns not
7932      line up too nicely with the headers, but the effect is relatively
7933      readable).  */
7934   if (opts.addressprint)
7935     {
7936       annotate_field (4);
7937       ui_out_field_skip (uiout, "addr");
7938     }
7939
7940   annotate_field (5);
7941   if (self->is_load)
7942     {
7943       if (self->regex)
7944         msg = xstrprintf (_("load of library matching %s"), self->regex);
7945       else
7946         msg = xstrdup (_("load of library"));
7947     }
7948   else
7949     {
7950       if (self->regex)
7951         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7952       else
7953         msg = xstrdup (_("unload of library"));
7954     }
7955   ui_out_field_string (uiout, "what", msg);
7956   xfree (msg);
7957
7958   if (ui_out_is_mi_like_p (uiout))
7959     ui_out_field_string (uiout, "catch-type",
7960                          self->is_load ? "load" : "unload");
7961 }
7962
7963 static void
7964 print_mention_catch_solib (struct breakpoint *b)
7965 {
7966   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7967
7968   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7969                    self->is_load ? "load" : "unload");
7970 }
7971
7972 static void
7973 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7974 {
7975   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7976
7977   fprintf_unfiltered (fp, "%s %s",
7978                       b->disposition == disp_del ? "tcatch" : "catch",
7979                       self->is_load ? "load" : "unload");
7980   if (self->regex)
7981     fprintf_unfiltered (fp, " %s", self->regex);
7982   fprintf_unfiltered (fp, "\n");
7983 }
7984
7985 static struct breakpoint_ops catch_solib_breakpoint_ops;
7986
7987 /* Shared helper function (MI and CLI) for creating and installing
7988    a shared object event catchpoint.  If IS_LOAD is non-zero then
7989    the events to be caught are load events, otherwise they are
7990    unload events.  If IS_TEMP is non-zero the catchpoint is a
7991    temporary one.  If ENABLED is non-zero the catchpoint is
7992    created in an enabled state.  */
7993
7994 void
7995 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
7996 {
7997   struct solib_catchpoint *c;
7998   struct gdbarch *gdbarch = get_current_arch ();
7999   struct cleanup *cleanup;
8000
8001   if (!arg)
8002     arg = "";
8003   arg = skip_spaces (arg);
8004
8005   c = XCNEW (struct solib_catchpoint);
8006   cleanup = make_cleanup (xfree, c);
8007
8008   if (*arg != '\0')
8009     {
8010       int errcode;
8011
8012       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8013       if (errcode != 0)
8014         {
8015           char *err = get_regcomp_error (errcode, &c->compiled);
8016
8017           make_cleanup (xfree, err);
8018           error (_("Invalid regexp (%s): %s"), err, arg);
8019         }
8020       c->regex = xstrdup (arg);
8021     }
8022
8023   c->is_load = is_load;
8024   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8025                    &catch_solib_breakpoint_ops);
8026
8027   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8028
8029   discard_cleanups (cleanup);
8030   install_breakpoint (0, &c->base, 1);
8031 }
8032
8033 /* A helper function that does all the work for "catch load" and
8034    "catch unload".  */
8035
8036 static void
8037 catch_load_or_unload (char *arg, int from_tty, int is_load,
8038                       struct cmd_list_element *command)
8039 {
8040   int tempflag;
8041   const int enabled = 1;
8042
8043   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8044
8045   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8046 }
8047
8048 static void
8049 catch_load_command_1 (char *arg, int from_tty,
8050                       struct cmd_list_element *command)
8051 {
8052   catch_load_or_unload (arg, from_tty, 1, command);
8053 }
8054
8055 static void
8056 catch_unload_command_1 (char *arg, int from_tty,
8057                         struct cmd_list_element *command)
8058 {
8059   catch_load_or_unload (arg, from_tty, 0, command);
8060 }
8061
8062 /* An instance of this type is used to represent a syscall catchpoint.
8063    It includes a "struct breakpoint" as a kind of base class; users
8064    downcast to "struct breakpoint *" when needed.  A breakpoint is
8065    really of this type iff its ops pointer points to
8066    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8067
8068 struct syscall_catchpoint
8069 {
8070   /* The base class.  */
8071   struct breakpoint base;
8072
8073   /* Syscall numbers used for the 'catch syscall' feature.  If no
8074      syscall has been specified for filtering, its value is NULL.
8075      Otherwise, it holds a list of all syscalls to be caught.  The
8076      list elements are allocated with xmalloc.  */
8077   VEC(int) *syscalls_to_be_caught;
8078 };
8079
8080 /* Implement the "dtor" breakpoint_ops method for syscall
8081    catchpoints.  */
8082
8083 static void
8084 dtor_catch_syscall (struct breakpoint *b)
8085 {
8086   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8087
8088   VEC_free (int, c->syscalls_to_be_caught);
8089
8090   base_breakpoint_ops.dtor (b);
8091 }
8092
8093 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8094
8095 struct catch_syscall_inferior_data
8096 {
8097   /* We keep a count of the number of times the user has requested a
8098      particular syscall to be tracked, and pass this information to the
8099      target.  This lets capable targets implement filtering directly.  */
8100
8101   /* Number of times that "any" syscall is requested.  */
8102   int any_syscall_count;
8103
8104   /* Count of each system call.  */
8105   VEC(int) *syscalls_counts;
8106
8107   /* This counts all syscall catch requests, so we can readily determine
8108      if any catching is necessary.  */
8109   int total_syscalls_count;
8110 };
8111
8112 static struct catch_syscall_inferior_data*
8113 get_catch_syscall_inferior_data (struct inferior *inf)
8114 {
8115   struct catch_syscall_inferior_data *inf_data;
8116
8117   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8118   if (inf_data == NULL)
8119     {
8120       inf_data = XZALLOC (struct catch_syscall_inferior_data);
8121       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8122     }
8123
8124   return inf_data;
8125 }
8126
8127 static void
8128 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8129 {
8130   xfree (arg);
8131 }
8132
8133
8134 /* Implement the "insert" breakpoint_ops method for syscall
8135    catchpoints.  */
8136
8137 static int
8138 insert_catch_syscall (struct bp_location *bl)
8139 {
8140   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8141   struct inferior *inf = current_inferior ();
8142   struct catch_syscall_inferior_data *inf_data
8143     = get_catch_syscall_inferior_data (inf);
8144
8145   ++inf_data->total_syscalls_count;
8146   if (!c->syscalls_to_be_caught)
8147     ++inf_data->any_syscall_count;
8148   else
8149     {
8150       int i, iter;
8151
8152       for (i = 0;
8153            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8154            i++)
8155         {
8156           int elem;
8157
8158           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8159             {
8160               int old_size = VEC_length (int, inf_data->syscalls_counts);
8161               uintptr_t vec_addr_offset
8162                 = old_size * ((uintptr_t) sizeof (int));
8163               uintptr_t vec_addr;
8164               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8165               vec_addr = ((uintptr_t) VEC_address (int,
8166                                                   inf_data->syscalls_counts)
8167                           + vec_addr_offset);
8168               memset ((void *) vec_addr, 0,
8169                       (iter + 1 - old_size) * sizeof (int));
8170             }
8171           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8172           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8173         }
8174     }
8175
8176   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8177                                         inf_data->total_syscalls_count != 0,
8178                                         inf_data->any_syscall_count,
8179                                         VEC_length (int,
8180                                                     inf_data->syscalls_counts),
8181                                         VEC_address (int,
8182                                                      inf_data->syscalls_counts));
8183 }
8184
8185 /* Implement the "remove" breakpoint_ops method for syscall
8186    catchpoints.  */
8187
8188 static int
8189 remove_catch_syscall (struct bp_location *bl)
8190 {
8191   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8192   struct inferior *inf = current_inferior ();
8193   struct catch_syscall_inferior_data *inf_data
8194     = get_catch_syscall_inferior_data (inf);
8195
8196   --inf_data->total_syscalls_count;
8197   if (!c->syscalls_to_be_caught)
8198     --inf_data->any_syscall_count;
8199   else
8200     {
8201       int i, iter;
8202
8203       for (i = 0;
8204            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8205            i++)
8206         {
8207           int elem;
8208           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8209             /* Shouldn't happen.  */
8210             continue;
8211           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8212           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8213         }
8214     }
8215
8216   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8217                                         inf_data->total_syscalls_count != 0,
8218                                         inf_data->any_syscall_count,
8219                                         VEC_length (int,
8220                                                     inf_data->syscalls_counts),
8221                                         VEC_address (int,
8222                                                      inf_data->syscalls_counts));
8223 }
8224
8225 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8226    catchpoints.  */
8227
8228 static int
8229 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8230                               struct address_space *aspace, CORE_ADDR bp_addr,
8231                               const struct target_waitstatus *ws)
8232 {
8233   /* We must check if we are catching specific syscalls in this
8234      breakpoint.  If we are, then we must guarantee that the called
8235      syscall is the same syscall we are catching.  */
8236   int syscall_number = 0;
8237   const struct syscall_catchpoint *c
8238     = (const struct syscall_catchpoint *) bl->owner;
8239
8240   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8241       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8242     return 0;
8243
8244   syscall_number = ws->value.syscall_number;
8245
8246   /* Now, checking if the syscall is the same.  */
8247   if (c->syscalls_to_be_caught)
8248     {
8249       int i, iter;
8250
8251       for (i = 0;
8252            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8253            i++)
8254         if (syscall_number == iter)
8255           break;
8256       /* Not the same.  */
8257       if (!iter)
8258         return 0;
8259     }
8260
8261   return 1;
8262 }
8263
8264 /* Implement the "print_it" breakpoint_ops method for syscall
8265    catchpoints.  */
8266
8267 static enum print_stop_action
8268 print_it_catch_syscall (bpstat bs)
8269 {
8270   struct ui_out *uiout = current_uiout;
8271   struct breakpoint *b = bs->breakpoint_at;
8272   /* These are needed because we want to know in which state a
8273      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8274      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8275      must print "called syscall" or "returned from syscall".  */
8276   ptid_t ptid;
8277   struct target_waitstatus last;
8278   struct syscall s;
8279
8280   get_last_target_status (&ptid, &last);
8281
8282   get_syscall_by_number (last.value.syscall_number, &s);
8283
8284   annotate_catchpoint (b->number);
8285
8286   if (b->disposition == disp_del)
8287     ui_out_text (uiout, "\nTemporary catchpoint ");
8288   else
8289     ui_out_text (uiout, "\nCatchpoint ");
8290   if (ui_out_is_mi_like_p (uiout))
8291     {
8292       ui_out_field_string (uiout, "reason",
8293                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8294                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8295                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8296       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8297     }
8298   ui_out_field_int (uiout, "bkptno", b->number);
8299
8300   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8301     ui_out_text (uiout, " (call to syscall ");
8302   else
8303     ui_out_text (uiout, " (returned from syscall ");
8304
8305   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8306     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8307   if (s.name != NULL)
8308     ui_out_field_string (uiout, "syscall-name", s.name);
8309
8310   ui_out_text (uiout, "), ");
8311
8312   return PRINT_SRC_AND_LOC;
8313 }
8314
8315 /* Implement the "print_one" breakpoint_ops method for syscall
8316    catchpoints.  */
8317
8318 static void
8319 print_one_catch_syscall (struct breakpoint *b,
8320                          struct bp_location **last_loc)
8321 {
8322   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8323   struct value_print_options opts;
8324   struct ui_out *uiout = current_uiout;
8325
8326   get_user_print_options (&opts);
8327   /* Field 4, the address, is omitted (which makes the columns not
8328      line up too nicely with the headers, but the effect is relatively
8329      readable).  */
8330   if (opts.addressprint)
8331     ui_out_field_skip (uiout, "addr");
8332   annotate_field (5);
8333
8334   if (c->syscalls_to_be_caught
8335       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8336     ui_out_text (uiout, "syscalls \"");
8337   else
8338     ui_out_text (uiout, "syscall \"");
8339
8340   if (c->syscalls_to_be_caught)
8341     {
8342       int i, iter;
8343       char *text = xstrprintf ("%s", "");
8344
8345       for (i = 0;
8346            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8347            i++)
8348         {
8349           char *x = text;
8350           struct syscall s;
8351           get_syscall_by_number (iter, &s);
8352
8353           if (s.name != NULL)
8354             text = xstrprintf ("%s%s, ", text, s.name);
8355           else
8356             text = xstrprintf ("%s%d, ", text, iter);
8357
8358           /* We have to xfree the last 'text' (now stored at 'x')
8359              because xstrprintf dynamically allocates new space for it
8360              on every call.  */
8361           xfree (x);
8362         }
8363       /* Remove the last comma.  */
8364       text[strlen (text) - 2] = '\0';
8365       ui_out_field_string (uiout, "what", text);
8366     }
8367   else
8368     ui_out_field_string (uiout, "what", "<any syscall>");
8369   ui_out_text (uiout, "\" ");
8370
8371   if (ui_out_is_mi_like_p (uiout))
8372     ui_out_field_string (uiout, "catch-type", "syscall");
8373 }
8374
8375 /* Implement the "print_mention" breakpoint_ops method for syscall
8376    catchpoints.  */
8377
8378 static void
8379 print_mention_catch_syscall (struct breakpoint *b)
8380 {
8381   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8382
8383   if (c->syscalls_to_be_caught)
8384     {
8385       int i, iter;
8386
8387       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8388         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8389       else
8390         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8391
8392       for (i = 0;
8393            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8394            i++)
8395         {
8396           struct syscall s;
8397           get_syscall_by_number (iter, &s);
8398
8399           if (s.name)
8400             printf_filtered (" '%s' [%d]", s.name, s.number);
8401           else
8402             printf_filtered (" %d", s.number);
8403         }
8404       printf_filtered (")");
8405     }
8406   else
8407     printf_filtered (_("Catchpoint %d (any syscall)"),
8408                      b->number);
8409 }
8410
8411 /* Implement the "print_recreate" breakpoint_ops method for syscall
8412    catchpoints.  */
8413
8414 static void
8415 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8416 {
8417   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8418
8419   fprintf_unfiltered (fp, "catch syscall");
8420
8421   if (c->syscalls_to_be_caught)
8422     {
8423       int i, iter;
8424
8425       for (i = 0;
8426            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8427            i++)
8428         {
8429           struct syscall s;
8430
8431           get_syscall_by_number (iter, &s);
8432           if (s.name)
8433             fprintf_unfiltered (fp, " %s", s.name);
8434           else
8435             fprintf_unfiltered (fp, " %d", s.number);
8436         }
8437     }
8438   print_recreate_thread (b, fp);
8439 }
8440
8441 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8442
8443 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8444
8445 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8446
8447 static int
8448 syscall_catchpoint_p (struct breakpoint *b)
8449 {
8450   return (b->ops == &catch_syscall_breakpoint_ops);
8451 }
8452
8453 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8454    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8455    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8456    the breakpoint_ops structure associated to the catchpoint.  */
8457
8458 void
8459 init_catchpoint (struct breakpoint *b,
8460                  struct gdbarch *gdbarch, int tempflag,
8461                  char *cond_string,
8462                  const struct breakpoint_ops *ops)
8463 {
8464   struct symtab_and_line sal;
8465
8466   init_sal (&sal);
8467   sal.pspace = current_program_space;
8468
8469   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8470
8471   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8472   b->disposition = tempflag ? disp_del : disp_donttouch;
8473 }
8474
8475 void
8476 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8477 {
8478   add_to_breakpoint_chain (b);
8479   set_breakpoint_number (internal, b);
8480   if (is_tracepoint (b))
8481     set_tracepoint_count (breakpoint_count);
8482   if (!internal)
8483     mention (b);
8484   observer_notify_breakpoint_created (b);
8485
8486   if (update_gll)
8487     update_global_location_list (1);
8488 }
8489
8490 static void
8491 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8492                                     int tempflag, char *cond_string,
8493                                     const struct breakpoint_ops *ops)
8494 {
8495   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8496
8497   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8498
8499   c->forked_inferior_pid = null_ptid;
8500
8501   install_breakpoint (0, &c->base, 1);
8502 }
8503
8504 /* Exec catchpoints.  */
8505
8506 /* An instance of this type is used to represent an exec catchpoint.
8507    It includes a "struct breakpoint" as a kind of base class; users
8508    downcast to "struct breakpoint *" when needed.  A breakpoint is
8509    really of this type iff its ops pointer points to
8510    CATCH_EXEC_BREAKPOINT_OPS.  */
8511
8512 struct exec_catchpoint
8513 {
8514   /* The base class.  */
8515   struct breakpoint base;
8516
8517   /* Filename of a program whose exec triggered this catchpoint.
8518      This field is only valid immediately after this catchpoint has
8519      triggered.  */
8520   char *exec_pathname;
8521 };
8522
8523 /* Implement the "dtor" breakpoint_ops method for exec
8524    catchpoints.  */
8525
8526 static void
8527 dtor_catch_exec (struct breakpoint *b)
8528 {
8529   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8530
8531   xfree (c->exec_pathname);
8532
8533   base_breakpoint_ops.dtor (b);
8534 }
8535
8536 static int
8537 insert_catch_exec (struct bp_location *bl)
8538 {
8539   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8540 }
8541
8542 static int
8543 remove_catch_exec (struct bp_location *bl)
8544 {
8545   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8546 }
8547
8548 static int
8549 breakpoint_hit_catch_exec (const struct bp_location *bl,
8550                            struct address_space *aspace, CORE_ADDR bp_addr,
8551                            const struct target_waitstatus *ws)
8552 {
8553   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8554
8555   if (ws->kind != TARGET_WAITKIND_EXECD)
8556     return 0;
8557
8558   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8559   return 1;
8560 }
8561
8562 static enum print_stop_action
8563 print_it_catch_exec (bpstat bs)
8564 {
8565   struct ui_out *uiout = current_uiout;
8566   struct breakpoint *b = bs->breakpoint_at;
8567   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8568
8569   annotate_catchpoint (b->number);
8570   if (b->disposition == disp_del)
8571     ui_out_text (uiout, "\nTemporary catchpoint ");
8572   else
8573     ui_out_text (uiout, "\nCatchpoint ");
8574   if (ui_out_is_mi_like_p (uiout))
8575     {
8576       ui_out_field_string (uiout, "reason",
8577                            async_reason_lookup (EXEC_ASYNC_EXEC));
8578       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8579     }
8580   ui_out_field_int (uiout, "bkptno", b->number);
8581   ui_out_text (uiout, " (exec'd ");
8582   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8583   ui_out_text (uiout, "), ");
8584
8585   return PRINT_SRC_AND_LOC;
8586 }
8587
8588 static void
8589 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8590 {
8591   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8592   struct value_print_options opts;
8593   struct ui_out *uiout = current_uiout;
8594
8595   get_user_print_options (&opts);
8596
8597   /* Field 4, the address, is omitted (which makes the columns
8598      not line up too nicely with the headers, but the effect
8599      is relatively readable).  */
8600   if (opts.addressprint)
8601     ui_out_field_skip (uiout, "addr");
8602   annotate_field (5);
8603   ui_out_text (uiout, "exec");
8604   if (c->exec_pathname != NULL)
8605     {
8606       ui_out_text (uiout, ", program \"");
8607       ui_out_field_string (uiout, "what", c->exec_pathname);
8608       ui_out_text (uiout, "\" ");
8609     }
8610
8611   if (ui_out_is_mi_like_p (uiout))
8612     ui_out_field_string (uiout, "catch-type", "exec");
8613 }
8614
8615 static void
8616 print_mention_catch_exec (struct breakpoint *b)
8617 {
8618   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8619 }
8620
8621 /* Implement the "print_recreate" breakpoint_ops method for exec
8622    catchpoints.  */
8623
8624 static void
8625 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8626 {
8627   fprintf_unfiltered (fp, "catch exec");
8628   print_recreate_thread (b, fp);
8629 }
8630
8631 static struct breakpoint_ops catch_exec_breakpoint_ops;
8632
8633 static void
8634 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8635                                  const struct breakpoint_ops *ops)
8636 {
8637   struct syscall_catchpoint *c;
8638   struct gdbarch *gdbarch = get_current_arch ();
8639
8640   c = XNEW (struct syscall_catchpoint);
8641   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8642   c->syscalls_to_be_caught = filter;
8643
8644   install_breakpoint (0, &c->base, 1);
8645 }
8646
8647 static int
8648 hw_breakpoint_used_count (void)
8649 {
8650   int i = 0;
8651   struct breakpoint *b;
8652   struct bp_location *bl;
8653
8654   ALL_BREAKPOINTS (b)
8655   {
8656     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8657       for (bl = b->loc; bl; bl = bl->next)
8658         {
8659           /* Special types of hardware breakpoints may use more than
8660              one register.  */
8661           i += b->ops->resources_needed (bl);
8662         }
8663   }
8664
8665   return i;
8666 }
8667
8668 /* Returns the resources B would use if it were a hardware
8669    watchpoint.  */
8670
8671 static int
8672 hw_watchpoint_use_count (struct breakpoint *b)
8673 {
8674   int i = 0;
8675   struct bp_location *bl;
8676
8677   if (!breakpoint_enabled (b))
8678     return 0;
8679
8680   for (bl = b->loc; bl; bl = bl->next)
8681     {
8682       /* Special types of hardware watchpoints may use more than
8683          one register.  */
8684       i += b->ops->resources_needed (bl);
8685     }
8686
8687   return i;
8688 }
8689
8690 /* Returns the sum the used resources of all hardware watchpoints of
8691    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8692    the sum of the used resources of all hardware watchpoints of other
8693    types _not_ TYPE.  */
8694
8695 static int
8696 hw_watchpoint_used_count_others (struct breakpoint *except,
8697                                  enum bptype type, int *other_type_used)
8698 {
8699   int i = 0;
8700   struct breakpoint *b;
8701
8702   *other_type_used = 0;
8703   ALL_BREAKPOINTS (b)
8704     {
8705       if (b == except)
8706         continue;
8707       if (!breakpoint_enabled (b))
8708         continue;
8709
8710       if (b->type == type)
8711         i += hw_watchpoint_use_count (b);
8712       else if (is_hardware_watchpoint (b))
8713         *other_type_used = 1;
8714     }
8715
8716   return i;
8717 }
8718
8719 void
8720 disable_watchpoints_before_interactive_call_start (void)
8721 {
8722   struct breakpoint *b;
8723
8724   ALL_BREAKPOINTS (b)
8725   {
8726     if (is_watchpoint (b) && breakpoint_enabled (b))
8727       {
8728         b->enable_state = bp_call_disabled;
8729         update_global_location_list (0);
8730       }
8731   }
8732 }
8733
8734 void
8735 enable_watchpoints_after_interactive_call_stop (void)
8736 {
8737   struct breakpoint *b;
8738
8739   ALL_BREAKPOINTS (b)
8740   {
8741     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8742       {
8743         b->enable_state = bp_enabled;
8744         update_global_location_list (1);
8745       }
8746   }
8747 }
8748
8749 void
8750 disable_breakpoints_before_startup (void)
8751 {
8752   current_program_space->executing_startup = 1;
8753   update_global_location_list (0);
8754 }
8755
8756 void
8757 enable_breakpoints_after_startup (void)
8758 {
8759   current_program_space->executing_startup = 0;
8760   breakpoint_re_set ();
8761 }
8762
8763
8764 /* Set a breakpoint that will evaporate an end of command
8765    at address specified by SAL.
8766    Restrict it to frame FRAME if FRAME is nonzero.  */
8767
8768 struct breakpoint *
8769 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8770                           struct frame_id frame_id, enum bptype type)
8771 {
8772   struct breakpoint *b;
8773
8774   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8775      tail-called one.  */
8776   gdb_assert (!frame_id_artificial_p (frame_id));
8777
8778   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8779   b->enable_state = bp_enabled;
8780   b->disposition = disp_donttouch;
8781   b->frame_id = frame_id;
8782
8783   /* If we're debugging a multi-threaded program, then we want
8784      momentary breakpoints to be active in only a single thread of
8785      control.  */
8786   if (in_thread_list (inferior_ptid))
8787     b->thread = pid_to_thread_id (inferior_ptid);
8788
8789   update_global_location_list_nothrow (1);
8790
8791   return b;
8792 }
8793
8794 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8795    The new breakpoint will have type TYPE, and use OPS as it
8796    breakpoint_ops.  */
8797
8798 static struct breakpoint *
8799 momentary_breakpoint_from_master (struct breakpoint *orig,
8800                                   enum bptype type,
8801                                   const struct breakpoint_ops *ops)
8802 {
8803   struct breakpoint *copy;
8804
8805   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8806   copy->loc = allocate_bp_location (copy);
8807   set_breakpoint_location_function (copy->loc, 1);
8808
8809   copy->loc->gdbarch = orig->loc->gdbarch;
8810   copy->loc->requested_address = orig->loc->requested_address;
8811   copy->loc->address = orig->loc->address;
8812   copy->loc->section = orig->loc->section;
8813   copy->loc->pspace = orig->loc->pspace;
8814   copy->loc->probe = orig->loc->probe;
8815   copy->loc->line_number = orig->loc->line_number;
8816   copy->loc->symtab = orig->loc->symtab;
8817   copy->frame_id = orig->frame_id;
8818   copy->thread = orig->thread;
8819   copy->pspace = orig->pspace;
8820
8821   copy->enable_state = bp_enabled;
8822   copy->disposition = disp_donttouch;
8823   copy->number = internal_breakpoint_number--;
8824
8825   update_global_location_list_nothrow (0);
8826   return copy;
8827 }
8828
8829 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8830    ORIG is NULL.  */
8831
8832 struct breakpoint *
8833 clone_momentary_breakpoint (struct breakpoint *orig)
8834 {
8835   /* If there's nothing to clone, then return nothing.  */
8836   if (orig == NULL)
8837     return NULL;
8838
8839   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8840 }
8841
8842 struct breakpoint *
8843 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8844                                 enum bptype type)
8845 {
8846   struct symtab_and_line sal;
8847
8848   sal = find_pc_line (pc, 0);
8849   sal.pc = pc;
8850   sal.section = find_pc_overlay (pc);
8851   sal.explicit_pc = 1;
8852
8853   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8854 }
8855 \f
8856
8857 /* Tell the user we have just set a breakpoint B.  */
8858
8859 static void
8860 mention (struct breakpoint *b)
8861 {
8862   b->ops->print_mention (b);
8863   if (ui_out_is_mi_like_p (current_uiout))
8864     return;
8865   printf_filtered ("\n");
8866 }
8867 \f
8868
8869 static struct bp_location *
8870 add_location_to_breakpoint (struct breakpoint *b,
8871                             const struct symtab_and_line *sal)
8872 {
8873   struct bp_location *loc, **tmp;
8874   CORE_ADDR adjusted_address;
8875   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8876
8877   if (loc_gdbarch == NULL)
8878     loc_gdbarch = b->gdbarch;
8879
8880   /* Adjust the breakpoint's address prior to allocating a location.
8881      Once we call allocate_bp_location(), that mostly uninitialized
8882      location will be placed on the location chain.  Adjustment of the
8883      breakpoint may cause target_read_memory() to be called and we do
8884      not want its scan of the location chain to find a breakpoint and
8885      location that's only been partially initialized.  */
8886   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8887                                                 sal->pc, b->type);
8888
8889   /* Sort the locations by their ADDRESS.  */
8890   loc = allocate_bp_location (b);
8891   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8892        tmp = &((*tmp)->next))
8893     ;
8894   loc->next = *tmp;
8895   *tmp = loc;
8896
8897   loc->requested_address = sal->pc;
8898   loc->address = adjusted_address;
8899   loc->pspace = sal->pspace;
8900   loc->probe = sal->probe;
8901   gdb_assert (loc->pspace != NULL);
8902   loc->section = sal->section;
8903   loc->gdbarch = loc_gdbarch;
8904   loc->line_number = sal->line;
8905   loc->symtab = sal->symtab;
8906
8907   set_breakpoint_location_function (loc,
8908                                     sal->explicit_pc || sal->explicit_line);
8909   return loc;
8910 }
8911 \f
8912
8913 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8914    return 0 otherwise.  */
8915
8916 static int
8917 bp_loc_is_permanent (struct bp_location *loc)
8918 {
8919   int len;
8920   CORE_ADDR addr;
8921   const gdb_byte *bpoint;
8922   gdb_byte *target_mem;
8923   struct cleanup *cleanup;
8924   int retval = 0;
8925
8926   gdb_assert (loc != NULL);
8927
8928   addr = loc->address;
8929   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8930
8931   /* Software breakpoints unsupported?  */
8932   if (bpoint == NULL)
8933     return 0;
8934
8935   target_mem = alloca (len);
8936
8937   /* Enable the automatic memory restoration from breakpoints while
8938      we read the memory.  Otherwise we could say about our temporary
8939      breakpoints they are permanent.  */
8940   cleanup = save_current_space_and_thread ();
8941
8942   switch_to_program_space_and_thread (loc->pspace);
8943   make_show_memory_breakpoints_cleanup (0);
8944
8945   if (target_read_memory (loc->address, target_mem, len) == 0
8946       && memcmp (target_mem, bpoint, len) == 0)
8947     retval = 1;
8948
8949   do_cleanups (cleanup);
8950
8951   return retval;
8952 }
8953
8954 /* Build a command list for the dprintf corresponding to the current
8955    settings of the dprintf style options.  */
8956
8957 static void
8958 update_dprintf_command_list (struct breakpoint *b)
8959 {
8960   char *dprintf_args = b->extra_string;
8961   char *printf_line = NULL;
8962
8963   if (!dprintf_args)
8964     return;
8965
8966   dprintf_args = skip_spaces (dprintf_args);
8967
8968   /* Allow a comma, as it may have terminated a location, but don't
8969      insist on it.  */
8970   if (*dprintf_args == ',')
8971     ++dprintf_args;
8972   dprintf_args = skip_spaces (dprintf_args);
8973
8974   if (*dprintf_args != '"')
8975     error (_("Bad format string, missing '\"'."));
8976
8977   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8978     printf_line = xstrprintf ("printf %s", dprintf_args);
8979   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8980     {
8981       if (!dprintf_function)
8982         error (_("No function supplied for dprintf call"));
8983
8984       if (dprintf_channel && strlen (dprintf_channel) > 0)
8985         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8986                                   dprintf_function,
8987                                   dprintf_channel,
8988                                   dprintf_args);
8989       else
8990         printf_line = xstrprintf ("call (void) %s (%s)",
8991                                   dprintf_function,
8992                                   dprintf_args);
8993     }
8994   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8995     {
8996       if (target_can_run_breakpoint_commands ())
8997         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8998       else
8999         {
9000           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9001           printf_line = xstrprintf ("printf %s", dprintf_args);
9002         }
9003     }
9004   else
9005     internal_error (__FILE__, __LINE__,
9006                     _("Invalid dprintf style."));
9007
9008   gdb_assert (printf_line != NULL);
9009   /* Manufacture a printf sequence.  */
9010   {
9011     struct command_line *printf_cmd_line
9012       = xmalloc (sizeof (struct command_line));
9013
9014     printf_cmd_line = xmalloc (sizeof (struct command_line));
9015     printf_cmd_line->control_type = simple_control;
9016     printf_cmd_line->body_count = 0;
9017     printf_cmd_line->body_list = NULL;
9018     printf_cmd_line->next = NULL;
9019     printf_cmd_line->line = printf_line;
9020
9021     breakpoint_set_commands (b, printf_cmd_line);
9022   }
9023 }
9024
9025 /* Update all dprintf commands, making their command lists reflect
9026    current style settings.  */
9027
9028 static void
9029 update_dprintf_commands (char *args, int from_tty,
9030                          struct cmd_list_element *c)
9031 {
9032   struct breakpoint *b;
9033
9034   ALL_BREAKPOINTS (b)
9035     {
9036       if (b->type == bp_dprintf)
9037         update_dprintf_command_list (b);
9038     }
9039 }
9040
9041 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9042    as textual description of the location, and COND_STRING
9043    as condition expression.  */
9044
9045 static void
9046 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9047                      struct symtabs_and_lines sals, char *addr_string,
9048                      char *filter, char *cond_string,
9049                      char *extra_string,
9050                      enum bptype type, enum bpdisp disposition,
9051                      int thread, int task, int ignore_count,
9052                      const struct breakpoint_ops *ops, int from_tty,
9053                      int enabled, int internal, unsigned flags,
9054                      int display_canonical)
9055 {
9056   int i;
9057
9058   if (type == bp_hardware_breakpoint)
9059     {
9060       int target_resources_ok;
9061
9062       i = hw_breakpoint_used_count ();
9063       target_resources_ok =
9064         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9065                                             i + 1, 0);
9066       if (target_resources_ok == 0)
9067         error (_("No hardware breakpoint support in the target."));
9068       else if (target_resources_ok < 0)
9069         error (_("Hardware breakpoints used exceeds limit."));
9070     }
9071
9072   gdb_assert (sals.nelts > 0);
9073
9074   for (i = 0; i < sals.nelts; ++i)
9075     {
9076       struct symtab_and_line sal = sals.sals[i];
9077       struct bp_location *loc;
9078
9079       if (from_tty)
9080         {
9081           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9082           if (!loc_gdbarch)
9083             loc_gdbarch = gdbarch;
9084
9085           describe_other_breakpoints (loc_gdbarch,
9086                                       sal.pspace, sal.pc, sal.section, thread);
9087         }
9088
9089       if (i == 0)
9090         {
9091           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9092           b->thread = thread;
9093           b->task = task;
9094
9095           b->cond_string = cond_string;
9096           b->extra_string = extra_string;
9097           b->ignore_count = ignore_count;
9098           b->enable_state = enabled ? bp_enabled : bp_disabled;
9099           b->disposition = disposition;
9100
9101           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9102             b->loc->inserted = 1;
9103
9104           if (type == bp_static_tracepoint)
9105             {
9106               struct tracepoint *t = (struct tracepoint *) b;
9107               struct static_tracepoint_marker marker;
9108
9109               if (strace_marker_p (b))
9110                 {
9111                   /* We already know the marker exists, otherwise, we
9112                      wouldn't see a sal for it.  */
9113                   char *p = &addr_string[3];
9114                   char *endp;
9115                   char *marker_str;
9116
9117                   p = skip_spaces (p);
9118
9119                   endp = skip_to_space (p);
9120
9121                   marker_str = savestring (p, endp - p);
9122                   t->static_trace_marker_id = marker_str;
9123
9124                   printf_filtered (_("Probed static tracepoint "
9125                                      "marker \"%s\"\n"),
9126                                    t->static_trace_marker_id);
9127                 }
9128               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9129                 {
9130                   t->static_trace_marker_id = xstrdup (marker.str_id);
9131                   release_static_tracepoint_marker (&marker);
9132
9133                   printf_filtered (_("Probed static tracepoint "
9134                                      "marker \"%s\"\n"),
9135                                    t->static_trace_marker_id);
9136                 }
9137               else
9138                 warning (_("Couldn't determine the static "
9139                            "tracepoint marker to probe"));
9140             }
9141
9142           loc = b->loc;
9143         }
9144       else
9145         {
9146           loc = add_location_to_breakpoint (b, &sal);
9147           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9148             loc->inserted = 1;
9149         }
9150
9151       if (bp_loc_is_permanent (loc))
9152         make_breakpoint_permanent (b);
9153
9154       if (b->cond_string)
9155         {
9156           const char *arg = b->cond_string;
9157
9158           loc->cond = parse_exp_1 (&arg, loc->address,
9159                                    block_for_pc (loc->address), 0);
9160           if (*arg)
9161               error (_("Garbage '%s' follows condition"), arg);
9162         }
9163
9164       /* Dynamic printf requires and uses additional arguments on the
9165          command line, otherwise it's an error.  */
9166       if (type == bp_dprintf)
9167         {
9168           if (b->extra_string)
9169             update_dprintf_command_list (b);
9170           else
9171             error (_("Format string required"));
9172         }
9173       else if (b->extra_string)
9174         error (_("Garbage '%s' at end of command"), b->extra_string);
9175     }
9176
9177   b->display_canonical = display_canonical;
9178   if (addr_string)
9179     b->addr_string = addr_string;
9180   else
9181     /* addr_string has to be used or breakpoint_re_set will delete
9182        me.  */
9183     b->addr_string
9184       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9185   b->filter = filter;
9186 }
9187
9188 static void
9189 create_breakpoint_sal (struct gdbarch *gdbarch,
9190                        struct symtabs_and_lines sals, char *addr_string,
9191                        char *filter, char *cond_string,
9192                        char *extra_string,
9193                        enum bptype type, enum bpdisp disposition,
9194                        int thread, int task, int ignore_count,
9195                        const struct breakpoint_ops *ops, int from_tty,
9196                        int enabled, int internal, unsigned flags,
9197                        int display_canonical)
9198 {
9199   struct breakpoint *b;
9200   struct cleanup *old_chain;
9201
9202   if (is_tracepoint_type (type))
9203     {
9204       struct tracepoint *t;
9205
9206       t = XCNEW (struct tracepoint);
9207       b = &t->base;
9208     }
9209   else
9210     b = XNEW (struct breakpoint);
9211
9212   old_chain = make_cleanup (xfree, b);
9213
9214   init_breakpoint_sal (b, gdbarch,
9215                        sals, addr_string,
9216                        filter, cond_string, extra_string,
9217                        type, disposition,
9218                        thread, task, ignore_count,
9219                        ops, from_tty,
9220                        enabled, internal, flags,
9221                        display_canonical);
9222   discard_cleanups (old_chain);
9223
9224   install_breakpoint (internal, b, 0);
9225 }
9226
9227 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9228    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9229    value.  COND_STRING, if not NULL, specified the condition to be
9230    used for all breakpoints.  Essentially the only case where
9231    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9232    function.  In that case, it's still not possible to specify
9233    separate conditions for different overloaded functions, so
9234    we take just a single condition string.
9235    
9236    NOTE: If the function succeeds, the caller is expected to cleanup
9237    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9238    array contents).  If the function fails (error() is called), the
9239    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9240    COND and SALS arrays and each of those arrays contents.  */
9241
9242 static void
9243 create_breakpoints_sal (struct gdbarch *gdbarch,
9244                         struct linespec_result *canonical,
9245                         char *cond_string, char *extra_string,
9246                         enum bptype type, enum bpdisp disposition,
9247                         int thread, int task, int ignore_count,
9248                         const struct breakpoint_ops *ops, int from_tty,
9249                         int enabled, int internal, unsigned flags)
9250 {
9251   int i;
9252   struct linespec_sals *lsal;
9253
9254   if (canonical->pre_expanded)
9255     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9256
9257   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9258     {
9259       /* Note that 'addr_string' can be NULL in the case of a plain
9260          'break', without arguments.  */
9261       char *addr_string = (canonical->addr_string
9262                            ? xstrdup (canonical->addr_string)
9263                            : NULL);
9264       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9265       struct cleanup *inner = make_cleanup (xfree, addr_string);
9266
9267       make_cleanup (xfree, filter_string);
9268       create_breakpoint_sal (gdbarch, lsal->sals,
9269                              addr_string,
9270                              filter_string,
9271                              cond_string, extra_string,
9272                              type, disposition,
9273                              thread, task, ignore_count, ops,
9274                              from_tty, enabled, internal, flags,
9275                              canonical->special_display);
9276       discard_cleanups (inner);
9277     }
9278 }
9279
9280 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9281    followed by conditionals.  On return, SALS contains an array of SAL
9282    addresses found.  ADDR_STRING contains a vector of (canonical)
9283    address strings.  ADDRESS points to the end of the SAL.
9284
9285    The array and the line spec strings are allocated on the heap, it is
9286    the caller's responsibility to free them.  */
9287
9288 static void
9289 parse_breakpoint_sals (char **address,
9290                        struct linespec_result *canonical)
9291 {
9292   /* If no arg given, or if first arg is 'if ', use the default
9293      breakpoint.  */
9294   if ((*address) == NULL
9295       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9296     {
9297       /* The last displayed codepoint, if it's valid, is our default breakpoint
9298          address.  */
9299       if (last_displayed_sal_is_valid ())
9300         {
9301           struct linespec_sals lsal;
9302           struct symtab_and_line sal;
9303           CORE_ADDR pc;
9304
9305           init_sal (&sal);              /* Initialize to zeroes.  */
9306           lsal.sals.sals = (struct symtab_and_line *)
9307             xmalloc (sizeof (struct symtab_and_line));
9308
9309           /* Set sal's pspace, pc, symtab, and line to the values
9310              corresponding to the last call to print_frame_info.
9311              Be sure to reinitialize LINE with NOTCURRENT == 0
9312              as the breakpoint line number is inappropriate otherwise.
9313              find_pc_line would adjust PC, re-set it back.  */
9314           get_last_displayed_sal (&sal);
9315           pc = sal.pc;
9316           sal = find_pc_line (pc, 0);
9317
9318           /* "break" without arguments is equivalent to "break *PC"
9319              where PC is the last displayed codepoint's address.  So
9320              make sure to set sal.explicit_pc to prevent GDB from
9321              trying to expand the list of sals to include all other
9322              instances with the same symtab and line.  */
9323           sal.pc = pc;
9324           sal.explicit_pc = 1;
9325
9326           lsal.sals.sals[0] = sal;
9327           lsal.sals.nelts = 1;
9328           lsal.canonical = NULL;
9329
9330           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9331         }
9332       else
9333         error (_("No default breakpoint address now."));
9334     }
9335   else
9336     {
9337       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9338
9339       /* Force almost all breakpoints to be in terms of the
9340          current_source_symtab (which is decode_line_1's default).
9341          This should produce the results we want almost all of the
9342          time while leaving default_breakpoint_* alone.
9343
9344          ObjC: However, don't match an Objective-C method name which
9345          may have a '+' or '-' succeeded by a '['.  */
9346       if (last_displayed_sal_is_valid ()
9347           && (!cursal.symtab
9348               || ((strchr ("+-", (*address)[0]) != NULL)
9349                   && ((*address)[1] != '['))))
9350         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9351                           get_last_displayed_symtab (),
9352                           get_last_displayed_line (),
9353                           canonical, NULL, NULL);
9354       else
9355         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9356                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9357     }
9358 }
9359
9360
9361 /* Convert each SAL into a real PC.  Verify that the PC can be
9362    inserted as a breakpoint.  If it can't throw an error.  */
9363
9364 static void
9365 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9366 {    
9367   int i;
9368
9369   for (i = 0; i < sals->nelts; i++)
9370     resolve_sal_pc (&sals->sals[i]);
9371 }
9372
9373 /* Fast tracepoints may have restrictions on valid locations.  For
9374    instance, a fast tracepoint using a jump instead of a trap will
9375    likely have to overwrite more bytes than a trap would, and so can
9376    only be placed where the instruction is longer than the jump, or a
9377    multi-instruction sequence does not have a jump into the middle of
9378    it, etc.  */
9379
9380 static void
9381 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9382                             struct symtabs_and_lines *sals)
9383 {
9384   int i, rslt;
9385   struct symtab_and_line *sal;
9386   char *msg;
9387   struct cleanup *old_chain;
9388
9389   for (i = 0; i < sals->nelts; i++)
9390     {
9391       struct gdbarch *sarch;
9392
9393       sal = &sals->sals[i];
9394
9395       sarch = get_sal_arch (*sal);
9396       /* We fall back to GDBARCH if there is no architecture
9397          associated with SAL.  */
9398       if (sarch == NULL)
9399         sarch = gdbarch;
9400       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9401                                                NULL, &msg);
9402       old_chain = make_cleanup (xfree, msg);
9403
9404       if (!rslt)
9405         error (_("May not have a fast tracepoint at 0x%s%s"),
9406                paddress (sarch, sal->pc), (msg ? msg : ""));
9407
9408       do_cleanups (old_chain);
9409     }
9410 }
9411
9412 /* Issue an invalid thread ID error.  */
9413
9414 static void ATTRIBUTE_NORETURN
9415 invalid_thread_id_error (int id)
9416 {
9417   error (_("Unknown thread %d."), id);
9418 }
9419
9420 /* Given TOK, a string specification of condition and thread, as
9421    accepted by the 'break' command, extract the condition
9422    string and thread number and set *COND_STRING and *THREAD.
9423    PC identifies the context at which the condition should be parsed.
9424    If no condition is found, *COND_STRING is set to NULL.
9425    If no thread is found, *THREAD is set to -1.  */
9426
9427 static void
9428 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9429                            char **cond_string, int *thread, int *task,
9430                            char **rest)
9431 {
9432   *cond_string = NULL;
9433   *thread = -1;
9434   *task = 0;
9435   *rest = NULL;
9436
9437   while (tok && *tok)
9438     {
9439       const char *end_tok;
9440       int toklen;
9441       const char *cond_start = NULL;
9442       const char *cond_end = NULL;
9443
9444       tok = skip_spaces_const (tok);
9445
9446       if ((*tok == '"' || *tok == ',') && rest)
9447         {
9448           *rest = savestring (tok, strlen (tok));
9449           return;
9450         }
9451
9452       end_tok = skip_to_space_const (tok);
9453
9454       toklen = end_tok - tok;
9455
9456       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9457         {
9458           struct expression *expr;
9459
9460           tok = cond_start = end_tok + 1;
9461           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9462           xfree (expr);
9463           cond_end = tok;
9464           *cond_string = savestring (cond_start, cond_end - cond_start);
9465         }
9466       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9467         {
9468           char *tmptok;
9469
9470           tok = end_tok + 1;
9471           *thread = strtol (tok, &tmptok, 0);
9472           if (tok == tmptok)
9473             error (_("Junk after thread keyword."));
9474           if (!valid_thread_id (*thread))
9475             invalid_thread_id_error (*thread);
9476           tok = tmptok;
9477         }
9478       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9479         {
9480           char *tmptok;
9481
9482           tok = end_tok + 1;
9483           *task = strtol (tok, &tmptok, 0);
9484           if (tok == tmptok)
9485             error (_("Junk after task keyword."));
9486           if (!valid_task_id (*task))
9487             error (_("Unknown task %d."), *task);
9488           tok = tmptok;
9489         }
9490       else if (rest)
9491         {
9492           *rest = savestring (tok, strlen (tok));
9493           return;
9494         }
9495       else
9496         error (_("Junk at end of arguments."));
9497     }
9498 }
9499
9500 /* Decode a static tracepoint marker spec.  */
9501
9502 static struct symtabs_and_lines
9503 decode_static_tracepoint_spec (char **arg_p)
9504 {
9505   VEC(static_tracepoint_marker_p) *markers = NULL;
9506   struct symtabs_and_lines sals;
9507   struct cleanup *old_chain;
9508   char *p = &(*arg_p)[3];
9509   char *endp;
9510   char *marker_str;
9511   int i;
9512
9513   p = skip_spaces (p);
9514
9515   endp = skip_to_space (p);
9516
9517   marker_str = savestring (p, endp - p);
9518   old_chain = make_cleanup (xfree, marker_str);
9519
9520   markers = target_static_tracepoint_markers_by_strid (marker_str);
9521   if (VEC_empty(static_tracepoint_marker_p, markers))
9522     error (_("No known static tracepoint marker named %s"), marker_str);
9523
9524   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9525   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9526
9527   for (i = 0; i < sals.nelts; i++)
9528     {
9529       struct static_tracepoint_marker *marker;
9530
9531       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9532
9533       init_sal (&sals.sals[i]);
9534
9535       sals.sals[i] = find_pc_line (marker->address, 0);
9536       sals.sals[i].pc = marker->address;
9537
9538       release_static_tracepoint_marker (marker);
9539     }
9540
9541   do_cleanups (old_chain);
9542
9543   *arg_p = endp;
9544   return sals;
9545 }
9546
9547 /* Set a breakpoint.  This function is shared between CLI and MI
9548    functions for setting a breakpoint.  This function has two major
9549    modes of operations, selected by the PARSE_ARG parameter.  If
9550    non-zero, the function will parse ARG, extracting location,
9551    condition, thread and extra string.  Otherwise, ARG is just the
9552    breakpoint's location, with condition, thread, and extra string
9553    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9554    If INTERNAL is non-zero, the breakpoint number will be allocated
9555    from the internal breakpoint count.  Returns true if any breakpoint
9556    was created; false otherwise.  */
9557
9558 int
9559 create_breakpoint (struct gdbarch *gdbarch,
9560                    char *arg, char *cond_string,
9561                    int thread, char *extra_string,
9562                    int parse_arg,
9563                    int tempflag, enum bptype type_wanted,
9564                    int ignore_count,
9565                    enum auto_boolean pending_break_support,
9566                    const struct breakpoint_ops *ops,
9567                    int from_tty, int enabled, int internal,
9568                    unsigned flags)
9569 {
9570   volatile struct gdb_exception e;
9571   char *copy_arg = NULL;
9572   char *addr_start = arg;
9573   struct linespec_result canonical;
9574   struct cleanup *old_chain;
9575   struct cleanup *bkpt_chain = NULL;
9576   int pending = 0;
9577   int task = 0;
9578   int prev_bkpt_count = breakpoint_count;
9579
9580   gdb_assert (ops != NULL);
9581
9582   init_linespec_result (&canonical);
9583
9584   TRY_CATCH (e, RETURN_MASK_ALL)
9585     {
9586       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9587                                      addr_start, &copy_arg);
9588     }
9589
9590   /* If caller is interested in rc value from parse, set value.  */
9591   switch (e.reason)
9592     {
9593     case GDB_NO_ERROR:
9594       if (VEC_empty (linespec_sals, canonical.sals))
9595         return 0;
9596       break;
9597     case RETURN_ERROR:
9598       switch (e.error)
9599         {
9600         case NOT_FOUND_ERROR:
9601
9602           /* If pending breakpoint support is turned off, throw
9603              error.  */
9604
9605           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9606             throw_exception (e);
9607
9608           exception_print (gdb_stderr, e);
9609
9610           /* If pending breakpoint support is auto query and the user
9611              selects no, then simply return the error code.  */
9612           if (pending_break_support == AUTO_BOOLEAN_AUTO
9613               && !nquery (_("Make %s pending on future shared library load? "),
9614                           bptype_string (type_wanted)))
9615             return 0;
9616
9617           /* At this point, either the user was queried about setting
9618              a pending breakpoint and selected yes, or pending
9619              breakpoint behavior is on and thus a pending breakpoint
9620              is defaulted on behalf of the user.  */
9621           {
9622             struct linespec_sals lsal;
9623
9624             copy_arg = xstrdup (addr_start);
9625             lsal.canonical = xstrdup (copy_arg);
9626             lsal.sals.nelts = 1;
9627             lsal.sals.sals = XNEW (struct symtab_and_line);
9628             init_sal (&lsal.sals.sals[0]);
9629             pending = 1;
9630             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9631           }
9632           break;
9633         default:
9634           throw_exception (e);
9635         }
9636       break;
9637     default:
9638       throw_exception (e);
9639     }
9640
9641   /* Create a chain of things that always need to be cleaned up.  */
9642   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9643
9644   /* ----------------------------- SNIP -----------------------------
9645      Anything added to the cleanup chain beyond this point is assumed
9646      to be part of a breakpoint.  If the breakpoint create succeeds
9647      then the memory is not reclaimed.  */
9648   bkpt_chain = make_cleanup (null_cleanup, 0);
9649
9650   /* Resolve all line numbers to PC's and verify that the addresses
9651      are ok for the target.  */
9652   if (!pending)
9653     {
9654       int ix;
9655       struct linespec_sals *iter;
9656
9657       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9658         breakpoint_sals_to_pc (&iter->sals);
9659     }
9660
9661   /* Fast tracepoints may have additional restrictions on location.  */
9662   if (!pending && type_wanted == bp_fast_tracepoint)
9663     {
9664       int ix;
9665       struct linespec_sals *iter;
9666
9667       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9668         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9669     }
9670
9671   /* Verify that condition can be parsed, before setting any
9672      breakpoints.  Allocate a separate condition expression for each
9673      breakpoint.  */
9674   if (!pending)
9675     {
9676       if (parse_arg)
9677         {
9678           char *rest;
9679           struct linespec_sals *lsal;
9680
9681           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9682
9683           /* Here we only parse 'arg' to separate condition
9684              from thread number, so parsing in context of first
9685              sal is OK.  When setting the breakpoint we'll
9686              re-parse it in context of each sal.  */
9687
9688           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9689                                      &thread, &task, &rest);
9690           if (cond_string)
9691             make_cleanup (xfree, cond_string);
9692           if (rest)
9693             make_cleanup (xfree, rest);
9694           if (rest)
9695             extra_string = rest;
9696         }
9697       else
9698         {
9699           if (*arg != '\0')
9700             error (_("Garbage '%s' at end of location"), arg);
9701
9702           /* Create a private copy of condition string.  */
9703           if (cond_string)
9704             {
9705               cond_string = xstrdup (cond_string);
9706               make_cleanup (xfree, cond_string);
9707             }
9708           /* Create a private copy of any extra string.  */
9709           if (extra_string)
9710             {
9711               extra_string = xstrdup (extra_string);
9712               make_cleanup (xfree, extra_string);
9713             }
9714         }
9715
9716       ops->create_breakpoints_sal (gdbarch, &canonical,
9717                                    cond_string, extra_string, type_wanted,
9718                                    tempflag ? disp_del : disp_donttouch,
9719                                    thread, task, ignore_count, ops,
9720                                    from_tty, enabled, internal, flags);
9721     }
9722   else
9723     {
9724       struct breakpoint *b;
9725
9726       make_cleanup (xfree, copy_arg);
9727
9728       if (is_tracepoint_type (type_wanted))
9729         {
9730           struct tracepoint *t;
9731
9732           t = XCNEW (struct tracepoint);
9733           b = &t->base;
9734         }
9735       else
9736         b = XNEW (struct breakpoint);
9737
9738       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9739
9740       b->addr_string = copy_arg;
9741       if (parse_arg)
9742         b->cond_string = NULL;
9743       else
9744         {
9745           /* Create a private copy of condition string.  */
9746           if (cond_string)
9747             {
9748               cond_string = xstrdup (cond_string);
9749               make_cleanup (xfree, cond_string);
9750             }
9751           b->cond_string = cond_string;
9752         }
9753       b->extra_string = NULL;
9754       b->ignore_count = ignore_count;
9755       b->disposition = tempflag ? disp_del : disp_donttouch;
9756       b->condition_not_parsed = 1;
9757       b->enable_state = enabled ? bp_enabled : bp_disabled;
9758       if ((type_wanted != bp_breakpoint
9759            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9760         b->pspace = current_program_space;
9761
9762       install_breakpoint (internal, b, 0);
9763     }
9764   
9765   if (VEC_length (linespec_sals, canonical.sals) > 1)
9766     {
9767       warning (_("Multiple breakpoints were set.\nUse the "
9768                  "\"delete\" command to delete unwanted breakpoints."));
9769       prev_breakpoint_count = prev_bkpt_count;
9770     }
9771
9772   /* That's it.  Discard the cleanups for data inserted into the
9773      breakpoint.  */
9774   discard_cleanups (bkpt_chain);
9775   /* But cleanup everything else.  */
9776   do_cleanups (old_chain);
9777
9778   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9779   update_global_location_list (1);
9780
9781   return 1;
9782 }
9783
9784 /* Set a breakpoint.
9785    ARG is a string describing breakpoint address,
9786    condition, and thread.
9787    FLAG specifies if a breakpoint is hardware on,
9788    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9789    and BP_TEMPFLAG.  */
9790
9791 static void
9792 break_command_1 (char *arg, int flag, int from_tty)
9793 {
9794   int tempflag = flag & BP_TEMPFLAG;
9795   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9796                              ? bp_hardware_breakpoint
9797                              : bp_breakpoint);
9798   struct breakpoint_ops *ops;
9799   const char *arg_cp = arg;
9800
9801   /* Matching breakpoints on probes.  */
9802   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9803     ops = &bkpt_probe_breakpoint_ops;
9804   else
9805     ops = &bkpt_breakpoint_ops;
9806
9807   create_breakpoint (get_current_arch (),
9808                      arg,
9809                      NULL, 0, NULL, 1 /* parse arg */,
9810                      tempflag, type_wanted,
9811                      0 /* Ignore count */,
9812                      pending_break_support,
9813                      ops,
9814                      from_tty,
9815                      1 /* enabled */,
9816                      0 /* internal */,
9817                      0);
9818 }
9819
9820 /* Helper function for break_command_1 and disassemble_command.  */
9821
9822 void
9823 resolve_sal_pc (struct symtab_and_line *sal)
9824 {
9825   CORE_ADDR pc;
9826
9827   if (sal->pc == 0 && sal->symtab != NULL)
9828     {
9829       if (!find_line_pc (sal->symtab, sal->line, &pc))
9830         error (_("No line %d in file \"%s\"."),
9831                sal->line, symtab_to_filename_for_display (sal->symtab));
9832       sal->pc = pc;
9833
9834       /* If this SAL corresponds to a breakpoint inserted using a line
9835          number, then skip the function prologue if necessary.  */
9836       if (sal->explicit_line)
9837         skip_prologue_sal (sal);
9838     }
9839
9840   if (sal->section == 0 && sal->symtab != NULL)
9841     {
9842       struct blockvector *bv;
9843       struct block *b;
9844       struct symbol *sym;
9845
9846       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9847       if (bv != NULL)
9848         {
9849           sym = block_linkage_function (b);
9850           if (sym != NULL)
9851             {
9852               fixup_symbol_section (sym, sal->symtab->objfile);
9853               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
9854             }
9855           else
9856             {
9857               /* It really is worthwhile to have the section, so we'll
9858                  just have to look harder. This case can be executed
9859                  if we have line numbers but no functions (as can
9860                  happen in assembly source).  */
9861
9862               struct bound_minimal_symbol msym;
9863               struct cleanup *old_chain = save_current_space_and_thread ();
9864
9865               switch_to_program_space_and_thread (sal->pspace);
9866
9867               msym = lookup_minimal_symbol_by_pc (sal->pc);
9868               if (msym.minsym)
9869                 sal->section = SYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9870
9871               do_cleanups (old_chain);
9872             }
9873         }
9874     }
9875 }
9876
9877 void
9878 break_command (char *arg, int from_tty)
9879 {
9880   break_command_1 (arg, 0, from_tty);
9881 }
9882
9883 void
9884 tbreak_command (char *arg, int from_tty)
9885 {
9886   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9887 }
9888
9889 static void
9890 hbreak_command (char *arg, int from_tty)
9891 {
9892   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9893 }
9894
9895 static void
9896 thbreak_command (char *arg, int from_tty)
9897 {
9898   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9899 }
9900
9901 static void
9902 stop_command (char *arg, int from_tty)
9903 {
9904   printf_filtered (_("Specify the type of breakpoint to set.\n\
9905 Usage: stop in <function | address>\n\
9906        stop at <line>\n"));
9907 }
9908
9909 static void
9910 stopin_command (char *arg, int from_tty)
9911 {
9912   int badInput = 0;
9913
9914   if (arg == (char *) NULL)
9915     badInput = 1;
9916   else if (*arg != '*')
9917     {
9918       char *argptr = arg;
9919       int hasColon = 0;
9920
9921       /* Look for a ':'.  If this is a line number specification, then
9922          say it is bad, otherwise, it should be an address or
9923          function/method name.  */
9924       while (*argptr && !hasColon)
9925         {
9926           hasColon = (*argptr == ':');
9927           argptr++;
9928         }
9929
9930       if (hasColon)
9931         badInput = (*argptr != ':');    /* Not a class::method */
9932       else
9933         badInput = isdigit (*arg);      /* a simple line number */
9934     }
9935
9936   if (badInput)
9937     printf_filtered (_("Usage: stop in <function | address>\n"));
9938   else
9939     break_command_1 (arg, 0, from_tty);
9940 }
9941
9942 static void
9943 stopat_command (char *arg, int from_tty)
9944 {
9945   int badInput = 0;
9946
9947   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9948     badInput = 1;
9949   else
9950     {
9951       char *argptr = arg;
9952       int hasColon = 0;
9953
9954       /* Look for a ':'.  If there is a '::' then get out, otherwise
9955          it is probably a line number.  */
9956       while (*argptr && !hasColon)
9957         {
9958           hasColon = (*argptr == ':');
9959           argptr++;
9960         }
9961
9962       if (hasColon)
9963         badInput = (*argptr == ':');    /* we have class::method */
9964       else
9965         badInput = !isdigit (*arg);     /* not a line number */
9966     }
9967
9968   if (badInput)
9969     printf_filtered (_("Usage: stop at <line>\n"));
9970   else
9971     break_command_1 (arg, 0, from_tty);
9972 }
9973
9974 /* The dynamic printf command is mostly like a regular breakpoint, but
9975    with a prewired command list consisting of a single output command,
9976    built from extra arguments supplied on the dprintf command
9977    line.  */
9978
9979 static void
9980 dprintf_command (char *arg, int from_tty)
9981 {
9982   create_breakpoint (get_current_arch (),
9983                      arg,
9984                      NULL, 0, NULL, 1 /* parse arg */,
9985                      0, bp_dprintf,
9986                      0 /* Ignore count */,
9987                      pending_break_support,
9988                      &dprintf_breakpoint_ops,
9989                      from_tty,
9990                      1 /* enabled */,
9991                      0 /* internal */,
9992                      0);
9993 }
9994
9995 static void
9996 agent_printf_command (char *arg, int from_tty)
9997 {
9998   error (_("May only run agent-printf on the target"));
9999 }
10000
10001 /* Implement the "breakpoint_hit" breakpoint_ops method for
10002    ranged breakpoints.  */
10003
10004 static int
10005 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10006                                   struct address_space *aspace,
10007                                   CORE_ADDR bp_addr,
10008                                   const struct target_waitstatus *ws)
10009 {
10010   if (ws->kind != TARGET_WAITKIND_STOPPED
10011       || ws->value.sig != GDB_SIGNAL_TRAP)
10012     return 0;
10013
10014   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10015                                          bl->length, aspace, bp_addr);
10016 }
10017
10018 /* Implement the "resources_needed" breakpoint_ops method for
10019    ranged breakpoints.  */
10020
10021 static int
10022 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10023 {
10024   return target_ranged_break_num_registers ();
10025 }
10026
10027 /* Implement the "print_it" breakpoint_ops method for
10028    ranged breakpoints.  */
10029
10030 static enum print_stop_action
10031 print_it_ranged_breakpoint (bpstat bs)
10032 {
10033   struct breakpoint *b = bs->breakpoint_at;
10034   struct bp_location *bl = b->loc;
10035   struct ui_out *uiout = current_uiout;
10036
10037   gdb_assert (b->type == bp_hardware_breakpoint);
10038
10039   /* Ranged breakpoints have only one location.  */
10040   gdb_assert (bl && bl->next == NULL);
10041
10042   annotate_breakpoint (b->number);
10043   if (b->disposition == disp_del)
10044     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10045   else
10046     ui_out_text (uiout, "\nRanged breakpoint ");
10047   if (ui_out_is_mi_like_p (uiout))
10048     {
10049       ui_out_field_string (uiout, "reason",
10050                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10051       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10052     }
10053   ui_out_field_int (uiout, "bkptno", b->number);
10054   ui_out_text (uiout, ", ");
10055
10056   return PRINT_SRC_AND_LOC;
10057 }
10058
10059 /* Implement the "print_one" breakpoint_ops method for
10060    ranged breakpoints.  */
10061
10062 static void
10063 print_one_ranged_breakpoint (struct breakpoint *b,
10064                              struct bp_location **last_loc)
10065 {
10066   struct bp_location *bl = b->loc;
10067   struct value_print_options opts;
10068   struct ui_out *uiout = current_uiout;
10069
10070   /* Ranged breakpoints have only one location.  */
10071   gdb_assert (bl && bl->next == NULL);
10072
10073   get_user_print_options (&opts);
10074
10075   if (opts.addressprint)
10076     /* We don't print the address range here, it will be printed later
10077        by print_one_detail_ranged_breakpoint.  */
10078     ui_out_field_skip (uiout, "addr");
10079   annotate_field (5);
10080   print_breakpoint_location (b, bl);
10081   *last_loc = bl;
10082 }
10083
10084 /* Implement the "print_one_detail" breakpoint_ops method for
10085    ranged breakpoints.  */
10086
10087 static void
10088 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10089                                     struct ui_out *uiout)
10090 {
10091   CORE_ADDR address_start, address_end;
10092   struct bp_location *bl = b->loc;
10093   struct ui_file *stb = mem_fileopen ();
10094   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10095
10096   gdb_assert (bl);
10097
10098   address_start = bl->address;
10099   address_end = address_start + bl->length - 1;
10100
10101   ui_out_text (uiout, "\taddress range: ");
10102   fprintf_unfiltered (stb, "[%s, %s]",
10103                       print_core_address (bl->gdbarch, address_start),
10104                       print_core_address (bl->gdbarch, address_end));
10105   ui_out_field_stream (uiout, "addr", stb);
10106   ui_out_text (uiout, "\n");
10107
10108   do_cleanups (cleanup);
10109 }
10110
10111 /* Implement the "print_mention" breakpoint_ops method for
10112    ranged breakpoints.  */
10113
10114 static void
10115 print_mention_ranged_breakpoint (struct breakpoint *b)
10116 {
10117   struct bp_location *bl = b->loc;
10118   struct ui_out *uiout = current_uiout;
10119
10120   gdb_assert (bl);
10121   gdb_assert (b->type == bp_hardware_breakpoint);
10122
10123   if (ui_out_is_mi_like_p (uiout))
10124     return;
10125
10126   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10127                    b->number, paddress (bl->gdbarch, bl->address),
10128                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10129 }
10130
10131 /* Implement the "print_recreate" breakpoint_ops method for
10132    ranged breakpoints.  */
10133
10134 static void
10135 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10136 {
10137   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10138                       b->addr_string_range_end);
10139   print_recreate_thread (b, fp);
10140 }
10141
10142 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10143
10144 static struct breakpoint_ops ranged_breakpoint_ops;
10145
10146 /* Find the address where the end of the breakpoint range should be
10147    placed, given the SAL of the end of the range.  This is so that if
10148    the user provides a line number, the end of the range is set to the
10149    last instruction of the given line.  */
10150
10151 static CORE_ADDR
10152 find_breakpoint_range_end (struct symtab_and_line sal)
10153 {
10154   CORE_ADDR end;
10155
10156   /* If the user provided a PC value, use it.  Otherwise,
10157      find the address of the end of the given location.  */
10158   if (sal.explicit_pc)
10159     end = sal.pc;
10160   else
10161     {
10162       int ret;
10163       CORE_ADDR start;
10164
10165       ret = find_line_pc_range (sal, &start, &end);
10166       if (!ret)
10167         error (_("Could not find location of the end of the range."));
10168
10169       /* find_line_pc_range returns the start of the next line.  */
10170       end--;
10171     }
10172
10173   return end;
10174 }
10175
10176 /* Implement the "break-range" CLI command.  */
10177
10178 static void
10179 break_range_command (char *arg, int from_tty)
10180 {
10181   char *arg_start, *addr_string_start, *addr_string_end;
10182   struct linespec_result canonical_start, canonical_end;
10183   int bp_count, can_use_bp, length;
10184   CORE_ADDR end;
10185   struct breakpoint *b;
10186   struct symtab_and_line sal_start, sal_end;
10187   struct cleanup *cleanup_bkpt;
10188   struct linespec_sals *lsal_start, *lsal_end;
10189
10190   /* We don't support software ranged breakpoints.  */
10191   if (target_ranged_break_num_registers () < 0)
10192     error (_("This target does not support hardware ranged breakpoints."));
10193
10194   bp_count = hw_breakpoint_used_count ();
10195   bp_count += target_ranged_break_num_registers ();
10196   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10197                                                    bp_count, 0);
10198   if (can_use_bp < 0)
10199     error (_("Hardware breakpoints used exceeds limit."));
10200
10201   arg = skip_spaces (arg);
10202   if (arg == NULL || arg[0] == '\0')
10203     error(_("No address range specified."));
10204
10205   init_linespec_result (&canonical_start);
10206
10207   arg_start = arg;
10208   parse_breakpoint_sals (&arg, &canonical_start);
10209
10210   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10211
10212   if (arg[0] != ',')
10213     error (_("Too few arguments."));
10214   else if (VEC_empty (linespec_sals, canonical_start.sals))
10215     error (_("Could not find location of the beginning of the range."));
10216
10217   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10218
10219   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10220       || lsal_start->sals.nelts != 1)
10221     error (_("Cannot create a ranged breakpoint with multiple locations."));
10222
10223   sal_start = lsal_start->sals.sals[0];
10224   addr_string_start = savestring (arg_start, arg - arg_start);
10225   make_cleanup (xfree, addr_string_start);
10226
10227   arg++;        /* Skip the comma.  */
10228   arg = skip_spaces (arg);
10229
10230   /* Parse the end location.  */
10231
10232   init_linespec_result (&canonical_end);
10233   arg_start = arg;
10234
10235   /* We call decode_line_full directly here instead of using
10236      parse_breakpoint_sals because we need to specify the start location's
10237      symtab and line as the default symtab and line for the end of the
10238      range.  This makes it possible to have ranges like "foo.c:27, +14",
10239      where +14 means 14 lines from the start location.  */
10240   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10241                     sal_start.symtab, sal_start.line,
10242                     &canonical_end, NULL, NULL);
10243
10244   make_cleanup_destroy_linespec_result (&canonical_end);
10245
10246   if (VEC_empty (linespec_sals, canonical_end.sals))
10247     error (_("Could not find location of the end of the range."));
10248
10249   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10250   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10251       || lsal_end->sals.nelts != 1)
10252     error (_("Cannot create a ranged breakpoint with multiple locations."));
10253
10254   sal_end = lsal_end->sals.sals[0];
10255   addr_string_end = savestring (arg_start, arg - arg_start);
10256   make_cleanup (xfree, addr_string_end);
10257
10258   end = find_breakpoint_range_end (sal_end);
10259   if (sal_start.pc > end)
10260     error (_("Invalid address range, end precedes start."));
10261
10262   length = end - sal_start.pc + 1;
10263   if (length < 0)
10264     /* Length overflowed.  */
10265     error (_("Address range too large."));
10266   else if (length == 1)
10267     {
10268       /* This range is simple enough to be handled by
10269          the `hbreak' command.  */
10270       hbreak_command (addr_string_start, 1);
10271
10272       do_cleanups (cleanup_bkpt);
10273
10274       return;
10275     }
10276
10277   /* Now set up the breakpoint.  */
10278   b = set_raw_breakpoint (get_current_arch (), sal_start,
10279                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10280   set_breakpoint_count (breakpoint_count + 1);
10281   b->number = breakpoint_count;
10282   b->disposition = disp_donttouch;
10283   b->addr_string = xstrdup (addr_string_start);
10284   b->addr_string_range_end = xstrdup (addr_string_end);
10285   b->loc->length = length;
10286
10287   do_cleanups (cleanup_bkpt);
10288
10289   mention (b);
10290   observer_notify_breakpoint_created (b);
10291   update_global_location_list (1);
10292 }
10293
10294 /*  Return non-zero if EXP is verified as constant.  Returned zero
10295     means EXP is variable.  Also the constant detection may fail for
10296     some constant expressions and in such case still falsely return
10297     zero.  */
10298
10299 static int
10300 watchpoint_exp_is_const (const struct expression *exp)
10301 {
10302   int i = exp->nelts;
10303
10304   while (i > 0)
10305     {
10306       int oplenp, argsp;
10307
10308       /* We are only interested in the descriptor of each element.  */
10309       operator_length (exp, i, &oplenp, &argsp);
10310       i -= oplenp;
10311
10312       switch (exp->elts[i].opcode)
10313         {
10314         case BINOP_ADD:
10315         case BINOP_SUB:
10316         case BINOP_MUL:
10317         case BINOP_DIV:
10318         case BINOP_REM:
10319         case BINOP_MOD:
10320         case BINOP_LSH:
10321         case BINOP_RSH:
10322         case BINOP_LOGICAL_AND:
10323         case BINOP_LOGICAL_OR:
10324         case BINOP_BITWISE_AND:
10325         case BINOP_BITWISE_IOR:
10326         case BINOP_BITWISE_XOR:
10327         case BINOP_EQUAL:
10328         case BINOP_NOTEQUAL:
10329         case BINOP_LESS:
10330         case BINOP_GTR:
10331         case BINOP_LEQ:
10332         case BINOP_GEQ:
10333         case BINOP_REPEAT:
10334         case BINOP_COMMA:
10335         case BINOP_EXP:
10336         case BINOP_MIN:
10337         case BINOP_MAX:
10338         case BINOP_INTDIV:
10339         case BINOP_CONCAT:
10340         case BINOP_IN:
10341         case BINOP_RANGE:
10342         case TERNOP_COND:
10343         case TERNOP_SLICE:
10344
10345         case OP_LONG:
10346         case OP_DOUBLE:
10347         case OP_DECFLOAT:
10348         case OP_LAST:
10349         case OP_COMPLEX:
10350         case OP_STRING:
10351         case OP_ARRAY:
10352         case OP_TYPE:
10353         case OP_TYPEOF:
10354         case OP_DECLTYPE:
10355         case OP_TYPEID:
10356         case OP_NAME:
10357         case OP_OBJC_NSSTRING:
10358
10359         case UNOP_NEG:
10360         case UNOP_LOGICAL_NOT:
10361         case UNOP_COMPLEMENT:
10362         case UNOP_ADDR:
10363         case UNOP_HIGH:
10364         case UNOP_CAST:
10365
10366         case UNOP_CAST_TYPE:
10367         case UNOP_REINTERPRET_CAST:
10368         case UNOP_DYNAMIC_CAST:
10369           /* Unary, binary and ternary operators: We have to check
10370              their operands.  If they are constant, then so is the
10371              result of that operation.  For instance, if A and B are
10372              determined to be constants, then so is "A + B".
10373
10374              UNOP_IND is one exception to the rule above, because the
10375              value of *ADDR is not necessarily a constant, even when
10376              ADDR is.  */
10377           break;
10378
10379         case OP_VAR_VALUE:
10380           /* Check whether the associated symbol is a constant.
10381
10382              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10383              possible that a buggy compiler could mark a variable as
10384              constant even when it is not, and TYPE_CONST would return
10385              true in this case, while SYMBOL_CLASS wouldn't.
10386
10387              We also have to check for function symbols because they
10388              are always constant.  */
10389           {
10390             struct symbol *s = exp->elts[i + 2].symbol;
10391
10392             if (SYMBOL_CLASS (s) != LOC_BLOCK
10393                 && SYMBOL_CLASS (s) != LOC_CONST
10394                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10395               return 0;
10396             break;
10397           }
10398
10399         /* The default action is to return 0 because we are using
10400            the optimistic approach here: If we don't know something,
10401            then it is not a constant.  */
10402         default:
10403           return 0;
10404         }
10405     }
10406
10407   return 1;
10408 }
10409
10410 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10411
10412 static void
10413 dtor_watchpoint (struct breakpoint *self)
10414 {
10415   struct watchpoint *w = (struct watchpoint *) self;
10416
10417   xfree (w->cond_exp);
10418   xfree (w->exp);
10419   xfree (w->exp_string);
10420   xfree (w->exp_string_reparse);
10421   value_free (w->val);
10422
10423   base_breakpoint_ops.dtor (self);
10424 }
10425
10426 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10427
10428 static void
10429 re_set_watchpoint (struct breakpoint *b)
10430 {
10431   struct watchpoint *w = (struct watchpoint *) b;
10432
10433   /* Watchpoint can be either on expression using entirely global
10434      variables, or it can be on local variables.
10435
10436      Watchpoints of the first kind are never auto-deleted, and even
10437      persist across program restarts.  Since they can use variables
10438      from shared libraries, we need to reparse expression as libraries
10439      are loaded and unloaded.
10440
10441      Watchpoints on local variables can also change meaning as result
10442      of solib event.  For example, if a watchpoint uses both a local
10443      and a global variables in expression, it's a local watchpoint,
10444      but unloading of a shared library will make the expression
10445      invalid.  This is not a very common use case, but we still
10446      re-evaluate expression, to avoid surprises to the user.
10447
10448      Note that for local watchpoints, we re-evaluate it only if
10449      watchpoints frame id is still valid.  If it's not, it means the
10450      watchpoint is out of scope and will be deleted soon.  In fact,
10451      I'm not sure we'll ever be called in this case.
10452
10453      If a local watchpoint's frame id is still valid, then
10454      w->exp_valid_block is likewise valid, and we can safely use it.
10455
10456      Don't do anything about disabled watchpoints, since they will be
10457      reevaluated again when enabled.  */
10458   update_watchpoint (w, 1 /* reparse */);
10459 }
10460
10461 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10462
10463 static int
10464 insert_watchpoint (struct bp_location *bl)
10465 {
10466   struct watchpoint *w = (struct watchpoint *) bl->owner;
10467   int length = w->exact ? 1 : bl->length;
10468
10469   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10470                                    w->cond_exp);
10471 }
10472
10473 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10474
10475 static int
10476 remove_watchpoint (struct bp_location *bl)
10477 {
10478   struct watchpoint *w = (struct watchpoint *) bl->owner;
10479   int length = w->exact ? 1 : bl->length;
10480
10481   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10482                                    w->cond_exp);
10483 }
10484
10485 static int
10486 breakpoint_hit_watchpoint (const struct bp_location *bl,
10487                            struct address_space *aspace, CORE_ADDR bp_addr,
10488                            const struct target_waitstatus *ws)
10489 {
10490   struct breakpoint *b = bl->owner;
10491   struct watchpoint *w = (struct watchpoint *) b;
10492
10493   /* Continuable hardware watchpoints are treated as non-existent if the
10494      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10495      some data address).  Otherwise gdb won't stop on a break instruction
10496      in the code (not from a breakpoint) when a hardware watchpoint has
10497      been defined.  Also skip watchpoints which we know did not trigger
10498      (did not match the data address).  */
10499   if (is_hardware_watchpoint (b)
10500       && w->watchpoint_triggered == watch_triggered_no)
10501     return 0;
10502
10503   return 1;
10504 }
10505
10506 static void
10507 check_status_watchpoint (bpstat bs)
10508 {
10509   gdb_assert (is_watchpoint (bs->breakpoint_at));
10510
10511   bpstat_check_watchpoint (bs);
10512 }
10513
10514 /* Implement the "resources_needed" breakpoint_ops method for
10515    hardware watchpoints.  */
10516
10517 static int
10518 resources_needed_watchpoint (const struct bp_location *bl)
10519 {
10520   struct watchpoint *w = (struct watchpoint *) bl->owner;
10521   int length = w->exact? 1 : bl->length;
10522
10523   return target_region_ok_for_hw_watchpoint (bl->address, length);
10524 }
10525
10526 /* Implement the "works_in_software_mode" breakpoint_ops method for
10527    hardware watchpoints.  */
10528
10529 static int
10530 works_in_software_mode_watchpoint (const struct breakpoint *b)
10531 {
10532   /* Read and access watchpoints only work with hardware support.  */
10533   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10534 }
10535
10536 static enum print_stop_action
10537 print_it_watchpoint (bpstat bs)
10538 {
10539   struct cleanup *old_chain;
10540   struct breakpoint *b;
10541   struct ui_file *stb;
10542   enum print_stop_action result;
10543   struct watchpoint *w;
10544   struct ui_out *uiout = current_uiout;
10545
10546   gdb_assert (bs->bp_location_at != NULL);
10547
10548   b = bs->breakpoint_at;
10549   w = (struct watchpoint *) b;
10550
10551   stb = mem_fileopen ();
10552   old_chain = make_cleanup_ui_file_delete (stb);
10553
10554   switch (b->type)
10555     {
10556     case bp_watchpoint:
10557     case bp_hardware_watchpoint:
10558       annotate_watchpoint (b->number);
10559       if (ui_out_is_mi_like_p (uiout))
10560         ui_out_field_string
10561           (uiout, "reason",
10562            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10563       mention (b);
10564       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10565       ui_out_text (uiout, "\nOld value = ");
10566       watchpoint_value_print (bs->old_val, stb);
10567       ui_out_field_stream (uiout, "old", stb);
10568       ui_out_text (uiout, "\nNew value = ");
10569       watchpoint_value_print (w->val, stb);
10570       ui_out_field_stream (uiout, "new", stb);
10571       ui_out_text (uiout, "\n");
10572       /* More than one watchpoint may have been triggered.  */
10573       result = PRINT_UNKNOWN;
10574       break;
10575
10576     case bp_read_watchpoint:
10577       if (ui_out_is_mi_like_p (uiout))
10578         ui_out_field_string
10579           (uiout, "reason",
10580            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10581       mention (b);
10582       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10583       ui_out_text (uiout, "\nValue = ");
10584       watchpoint_value_print (w->val, stb);
10585       ui_out_field_stream (uiout, "value", stb);
10586       ui_out_text (uiout, "\n");
10587       result = PRINT_UNKNOWN;
10588       break;
10589
10590     case bp_access_watchpoint:
10591       if (bs->old_val != NULL)
10592         {
10593           annotate_watchpoint (b->number);
10594           if (ui_out_is_mi_like_p (uiout))
10595             ui_out_field_string
10596               (uiout, "reason",
10597                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10598           mention (b);
10599           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10600           ui_out_text (uiout, "\nOld value = ");
10601           watchpoint_value_print (bs->old_val, stb);
10602           ui_out_field_stream (uiout, "old", stb);
10603           ui_out_text (uiout, "\nNew value = ");
10604         }
10605       else
10606         {
10607           mention (b);
10608           if (ui_out_is_mi_like_p (uiout))
10609             ui_out_field_string
10610               (uiout, "reason",
10611                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10612           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10613           ui_out_text (uiout, "\nValue = ");
10614         }
10615       watchpoint_value_print (w->val, stb);
10616       ui_out_field_stream (uiout, "new", stb);
10617       ui_out_text (uiout, "\n");
10618       result = PRINT_UNKNOWN;
10619       break;
10620     default:
10621       result = PRINT_UNKNOWN;
10622     }
10623
10624   do_cleanups (old_chain);
10625   return result;
10626 }
10627
10628 /* Implement the "print_mention" breakpoint_ops method for hardware
10629    watchpoints.  */
10630
10631 static void
10632 print_mention_watchpoint (struct breakpoint *b)
10633 {
10634   struct cleanup *ui_out_chain;
10635   struct watchpoint *w = (struct watchpoint *) b;
10636   struct ui_out *uiout = current_uiout;
10637
10638   switch (b->type)
10639     {
10640     case bp_watchpoint:
10641       ui_out_text (uiout, "Watchpoint ");
10642       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10643       break;
10644     case bp_hardware_watchpoint:
10645       ui_out_text (uiout, "Hardware watchpoint ");
10646       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10647       break;
10648     case bp_read_watchpoint:
10649       ui_out_text (uiout, "Hardware read watchpoint ");
10650       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10651       break;
10652     case bp_access_watchpoint:
10653       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10654       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10655       break;
10656     default:
10657       internal_error (__FILE__, __LINE__,
10658                       _("Invalid hardware watchpoint type."));
10659     }
10660
10661   ui_out_field_int (uiout, "number", b->number);
10662   ui_out_text (uiout, ": ");
10663   ui_out_field_string (uiout, "exp", w->exp_string);
10664   do_cleanups (ui_out_chain);
10665 }
10666
10667 /* Implement the "print_recreate" breakpoint_ops method for
10668    watchpoints.  */
10669
10670 static void
10671 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10672 {
10673   struct watchpoint *w = (struct watchpoint *) b;
10674
10675   switch (b->type)
10676     {
10677     case bp_watchpoint:
10678     case bp_hardware_watchpoint:
10679       fprintf_unfiltered (fp, "watch");
10680       break;
10681     case bp_read_watchpoint:
10682       fprintf_unfiltered (fp, "rwatch");
10683       break;
10684     case bp_access_watchpoint:
10685       fprintf_unfiltered (fp, "awatch");
10686       break;
10687     default:
10688       internal_error (__FILE__, __LINE__,
10689                       _("Invalid watchpoint type."));
10690     }
10691
10692   fprintf_unfiltered (fp, " %s", w->exp_string);
10693   print_recreate_thread (b, fp);
10694 }
10695
10696 /* Implement the "explains_signal" breakpoint_ops method for
10697    watchpoints.  */
10698
10699 static enum bpstat_signal_value
10700 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10701 {
10702   /* A software watchpoint cannot cause a signal other than
10703      GDB_SIGNAL_TRAP.  */
10704   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10705     return BPSTAT_SIGNAL_NO;
10706
10707   return BPSTAT_SIGNAL_HIDE;
10708 }
10709
10710 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10711
10712 static struct breakpoint_ops watchpoint_breakpoint_ops;
10713
10714 /* Implement the "insert" breakpoint_ops method for
10715    masked hardware watchpoints.  */
10716
10717 static int
10718 insert_masked_watchpoint (struct bp_location *bl)
10719 {
10720   struct watchpoint *w = (struct watchpoint *) bl->owner;
10721
10722   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10723                                         bl->watchpoint_type);
10724 }
10725
10726 /* Implement the "remove" breakpoint_ops method for
10727    masked hardware watchpoints.  */
10728
10729 static int
10730 remove_masked_watchpoint (struct bp_location *bl)
10731 {
10732   struct watchpoint *w = (struct watchpoint *) bl->owner;
10733
10734   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10735                                         bl->watchpoint_type);
10736 }
10737
10738 /* Implement the "resources_needed" breakpoint_ops method for
10739    masked hardware watchpoints.  */
10740
10741 static int
10742 resources_needed_masked_watchpoint (const struct bp_location *bl)
10743 {
10744   struct watchpoint *w = (struct watchpoint *) bl->owner;
10745
10746   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10747 }
10748
10749 /* Implement the "works_in_software_mode" breakpoint_ops method for
10750    masked hardware watchpoints.  */
10751
10752 static int
10753 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10754 {
10755   return 0;
10756 }
10757
10758 /* Implement the "print_it" breakpoint_ops method for
10759    masked hardware watchpoints.  */
10760
10761 static enum print_stop_action
10762 print_it_masked_watchpoint (bpstat bs)
10763 {
10764   struct breakpoint *b = bs->breakpoint_at;
10765   struct ui_out *uiout = current_uiout;
10766
10767   /* Masked watchpoints have only one location.  */
10768   gdb_assert (b->loc && b->loc->next == NULL);
10769
10770   switch (b->type)
10771     {
10772     case bp_hardware_watchpoint:
10773       annotate_watchpoint (b->number);
10774       if (ui_out_is_mi_like_p (uiout))
10775         ui_out_field_string
10776           (uiout, "reason",
10777            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10778       break;
10779
10780     case bp_read_watchpoint:
10781       if (ui_out_is_mi_like_p (uiout))
10782         ui_out_field_string
10783           (uiout, "reason",
10784            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10785       break;
10786
10787     case bp_access_watchpoint:
10788       if (ui_out_is_mi_like_p (uiout))
10789         ui_out_field_string
10790           (uiout, "reason",
10791            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10792       break;
10793     default:
10794       internal_error (__FILE__, __LINE__,
10795                       _("Invalid hardware watchpoint type."));
10796     }
10797
10798   mention (b);
10799   ui_out_text (uiout, _("\n\
10800 Check the underlying instruction at PC for the memory\n\
10801 address and value which triggered this watchpoint.\n"));
10802   ui_out_text (uiout, "\n");
10803
10804   /* More than one watchpoint may have been triggered.  */
10805   return PRINT_UNKNOWN;
10806 }
10807
10808 /* Implement the "print_one_detail" breakpoint_ops method for
10809    masked hardware watchpoints.  */
10810
10811 static void
10812 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10813                                     struct ui_out *uiout)
10814 {
10815   struct watchpoint *w = (struct watchpoint *) b;
10816
10817   /* Masked watchpoints have only one location.  */
10818   gdb_assert (b->loc && b->loc->next == NULL);
10819
10820   ui_out_text (uiout, "\tmask ");
10821   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10822   ui_out_text (uiout, "\n");
10823 }
10824
10825 /* Implement the "print_mention" breakpoint_ops method for
10826    masked hardware watchpoints.  */
10827
10828 static void
10829 print_mention_masked_watchpoint (struct breakpoint *b)
10830 {
10831   struct watchpoint *w = (struct watchpoint *) b;
10832   struct ui_out *uiout = current_uiout;
10833   struct cleanup *ui_out_chain;
10834
10835   switch (b->type)
10836     {
10837     case bp_hardware_watchpoint:
10838       ui_out_text (uiout, "Masked hardware watchpoint ");
10839       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10840       break;
10841     case bp_read_watchpoint:
10842       ui_out_text (uiout, "Masked hardware read watchpoint ");
10843       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10844       break;
10845     case bp_access_watchpoint:
10846       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10847       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10848       break;
10849     default:
10850       internal_error (__FILE__, __LINE__,
10851                       _("Invalid hardware watchpoint type."));
10852     }
10853
10854   ui_out_field_int (uiout, "number", b->number);
10855   ui_out_text (uiout, ": ");
10856   ui_out_field_string (uiout, "exp", w->exp_string);
10857   do_cleanups (ui_out_chain);
10858 }
10859
10860 /* Implement the "print_recreate" breakpoint_ops method for
10861    masked hardware watchpoints.  */
10862
10863 static void
10864 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10865 {
10866   struct watchpoint *w = (struct watchpoint *) b;
10867   char tmp[40];
10868
10869   switch (b->type)
10870     {
10871     case bp_hardware_watchpoint:
10872       fprintf_unfiltered (fp, "watch");
10873       break;
10874     case bp_read_watchpoint:
10875       fprintf_unfiltered (fp, "rwatch");
10876       break;
10877     case bp_access_watchpoint:
10878       fprintf_unfiltered (fp, "awatch");
10879       break;
10880     default:
10881       internal_error (__FILE__, __LINE__,
10882                       _("Invalid hardware watchpoint type."));
10883     }
10884
10885   sprintf_vma (tmp, w->hw_wp_mask);
10886   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10887   print_recreate_thread (b, fp);
10888 }
10889
10890 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10891
10892 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10893
10894 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10895
10896 static int
10897 is_masked_watchpoint (const struct breakpoint *b)
10898 {
10899   return b->ops == &masked_watchpoint_breakpoint_ops;
10900 }
10901
10902 /* accessflag:  hw_write:  watch write, 
10903                 hw_read:   watch read, 
10904                 hw_access: watch access (read or write) */
10905 static void
10906 watch_command_1 (const char *arg, int accessflag, int from_tty,
10907                  int just_location, int internal)
10908 {
10909   volatile struct gdb_exception e;
10910   struct breakpoint *b, *scope_breakpoint = NULL;
10911   struct expression *exp;
10912   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10913   struct value *val, *mark, *result;
10914   struct frame_info *frame;
10915   const char *exp_start = NULL;
10916   const char *exp_end = NULL;
10917   const char *tok, *end_tok;
10918   int toklen = -1;
10919   const char *cond_start = NULL;
10920   const char *cond_end = NULL;
10921   enum bptype bp_type;
10922   int thread = -1;
10923   int pc = 0;
10924   /* Flag to indicate whether we are going to use masks for
10925      the hardware watchpoint.  */
10926   int use_mask = 0;
10927   CORE_ADDR mask = 0;
10928   struct watchpoint *w;
10929   char *expression;
10930   struct cleanup *back_to;
10931
10932   /* Make sure that we actually have parameters to parse.  */
10933   if (arg != NULL && arg[0] != '\0')
10934     {
10935       const char *value_start;
10936
10937       exp_end = arg + strlen (arg);
10938
10939       /* Look for "parameter value" pairs at the end
10940          of the arguments string.  */
10941       for (tok = exp_end - 1; tok > arg; tok--)
10942         {
10943           /* Skip whitespace at the end of the argument list.  */
10944           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10945             tok--;
10946
10947           /* Find the beginning of the last token.
10948              This is the value of the parameter.  */
10949           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10950             tok--;
10951           value_start = tok + 1;
10952
10953           /* Skip whitespace.  */
10954           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10955             tok--;
10956
10957           end_tok = tok;
10958
10959           /* Find the beginning of the second to last token.
10960              This is the parameter itself.  */
10961           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10962             tok--;
10963           tok++;
10964           toklen = end_tok - tok + 1;
10965
10966           if (toklen == 6 && !strncmp (tok, "thread", 6))
10967             {
10968               /* At this point we've found a "thread" token, which means
10969                  the user is trying to set a watchpoint that triggers
10970                  only in a specific thread.  */
10971               char *endp;
10972
10973               if (thread != -1)
10974                 error(_("You can specify only one thread."));
10975
10976               /* Extract the thread ID from the next token.  */
10977               thread = strtol (value_start, &endp, 0);
10978
10979               /* Check if the user provided a valid numeric value for the
10980                  thread ID.  */
10981               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10982                 error (_("Invalid thread ID specification %s."), value_start);
10983
10984               /* Check if the thread actually exists.  */
10985               if (!valid_thread_id (thread))
10986                 invalid_thread_id_error (thread);
10987             }
10988           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10989             {
10990               /* We've found a "mask" token, which means the user wants to
10991                  create a hardware watchpoint that is going to have the mask
10992                  facility.  */
10993               struct value *mask_value, *mark;
10994
10995               if (use_mask)
10996                 error(_("You can specify only one mask."));
10997
10998               use_mask = just_location = 1;
10999
11000               mark = value_mark ();
11001               mask_value = parse_to_comma_and_eval (&value_start);
11002               mask = value_as_address (mask_value);
11003               value_free_to_mark (mark);
11004             }
11005           else
11006             /* We didn't recognize what we found.  We should stop here.  */
11007             break;
11008
11009           /* Truncate the string and get rid of the "parameter value" pair before
11010              the arguments string is parsed by the parse_exp_1 function.  */
11011           exp_end = tok;
11012         }
11013     }
11014   else
11015     exp_end = arg;
11016
11017   /* Parse the rest of the arguments.  From here on out, everything
11018      is in terms of a newly allocated string instead of the original
11019      ARG.  */
11020   innermost_block = NULL;
11021   expression = savestring (arg, exp_end - arg);
11022   back_to = make_cleanup (xfree, expression);
11023   exp_start = arg = expression;
11024   exp = parse_exp_1 (&arg, 0, 0, 0);
11025   exp_end = arg;
11026   /* Remove trailing whitespace from the expression before saving it.
11027      This makes the eventual display of the expression string a bit
11028      prettier.  */
11029   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11030     --exp_end;
11031
11032   /* Checking if the expression is not constant.  */
11033   if (watchpoint_exp_is_const (exp))
11034     {
11035       int len;
11036
11037       len = exp_end - exp_start;
11038       while (len > 0 && isspace (exp_start[len - 1]))
11039         len--;
11040       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11041     }
11042
11043   exp_valid_block = innermost_block;
11044   mark = value_mark ();
11045   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11046
11047   if (just_location)
11048     {
11049       int ret;
11050
11051       exp_valid_block = NULL;
11052       val = value_addr (result);
11053       release_value (val);
11054       value_free_to_mark (mark);
11055
11056       if (use_mask)
11057         {
11058           ret = target_masked_watch_num_registers (value_as_address (val),
11059                                                    mask);
11060           if (ret == -1)
11061             error (_("This target does not support masked watchpoints."));
11062           else if (ret == -2)
11063             error (_("Invalid mask or memory region."));
11064         }
11065     }
11066   else if (val != NULL)
11067     release_value (val);
11068
11069   tok = skip_spaces_const (arg);
11070   end_tok = skip_to_space_const (tok);
11071
11072   toklen = end_tok - tok;
11073   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11074     {
11075       struct expression *cond;
11076
11077       innermost_block = NULL;
11078       tok = cond_start = end_tok + 1;
11079       cond = parse_exp_1 (&tok, 0, 0, 0);
11080
11081       /* The watchpoint expression may not be local, but the condition
11082          may still be.  E.g.: `watch global if local > 0'.  */
11083       cond_exp_valid_block = innermost_block;
11084
11085       xfree (cond);
11086       cond_end = tok;
11087     }
11088   if (*tok)
11089     error (_("Junk at end of command."));
11090
11091   frame = block_innermost_frame (exp_valid_block);
11092
11093   /* If the expression is "local", then set up a "watchpoint scope"
11094      breakpoint at the point where we've left the scope of the watchpoint
11095      expression.  Create the scope breakpoint before the watchpoint, so
11096      that we will encounter it first in bpstat_stop_status.  */
11097   if (exp_valid_block && frame)
11098     {
11099       if (frame_id_p (frame_unwind_caller_id (frame)))
11100         {
11101           scope_breakpoint
11102             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11103                                           frame_unwind_caller_pc (frame),
11104                                           bp_watchpoint_scope,
11105                                           &momentary_breakpoint_ops);
11106
11107           scope_breakpoint->enable_state = bp_enabled;
11108
11109           /* Automatically delete the breakpoint when it hits.  */
11110           scope_breakpoint->disposition = disp_del;
11111
11112           /* Only break in the proper frame (help with recursion).  */
11113           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11114
11115           /* Set the address at which we will stop.  */
11116           scope_breakpoint->loc->gdbarch
11117             = frame_unwind_caller_arch (frame);
11118           scope_breakpoint->loc->requested_address
11119             = frame_unwind_caller_pc (frame);
11120           scope_breakpoint->loc->address
11121             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11122                                          scope_breakpoint->loc->requested_address,
11123                                          scope_breakpoint->type);
11124         }
11125     }
11126
11127   /* Now set up the breakpoint.  We create all watchpoints as hardware
11128      watchpoints here even if hardware watchpoints are turned off, a call
11129      to update_watchpoint later in this function will cause the type to
11130      drop back to bp_watchpoint (software watchpoint) if required.  */
11131
11132   if (accessflag == hw_read)
11133     bp_type = bp_read_watchpoint;
11134   else if (accessflag == hw_access)
11135     bp_type = bp_access_watchpoint;
11136   else
11137     bp_type = bp_hardware_watchpoint;
11138
11139   w = XCNEW (struct watchpoint);
11140   b = &w->base;
11141   if (use_mask)
11142     init_raw_breakpoint_without_location (b, NULL, bp_type,
11143                                           &masked_watchpoint_breakpoint_ops);
11144   else
11145     init_raw_breakpoint_without_location (b, NULL, bp_type,
11146                                           &watchpoint_breakpoint_ops);
11147   b->thread = thread;
11148   b->disposition = disp_donttouch;
11149   b->pspace = current_program_space;
11150   w->exp = exp;
11151   w->exp_valid_block = exp_valid_block;
11152   w->cond_exp_valid_block = cond_exp_valid_block;
11153   if (just_location)
11154     {
11155       struct type *t = value_type (val);
11156       CORE_ADDR addr = value_as_address (val);
11157       char *name;
11158
11159       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11160       name = type_to_string (t);
11161
11162       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11163                                           core_addr_to_string (addr));
11164       xfree (name);
11165
11166       w->exp_string = xstrprintf ("-location %.*s",
11167                                   (int) (exp_end - exp_start), exp_start);
11168
11169       /* The above expression is in C.  */
11170       b->language = language_c;
11171     }
11172   else
11173     w->exp_string = savestring (exp_start, exp_end - exp_start);
11174
11175   if (use_mask)
11176     {
11177       w->hw_wp_mask = mask;
11178     }
11179   else
11180     {
11181       w->val = val;
11182       w->val_valid = 1;
11183     }
11184
11185   if (cond_start)
11186     b->cond_string = savestring (cond_start, cond_end - cond_start);
11187   else
11188     b->cond_string = 0;
11189
11190   if (frame)
11191     {
11192       w->watchpoint_frame = get_frame_id (frame);
11193       w->watchpoint_thread = inferior_ptid;
11194     }
11195   else
11196     {
11197       w->watchpoint_frame = null_frame_id;
11198       w->watchpoint_thread = null_ptid;
11199     }
11200
11201   if (scope_breakpoint != NULL)
11202     {
11203       /* The scope breakpoint is related to the watchpoint.  We will
11204          need to act on them together.  */
11205       b->related_breakpoint = scope_breakpoint;
11206       scope_breakpoint->related_breakpoint = b;
11207     }
11208
11209   if (!just_location)
11210     value_free_to_mark (mark);
11211
11212   TRY_CATCH (e, RETURN_MASK_ALL)
11213     {
11214       /* Finally update the new watchpoint.  This creates the locations
11215          that should be inserted.  */
11216       update_watchpoint (w, 1);
11217     }
11218   if (e.reason < 0)
11219     {
11220       delete_breakpoint (b);
11221       throw_exception (e);
11222     }
11223
11224   install_breakpoint (internal, b, 1);
11225   do_cleanups (back_to);
11226 }
11227
11228 /* Return count of debug registers needed to watch the given expression.
11229    If the watchpoint cannot be handled in hardware return zero.  */
11230
11231 static int
11232 can_use_hardware_watchpoint (struct value *v)
11233 {
11234   int found_memory_cnt = 0;
11235   struct value *head = v;
11236
11237   /* Did the user specifically forbid us to use hardware watchpoints? */
11238   if (!can_use_hw_watchpoints)
11239     return 0;
11240
11241   /* Make sure that the value of the expression depends only upon
11242      memory contents, and values computed from them within GDB.  If we
11243      find any register references or function calls, we can't use a
11244      hardware watchpoint.
11245
11246      The idea here is that evaluating an expression generates a series
11247      of values, one holding the value of every subexpression.  (The
11248      expression a*b+c has five subexpressions: a, b, a*b, c, and
11249      a*b+c.)  GDB's values hold almost enough information to establish
11250      the criteria given above --- they identify memory lvalues,
11251      register lvalues, computed values, etcetera.  So we can evaluate
11252      the expression, and then scan the chain of values that leaves
11253      behind to decide whether we can detect any possible change to the
11254      expression's final value using only hardware watchpoints.
11255
11256      However, I don't think that the values returned by inferior
11257      function calls are special in any way.  So this function may not
11258      notice that an expression involving an inferior function call
11259      can't be watched with hardware watchpoints.  FIXME.  */
11260   for (; v; v = value_next (v))
11261     {
11262       if (VALUE_LVAL (v) == lval_memory)
11263         {
11264           if (v != head && value_lazy (v))
11265             /* A lazy memory lvalue in the chain is one that GDB never
11266                needed to fetch; we either just used its address (e.g.,
11267                `a' in `a.b') or we never needed it at all (e.g., `a'
11268                in `a,b').  This doesn't apply to HEAD; if that is
11269                lazy then it was not readable, but watch it anyway.  */
11270             ;
11271           else
11272             {
11273               /* Ahh, memory we actually used!  Check if we can cover
11274                  it with hardware watchpoints.  */
11275               struct type *vtype = check_typedef (value_type (v));
11276
11277               /* We only watch structs and arrays if user asked for it
11278                  explicitly, never if they just happen to appear in a
11279                  middle of some value chain.  */
11280               if (v == head
11281                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11282                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11283                 {
11284                   CORE_ADDR vaddr = value_address (v);
11285                   int len;
11286                   int num_regs;
11287
11288                   len = (target_exact_watchpoints
11289                          && is_scalar_type_recursive (vtype))?
11290                     1 : TYPE_LENGTH (value_type (v));
11291
11292                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11293                   if (!num_regs)
11294                     return 0;
11295                   else
11296                     found_memory_cnt += num_regs;
11297                 }
11298             }
11299         }
11300       else if (VALUE_LVAL (v) != not_lval
11301                && deprecated_value_modifiable (v) == 0)
11302         return 0;       /* These are values from the history (e.g., $1).  */
11303       else if (VALUE_LVAL (v) == lval_register)
11304         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11305     }
11306
11307   /* The expression itself looks suitable for using a hardware
11308      watchpoint, but give the target machine a chance to reject it.  */
11309   return found_memory_cnt;
11310 }
11311
11312 void
11313 watch_command_wrapper (char *arg, int from_tty, int internal)
11314 {
11315   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11316 }
11317
11318 /* A helper function that looks for the "-location" argument and then
11319    calls watch_command_1.  */
11320
11321 static void
11322 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11323 {
11324   int just_location = 0;
11325
11326   if (arg
11327       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11328           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11329     {
11330       arg = skip_spaces (arg);
11331       just_location = 1;
11332     }
11333
11334   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11335 }
11336
11337 static void
11338 watch_command (char *arg, int from_tty)
11339 {
11340   watch_maybe_just_location (arg, hw_write, from_tty);
11341 }
11342
11343 void
11344 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11345 {
11346   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11347 }
11348
11349 static void
11350 rwatch_command (char *arg, int from_tty)
11351 {
11352   watch_maybe_just_location (arg, hw_read, from_tty);
11353 }
11354
11355 void
11356 awatch_command_wrapper (char *arg, int from_tty, int internal)
11357 {
11358   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11359 }
11360
11361 static void
11362 awatch_command (char *arg, int from_tty)
11363 {
11364   watch_maybe_just_location (arg, hw_access, from_tty);
11365 }
11366 \f
11367
11368 /* Helper routines for the until_command routine in infcmd.c.  Here
11369    because it uses the mechanisms of breakpoints.  */
11370
11371 struct until_break_command_continuation_args
11372 {
11373   struct breakpoint *breakpoint;
11374   struct breakpoint *breakpoint2;
11375   int thread_num;
11376 };
11377
11378 /* This function is called by fetch_inferior_event via the
11379    cmd_continuation pointer, to complete the until command.  It takes
11380    care of cleaning up the temporary breakpoints set up by the until
11381    command.  */
11382 static void
11383 until_break_command_continuation (void *arg, int err)
11384 {
11385   struct until_break_command_continuation_args *a = arg;
11386
11387   delete_breakpoint (a->breakpoint);
11388   if (a->breakpoint2)
11389     delete_breakpoint (a->breakpoint2);
11390   delete_longjmp_breakpoint (a->thread_num);
11391 }
11392
11393 void
11394 until_break_command (char *arg, int from_tty, int anywhere)
11395 {
11396   struct symtabs_and_lines sals;
11397   struct symtab_and_line sal;
11398   struct frame_info *frame;
11399   struct gdbarch *frame_gdbarch;
11400   struct frame_id stack_frame_id;
11401   struct frame_id caller_frame_id;
11402   struct breakpoint *breakpoint;
11403   struct breakpoint *breakpoint2 = NULL;
11404   struct cleanup *old_chain;
11405   int thread;
11406   struct thread_info *tp;
11407
11408   clear_proceed_status ();
11409
11410   /* Set a breakpoint where the user wants it and at return from
11411      this function.  */
11412
11413   if (last_displayed_sal_is_valid ())
11414     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11415                           get_last_displayed_symtab (),
11416                           get_last_displayed_line ());
11417   else
11418     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11419                           (struct symtab *) NULL, 0);
11420
11421   if (sals.nelts != 1)
11422     error (_("Couldn't get information on specified line."));
11423
11424   sal = sals.sals[0];
11425   xfree (sals.sals);    /* malloc'd, so freed.  */
11426
11427   if (*arg)
11428     error (_("Junk at end of arguments."));
11429
11430   resolve_sal_pc (&sal);
11431
11432   tp = inferior_thread ();
11433   thread = tp->num;
11434
11435   old_chain = make_cleanup (null_cleanup, NULL);
11436
11437   /* Note linespec handling above invalidates the frame chain.
11438      Installing a breakpoint also invalidates the frame chain (as it
11439      may need to switch threads), so do any frame handling before
11440      that.  */
11441
11442   frame = get_selected_frame (NULL);
11443   frame_gdbarch = get_frame_arch (frame);
11444   stack_frame_id = get_stack_frame_id (frame);
11445   caller_frame_id = frame_unwind_caller_id (frame);
11446
11447   /* Keep within the current frame, or in frames called by the current
11448      one.  */
11449
11450   if (frame_id_p (caller_frame_id))
11451     {
11452       struct symtab_and_line sal2;
11453
11454       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11455       sal2.pc = frame_unwind_caller_pc (frame);
11456       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11457                                               sal2,
11458                                               caller_frame_id,
11459                                               bp_until);
11460       make_cleanup_delete_breakpoint (breakpoint2);
11461
11462       set_longjmp_breakpoint (tp, caller_frame_id);
11463       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11464     }
11465
11466   /* set_momentary_breakpoint could invalidate FRAME.  */
11467   frame = NULL;
11468
11469   if (anywhere)
11470     /* If the user told us to continue until a specified location,
11471        we don't specify a frame at which we need to stop.  */
11472     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11473                                            null_frame_id, bp_until);
11474   else
11475     /* Otherwise, specify the selected frame, because we want to stop
11476        only at the very same frame.  */
11477     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11478                                            stack_frame_id, bp_until);
11479   make_cleanup_delete_breakpoint (breakpoint);
11480
11481   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11482
11483   /* If we are running asynchronously, and proceed call above has
11484      actually managed to start the target, arrange for breakpoints to
11485      be deleted when the target stops.  Otherwise, we're already
11486      stopped and delete breakpoints via cleanup chain.  */
11487
11488   if (target_can_async_p () && is_running (inferior_ptid))
11489     {
11490       struct until_break_command_continuation_args *args;
11491       args = xmalloc (sizeof (*args));
11492
11493       args->breakpoint = breakpoint;
11494       args->breakpoint2 = breakpoint2;
11495       args->thread_num = thread;
11496
11497       discard_cleanups (old_chain);
11498       add_continuation (inferior_thread (),
11499                         until_break_command_continuation, args,
11500                         xfree);
11501     }
11502   else
11503     do_cleanups (old_chain);
11504 }
11505
11506 /* This function attempts to parse an optional "if <cond>" clause
11507    from the arg string.  If one is not found, it returns NULL.
11508
11509    Else, it returns a pointer to the condition string.  (It does not
11510    attempt to evaluate the string against a particular block.)  And,
11511    it updates arg to point to the first character following the parsed
11512    if clause in the arg string.  */
11513
11514 char *
11515 ep_parse_optional_if_clause (char **arg)
11516 {
11517   char *cond_string;
11518
11519   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11520     return NULL;
11521
11522   /* Skip the "if" keyword.  */
11523   (*arg) += 2;
11524
11525   /* Skip any extra leading whitespace, and record the start of the
11526      condition string.  */
11527   *arg = skip_spaces (*arg);
11528   cond_string = *arg;
11529
11530   /* Assume that the condition occupies the remainder of the arg
11531      string.  */
11532   (*arg) += strlen (cond_string);
11533
11534   return cond_string;
11535 }
11536
11537 /* Commands to deal with catching events, such as signals, exceptions,
11538    process start/exit, etc.  */
11539
11540 typedef enum
11541 {
11542   catch_fork_temporary, catch_vfork_temporary,
11543   catch_fork_permanent, catch_vfork_permanent
11544 }
11545 catch_fork_kind;
11546
11547 static void
11548 catch_fork_command_1 (char *arg, int from_tty, 
11549                       struct cmd_list_element *command)
11550 {
11551   struct gdbarch *gdbarch = get_current_arch ();
11552   char *cond_string = NULL;
11553   catch_fork_kind fork_kind;
11554   int tempflag;
11555
11556   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11557   tempflag = (fork_kind == catch_fork_temporary
11558               || fork_kind == catch_vfork_temporary);
11559
11560   if (!arg)
11561     arg = "";
11562   arg = skip_spaces (arg);
11563
11564   /* The allowed syntax is:
11565      catch [v]fork
11566      catch [v]fork if <cond>
11567
11568      First, check if there's an if clause.  */
11569   cond_string = ep_parse_optional_if_clause (&arg);
11570
11571   if ((*arg != '\0') && !isspace (*arg))
11572     error (_("Junk at end of arguments."));
11573
11574   /* If this target supports it, create a fork or vfork catchpoint
11575      and enable reporting of such events.  */
11576   switch (fork_kind)
11577     {
11578     case catch_fork_temporary:
11579     case catch_fork_permanent:
11580       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11581                                           &catch_fork_breakpoint_ops);
11582       break;
11583     case catch_vfork_temporary:
11584     case catch_vfork_permanent:
11585       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11586                                           &catch_vfork_breakpoint_ops);
11587       break;
11588     default:
11589       error (_("unsupported or unknown fork kind; cannot catch it"));
11590       break;
11591     }
11592 }
11593
11594 static void
11595 catch_exec_command_1 (char *arg, int from_tty, 
11596                       struct cmd_list_element *command)
11597 {
11598   struct exec_catchpoint *c;
11599   struct gdbarch *gdbarch = get_current_arch ();
11600   int tempflag;
11601   char *cond_string = NULL;
11602
11603   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11604
11605   if (!arg)
11606     arg = "";
11607   arg = skip_spaces (arg);
11608
11609   /* The allowed syntax is:
11610      catch exec
11611      catch exec if <cond>
11612
11613      First, check if there's an if clause.  */
11614   cond_string = ep_parse_optional_if_clause (&arg);
11615
11616   if ((*arg != '\0') && !isspace (*arg))
11617     error (_("Junk at end of arguments."));
11618
11619   c = XNEW (struct exec_catchpoint);
11620   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11621                    &catch_exec_breakpoint_ops);
11622   c->exec_pathname = NULL;
11623
11624   install_breakpoint (0, &c->base, 1);
11625 }
11626
11627 void
11628 init_ada_exception_breakpoint (struct breakpoint *b,
11629                                struct gdbarch *gdbarch,
11630                                struct symtab_and_line sal,
11631                                char *addr_string,
11632                                const struct breakpoint_ops *ops,
11633                                int tempflag,
11634                                int enabled,
11635                                int from_tty)
11636 {
11637   if (from_tty)
11638     {
11639       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11640       if (!loc_gdbarch)
11641         loc_gdbarch = gdbarch;
11642
11643       describe_other_breakpoints (loc_gdbarch,
11644                                   sal.pspace, sal.pc, sal.section, -1);
11645       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11646          version for exception catchpoints, because two catchpoints
11647          used for different exception names will use the same address.
11648          In this case, a "breakpoint ... also set at..." warning is
11649          unproductive.  Besides, the warning phrasing is also a bit
11650          inappropriate, we should use the word catchpoint, and tell
11651          the user what type of catchpoint it is.  The above is good
11652          enough for now, though.  */
11653     }
11654
11655   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11656
11657   b->enable_state = enabled ? bp_enabled : bp_disabled;
11658   b->disposition = tempflag ? disp_del : disp_donttouch;
11659   b->addr_string = addr_string;
11660   b->language = language_ada;
11661 }
11662
11663 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11664    filter list, or NULL if no filtering is required.  */
11665 static VEC(int) *
11666 catch_syscall_split_args (char *arg)
11667 {
11668   VEC(int) *result = NULL;
11669   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11670
11671   while (*arg != '\0')
11672     {
11673       int i, syscall_number;
11674       char *endptr;
11675       char cur_name[128];
11676       struct syscall s;
11677
11678       /* Skip whitespace.  */
11679       arg = skip_spaces (arg);
11680
11681       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11682         cur_name[i] = arg[i];
11683       cur_name[i] = '\0';
11684       arg += i;
11685
11686       /* Check if the user provided a syscall name or a number.  */
11687       syscall_number = (int) strtol (cur_name, &endptr, 0);
11688       if (*endptr == '\0')
11689         get_syscall_by_number (syscall_number, &s);
11690       else
11691         {
11692           /* We have a name.  Let's check if it's valid and convert it
11693              to a number.  */
11694           get_syscall_by_name (cur_name, &s);
11695
11696           if (s.number == UNKNOWN_SYSCALL)
11697             /* Here we have to issue an error instead of a warning,
11698                because GDB cannot do anything useful if there's no
11699                syscall number to be caught.  */
11700             error (_("Unknown syscall name '%s'."), cur_name);
11701         }
11702
11703       /* Ok, it's valid.  */
11704       VEC_safe_push (int, result, s.number);
11705     }
11706
11707   discard_cleanups (cleanup);
11708   return result;
11709 }
11710
11711 /* Implement the "catch syscall" command.  */
11712
11713 static void
11714 catch_syscall_command_1 (char *arg, int from_tty, 
11715                          struct cmd_list_element *command)
11716 {
11717   int tempflag;
11718   VEC(int) *filter;
11719   struct syscall s;
11720   struct gdbarch *gdbarch = get_current_arch ();
11721
11722   /* Checking if the feature if supported.  */
11723   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11724     error (_("The feature 'catch syscall' is not supported on \
11725 this architecture yet."));
11726
11727   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11728
11729   arg = skip_spaces (arg);
11730
11731   /* We need to do this first "dummy" translation in order
11732      to get the syscall XML file loaded or, most important,
11733      to display a warning to the user if there's no XML file
11734      for his/her architecture.  */
11735   get_syscall_by_number (0, &s);
11736
11737   /* The allowed syntax is:
11738      catch syscall
11739      catch syscall <name | number> [<name | number> ... <name | number>]
11740
11741      Let's check if there's a syscall name.  */
11742
11743   if (arg != NULL)
11744     filter = catch_syscall_split_args (arg);
11745   else
11746     filter = NULL;
11747
11748   create_syscall_event_catchpoint (tempflag, filter,
11749                                    &catch_syscall_breakpoint_ops);
11750 }
11751
11752 static void
11753 catch_command (char *arg, int from_tty)
11754 {
11755   error (_("Catch requires an event name."));
11756 }
11757 \f
11758
11759 static void
11760 tcatch_command (char *arg, int from_tty)
11761 {
11762   error (_("Catch requires an event name."));
11763 }
11764
11765 /* A qsort comparison function that sorts breakpoints in order.  */
11766
11767 static int
11768 compare_breakpoints (const void *a, const void *b)
11769 {
11770   const breakpoint_p *ba = a;
11771   uintptr_t ua = (uintptr_t) *ba;
11772   const breakpoint_p *bb = b;
11773   uintptr_t ub = (uintptr_t) *bb;
11774
11775   if ((*ba)->number < (*bb)->number)
11776     return -1;
11777   else if ((*ba)->number > (*bb)->number)
11778     return 1;
11779
11780   /* Now sort by address, in case we see, e..g, two breakpoints with
11781      the number 0.  */
11782   if (ua < ub)
11783     return -1;
11784   return ua > ub ? 1 : 0;
11785 }
11786
11787 /* Delete breakpoints by address or line.  */
11788
11789 static void
11790 clear_command (char *arg, int from_tty)
11791 {
11792   struct breakpoint *b, *prev;
11793   VEC(breakpoint_p) *found = 0;
11794   int ix;
11795   int default_match;
11796   struct symtabs_and_lines sals;
11797   struct symtab_and_line sal;
11798   int i;
11799   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11800
11801   if (arg)
11802     {
11803       sals = decode_line_with_current_source (arg,
11804                                               (DECODE_LINE_FUNFIRSTLINE
11805                                                | DECODE_LINE_LIST_MODE));
11806       make_cleanup (xfree, sals.sals);
11807       default_match = 0;
11808     }
11809   else
11810     {
11811       sals.sals = (struct symtab_and_line *)
11812         xmalloc (sizeof (struct symtab_and_line));
11813       make_cleanup (xfree, sals.sals);
11814       init_sal (&sal);          /* Initialize to zeroes.  */
11815
11816       /* Set sal's line, symtab, pc, and pspace to the values
11817          corresponding to the last call to print_frame_info.  If the
11818          codepoint is not valid, this will set all the fields to 0.  */
11819       get_last_displayed_sal (&sal);
11820       if (sal.symtab == 0)
11821         error (_("No source file specified."));
11822
11823       sals.sals[0] = sal;
11824       sals.nelts = 1;
11825
11826       default_match = 1;
11827     }
11828
11829   /* We don't call resolve_sal_pc here.  That's not as bad as it
11830      seems, because all existing breakpoints typically have both
11831      file/line and pc set.  So, if clear is given file/line, we can
11832      match this to existing breakpoint without obtaining pc at all.
11833
11834      We only support clearing given the address explicitly 
11835      present in breakpoint table.  Say, we've set breakpoint 
11836      at file:line.  There were several PC values for that file:line,
11837      due to optimization, all in one block.
11838
11839      We've picked one PC value.  If "clear" is issued with another
11840      PC corresponding to the same file:line, the breakpoint won't
11841      be cleared.  We probably can still clear the breakpoint, but 
11842      since the other PC value is never presented to user, user
11843      can only find it by guessing, and it does not seem important
11844      to support that.  */
11845
11846   /* For each line spec given, delete bps which correspond to it.  Do
11847      it in two passes, solely to preserve the current behavior that
11848      from_tty is forced true if we delete more than one
11849      breakpoint.  */
11850
11851   found = NULL;
11852   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11853   for (i = 0; i < sals.nelts; i++)
11854     {
11855       const char *sal_fullname;
11856
11857       /* If exact pc given, clear bpts at that pc.
11858          If line given (pc == 0), clear all bpts on specified line.
11859          If defaulting, clear all bpts on default line
11860          or at default pc.
11861
11862          defaulting    sal.pc != 0    tests to do
11863
11864          0              1             pc
11865          1              1             pc _and_ line
11866          0              0             line
11867          1              0             <can't happen> */
11868
11869       sal = sals.sals[i];
11870       sal_fullname = (sal.symtab == NULL
11871                       ? NULL : symtab_to_fullname (sal.symtab));
11872
11873       /* Find all matching breakpoints and add them to 'found'.  */
11874       ALL_BREAKPOINTS (b)
11875         {
11876           int match = 0;
11877           /* Are we going to delete b?  */
11878           if (b->type != bp_none && !is_watchpoint (b))
11879             {
11880               struct bp_location *loc = b->loc;
11881               for (; loc; loc = loc->next)
11882                 {
11883                   /* If the user specified file:line, don't allow a PC
11884                      match.  This matches historical gdb behavior.  */
11885                   int pc_match = (!sal.explicit_line
11886                                   && sal.pc
11887                                   && (loc->pspace == sal.pspace)
11888                                   && (loc->address == sal.pc)
11889                                   && (!section_is_overlay (loc->section)
11890                                       || loc->section == sal.section));
11891                   int line_match = 0;
11892
11893                   if ((default_match || sal.explicit_line)
11894                       && loc->symtab != NULL
11895                       && sal_fullname != NULL
11896                       && sal.pspace == loc->pspace
11897                       && loc->line_number == sal.line
11898                       && filename_cmp (symtab_to_fullname (loc->symtab),
11899                                        sal_fullname) == 0)
11900                     line_match = 1;
11901
11902                   if (pc_match || line_match)
11903                     {
11904                       match = 1;
11905                       break;
11906                     }
11907                 }
11908             }
11909
11910           if (match)
11911             VEC_safe_push(breakpoint_p, found, b);
11912         }
11913     }
11914
11915   /* Now go thru the 'found' chain and delete them.  */
11916   if (VEC_empty(breakpoint_p, found))
11917     {
11918       if (arg)
11919         error (_("No breakpoint at %s."), arg);
11920       else
11921         error (_("No breakpoint at this line."));
11922     }
11923
11924   /* Remove duplicates from the vec.  */
11925   qsort (VEC_address (breakpoint_p, found),
11926          VEC_length (breakpoint_p, found),
11927          sizeof (breakpoint_p),
11928          compare_breakpoints);
11929   prev = VEC_index (breakpoint_p, found, 0);
11930   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11931     {
11932       if (b == prev)
11933         {
11934           VEC_ordered_remove (breakpoint_p, found, ix);
11935           --ix;
11936         }
11937     }
11938
11939   if (VEC_length(breakpoint_p, found) > 1)
11940     from_tty = 1;       /* Always report if deleted more than one.  */
11941   if (from_tty)
11942     {
11943       if (VEC_length(breakpoint_p, found) == 1)
11944         printf_unfiltered (_("Deleted breakpoint "));
11945       else
11946         printf_unfiltered (_("Deleted breakpoints "));
11947     }
11948
11949   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11950     {
11951       if (from_tty)
11952         printf_unfiltered ("%d ", b->number);
11953       delete_breakpoint (b);
11954     }
11955   if (from_tty)
11956     putchar_unfiltered ('\n');
11957
11958   do_cleanups (cleanups);
11959 }
11960 \f
11961 /* Delete breakpoint in BS if they are `delete' breakpoints and
11962    all breakpoints that are marked for deletion, whether hit or not.
11963    This is called after any breakpoint is hit, or after errors.  */
11964
11965 void
11966 breakpoint_auto_delete (bpstat bs)
11967 {
11968   struct breakpoint *b, *b_tmp;
11969
11970   for (; bs; bs = bs->next)
11971     if (bs->breakpoint_at
11972         && bs->breakpoint_at->disposition == disp_del
11973         && bs->stop)
11974       delete_breakpoint (bs->breakpoint_at);
11975
11976   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11977   {
11978     if (b->disposition == disp_del_at_next_stop)
11979       delete_breakpoint (b);
11980   }
11981 }
11982
11983 /* A comparison function for bp_location AP and BP being interfaced to
11984    qsort.  Sort elements primarily by their ADDRESS (no matter what
11985    does breakpoint_address_is_meaningful say for its OWNER),
11986    secondarily by ordering first bp_permanent OWNERed elements and
11987    terciarily just ensuring the array is sorted stable way despite
11988    qsort being an unstable algorithm.  */
11989
11990 static int
11991 bp_location_compare (const void *ap, const void *bp)
11992 {
11993   struct bp_location *a = *(void **) ap;
11994   struct bp_location *b = *(void **) bp;
11995   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11996   int a_perm = a->owner->enable_state == bp_permanent;
11997   int b_perm = b->owner->enable_state == bp_permanent;
11998
11999   if (a->address != b->address)
12000     return (a->address > b->address) - (a->address < b->address);
12001
12002   /* Sort locations at the same address by their pspace number, keeping
12003      locations of the same inferior (in a multi-inferior environment)
12004      grouped.  */
12005
12006   if (a->pspace->num != b->pspace->num)
12007     return ((a->pspace->num > b->pspace->num)
12008             - (a->pspace->num < b->pspace->num));
12009
12010   /* Sort permanent breakpoints first.  */
12011   if (a_perm != b_perm)
12012     return (a_perm < b_perm) - (a_perm > b_perm);
12013
12014   /* Make the internal GDB representation stable across GDB runs
12015      where A and B memory inside GDB can differ.  Breakpoint locations of
12016      the same type at the same address can be sorted in arbitrary order.  */
12017
12018   if (a->owner->number != b->owner->number)
12019     return ((a->owner->number > b->owner->number)
12020             - (a->owner->number < b->owner->number));
12021
12022   return (a > b) - (a < b);
12023 }
12024
12025 /* Set bp_location_placed_address_before_address_max and
12026    bp_location_shadow_len_after_address_max according to the current
12027    content of the bp_location array.  */
12028
12029 static void
12030 bp_location_target_extensions_update (void)
12031 {
12032   struct bp_location *bl, **blp_tmp;
12033
12034   bp_location_placed_address_before_address_max = 0;
12035   bp_location_shadow_len_after_address_max = 0;
12036
12037   ALL_BP_LOCATIONS (bl, blp_tmp)
12038     {
12039       CORE_ADDR start, end, addr;
12040
12041       if (!bp_location_has_shadow (bl))
12042         continue;
12043
12044       start = bl->target_info.placed_address;
12045       end = start + bl->target_info.shadow_len;
12046
12047       gdb_assert (bl->address >= start);
12048       addr = bl->address - start;
12049       if (addr > bp_location_placed_address_before_address_max)
12050         bp_location_placed_address_before_address_max = addr;
12051
12052       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12053
12054       gdb_assert (bl->address < end);
12055       addr = end - bl->address;
12056       if (addr > bp_location_shadow_len_after_address_max)
12057         bp_location_shadow_len_after_address_max = addr;
12058     }
12059 }
12060
12061 /* Download tracepoint locations if they haven't been.  */
12062
12063 static void
12064 download_tracepoint_locations (void)
12065 {
12066   struct breakpoint *b;
12067   struct cleanup *old_chain;
12068
12069   if (!target_can_download_tracepoint ())
12070     return;
12071
12072   old_chain = save_current_space_and_thread ();
12073
12074   ALL_TRACEPOINTS (b)
12075     {
12076       struct bp_location *bl;
12077       struct tracepoint *t;
12078       int bp_location_downloaded = 0;
12079
12080       if ((b->type == bp_fast_tracepoint
12081            ? !may_insert_fast_tracepoints
12082            : !may_insert_tracepoints))
12083         continue;
12084
12085       for (bl = b->loc; bl; bl = bl->next)
12086         {
12087           /* In tracepoint, locations are _never_ duplicated, so
12088              should_be_inserted is equivalent to
12089              unduplicated_should_be_inserted.  */
12090           if (!should_be_inserted (bl) || bl->inserted)
12091             continue;
12092
12093           switch_to_program_space_and_thread (bl->pspace);
12094
12095           target_download_tracepoint (bl);
12096
12097           bl->inserted = 1;
12098           bp_location_downloaded = 1;
12099         }
12100       t = (struct tracepoint *) b;
12101       t->number_on_target = b->number;
12102       if (bp_location_downloaded)
12103         observer_notify_breakpoint_modified (b);
12104     }
12105
12106   do_cleanups (old_chain);
12107 }
12108
12109 /* Swap the insertion/duplication state between two locations.  */
12110
12111 static void
12112 swap_insertion (struct bp_location *left, struct bp_location *right)
12113 {
12114   const int left_inserted = left->inserted;
12115   const int left_duplicate = left->duplicate;
12116   const int left_needs_update = left->needs_update;
12117   const struct bp_target_info left_target_info = left->target_info;
12118
12119   /* Locations of tracepoints can never be duplicated.  */
12120   if (is_tracepoint (left->owner))
12121     gdb_assert (!left->duplicate);
12122   if (is_tracepoint (right->owner))
12123     gdb_assert (!right->duplicate);
12124
12125   left->inserted = right->inserted;
12126   left->duplicate = right->duplicate;
12127   left->needs_update = right->needs_update;
12128   left->target_info = right->target_info;
12129   right->inserted = left_inserted;
12130   right->duplicate = left_duplicate;
12131   right->needs_update = left_needs_update;
12132   right->target_info = left_target_info;
12133 }
12134
12135 /* Force the re-insertion of the locations at ADDRESS.  This is called
12136    once a new/deleted/modified duplicate location is found and we are evaluating
12137    conditions on the target's side.  Such conditions need to be updated on
12138    the target.  */
12139
12140 static void
12141 force_breakpoint_reinsertion (struct bp_location *bl)
12142 {
12143   struct bp_location **locp = NULL, **loc2p;
12144   struct bp_location *loc;
12145   CORE_ADDR address = 0;
12146   int pspace_num;
12147
12148   address = bl->address;
12149   pspace_num = bl->pspace->num;
12150
12151   /* This is only meaningful if the target is
12152      evaluating conditions and if the user has
12153      opted for condition evaluation on the target's
12154      side.  */
12155   if (gdb_evaluates_breakpoint_condition_p ()
12156       || !target_supports_evaluation_of_breakpoint_conditions ())
12157     return;
12158
12159   /* Flag all breakpoint locations with this address and
12160      the same program space as the location
12161      as "its condition has changed".  We need to
12162      update the conditions on the target's side.  */
12163   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12164     {
12165       loc = *loc2p;
12166
12167       if (!is_breakpoint (loc->owner)
12168           || pspace_num != loc->pspace->num)
12169         continue;
12170
12171       /* Flag the location appropriately.  We use a different state to
12172          let everyone know that we already updated the set of locations
12173          with addr bl->address and program space bl->pspace.  This is so
12174          we don't have to keep calling these functions just to mark locations
12175          that have already been marked.  */
12176       loc->condition_changed = condition_updated;
12177
12178       /* Free the agent expression bytecode as well.  We will compute
12179          it later on.  */
12180       if (loc->cond_bytecode)
12181         {
12182           free_agent_expr (loc->cond_bytecode);
12183           loc->cond_bytecode = NULL;
12184         }
12185     }
12186 }
12187
12188 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12189    into the inferior, only remove already-inserted locations that no
12190    longer should be inserted.  Functions that delete a breakpoint or
12191    breakpoints should pass false, so that deleting a breakpoint
12192    doesn't have the side effect of inserting the locations of other
12193    breakpoints that are marked not-inserted, but should_be_inserted
12194    returns true on them.
12195
12196    This behaviour is useful is situations close to tear-down -- e.g.,
12197    after an exec, while the target still has execution, but breakpoint
12198    shadows of the previous executable image should *NOT* be restored
12199    to the new image; or before detaching, where the target still has
12200    execution and wants to delete breakpoints from GDB's lists, and all
12201    breakpoints had already been removed from the inferior.  */
12202
12203 static void
12204 update_global_location_list (int should_insert)
12205 {
12206   struct breakpoint *b;
12207   struct bp_location **locp, *loc;
12208   struct cleanup *cleanups;
12209   /* Last breakpoint location address that was marked for update.  */
12210   CORE_ADDR last_addr = 0;
12211   /* Last breakpoint location program space that was marked for update.  */
12212   int last_pspace_num = -1;
12213
12214   /* Used in the duplicates detection below.  When iterating over all
12215      bp_locations, points to the first bp_location of a given address.
12216      Breakpoints and watchpoints of different types are never
12217      duplicates of each other.  Keep one pointer for each type of
12218      breakpoint/watchpoint, so we only need to loop over all locations
12219      once.  */
12220   struct bp_location *bp_loc_first;  /* breakpoint */
12221   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12222   struct bp_location *awp_loc_first; /* access watchpoint */
12223   struct bp_location *rwp_loc_first; /* read watchpoint */
12224
12225   /* Saved former bp_location array which we compare against the newly
12226      built bp_location from the current state of ALL_BREAKPOINTS.  */
12227   struct bp_location **old_location, **old_locp;
12228   unsigned old_location_count;
12229
12230   old_location = bp_location;
12231   old_location_count = bp_location_count;
12232   bp_location = NULL;
12233   bp_location_count = 0;
12234   cleanups = make_cleanup (xfree, old_location);
12235
12236   ALL_BREAKPOINTS (b)
12237     for (loc = b->loc; loc; loc = loc->next)
12238       bp_location_count++;
12239
12240   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12241   locp = bp_location;
12242   ALL_BREAKPOINTS (b)
12243     for (loc = b->loc; loc; loc = loc->next)
12244       *locp++ = loc;
12245   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12246          bp_location_compare);
12247
12248   bp_location_target_extensions_update ();
12249
12250   /* Identify bp_location instances that are no longer present in the
12251      new list, and therefore should be freed.  Note that it's not
12252      necessary that those locations should be removed from inferior --
12253      if there's another location at the same address (previously
12254      marked as duplicate), we don't need to remove/insert the
12255      location.
12256      
12257      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12258      and former bp_location array state respectively.  */
12259
12260   locp = bp_location;
12261   for (old_locp = old_location; old_locp < old_location + old_location_count;
12262        old_locp++)
12263     {
12264       struct bp_location *old_loc = *old_locp;
12265       struct bp_location **loc2p;
12266
12267       /* Tells if 'old_loc' is found among the new locations.  If
12268          not, we have to free it.  */
12269       int found_object = 0;
12270       /* Tells if the location should remain inserted in the target.  */
12271       int keep_in_target = 0;
12272       int removed = 0;
12273
12274       /* Skip LOCP entries which will definitely never be needed.
12275          Stop either at or being the one matching OLD_LOC.  */
12276       while (locp < bp_location + bp_location_count
12277              && (*locp)->address < old_loc->address)
12278         locp++;
12279
12280       for (loc2p = locp;
12281            (loc2p < bp_location + bp_location_count
12282             && (*loc2p)->address == old_loc->address);
12283            loc2p++)
12284         {
12285           /* Check if this is a new/duplicated location or a duplicated
12286              location that had its condition modified.  If so, we want to send
12287              its condition to the target if evaluation of conditions is taking
12288              place there.  */
12289           if ((*loc2p)->condition_changed == condition_modified
12290               && (last_addr != old_loc->address
12291                   || last_pspace_num != old_loc->pspace->num))
12292             {
12293               force_breakpoint_reinsertion (*loc2p);
12294               last_pspace_num = old_loc->pspace->num;
12295             }
12296
12297           if (*loc2p == old_loc)
12298             found_object = 1;
12299         }
12300
12301       /* We have already handled this address, update it so that we don't
12302          have to go through updates again.  */
12303       last_addr = old_loc->address;
12304
12305       /* Target-side condition evaluation: Handle deleted locations.  */
12306       if (!found_object)
12307         force_breakpoint_reinsertion (old_loc);
12308
12309       /* If this location is no longer present, and inserted, look if
12310          there's maybe a new location at the same address.  If so,
12311          mark that one inserted, and don't remove this one.  This is
12312          needed so that we don't have a time window where a breakpoint
12313          at certain location is not inserted.  */
12314
12315       if (old_loc->inserted)
12316         {
12317           /* If the location is inserted now, we might have to remove
12318              it.  */
12319
12320           if (found_object && should_be_inserted (old_loc))
12321             {
12322               /* The location is still present in the location list,
12323                  and still should be inserted.  Don't do anything.  */
12324               keep_in_target = 1;
12325             }
12326           else
12327             {
12328               /* This location still exists, but it won't be kept in the
12329                  target since it may have been disabled.  We proceed to
12330                  remove its target-side condition.  */
12331
12332               /* The location is either no longer present, or got
12333                  disabled.  See if there's another location at the
12334                  same address, in which case we don't need to remove
12335                  this one from the target.  */
12336
12337               /* OLD_LOC comes from existing struct breakpoint.  */
12338               if (breakpoint_address_is_meaningful (old_loc->owner))
12339                 {
12340                   for (loc2p = locp;
12341                        (loc2p < bp_location + bp_location_count
12342                         && (*loc2p)->address == old_loc->address);
12343                        loc2p++)
12344                     {
12345                       struct bp_location *loc2 = *loc2p;
12346
12347                       if (breakpoint_locations_match (loc2, old_loc))
12348                         {
12349                           /* Read watchpoint locations are switched to
12350                              access watchpoints, if the former are not
12351                              supported, but the latter are.  */
12352                           if (is_hardware_watchpoint (old_loc->owner))
12353                             {
12354                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12355                               loc2->watchpoint_type = old_loc->watchpoint_type;
12356                             }
12357
12358                           /* loc2 is a duplicated location. We need to check
12359                              if it should be inserted in case it will be
12360                              unduplicated.  */
12361                           if (loc2 != old_loc
12362                               && unduplicated_should_be_inserted (loc2))
12363                             {
12364                               swap_insertion (old_loc, loc2);
12365                               keep_in_target = 1;
12366                               break;
12367                             }
12368                         }
12369                     }
12370                 }
12371             }
12372
12373           if (!keep_in_target)
12374             {
12375               if (remove_breakpoint (old_loc, mark_uninserted))
12376                 {
12377                   /* This is just about all we can do.  We could keep
12378                      this location on the global list, and try to
12379                      remove it next time, but there's no particular
12380                      reason why we will succeed next time.
12381                      
12382                      Note that at this point, old_loc->owner is still
12383                      valid, as delete_breakpoint frees the breakpoint
12384                      only after calling us.  */
12385                   printf_filtered (_("warning: Error removing "
12386                                      "breakpoint %d\n"), 
12387                                    old_loc->owner->number);
12388                 }
12389               removed = 1;
12390             }
12391         }
12392
12393       if (!found_object)
12394         {
12395           if (removed && non_stop
12396               && breakpoint_address_is_meaningful (old_loc->owner)
12397               && !is_hardware_watchpoint (old_loc->owner))
12398             {
12399               /* This location was removed from the target.  In
12400                  non-stop mode, a race condition is possible where
12401                  we've removed a breakpoint, but stop events for that
12402                  breakpoint are already queued and will arrive later.
12403                  We apply an heuristic to be able to distinguish such
12404                  SIGTRAPs from other random SIGTRAPs: we keep this
12405                  breakpoint location for a bit, and will retire it
12406                  after we see some number of events.  The theory here
12407                  is that reporting of events should, "on the average",
12408                  be fair, so after a while we'll see events from all
12409                  threads that have anything of interest, and no longer
12410                  need to keep this breakpoint location around.  We
12411                  don't hold locations forever so to reduce chances of
12412                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12413                  SIGTRAP.
12414
12415                  The heuristic failing can be disastrous on
12416                  decr_pc_after_break targets.
12417
12418                  On decr_pc_after_break targets, like e.g., x86-linux,
12419                  if we fail to recognize a late breakpoint SIGTRAP,
12420                  because events_till_retirement has reached 0 too
12421                  soon, we'll fail to do the PC adjustment, and report
12422                  a random SIGTRAP to the user.  When the user resumes
12423                  the inferior, it will most likely immediately crash
12424                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12425                  corrupted, because of being resumed e.g., in the
12426                  middle of a multi-byte instruction, or skipped a
12427                  one-byte instruction.  This was actually seen happen
12428                  on native x86-linux, and should be less rare on
12429                  targets that do not support new thread events, like
12430                  remote, due to the heuristic depending on
12431                  thread_count.
12432
12433                  Mistaking a random SIGTRAP for a breakpoint trap
12434                  causes similar symptoms (PC adjustment applied when
12435                  it shouldn't), but then again, playing with SIGTRAPs
12436                  behind the debugger's back is asking for trouble.
12437
12438                  Since hardware watchpoint traps are always
12439                  distinguishable from other traps, so we don't need to
12440                  apply keep hardware watchpoint moribund locations
12441                  around.  We simply always ignore hardware watchpoint
12442                  traps we can no longer explain.  */
12443
12444               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12445               old_loc->owner = NULL;
12446
12447               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12448             }
12449           else
12450             {
12451               old_loc->owner = NULL;
12452               decref_bp_location (&old_loc);
12453             }
12454         }
12455     }
12456
12457   /* Rescan breakpoints at the same address and section, marking the
12458      first one as "first" and any others as "duplicates".  This is so
12459      that the bpt instruction is only inserted once.  If we have a
12460      permanent breakpoint at the same place as BPT, make that one the
12461      official one, and the rest as duplicates.  Permanent breakpoints
12462      are sorted first for the same address.
12463
12464      Do the same for hardware watchpoints, but also considering the
12465      watchpoint's type (regular/access/read) and length.  */
12466
12467   bp_loc_first = NULL;
12468   wp_loc_first = NULL;
12469   awp_loc_first = NULL;
12470   rwp_loc_first = NULL;
12471   ALL_BP_LOCATIONS (loc, locp)
12472     {
12473       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12474          non-NULL.  */
12475       struct bp_location **loc_first_p;
12476       b = loc->owner;
12477
12478       if (!unduplicated_should_be_inserted (loc)
12479           || !breakpoint_address_is_meaningful (b)
12480           /* Don't detect duplicate for tracepoint locations because they are
12481            never duplicated.  See the comments in field `duplicate' of
12482            `struct bp_location'.  */
12483           || is_tracepoint (b))
12484         {
12485           /* Clear the condition modification flag.  */
12486           loc->condition_changed = condition_unchanged;
12487           continue;
12488         }
12489
12490       /* Permanent breakpoint should always be inserted.  */
12491       if (b->enable_state == bp_permanent && ! loc->inserted)
12492         internal_error (__FILE__, __LINE__,
12493                         _("allegedly permanent breakpoint is not "
12494                         "actually inserted"));
12495
12496       if (b->type == bp_hardware_watchpoint)
12497         loc_first_p = &wp_loc_first;
12498       else if (b->type == bp_read_watchpoint)
12499         loc_first_p = &rwp_loc_first;
12500       else if (b->type == bp_access_watchpoint)
12501         loc_first_p = &awp_loc_first;
12502       else
12503         loc_first_p = &bp_loc_first;
12504
12505       if (*loc_first_p == NULL
12506           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12507           || !breakpoint_locations_match (loc, *loc_first_p))
12508         {
12509           *loc_first_p = loc;
12510           loc->duplicate = 0;
12511
12512           if (is_breakpoint (loc->owner) && loc->condition_changed)
12513             {
12514               loc->needs_update = 1;
12515               /* Clear the condition modification flag.  */
12516               loc->condition_changed = condition_unchanged;
12517             }
12518           continue;
12519         }
12520
12521
12522       /* This and the above ensure the invariant that the first location
12523          is not duplicated, and is the inserted one.
12524          All following are marked as duplicated, and are not inserted.  */
12525       if (loc->inserted)
12526         swap_insertion (loc, *loc_first_p);
12527       loc->duplicate = 1;
12528
12529       /* Clear the condition modification flag.  */
12530       loc->condition_changed = condition_unchanged;
12531
12532       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12533           && b->enable_state != bp_permanent)
12534         internal_error (__FILE__, __LINE__,
12535                         _("another breakpoint was inserted on top of "
12536                         "a permanent breakpoint"));
12537     }
12538
12539   if (breakpoints_always_inserted_mode ()
12540       && (have_live_inferiors ()
12541           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12542     {
12543       if (should_insert)
12544         insert_breakpoint_locations ();
12545       else
12546         {
12547           /* Though should_insert is false, we may need to update conditions
12548              on the target's side if it is evaluating such conditions.  We
12549              only update conditions for locations that are marked
12550              "needs_update".  */
12551           update_inserted_breakpoint_locations ();
12552         }
12553     }
12554
12555   if (should_insert)
12556     download_tracepoint_locations ();
12557
12558   do_cleanups (cleanups);
12559 }
12560
12561 void
12562 breakpoint_retire_moribund (void)
12563 {
12564   struct bp_location *loc;
12565   int ix;
12566
12567   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12568     if (--(loc->events_till_retirement) == 0)
12569       {
12570         decref_bp_location (&loc);
12571         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12572         --ix;
12573       }
12574 }
12575
12576 static void
12577 update_global_location_list_nothrow (int inserting)
12578 {
12579   volatile struct gdb_exception e;
12580
12581   TRY_CATCH (e, RETURN_MASK_ERROR)
12582     update_global_location_list (inserting);
12583 }
12584
12585 /* Clear BKP from a BPS.  */
12586
12587 static void
12588 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12589 {
12590   bpstat bs;
12591
12592   for (bs = bps; bs; bs = bs->next)
12593     if (bs->breakpoint_at == bpt)
12594       {
12595         bs->breakpoint_at = NULL;
12596         bs->old_val = NULL;
12597         /* bs->commands will be freed later.  */
12598       }
12599 }
12600
12601 /* Callback for iterate_over_threads.  */
12602 static int
12603 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12604 {
12605   struct breakpoint *bpt = data;
12606
12607   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12608   return 0;
12609 }
12610
12611 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12612    callbacks.  */
12613
12614 static void
12615 say_where (struct breakpoint *b)
12616 {
12617   struct value_print_options opts;
12618
12619   get_user_print_options (&opts);
12620
12621   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12622      single string.  */
12623   if (b->loc == NULL)
12624     {
12625       printf_filtered (_(" (%s) pending."), b->addr_string);
12626     }
12627   else
12628     {
12629       if (opts.addressprint || b->loc->symtab == NULL)
12630         {
12631           printf_filtered (" at ");
12632           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12633                           gdb_stdout);
12634         }
12635       if (b->loc->symtab != NULL)
12636         {
12637           /* If there is a single location, we can print the location
12638              more nicely.  */
12639           if (b->loc->next == NULL)
12640             printf_filtered (": file %s, line %d.",
12641                              symtab_to_filename_for_display (b->loc->symtab),
12642                              b->loc->line_number);
12643           else
12644             /* This is not ideal, but each location may have a
12645                different file name, and this at least reflects the
12646                real situation somewhat.  */
12647             printf_filtered (": %s.", b->addr_string);
12648         }
12649
12650       if (b->loc->next)
12651         {
12652           struct bp_location *loc = b->loc;
12653           int n = 0;
12654           for (; loc; loc = loc->next)
12655             ++n;
12656           printf_filtered (" (%d locations)", n);
12657         }
12658     }
12659 }
12660
12661 /* Default bp_location_ops methods.  */
12662
12663 static void
12664 bp_location_dtor (struct bp_location *self)
12665 {
12666   xfree (self->cond);
12667   if (self->cond_bytecode)
12668     free_agent_expr (self->cond_bytecode);
12669   xfree (self->function_name);
12670 }
12671
12672 static const struct bp_location_ops bp_location_ops =
12673 {
12674   bp_location_dtor
12675 };
12676
12677 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12678    inherit from.  */
12679
12680 static void
12681 base_breakpoint_dtor (struct breakpoint *self)
12682 {
12683   decref_counted_command_line (&self->commands);
12684   xfree (self->cond_string);
12685   xfree (self->extra_string);
12686   xfree (self->addr_string);
12687   xfree (self->filter);
12688   xfree (self->addr_string_range_end);
12689 }
12690
12691 static struct bp_location *
12692 base_breakpoint_allocate_location (struct breakpoint *self)
12693 {
12694   struct bp_location *loc;
12695
12696   loc = XNEW (struct bp_location);
12697   init_bp_location (loc, &bp_location_ops, self);
12698   return loc;
12699 }
12700
12701 static void
12702 base_breakpoint_re_set (struct breakpoint *b)
12703 {
12704   /* Nothing to re-set. */
12705 }
12706
12707 #define internal_error_pure_virtual_called() \
12708   gdb_assert_not_reached ("pure virtual function called")
12709
12710 static int
12711 base_breakpoint_insert_location (struct bp_location *bl)
12712 {
12713   internal_error_pure_virtual_called ();
12714 }
12715
12716 static int
12717 base_breakpoint_remove_location (struct bp_location *bl)
12718 {
12719   internal_error_pure_virtual_called ();
12720 }
12721
12722 static int
12723 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12724                                 struct address_space *aspace,
12725                                 CORE_ADDR bp_addr,
12726                                 const struct target_waitstatus *ws)
12727 {
12728   internal_error_pure_virtual_called ();
12729 }
12730
12731 static void
12732 base_breakpoint_check_status (bpstat bs)
12733 {
12734   /* Always stop.   */
12735 }
12736
12737 /* A "works_in_software_mode" breakpoint_ops method that just internal
12738    errors.  */
12739
12740 static int
12741 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12742 {
12743   internal_error_pure_virtual_called ();
12744 }
12745
12746 /* A "resources_needed" breakpoint_ops method that just internal
12747    errors.  */
12748
12749 static int
12750 base_breakpoint_resources_needed (const struct bp_location *bl)
12751 {
12752   internal_error_pure_virtual_called ();
12753 }
12754
12755 static enum print_stop_action
12756 base_breakpoint_print_it (bpstat bs)
12757 {
12758   internal_error_pure_virtual_called ();
12759 }
12760
12761 static void
12762 base_breakpoint_print_one_detail (const struct breakpoint *self,
12763                                   struct ui_out *uiout)
12764 {
12765   /* nothing */
12766 }
12767
12768 static void
12769 base_breakpoint_print_mention (struct breakpoint *b)
12770 {
12771   internal_error_pure_virtual_called ();
12772 }
12773
12774 static void
12775 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12776 {
12777   internal_error_pure_virtual_called ();
12778 }
12779
12780 static void
12781 base_breakpoint_create_sals_from_address (char **arg,
12782                                           struct linespec_result *canonical,
12783                                           enum bptype type_wanted,
12784                                           char *addr_start,
12785                                           char **copy_arg)
12786 {
12787   internal_error_pure_virtual_called ();
12788 }
12789
12790 static void
12791 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12792                                         struct linespec_result *c,
12793                                         char *cond_string,
12794                                         char *extra_string,
12795                                         enum bptype type_wanted,
12796                                         enum bpdisp disposition,
12797                                         int thread,
12798                                         int task, int ignore_count,
12799                                         const struct breakpoint_ops *o,
12800                                         int from_tty, int enabled,
12801                                         int internal, unsigned flags)
12802 {
12803   internal_error_pure_virtual_called ();
12804 }
12805
12806 static void
12807 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12808                                  struct symtabs_and_lines *sals)
12809 {
12810   internal_error_pure_virtual_called ();
12811 }
12812
12813 /* The default 'explains_signal' method.  */
12814
12815 static enum bpstat_signal_value
12816 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12817 {
12818   return BPSTAT_SIGNAL_HIDE;
12819 }
12820
12821 /* The default "after_condition_true" method.  */
12822
12823 static void
12824 base_breakpoint_after_condition_true (struct bpstats *bs)
12825 {
12826   /* Nothing to do.   */
12827 }
12828
12829 struct breakpoint_ops base_breakpoint_ops =
12830 {
12831   base_breakpoint_dtor,
12832   base_breakpoint_allocate_location,
12833   base_breakpoint_re_set,
12834   base_breakpoint_insert_location,
12835   base_breakpoint_remove_location,
12836   base_breakpoint_breakpoint_hit,
12837   base_breakpoint_check_status,
12838   base_breakpoint_resources_needed,
12839   base_breakpoint_works_in_software_mode,
12840   base_breakpoint_print_it,
12841   NULL,
12842   base_breakpoint_print_one_detail,
12843   base_breakpoint_print_mention,
12844   base_breakpoint_print_recreate,
12845   base_breakpoint_create_sals_from_address,
12846   base_breakpoint_create_breakpoints_sal,
12847   base_breakpoint_decode_linespec,
12848   base_breakpoint_explains_signal,
12849   base_breakpoint_after_condition_true,
12850 };
12851
12852 /* Default breakpoint_ops methods.  */
12853
12854 static void
12855 bkpt_re_set (struct breakpoint *b)
12856 {
12857   /* FIXME: is this still reachable?  */
12858   if (b->addr_string == NULL)
12859     {
12860       /* Anything without a string can't be re-set.  */
12861       delete_breakpoint (b);
12862       return;
12863     }
12864
12865   breakpoint_re_set_default (b);
12866 }
12867
12868 static int
12869 bkpt_insert_location (struct bp_location *bl)
12870 {
12871   if (bl->loc_type == bp_loc_hardware_breakpoint)
12872     return target_insert_hw_breakpoint (bl->gdbarch,
12873                                         &bl->target_info);
12874   else
12875     return target_insert_breakpoint (bl->gdbarch,
12876                                      &bl->target_info);
12877 }
12878
12879 static int
12880 bkpt_remove_location (struct bp_location *bl)
12881 {
12882   if (bl->loc_type == bp_loc_hardware_breakpoint)
12883     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12884   else
12885     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12886 }
12887
12888 static int
12889 bkpt_breakpoint_hit (const struct bp_location *bl,
12890                      struct address_space *aspace, CORE_ADDR bp_addr,
12891                      const struct target_waitstatus *ws)
12892 {
12893   if (ws->kind != TARGET_WAITKIND_STOPPED
12894       || ws->value.sig != GDB_SIGNAL_TRAP)
12895     return 0;
12896
12897   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12898                                  aspace, bp_addr))
12899     return 0;
12900
12901   if (overlay_debugging         /* unmapped overlay section */
12902       && section_is_overlay (bl->section)
12903       && !section_is_mapped (bl->section))
12904     return 0;
12905
12906   return 1;
12907 }
12908
12909 static int
12910 bkpt_resources_needed (const struct bp_location *bl)
12911 {
12912   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12913
12914   return 1;
12915 }
12916
12917 static enum print_stop_action
12918 bkpt_print_it (bpstat bs)
12919 {
12920   struct breakpoint *b;
12921   const struct bp_location *bl;
12922   int bp_temp;
12923   struct ui_out *uiout = current_uiout;
12924
12925   gdb_assert (bs->bp_location_at != NULL);
12926
12927   bl = bs->bp_location_at;
12928   b = bs->breakpoint_at;
12929
12930   bp_temp = b->disposition == disp_del;
12931   if (bl->address != bl->requested_address)
12932     breakpoint_adjustment_warning (bl->requested_address,
12933                                    bl->address,
12934                                    b->number, 1);
12935   annotate_breakpoint (b->number);
12936   if (bp_temp)
12937     ui_out_text (uiout, "\nTemporary breakpoint ");
12938   else
12939     ui_out_text (uiout, "\nBreakpoint ");
12940   if (ui_out_is_mi_like_p (uiout))
12941     {
12942       ui_out_field_string (uiout, "reason",
12943                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12944       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12945     }
12946   ui_out_field_int (uiout, "bkptno", b->number);
12947   ui_out_text (uiout, ", ");
12948
12949   return PRINT_SRC_AND_LOC;
12950 }
12951
12952 static void
12953 bkpt_print_mention (struct breakpoint *b)
12954 {
12955   if (ui_out_is_mi_like_p (current_uiout))
12956     return;
12957
12958   switch (b->type)
12959     {
12960     case bp_breakpoint:
12961     case bp_gnu_ifunc_resolver:
12962       if (b->disposition == disp_del)
12963         printf_filtered (_("Temporary breakpoint"));
12964       else
12965         printf_filtered (_("Breakpoint"));
12966       printf_filtered (_(" %d"), b->number);
12967       if (b->type == bp_gnu_ifunc_resolver)
12968         printf_filtered (_(" at gnu-indirect-function resolver"));
12969       break;
12970     case bp_hardware_breakpoint:
12971       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12972       break;
12973     case bp_dprintf:
12974       printf_filtered (_("Dprintf %d"), b->number);
12975       break;
12976     }
12977
12978   say_where (b);
12979 }
12980
12981 static void
12982 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12983 {
12984   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12985     fprintf_unfiltered (fp, "tbreak");
12986   else if (tp->type == bp_breakpoint)
12987     fprintf_unfiltered (fp, "break");
12988   else if (tp->type == bp_hardware_breakpoint
12989            && tp->disposition == disp_del)
12990     fprintf_unfiltered (fp, "thbreak");
12991   else if (tp->type == bp_hardware_breakpoint)
12992     fprintf_unfiltered (fp, "hbreak");
12993   else
12994     internal_error (__FILE__, __LINE__,
12995                     _("unhandled breakpoint type %d"), (int) tp->type);
12996
12997   fprintf_unfiltered (fp, " %s", tp->addr_string);
12998   print_recreate_thread (tp, fp);
12999 }
13000
13001 static void
13002 bkpt_create_sals_from_address (char **arg,
13003                                struct linespec_result *canonical,
13004                                enum bptype type_wanted,
13005                                char *addr_start, char **copy_arg)
13006 {
13007   create_sals_from_address_default (arg, canonical, type_wanted,
13008                                     addr_start, copy_arg);
13009 }
13010
13011 static void
13012 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13013                              struct linespec_result *canonical,
13014                              char *cond_string,
13015                              char *extra_string,
13016                              enum bptype type_wanted,
13017                              enum bpdisp disposition,
13018                              int thread,
13019                              int task, int ignore_count,
13020                              const struct breakpoint_ops *ops,
13021                              int from_tty, int enabled,
13022                              int internal, unsigned flags)
13023 {
13024   create_breakpoints_sal_default (gdbarch, canonical,
13025                                   cond_string, extra_string,
13026                                   type_wanted,
13027                                   disposition, thread, task,
13028                                   ignore_count, ops, from_tty,
13029                                   enabled, internal, flags);
13030 }
13031
13032 static void
13033 bkpt_decode_linespec (struct breakpoint *b, char **s,
13034                       struct symtabs_and_lines *sals)
13035 {
13036   decode_linespec_default (b, s, sals);
13037 }
13038
13039 /* Virtual table for internal breakpoints.  */
13040
13041 static void
13042 internal_bkpt_re_set (struct breakpoint *b)
13043 {
13044   switch (b->type)
13045     {
13046       /* Delete overlay event and longjmp master breakpoints; they
13047          will be reset later by breakpoint_re_set.  */
13048     case bp_overlay_event:
13049     case bp_longjmp_master:
13050     case bp_std_terminate_master:
13051     case bp_exception_master:
13052       delete_breakpoint (b);
13053       break;
13054
13055       /* This breakpoint is special, it's set up when the inferior
13056          starts and we really don't want to touch it.  */
13057     case bp_shlib_event:
13058
13059       /* Like bp_shlib_event, this breakpoint type is special.  Once
13060          it is set up, we do not want to touch it.  */
13061     case bp_thread_event:
13062       break;
13063     }
13064 }
13065
13066 static void
13067 internal_bkpt_check_status (bpstat bs)
13068 {
13069   if (bs->breakpoint_at->type == bp_shlib_event)
13070     {
13071       /* If requested, stop when the dynamic linker notifies GDB of
13072          events.  This allows the user to get control and place
13073          breakpoints in initializer routines for dynamically loaded
13074          objects (among other things).  */
13075       bs->stop = stop_on_solib_events;
13076       bs->print = stop_on_solib_events;
13077     }
13078   else
13079     bs->stop = 0;
13080 }
13081
13082 static enum print_stop_action
13083 internal_bkpt_print_it (bpstat bs)
13084 {
13085   struct breakpoint *b;
13086
13087   b = bs->breakpoint_at;
13088
13089   switch (b->type)
13090     {
13091     case bp_shlib_event:
13092       /* Did we stop because the user set the stop_on_solib_events
13093          variable?  (If so, we report this as a generic, "Stopped due
13094          to shlib event" message.) */
13095       print_solib_event (0);
13096       break;
13097
13098     case bp_thread_event:
13099       /* Not sure how we will get here.
13100          GDB should not stop for these breakpoints.  */
13101       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13102       break;
13103
13104     case bp_overlay_event:
13105       /* By analogy with the thread event, GDB should not stop for these.  */
13106       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13107       break;
13108
13109     case bp_longjmp_master:
13110       /* These should never be enabled.  */
13111       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13112       break;
13113
13114     case bp_std_terminate_master:
13115       /* These should never be enabled.  */
13116       printf_filtered (_("std::terminate Master Breakpoint: "
13117                          "gdb should not stop!\n"));
13118       break;
13119
13120     case bp_exception_master:
13121       /* These should never be enabled.  */
13122       printf_filtered (_("Exception Master Breakpoint: "
13123                          "gdb should not stop!\n"));
13124       break;
13125     }
13126
13127   return PRINT_NOTHING;
13128 }
13129
13130 static void
13131 internal_bkpt_print_mention (struct breakpoint *b)
13132 {
13133   /* Nothing to mention.  These breakpoints are internal.  */
13134 }
13135
13136 /* Virtual table for momentary breakpoints  */
13137
13138 static void
13139 momentary_bkpt_re_set (struct breakpoint *b)
13140 {
13141   /* Keep temporary breakpoints, which can be encountered when we step
13142      over a dlopen call and solib_add is resetting the breakpoints.
13143      Otherwise these should have been blown away via the cleanup chain
13144      or by breakpoint_init_inferior when we rerun the executable.  */
13145 }
13146
13147 static void
13148 momentary_bkpt_check_status (bpstat bs)
13149 {
13150   /* Nothing.  The point of these breakpoints is causing a stop.  */
13151 }
13152
13153 static enum print_stop_action
13154 momentary_bkpt_print_it (bpstat bs)
13155 {
13156   struct ui_out *uiout = current_uiout;
13157
13158   if (ui_out_is_mi_like_p (uiout))
13159     {
13160       struct breakpoint *b = bs->breakpoint_at;
13161
13162       switch (b->type)
13163         {
13164         case bp_finish:
13165           ui_out_field_string
13166             (uiout, "reason",
13167              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13168           break;
13169
13170         case bp_until:
13171           ui_out_field_string
13172             (uiout, "reason",
13173              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13174           break;
13175         }
13176     }
13177
13178   return PRINT_UNKNOWN;
13179 }
13180
13181 static void
13182 momentary_bkpt_print_mention (struct breakpoint *b)
13183 {
13184   /* Nothing to mention.  These breakpoints are internal.  */
13185 }
13186
13187 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13188
13189    It gets cleared already on the removal of the first one of such placed
13190    breakpoints.  This is OK as they get all removed altogether.  */
13191
13192 static void
13193 longjmp_bkpt_dtor (struct breakpoint *self)
13194 {
13195   struct thread_info *tp = find_thread_id (self->thread);
13196
13197   if (tp)
13198     tp->initiating_frame = null_frame_id;
13199
13200   momentary_breakpoint_ops.dtor (self);
13201 }
13202
13203 /* Specific methods for probe breakpoints.  */
13204
13205 static int
13206 bkpt_probe_insert_location (struct bp_location *bl)
13207 {
13208   int v = bkpt_insert_location (bl);
13209
13210   if (v == 0)
13211     {
13212       /* The insertion was successful, now let's set the probe's semaphore
13213          if needed.  */
13214       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
13215     }
13216
13217   return v;
13218 }
13219
13220 static int
13221 bkpt_probe_remove_location (struct bp_location *bl)
13222 {
13223   /* Let's clear the semaphore before removing the location.  */
13224   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
13225
13226   return bkpt_remove_location (bl);
13227 }
13228
13229 static void
13230 bkpt_probe_create_sals_from_address (char **arg,
13231                                      struct linespec_result *canonical,
13232                                      enum bptype type_wanted,
13233                                      char *addr_start, char **copy_arg)
13234 {
13235   struct linespec_sals lsal;
13236
13237   lsal.sals = parse_probes (arg, canonical);
13238
13239   *copy_arg = xstrdup (canonical->addr_string);
13240   lsal.canonical = xstrdup (*copy_arg);
13241
13242   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13243 }
13244
13245 static void
13246 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13247                             struct symtabs_and_lines *sals)
13248 {
13249   *sals = parse_probes (s, NULL);
13250   if (!sals->sals)
13251     error (_("probe not found"));
13252 }
13253
13254 /* The breakpoint_ops structure to be used in tracepoints.  */
13255
13256 static void
13257 tracepoint_re_set (struct breakpoint *b)
13258 {
13259   breakpoint_re_set_default (b);
13260 }
13261
13262 static int
13263 tracepoint_breakpoint_hit (const struct bp_location *bl,
13264                            struct address_space *aspace, CORE_ADDR bp_addr,
13265                            const struct target_waitstatus *ws)
13266 {
13267   /* By definition, the inferior does not report stops at
13268      tracepoints.  */
13269   return 0;
13270 }
13271
13272 static void
13273 tracepoint_print_one_detail (const struct breakpoint *self,
13274                              struct ui_out *uiout)
13275 {
13276   struct tracepoint *tp = (struct tracepoint *) self;
13277   if (tp->static_trace_marker_id)
13278     {
13279       gdb_assert (self->type == bp_static_tracepoint);
13280
13281       ui_out_text (uiout, "\tmarker id is ");
13282       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13283                            tp->static_trace_marker_id);
13284       ui_out_text (uiout, "\n");
13285     }
13286 }
13287
13288 static void
13289 tracepoint_print_mention (struct breakpoint *b)
13290 {
13291   if (ui_out_is_mi_like_p (current_uiout))
13292     return;
13293
13294   switch (b->type)
13295     {
13296     case bp_tracepoint:
13297       printf_filtered (_("Tracepoint"));
13298       printf_filtered (_(" %d"), b->number);
13299       break;
13300     case bp_fast_tracepoint:
13301       printf_filtered (_("Fast tracepoint"));
13302       printf_filtered (_(" %d"), b->number);
13303       break;
13304     case bp_static_tracepoint:
13305       printf_filtered (_("Static tracepoint"));
13306       printf_filtered (_(" %d"), b->number);
13307       break;
13308     default:
13309       internal_error (__FILE__, __LINE__,
13310                       _("unhandled tracepoint type %d"), (int) b->type);
13311     }
13312
13313   say_where (b);
13314 }
13315
13316 static void
13317 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13318 {
13319   struct tracepoint *tp = (struct tracepoint *) self;
13320
13321   if (self->type == bp_fast_tracepoint)
13322     fprintf_unfiltered (fp, "ftrace");
13323   if (self->type == bp_static_tracepoint)
13324     fprintf_unfiltered (fp, "strace");
13325   else if (self->type == bp_tracepoint)
13326     fprintf_unfiltered (fp, "trace");
13327   else
13328     internal_error (__FILE__, __LINE__,
13329                     _("unhandled tracepoint type %d"), (int) self->type);
13330
13331   fprintf_unfiltered (fp, " %s", self->addr_string);
13332   print_recreate_thread (self, fp);
13333
13334   if (tp->pass_count)
13335     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13336 }
13337
13338 static void
13339 tracepoint_create_sals_from_address (char **arg,
13340                                      struct linespec_result *canonical,
13341                                      enum bptype type_wanted,
13342                                      char *addr_start, char **copy_arg)
13343 {
13344   create_sals_from_address_default (arg, canonical, type_wanted,
13345                                     addr_start, copy_arg);
13346 }
13347
13348 static void
13349 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13350                                    struct linespec_result *canonical,
13351                                    char *cond_string,
13352                                    char *extra_string,
13353                                    enum bptype type_wanted,
13354                                    enum bpdisp disposition,
13355                                    int thread,
13356                                    int task, int ignore_count,
13357                                    const struct breakpoint_ops *ops,
13358                                    int from_tty, int enabled,
13359                                    int internal, unsigned flags)
13360 {
13361   create_breakpoints_sal_default (gdbarch, canonical,
13362                                   cond_string, extra_string,
13363                                   type_wanted,
13364                                   disposition, thread, task,
13365                                   ignore_count, ops, from_tty,
13366                                   enabled, internal, flags);
13367 }
13368
13369 static void
13370 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13371                             struct symtabs_and_lines *sals)
13372 {
13373   decode_linespec_default (b, s, sals);
13374 }
13375
13376 struct breakpoint_ops tracepoint_breakpoint_ops;
13377
13378 /* The breakpoint_ops structure to be use on tracepoints placed in a
13379    static probe.  */
13380
13381 static void
13382 tracepoint_probe_create_sals_from_address (char **arg,
13383                                            struct linespec_result *canonical,
13384                                            enum bptype type_wanted,
13385                                            char *addr_start, char **copy_arg)
13386 {
13387   /* We use the same method for breakpoint on probes.  */
13388   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13389                                        addr_start, copy_arg);
13390 }
13391
13392 static void
13393 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13394                                   struct symtabs_and_lines *sals)
13395 {
13396   /* We use the same method for breakpoint on probes.  */
13397   bkpt_probe_decode_linespec (b, s, sals);
13398 }
13399
13400 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13401
13402 /* Dprintf breakpoint_ops methods.  */
13403
13404 static void
13405 dprintf_re_set (struct breakpoint *b)
13406 {
13407   breakpoint_re_set_default (b);
13408
13409   /* This breakpoint could have been pending, and be resolved now, and
13410      if so, we should now have the extra string.  If we don't, the
13411      dprintf was malformed when created, but we couldn't tell because
13412      we can't extract the extra string until the location is
13413      resolved.  */
13414   if (b->loc != NULL && b->extra_string == NULL)
13415     error (_("Format string required"));
13416
13417   /* 1 - connect to target 1, that can run breakpoint commands.
13418      2 - create a dprintf, which resolves fine.
13419      3 - disconnect from target 1
13420      4 - connect to target 2, that can NOT run breakpoint commands.
13421
13422      After steps #3/#4, you'll want the dprintf command list to
13423      be updated, because target 1 and 2 may well return different
13424      answers for target_can_run_breakpoint_commands().
13425      Given absence of finer grained resetting, we get to do
13426      it all the time.  */
13427   if (b->extra_string != NULL)
13428     update_dprintf_command_list (b);
13429 }
13430
13431 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13432
13433 static void
13434 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13435 {
13436   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13437                       tp->extra_string);
13438   print_recreate_thread (tp, fp);
13439 }
13440
13441 /* Implement the "after_condition_true" breakpoint_ops method for
13442    dprintf.
13443
13444    dprintf's are implemented with regular commands in their command
13445    list, but we run the commands here instead of before presenting the
13446    stop to the user, as dprintf's don't actually cause a stop.  This
13447    also makes it so that the commands of multiple dprintfs at the same
13448    address are all handled.  */
13449
13450 static void
13451 dprintf_after_condition_true (struct bpstats *bs)
13452 {
13453   struct cleanup *old_chain;
13454   struct bpstats tmp_bs = { NULL };
13455   struct bpstats *tmp_bs_p = &tmp_bs;
13456
13457   /* dprintf's never cause a stop.  This wasn't set in the
13458      check_status hook instead because that would make the dprintf's
13459      condition not be evaluated.  */
13460   bs->stop = 0;
13461
13462   /* Run the command list here.  Take ownership of it instead of
13463      copying.  We never want these commands to run later in
13464      bpstat_do_actions, if a breakpoint that causes a stop happens to
13465      be set at same address as this dprintf, or even if running the
13466      commands here throws.  */
13467   tmp_bs.commands = bs->commands;
13468   bs->commands = NULL;
13469   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13470
13471   bpstat_do_actions_1 (&tmp_bs_p);
13472
13473   /* 'tmp_bs.commands' will usually be NULL by now, but
13474      bpstat_do_actions_1 may return early without processing the whole
13475      list.  */
13476   do_cleanups (old_chain);
13477 }
13478
13479 /* The breakpoint_ops structure to be used on static tracepoints with
13480    markers (`-m').  */
13481
13482 static void
13483 strace_marker_create_sals_from_address (char **arg,
13484                                         struct linespec_result *canonical,
13485                                         enum bptype type_wanted,
13486                                         char *addr_start, char **copy_arg)
13487 {
13488   struct linespec_sals lsal;
13489
13490   lsal.sals = decode_static_tracepoint_spec (arg);
13491
13492   *copy_arg = savestring (addr_start, *arg - addr_start);
13493
13494   canonical->addr_string = xstrdup (*copy_arg);
13495   lsal.canonical = xstrdup (*copy_arg);
13496   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13497 }
13498
13499 static void
13500 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13501                                       struct linespec_result *canonical,
13502                                       char *cond_string,
13503                                       char *extra_string,
13504                                       enum bptype type_wanted,
13505                                       enum bpdisp disposition,
13506                                       int thread,
13507                                       int task, int ignore_count,
13508                                       const struct breakpoint_ops *ops,
13509                                       int from_tty, int enabled,
13510                                       int internal, unsigned flags)
13511 {
13512   int i;
13513   struct linespec_sals *lsal = VEC_index (linespec_sals,
13514                                           canonical->sals, 0);
13515
13516   /* If the user is creating a static tracepoint by marker id
13517      (strace -m MARKER_ID), then store the sals index, so that
13518      breakpoint_re_set can try to match up which of the newly
13519      found markers corresponds to this one, and, don't try to
13520      expand multiple locations for each sal, given than SALS
13521      already should contain all sals for MARKER_ID.  */
13522
13523   for (i = 0; i < lsal->sals.nelts; ++i)
13524     {
13525       struct symtabs_and_lines expanded;
13526       struct tracepoint *tp;
13527       struct cleanup *old_chain;
13528       char *addr_string;
13529
13530       expanded.nelts = 1;
13531       expanded.sals = &lsal->sals.sals[i];
13532
13533       addr_string = xstrdup (canonical->addr_string);
13534       old_chain = make_cleanup (xfree, addr_string);
13535
13536       tp = XCNEW (struct tracepoint);
13537       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13538                            addr_string, NULL,
13539                            cond_string, extra_string,
13540                            type_wanted, disposition,
13541                            thread, task, ignore_count, ops,
13542                            from_tty, enabled, internal, flags,
13543                            canonical->special_display);
13544       /* Given that its possible to have multiple markers with
13545          the same string id, if the user is creating a static
13546          tracepoint by marker id ("strace -m MARKER_ID"), then
13547          store the sals index, so that breakpoint_re_set can
13548          try to match up which of the newly found markers
13549          corresponds to this one  */
13550       tp->static_trace_marker_id_idx = i;
13551
13552       install_breakpoint (internal, &tp->base, 0);
13553
13554       discard_cleanups (old_chain);
13555     }
13556 }
13557
13558 static void
13559 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13560                                struct symtabs_and_lines *sals)
13561 {
13562   struct tracepoint *tp = (struct tracepoint *) b;
13563
13564   *sals = decode_static_tracepoint_spec (s);
13565   if (sals->nelts > tp->static_trace_marker_id_idx)
13566     {
13567       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13568       sals->nelts = 1;
13569     }
13570   else
13571     error (_("marker %s not found"), tp->static_trace_marker_id);
13572 }
13573
13574 static struct breakpoint_ops strace_marker_breakpoint_ops;
13575
13576 static int
13577 strace_marker_p (struct breakpoint *b)
13578 {
13579   return b->ops == &strace_marker_breakpoint_ops;
13580 }
13581
13582 /* Delete a breakpoint and clean up all traces of it in the data
13583    structures.  */
13584
13585 void
13586 delete_breakpoint (struct breakpoint *bpt)
13587 {
13588   struct breakpoint *b;
13589
13590   gdb_assert (bpt != NULL);
13591
13592   /* Has this bp already been deleted?  This can happen because
13593      multiple lists can hold pointers to bp's.  bpstat lists are
13594      especial culprits.
13595
13596      One example of this happening is a watchpoint's scope bp.  When
13597      the scope bp triggers, we notice that the watchpoint is out of
13598      scope, and delete it.  We also delete its scope bp.  But the
13599      scope bp is marked "auto-deleting", and is already on a bpstat.
13600      That bpstat is then checked for auto-deleting bp's, which are
13601      deleted.
13602
13603      A real solution to this problem might involve reference counts in
13604      bp's, and/or giving them pointers back to their referencing
13605      bpstat's, and teaching delete_breakpoint to only free a bp's
13606      storage when no more references were extent.  A cheaper bandaid
13607      was chosen.  */
13608   if (bpt->type == bp_none)
13609     return;
13610
13611   /* At least avoid this stale reference until the reference counting
13612      of breakpoints gets resolved.  */
13613   if (bpt->related_breakpoint != bpt)
13614     {
13615       struct breakpoint *related;
13616       struct watchpoint *w;
13617
13618       if (bpt->type == bp_watchpoint_scope)
13619         w = (struct watchpoint *) bpt->related_breakpoint;
13620       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13621         w = (struct watchpoint *) bpt;
13622       else
13623         w = NULL;
13624       if (w != NULL)
13625         watchpoint_del_at_next_stop (w);
13626
13627       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13628       for (related = bpt; related->related_breakpoint != bpt;
13629            related = related->related_breakpoint);
13630       related->related_breakpoint = bpt->related_breakpoint;
13631       bpt->related_breakpoint = bpt;
13632     }
13633
13634   /* watch_command_1 creates a watchpoint but only sets its number if
13635      update_watchpoint succeeds in creating its bp_locations.  If there's
13636      a problem in that process, we'll be asked to delete the half-created
13637      watchpoint.  In that case, don't announce the deletion.  */
13638   if (bpt->number)
13639     observer_notify_breakpoint_deleted (bpt);
13640
13641   if (breakpoint_chain == bpt)
13642     breakpoint_chain = bpt->next;
13643
13644   ALL_BREAKPOINTS (b)
13645     if (b->next == bpt)
13646     {
13647       b->next = bpt->next;
13648       break;
13649     }
13650
13651   /* Be sure no bpstat's are pointing at the breakpoint after it's
13652      been freed.  */
13653   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13654      in all threads for now.  Note that we cannot just remove bpstats
13655      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13656      commands are associated with the bpstat; if we remove it here,
13657      then the later call to bpstat_do_actions (&stop_bpstat); in
13658      event-top.c won't do anything, and temporary breakpoints with
13659      commands won't work.  */
13660
13661   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13662
13663   /* Now that breakpoint is removed from breakpoint list, update the
13664      global location list.  This will remove locations that used to
13665      belong to this breakpoint.  Do this before freeing the breakpoint
13666      itself, since remove_breakpoint looks at location's owner.  It
13667      might be better design to have location completely
13668      self-contained, but it's not the case now.  */
13669   update_global_location_list (0);
13670
13671   bpt->ops->dtor (bpt);
13672   /* On the chance that someone will soon try again to delete this
13673      same bp, we mark it as deleted before freeing its storage.  */
13674   bpt->type = bp_none;
13675   xfree (bpt);
13676 }
13677
13678 static void
13679 do_delete_breakpoint_cleanup (void *b)
13680 {
13681   delete_breakpoint (b);
13682 }
13683
13684 struct cleanup *
13685 make_cleanup_delete_breakpoint (struct breakpoint *b)
13686 {
13687   return make_cleanup (do_delete_breakpoint_cleanup, b);
13688 }
13689
13690 /* Iterator function to call a user-provided callback function once
13691    for each of B and its related breakpoints.  */
13692
13693 static void
13694 iterate_over_related_breakpoints (struct breakpoint *b,
13695                                   void (*function) (struct breakpoint *,
13696                                                     void *),
13697                                   void *data)
13698 {
13699   struct breakpoint *related;
13700
13701   related = b;
13702   do
13703     {
13704       struct breakpoint *next;
13705
13706       /* FUNCTION may delete RELATED.  */
13707       next = related->related_breakpoint;
13708
13709       if (next == related)
13710         {
13711           /* RELATED is the last ring entry.  */
13712           function (related, data);
13713
13714           /* FUNCTION may have deleted it, so we'd never reach back to
13715              B.  There's nothing left to do anyway, so just break
13716              out.  */
13717           break;
13718         }
13719       else
13720         function (related, data);
13721
13722       related = next;
13723     }
13724   while (related != b);
13725 }
13726
13727 static void
13728 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13729 {
13730   delete_breakpoint (b);
13731 }
13732
13733 /* A callback for map_breakpoint_numbers that calls
13734    delete_breakpoint.  */
13735
13736 static void
13737 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13738 {
13739   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13740 }
13741
13742 void
13743 delete_command (char *arg, int from_tty)
13744 {
13745   struct breakpoint *b, *b_tmp;
13746
13747   dont_repeat ();
13748
13749   if (arg == 0)
13750     {
13751       int breaks_to_delete = 0;
13752
13753       /* Delete all breakpoints if no argument.  Do not delete
13754          internal breakpoints, these have to be deleted with an
13755          explicit breakpoint number argument.  */
13756       ALL_BREAKPOINTS (b)
13757         if (user_breakpoint_p (b))
13758           {
13759             breaks_to_delete = 1;
13760             break;
13761           }
13762
13763       /* Ask user only if there are some breakpoints to delete.  */
13764       if (!from_tty
13765           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13766         {
13767           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13768             if (user_breakpoint_p (b))
13769               delete_breakpoint (b);
13770         }
13771     }
13772   else
13773     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13774 }
13775
13776 static int
13777 all_locations_are_pending (struct bp_location *loc)
13778 {
13779   for (; loc; loc = loc->next)
13780     if (!loc->shlib_disabled
13781         && !loc->pspace->executing_startup)
13782       return 0;
13783   return 1;
13784 }
13785
13786 /* Subroutine of update_breakpoint_locations to simplify it.
13787    Return non-zero if multiple fns in list LOC have the same name.
13788    Null names are ignored.  */
13789
13790 static int
13791 ambiguous_names_p (struct bp_location *loc)
13792 {
13793   struct bp_location *l;
13794   htab_t htab = htab_create_alloc (13, htab_hash_string,
13795                                    (int (*) (const void *, 
13796                                              const void *)) streq,
13797                                    NULL, xcalloc, xfree);
13798
13799   for (l = loc; l != NULL; l = l->next)
13800     {
13801       const char **slot;
13802       const char *name = l->function_name;
13803
13804       /* Allow for some names to be NULL, ignore them.  */
13805       if (name == NULL)
13806         continue;
13807
13808       slot = (const char **) htab_find_slot (htab, (const void *) name,
13809                                              INSERT);
13810       /* NOTE: We can assume slot != NULL here because xcalloc never
13811          returns NULL.  */
13812       if (*slot != NULL)
13813         {
13814           htab_delete (htab);
13815           return 1;
13816         }
13817       *slot = name;
13818     }
13819
13820   htab_delete (htab);
13821   return 0;
13822 }
13823
13824 /* When symbols change, it probably means the sources changed as well,
13825    and it might mean the static tracepoint markers are no longer at
13826    the same address or line numbers they used to be at last we
13827    checked.  Losing your static tracepoints whenever you rebuild is
13828    undesirable.  This function tries to resync/rematch gdb static
13829    tracepoints with the markers on the target, for static tracepoints
13830    that have not been set by marker id.  Static tracepoint that have
13831    been set by marker id are reset by marker id in breakpoint_re_set.
13832    The heuristic is:
13833
13834    1) For a tracepoint set at a specific address, look for a marker at
13835    the old PC.  If one is found there, assume to be the same marker.
13836    If the name / string id of the marker found is different from the
13837    previous known name, assume that means the user renamed the marker
13838    in the sources, and output a warning.
13839
13840    2) For a tracepoint set at a given line number, look for a marker
13841    at the new address of the old line number.  If one is found there,
13842    assume to be the same marker.  If the name / string id of the
13843    marker found is different from the previous known name, assume that
13844    means the user renamed the marker in the sources, and output a
13845    warning.
13846
13847    3) If a marker is no longer found at the same address or line, it
13848    may mean the marker no longer exists.  But it may also just mean
13849    the code changed a bit.  Maybe the user added a few lines of code
13850    that made the marker move up or down (in line number terms).  Ask
13851    the target for info about the marker with the string id as we knew
13852    it.  If found, update line number and address in the matching
13853    static tracepoint.  This will get confused if there's more than one
13854    marker with the same ID (possible in UST, although unadvised
13855    precisely because it confuses tools).  */
13856
13857 static struct symtab_and_line
13858 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13859 {
13860   struct tracepoint *tp = (struct tracepoint *) b;
13861   struct static_tracepoint_marker marker;
13862   CORE_ADDR pc;
13863
13864   pc = sal.pc;
13865   if (sal.line)
13866     find_line_pc (sal.symtab, sal.line, &pc);
13867
13868   if (target_static_tracepoint_marker_at (pc, &marker))
13869     {
13870       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13871         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13872                  b->number,
13873                  tp->static_trace_marker_id, marker.str_id);
13874
13875       xfree (tp->static_trace_marker_id);
13876       tp->static_trace_marker_id = xstrdup (marker.str_id);
13877       release_static_tracepoint_marker (&marker);
13878
13879       return sal;
13880     }
13881
13882   /* Old marker wasn't found on target at lineno.  Try looking it up
13883      by string ID.  */
13884   if (!sal.explicit_pc
13885       && sal.line != 0
13886       && sal.symtab != NULL
13887       && tp->static_trace_marker_id != NULL)
13888     {
13889       VEC(static_tracepoint_marker_p) *markers;
13890
13891       markers
13892         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13893
13894       if (!VEC_empty(static_tracepoint_marker_p, markers))
13895         {
13896           struct symtab_and_line sal2;
13897           struct symbol *sym;
13898           struct static_tracepoint_marker *tpmarker;
13899           struct ui_out *uiout = current_uiout;
13900
13901           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13902
13903           xfree (tp->static_trace_marker_id);
13904           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13905
13906           warning (_("marker for static tracepoint %d (%s) not "
13907                      "found at previous line number"),
13908                    b->number, tp->static_trace_marker_id);
13909
13910           init_sal (&sal2);
13911
13912           sal2.pc = tpmarker->address;
13913
13914           sal2 = find_pc_line (tpmarker->address, 0);
13915           sym = find_pc_sect_function (tpmarker->address, NULL);
13916           ui_out_text (uiout, "Now in ");
13917           if (sym)
13918             {
13919               ui_out_field_string (uiout, "func",
13920                                    SYMBOL_PRINT_NAME (sym));
13921               ui_out_text (uiout, " at ");
13922             }
13923           ui_out_field_string (uiout, "file",
13924                                symtab_to_filename_for_display (sal2.symtab));
13925           ui_out_text (uiout, ":");
13926
13927           if (ui_out_is_mi_like_p (uiout))
13928             {
13929               const char *fullname = symtab_to_fullname (sal2.symtab);
13930
13931               ui_out_field_string (uiout, "fullname", fullname);
13932             }
13933
13934           ui_out_field_int (uiout, "line", sal2.line);
13935           ui_out_text (uiout, "\n");
13936
13937           b->loc->line_number = sal2.line;
13938           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13939
13940           xfree (b->addr_string);
13941           b->addr_string = xstrprintf ("%s:%d",
13942                                    symtab_to_filename_for_display (sal2.symtab),
13943                                        b->loc->line_number);
13944
13945           /* Might be nice to check if function changed, and warn if
13946              so.  */
13947
13948           release_static_tracepoint_marker (tpmarker);
13949         }
13950     }
13951   return sal;
13952 }
13953
13954 /* Returns 1 iff locations A and B are sufficiently same that
13955    we don't need to report breakpoint as changed.  */
13956
13957 static int
13958 locations_are_equal (struct bp_location *a, struct bp_location *b)
13959 {
13960   while (a && b)
13961     {
13962       if (a->address != b->address)
13963         return 0;
13964
13965       if (a->shlib_disabled != b->shlib_disabled)
13966         return 0;
13967
13968       if (a->enabled != b->enabled)
13969         return 0;
13970
13971       a = a->next;
13972       b = b->next;
13973     }
13974
13975   if ((a == NULL) != (b == NULL))
13976     return 0;
13977
13978   return 1;
13979 }
13980
13981 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13982    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13983    a ranged breakpoint.  */
13984
13985 void
13986 update_breakpoint_locations (struct breakpoint *b,
13987                              struct symtabs_and_lines sals,
13988                              struct symtabs_and_lines sals_end)
13989 {
13990   int i;
13991   struct bp_location *existing_locations = b->loc;
13992
13993   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13994     {
13995       /* Ranged breakpoints have only one start location and one end
13996          location.  */
13997       b->enable_state = bp_disabled;
13998       update_global_location_list (1);
13999       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14000                            "multiple locations found\n"),
14001                          b->number);
14002       return;
14003     }
14004
14005   /* If there's no new locations, and all existing locations are
14006      pending, don't do anything.  This optimizes the common case where
14007      all locations are in the same shared library, that was unloaded.
14008      We'd like to retain the location, so that when the library is
14009      loaded again, we don't loose the enabled/disabled status of the
14010      individual locations.  */
14011   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14012     return;
14013
14014   b->loc = NULL;
14015
14016   for (i = 0; i < sals.nelts; ++i)
14017     {
14018       struct bp_location *new_loc;
14019
14020       switch_to_program_space_and_thread (sals.sals[i].pspace);
14021
14022       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14023
14024       /* Reparse conditions, they might contain references to the
14025          old symtab.  */
14026       if (b->cond_string != NULL)
14027         {
14028           const char *s;
14029           volatile struct gdb_exception e;
14030
14031           s = b->cond_string;
14032           TRY_CATCH (e, RETURN_MASK_ERROR)
14033             {
14034               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14035                                            block_for_pc (sals.sals[i].pc), 
14036                                            0);
14037             }
14038           if (e.reason < 0)
14039             {
14040               warning (_("failed to reevaluate condition "
14041                          "for breakpoint %d: %s"), 
14042                        b->number, e.message);
14043               new_loc->enabled = 0;
14044             }
14045         }
14046
14047       if (sals_end.nelts)
14048         {
14049           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14050
14051           new_loc->length = end - sals.sals[0].pc + 1;
14052         }
14053     }
14054
14055   /* Update locations of permanent breakpoints.  */
14056   if (b->enable_state == bp_permanent)
14057     make_breakpoint_permanent (b);
14058
14059   /* If possible, carry over 'disable' status from existing
14060      breakpoints.  */
14061   {
14062     struct bp_location *e = existing_locations;
14063     /* If there are multiple breakpoints with the same function name,
14064        e.g. for inline functions, comparing function names won't work.
14065        Instead compare pc addresses; this is just a heuristic as things
14066        may have moved, but in practice it gives the correct answer
14067        often enough until a better solution is found.  */
14068     int have_ambiguous_names = ambiguous_names_p (b->loc);
14069
14070     for (; e; e = e->next)
14071       {
14072         if (!e->enabled && e->function_name)
14073           {
14074             struct bp_location *l = b->loc;
14075             if (have_ambiguous_names)
14076               {
14077                 for (; l; l = l->next)
14078                   if (breakpoint_locations_match (e, l))
14079                     {
14080                       l->enabled = 0;
14081                       break;
14082                     }
14083               }
14084             else
14085               {
14086                 for (; l; l = l->next)
14087                   if (l->function_name
14088                       && strcmp (e->function_name, l->function_name) == 0)
14089                     {
14090                       l->enabled = 0;
14091                       break;
14092                     }
14093               }
14094           }
14095       }
14096   }
14097
14098   if (!locations_are_equal (existing_locations, b->loc))
14099     observer_notify_breakpoint_modified (b);
14100
14101   update_global_location_list (1);
14102 }
14103
14104 /* Find the SaL locations corresponding to the given ADDR_STRING.
14105    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14106
14107 static struct symtabs_and_lines
14108 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14109 {
14110   char *s;
14111   struct symtabs_and_lines sals = {0};
14112   volatile struct gdb_exception e;
14113
14114   gdb_assert (b->ops != NULL);
14115   s = addr_string;
14116
14117   TRY_CATCH (e, RETURN_MASK_ERROR)
14118     {
14119       b->ops->decode_linespec (b, &s, &sals);
14120     }
14121   if (e.reason < 0)
14122     {
14123       int not_found_and_ok = 0;
14124       /* For pending breakpoints, it's expected that parsing will
14125          fail until the right shared library is loaded.  User has
14126          already told to create pending breakpoints and don't need
14127          extra messages.  If breakpoint is in bp_shlib_disabled
14128          state, then user already saw the message about that
14129          breakpoint being disabled, and don't want to see more
14130          errors.  */
14131       if (e.error == NOT_FOUND_ERROR
14132           && (b->condition_not_parsed 
14133               || (b->loc && b->loc->shlib_disabled)
14134               || (b->loc && b->loc->pspace->executing_startup)
14135               || b->enable_state == bp_disabled))
14136         not_found_and_ok = 1;
14137
14138       if (!not_found_and_ok)
14139         {
14140           /* We surely don't want to warn about the same breakpoint
14141              10 times.  One solution, implemented here, is disable
14142              the breakpoint on error.  Another solution would be to
14143              have separate 'warning emitted' flag.  Since this
14144              happens only when a binary has changed, I don't know
14145              which approach is better.  */
14146           b->enable_state = bp_disabled;
14147           throw_exception (e);
14148         }
14149     }
14150
14151   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14152     {
14153       int i;
14154
14155       for (i = 0; i < sals.nelts; ++i)
14156         resolve_sal_pc (&sals.sals[i]);
14157       if (b->condition_not_parsed && s && s[0])
14158         {
14159           char *cond_string, *extra_string;
14160           int thread, task;
14161
14162           find_condition_and_thread (s, sals.sals[0].pc,
14163                                      &cond_string, &thread, &task,
14164                                      &extra_string);
14165           if (cond_string)
14166             b->cond_string = cond_string;
14167           b->thread = thread;
14168           b->task = task;
14169           if (extra_string)
14170             b->extra_string = extra_string;
14171           b->condition_not_parsed = 0;
14172         }
14173
14174       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14175         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14176
14177       *found = 1;
14178     }
14179   else
14180     *found = 0;
14181
14182   return sals;
14183 }
14184
14185 /* The default re_set method, for typical hardware or software
14186    breakpoints.  Reevaluate the breakpoint and recreate its
14187    locations.  */
14188
14189 static void
14190 breakpoint_re_set_default (struct breakpoint *b)
14191 {
14192   int found;
14193   struct symtabs_and_lines sals, sals_end;
14194   struct symtabs_and_lines expanded = {0};
14195   struct symtabs_and_lines expanded_end = {0};
14196
14197   sals = addr_string_to_sals (b, b->addr_string, &found);
14198   if (found)
14199     {
14200       make_cleanup (xfree, sals.sals);
14201       expanded = sals;
14202     }
14203
14204   if (b->addr_string_range_end)
14205     {
14206       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14207       if (found)
14208         {
14209           make_cleanup (xfree, sals_end.sals);
14210           expanded_end = sals_end;
14211         }
14212     }
14213
14214   update_breakpoint_locations (b, expanded, expanded_end);
14215 }
14216
14217 /* Default method for creating SALs from an address string.  It basically
14218    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14219
14220 static void
14221 create_sals_from_address_default (char **arg,
14222                                   struct linespec_result *canonical,
14223                                   enum bptype type_wanted,
14224                                   char *addr_start, char **copy_arg)
14225 {
14226   parse_breakpoint_sals (arg, canonical);
14227 }
14228
14229 /* Call create_breakpoints_sal for the given arguments.  This is the default
14230    function for the `create_breakpoints_sal' method of
14231    breakpoint_ops.  */
14232
14233 static void
14234 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14235                                 struct linespec_result *canonical,
14236                                 char *cond_string,
14237                                 char *extra_string,
14238                                 enum bptype type_wanted,
14239                                 enum bpdisp disposition,
14240                                 int thread,
14241                                 int task, int ignore_count,
14242                                 const struct breakpoint_ops *ops,
14243                                 int from_tty, int enabled,
14244                                 int internal, unsigned flags)
14245 {
14246   create_breakpoints_sal (gdbarch, canonical, cond_string,
14247                           extra_string,
14248                           type_wanted, disposition,
14249                           thread, task, ignore_count, ops, from_tty,
14250                           enabled, internal, flags);
14251 }
14252
14253 /* Decode the line represented by S by calling decode_line_full.  This is the
14254    default function for the `decode_linespec' method of breakpoint_ops.  */
14255
14256 static void
14257 decode_linespec_default (struct breakpoint *b, char **s,
14258                          struct symtabs_and_lines *sals)
14259 {
14260   struct linespec_result canonical;
14261
14262   init_linespec_result (&canonical);
14263   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14264                     (struct symtab *) NULL, 0,
14265                     &canonical, multiple_symbols_all,
14266                     b->filter);
14267
14268   /* We should get 0 or 1 resulting SALs.  */
14269   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14270
14271   if (VEC_length (linespec_sals, canonical.sals) > 0)
14272     {
14273       struct linespec_sals *lsal;
14274
14275       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14276       *sals = lsal->sals;
14277       /* Arrange it so the destructor does not free the
14278          contents.  */
14279       lsal->sals.sals = NULL;
14280     }
14281
14282   destroy_linespec_result (&canonical);
14283 }
14284
14285 /* Prepare the global context for a re-set of breakpoint B.  */
14286
14287 static struct cleanup *
14288 prepare_re_set_context (struct breakpoint *b)
14289 {
14290   struct cleanup *cleanups;
14291
14292   input_radix = b->input_radix;
14293   cleanups = save_current_space_and_thread ();
14294   if (b->pspace != NULL)
14295     switch_to_program_space_and_thread (b->pspace);
14296   set_language (b->language);
14297
14298   return cleanups;
14299 }
14300
14301 /* Reset a breakpoint given it's struct breakpoint * BINT.
14302    The value we return ends up being the return value from catch_errors.
14303    Unused in this case.  */
14304
14305 static int
14306 breakpoint_re_set_one (void *bint)
14307 {
14308   /* Get past catch_errs.  */
14309   struct breakpoint *b = (struct breakpoint *) bint;
14310   struct cleanup *cleanups;
14311
14312   cleanups = prepare_re_set_context (b);
14313   b->ops->re_set (b);
14314   do_cleanups (cleanups);
14315   return 0;
14316 }
14317
14318 /* Re-set all breakpoints after symbols have been re-loaded.  */
14319 void
14320 breakpoint_re_set (void)
14321 {
14322   struct breakpoint *b, *b_tmp;
14323   enum language save_language;
14324   int save_input_radix;
14325   struct cleanup *old_chain;
14326
14327   save_language = current_language->la_language;
14328   save_input_radix = input_radix;
14329   old_chain = save_current_program_space ();
14330
14331   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14332   {
14333     /* Format possible error msg.  */
14334     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14335                                 b->number);
14336     struct cleanup *cleanups = make_cleanup (xfree, message);
14337     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14338     do_cleanups (cleanups);
14339   }
14340   set_language (save_language);
14341   input_radix = save_input_radix;
14342
14343   jit_breakpoint_re_set ();
14344
14345   do_cleanups (old_chain);
14346
14347   create_overlay_event_breakpoint ();
14348   create_longjmp_master_breakpoint ();
14349   create_std_terminate_master_breakpoint ();
14350   create_exception_master_breakpoint ();
14351 }
14352 \f
14353 /* Reset the thread number of this breakpoint:
14354
14355    - If the breakpoint is for all threads, leave it as-is.
14356    - Else, reset it to the current thread for inferior_ptid.  */
14357 void
14358 breakpoint_re_set_thread (struct breakpoint *b)
14359 {
14360   if (b->thread != -1)
14361     {
14362       if (in_thread_list (inferior_ptid))
14363         b->thread = pid_to_thread_id (inferior_ptid);
14364
14365       /* We're being called after following a fork.  The new fork is
14366          selected as current, and unless this was a vfork will have a
14367          different program space from the original thread.  Reset that
14368          as well.  */
14369       b->loc->pspace = current_program_space;
14370     }
14371 }
14372
14373 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14374    If from_tty is nonzero, it prints a message to that effect,
14375    which ends with a period (no newline).  */
14376
14377 void
14378 set_ignore_count (int bptnum, int count, int from_tty)
14379 {
14380   struct breakpoint *b;
14381
14382   if (count < 0)
14383     count = 0;
14384
14385   ALL_BREAKPOINTS (b)
14386     if (b->number == bptnum)
14387     {
14388       if (is_tracepoint (b))
14389         {
14390           if (from_tty && count != 0)
14391             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14392                              bptnum);
14393           return;
14394         }
14395       
14396       b->ignore_count = count;
14397       if (from_tty)
14398         {
14399           if (count == 0)
14400             printf_filtered (_("Will stop next time "
14401                                "breakpoint %d is reached."),
14402                              bptnum);
14403           else if (count == 1)
14404             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14405                              bptnum);
14406           else
14407             printf_filtered (_("Will ignore next %d "
14408                                "crossings of breakpoint %d."),
14409                              count, bptnum);
14410         }
14411       observer_notify_breakpoint_modified (b);
14412       return;
14413     }
14414
14415   error (_("No breakpoint number %d."), bptnum);
14416 }
14417
14418 /* Command to set ignore-count of breakpoint N to COUNT.  */
14419
14420 static void
14421 ignore_command (char *args, int from_tty)
14422 {
14423   char *p = args;
14424   int num;
14425
14426   if (p == 0)
14427     error_no_arg (_("a breakpoint number"));
14428
14429   num = get_number (&p);
14430   if (num == 0)
14431     error (_("bad breakpoint number: '%s'"), args);
14432   if (*p == 0)
14433     error (_("Second argument (specified ignore-count) is missing."));
14434
14435   set_ignore_count (num,
14436                     longest_to_int (value_as_long (parse_and_eval (p))),
14437                     from_tty);
14438   if (from_tty)
14439     printf_filtered ("\n");
14440 }
14441 \f
14442 /* Call FUNCTION on each of the breakpoints
14443    whose numbers are given in ARGS.  */
14444
14445 static void
14446 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14447                                                       void *),
14448                         void *data)
14449 {
14450   int num;
14451   struct breakpoint *b, *tmp;
14452   int match;
14453   struct get_number_or_range_state state;
14454
14455   if (args == 0)
14456     error_no_arg (_("one or more breakpoint numbers"));
14457
14458   init_number_or_range (&state, args);
14459
14460   while (!state.finished)
14461     {
14462       char *p = state.string;
14463
14464       match = 0;
14465
14466       num = get_number_or_range (&state);
14467       if (num == 0)
14468         {
14469           warning (_("bad breakpoint number at or near '%s'"), p);
14470         }
14471       else
14472         {
14473           ALL_BREAKPOINTS_SAFE (b, tmp)
14474             if (b->number == num)
14475               {
14476                 match = 1;
14477                 function (b, data);
14478                 break;
14479               }
14480           if (match == 0)
14481             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14482         }
14483     }
14484 }
14485
14486 static struct bp_location *
14487 find_location_by_number (char *number)
14488 {
14489   char *dot = strchr (number, '.');
14490   char *p1;
14491   int bp_num;
14492   int loc_num;
14493   struct breakpoint *b;
14494   struct bp_location *loc;  
14495
14496   *dot = '\0';
14497
14498   p1 = number;
14499   bp_num = get_number (&p1);
14500   if (bp_num == 0)
14501     error (_("Bad breakpoint number '%s'"), number);
14502
14503   ALL_BREAKPOINTS (b)
14504     if (b->number == bp_num)
14505       {
14506         break;
14507       }
14508
14509   if (!b || b->number != bp_num)
14510     error (_("Bad breakpoint number '%s'"), number);
14511   
14512   p1 = dot+1;
14513   loc_num = get_number (&p1);
14514   if (loc_num == 0)
14515     error (_("Bad breakpoint location number '%s'"), number);
14516
14517   --loc_num;
14518   loc = b->loc;
14519   for (;loc_num && loc; --loc_num, loc = loc->next)
14520     ;
14521   if (!loc)
14522     error (_("Bad breakpoint location number '%s'"), dot+1);
14523     
14524   return loc;  
14525 }
14526
14527
14528 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14529    If from_tty is nonzero, it prints a message to that effect,
14530    which ends with a period (no newline).  */
14531
14532 void
14533 disable_breakpoint (struct breakpoint *bpt)
14534 {
14535   /* Never disable a watchpoint scope breakpoint; we want to
14536      hit them when we leave scope so we can delete both the
14537      watchpoint and its scope breakpoint at that time.  */
14538   if (bpt->type == bp_watchpoint_scope)
14539     return;
14540
14541   /* You can't disable permanent breakpoints.  */
14542   if (bpt->enable_state == bp_permanent)
14543     return;
14544
14545   bpt->enable_state = bp_disabled;
14546
14547   /* Mark breakpoint locations modified.  */
14548   mark_breakpoint_modified (bpt);
14549
14550   if (target_supports_enable_disable_tracepoint ()
14551       && current_trace_status ()->running && is_tracepoint (bpt))
14552     {
14553       struct bp_location *location;
14554      
14555       for (location = bpt->loc; location; location = location->next)
14556         target_disable_tracepoint (location);
14557     }
14558
14559   update_global_location_list (0);
14560
14561   observer_notify_breakpoint_modified (bpt);
14562 }
14563
14564 /* A callback for iterate_over_related_breakpoints.  */
14565
14566 static void
14567 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14568 {
14569   disable_breakpoint (b);
14570 }
14571
14572 /* A callback for map_breakpoint_numbers that calls
14573    disable_breakpoint.  */
14574
14575 static void
14576 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14577 {
14578   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14579 }
14580
14581 static void
14582 disable_command (char *args, int from_tty)
14583 {
14584   if (args == 0)
14585     {
14586       struct breakpoint *bpt;
14587
14588       ALL_BREAKPOINTS (bpt)
14589         if (user_breakpoint_p (bpt))
14590           disable_breakpoint (bpt);
14591     }
14592   else
14593     {
14594       char *num = extract_arg (&args);
14595
14596       while (num)
14597         {
14598           if (strchr (num, '.'))
14599             {
14600               struct bp_location *loc = find_location_by_number (num);
14601
14602               if (loc)
14603                 {
14604                   if (loc->enabled)
14605                     {
14606                       loc->enabled = 0;
14607                       mark_breakpoint_location_modified (loc);
14608                     }
14609                   if (target_supports_enable_disable_tracepoint ()
14610                       && current_trace_status ()->running && loc->owner
14611                       && is_tracepoint (loc->owner))
14612                     target_disable_tracepoint (loc);
14613                 }
14614               update_global_location_list (0);
14615             }
14616           else
14617             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14618           num = extract_arg (&args);
14619         }
14620     }
14621 }
14622
14623 static void
14624 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14625                         int count)
14626 {
14627   int target_resources_ok;
14628
14629   if (bpt->type == bp_hardware_breakpoint)
14630     {
14631       int i;
14632       i = hw_breakpoint_used_count ();
14633       target_resources_ok = 
14634         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14635                                             i + 1, 0);
14636       if (target_resources_ok == 0)
14637         error (_("No hardware breakpoint support in the target."));
14638       else if (target_resources_ok < 0)
14639         error (_("Hardware breakpoints used exceeds limit."));
14640     }
14641
14642   if (is_watchpoint (bpt))
14643     {
14644       /* Initialize it just to avoid a GCC false warning.  */
14645       enum enable_state orig_enable_state = 0;
14646       volatile struct gdb_exception e;
14647
14648       TRY_CATCH (e, RETURN_MASK_ALL)
14649         {
14650           struct watchpoint *w = (struct watchpoint *) bpt;
14651
14652           orig_enable_state = bpt->enable_state;
14653           bpt->enable_state = bp_enabled;
14654           update_watchpoint (w, 1 /* reparse */);
14655         }
14656       if (e.reason < 0)
14657         {
14658           bpt->enable_state = orig_enable_state;
14659           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14660                              bpt->number);
14661           return;
14662         }
14663     }
14664
14665   if (bpt->enable_state != bp_permanent)
14666     bpt->enable_state = bp_enabled;
14667
14668   bpt->enable_state = bp_enabled;
14669
14670   /* Mark breakpoint locations modified.  */
14671   mark_breakpoint_modified (bpt);
14672
14673   if (target_supports_enable_disable_tracepoint ()
14674       && current_trace_status ()->running && is_tracepoint (bpt))
14675     {
14676       struct bp_location *location;
14677
14678       for (location = bpt->loc; location; location = location->next)
14679         target_enable_tracepoint (location);
14680     }
14681
14682   bpt->disposition = disposition;
14683   bpt->enable_count = count;
14684   update_global_location_list (1);
14685
14686   observer_notify_breakpoint_modified (bpt);
14687 }
14688
14689
14690 void
14691 enable_breakpoint (struct breakpoint *bpt)
14692 {
14693   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14694 }
14695
14696 static void
14697 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14698 {
14699   enable_breakpoint (bpt);
14700 }
14701
14702 /* A callback for map_breakpoint_numbers that calls
14703    enable_breakpoint.  */
14704
14705 static void
14706 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14707 {
14708   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14709 }
14710
14711 /* The enable command enables the specified breakpoints (or all defined
14712    breakpoints) so they once again become (or continue to be) effective
14713    in stopping the inferior.  */
14714
14715 static void
14716 enable_command (char *args, int from_tty)
14717 {
14718   if (args == 0)
14719     {
14720       struct breakpoint *bpt;
14721
14722       ALL_BREAKPOINTS (bpt)
14723         if (user_breakpoint_p (bpt))
14724           enable_breakpoint (bpt);
14725     }
14726   else
14727     {
14728       char *num = extract_arg (&args);
14729
14730       while (num)
14731         {
14732           if (strchr (num, '.'))
14733             {
14734               struct bp_location *loc = find_location_by_number (num);
14735
14736               if (loc)
14737                 {
14738                   if (!loc->enabled)
14739                     {
14740                       loc->enabled = 1;
14741                       mark_breakpoint_location_modified (loc);
14742                     }
14743                   if (target_supports_enable_disable_tracepoint ()
14744                       && current_trace_status ()->running && loc->owner
14745                       && is_tracepoint (loc->owner))
14746                     target_enable_tracepoint (loc);
14747                 }
14748               update_global_location_list (1);
14749             }
14750           else
14751             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14752           num = extract_arg (&args);
14753         }
14754     }
14755 }
14756
14757 /* This struct packages up disposition data for application to multiple
14758    breakpoints.  */
14759
14760 struct disp_data
14761 {
14762   enum bpdisp disp;
14763   int count;
14764 };
14765
14766 static void
14767 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14768 {
14769   struct disp_data disp_data = *(struct disp_data *) arg;
14770
14771   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14772 }
14773
14774 static void
14775 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14776 {
14777   struct disp_data disp = { disp_disable, 1 };
14778
14779   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14780 }
14781
14782 static void
14783 enable_once_command (char *args, int from_tty)
14784 {
14785   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14786 }
14787
14788 static void
14789 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14790 {
14791   struct disp_data disp = { disp_disable, *(int *) countptr };
14792
14793   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14794 }
14795
14796 static void
14797 enable_count_command (char *args, int from_tty)
14798 {
14799   int count = get_number (&args);
14800
14801   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14802 }
14803
14804 static void
14805 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14806 {
14807   struct disp_data disp = { disp_del, 1 };
14808
14809   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14810 }
14811
14812 static void
14813 enable_delete_command (char *args, int from_tty)
14814 {
14815   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14816 }
14817 \f
14818 static void
14819 set_breakpoint_cmd (char *args, int from_tty)
14820 {
14821 }
14822
14823 static void
14824 show_breakpoint_cmd (char *args, int from_tty)
14825 {
14826 }
14827
14828 /* Invalidate last known value of any hardware watchpoint if
14829    the memory which that value represents has been written to by
14830    GDB itself.  */
14831
14832 static void
14833 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14834                                       CORE_ADDR addr, ssize_t len,
14835                                       const bfd_byte *data)
14836 {
14837   struct breakpoint *bp;
14838
14839   ALL_BREAKPOINTS (bp)
14840     if (bp->enable_state == bp_enabled
14841         && bp->type == bp_hardware_watchpoint)
14842       {
14843         struct watchpoint *wp = (struct watchpoint *) bp;
14844
14845         if (wp->val_valid && wp->val)
14846           {
14847             struct bp_location *loc;
14848
14849             for (loc = bp->loc; loc != NULL; loc = loc->next)
14850               if (loc->loc_type == bp_loc_hardware_watchpoint
14851                   && loc->address + loc->length > addr
14852                   && addr + len > loc->address)
14853                 {
14854                   value_free (wp->val);
14855                   wp->val = NULL;
14856                   wp->val_valid = 0;
14857                 }
14858           }
14859       }
14860 }
14861
14862 /* Create and insert a raw software breakpoint at PC.  Return an
14863    identifier, which should be used to remove the breakpoint later.
14864    In general, places which call this should be using something on the
14865    breakpoint chain instead; this function should be eliminated
14866    someday.  */
14867
14868 void *
14869 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14870                                   struct address_space *aspace, CORE_ADDR pc)
14871 {
14872   struct bp_target_info *bp_tgt;
14873
14874   bp_tgt = XZALLOC (struct bp_target_info);
14875
14876   bp_tgt->placed_address_space = aspace;
14877   bp_tgt->placed_address = pc;
14878
14879   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14880     {
14881       /* Could not insert the breakpoint.  */
14882       xfree (bp_tgt);
14883       return NULL;
14884     }
14885
14886   return bp_tgt;
14887 }
14888
14889 /* Remove a breakpoint BP inserted by
14890    deprecated_insert_raw_breakpoint.  */
14891
14892 int
14893 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14894 {
14895   struct bp_target_info *bp_tgt = bp;
14896   int ret;
14897
14898   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14899   xfree (bp_tgt);
14900
14901   return ret;
14902 }
14903
14904 /* One (or perhaps two) breakpoints used for software single
14905    stepping.  */
14906
14907 static void *single_step_breakpoints[2];
14908 static struct gdbarch *single_step_gdbarch[2];
14909
14910 /* Create and insert a breakpoint for software single step.  */
14911
14912 void
14913 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14914                                struct address_space *aspace, 
14915                                CORE_ADDR next_pc)
14916 {
14917   void **bpt_p;
14918
14919   if (single_step_breakpoints[0] == NULL)
14920     {
14921       bpt_p = &single_step_breakpoints[0];
14922       single_step_gdbarch[0] = gdbarch;
14923     }
14924   else
14925     {
14926       gdb_assert (single_step_breakpoints[1] == NULL);
14927       bpt_p = &single_step_breakpoints[1];
14928       single_step_gdbarch[1] = gdbarch;
14929     }
14930
14931   /* NOTE drow/2006-04-11: A future improvement to this function would
14932      be to only create the breakpoints once, and actually put them on
14933      the breakpoint chain.  That would let us use set_raw_breakpoint.
14934      We could adjust the addresses each time they were needed.  Doing
14935      this requires corresponding changes elsewhere where single step
14936      breakpoints are handled, however.  So, for now, we use this.  */
14937
14938   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14939   if (*bpt_p == NULL)
14940     error (_("Could not insert single-step breakpoint at %s"),
14941              paddress (gdbarch, next_pc));
14942 }
14943
14944 /* Check if the breakpoints used for software single stepping
14945    were inserted or not.  */
14946
14947 int
14948 single_step_breakpoints_inserted (void)
14949 {
14950   return (single_step_breakpoints[0] != NULL
14951           || single_step_breakpoints[1] != NULL);
14952 }
14953
14954 /* Remove and delete any breakpoints used for software single step.  */
14955
14956 void
14957 remove_single_step_breakpoints (void)
14958 {
14959   gdb_assert (single_step_breakpoints[0] != NULL);
14960
14961   /* See insert_single_step_breakpoint for more about this deprecated
14962      call.  */
14963   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14964                                     single_step_breakpoints[0]);
14965   single_step_gdbarch[0] = NULL;
14966   single_step_breakpoints[0] = NULL;
14967
14968   if (single_step_breakpoints[1] != NULL)
14969     {
14970       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14971                                         single_step_breakpoints[1]);
14972       single_step_gdbarch[1] = NULL;
14973       single_step_breakpoints[1] = NULL;
14974     }
14975 }
14976
14977 /* Delete software single step breakpoints without removing them from
14978    the inferior.  This is intended to be used if the inferior's address
14979    space where they were inserted is already gone, e.g. after exit or
14980    exec.  */
14981
14982 void
14983 cancel_single_step_breakpoints (void)
14984 {
14985   int i;
14986
14987   for (i = 0; i < 2; i++)
14988     if (single_step_breakpoints[i])
14989       {
14990         xfree (single_step_breakpoints[i]);
14991         single_step_breakpoints[i] = NULL;
14992         single_step_gdbarch[i] = NULL;
14993       }
14994 }
14995
14996 /* Detach software single-step breakpoints from INFERIOR_PTID without
14997    removing them.  */
14998
14999 static void
15000 detach_single_step_breakpoints (void)
15001 {
15002   int i;
15003
15004   for (i = 0; i < 2; i++)
15005     if (single_step_breakpoints[i])
15006       target_remove_breakpoint (single_step_gdbarch[i],
15007                                 single_step_breakpoints[i]);
15008 }
15009
15010 /* Check whether a software single-step breakpoint is inserted at
15011    PC.  */
15012
15013 static int
15014 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15015                                         CORE_ADDR pc)
15016 {
15017   int i;
15018
15019   for (i = 0; i < 2; i++)
15020     {
15021       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15022       if (bp_tgt
15023           && breakpoint_address_match (bp_tgt->placed_address_space,
15024                                        bp_tgt->placed_address,
15025                                        aspace, pc))
15026         return 1;
15027     }
15028
15029   return 0;
15030 }
15031
15032 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15033    non-zero otherwise.  */
15034 static int
15035 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15036 {
15037   if (syscall_catchpoint_p (bp)
15038       && bp->enable_state != bp_disabled
15039       && bp->enable_state != bp_call_disabled)
15040     return 1;
15041   else
15042     return 0;
15043 }
15044
15045 int
15046 catch_syscall_enabled (void)
15047 {
15048   struct catch_syscall_inferior_data *inf_data
15049     = get_catch_syscall_inferior_data (current_inferior ());
15050
15051   return inf_data->total_syscalls_count != 0;
15052 }
15053
15054 int
15055 catching_syscall_number (int syscall_number)
15056 {
15057   struct breakpoint *bp;
15058
15059   ALL_BREAKPOINTS (bp)
15060     if (is_syscall_catchpoint_enabled (bp))
15061       {
15062         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15063
15064         if (c->syscalls_to_be_caught)
15065           {
15066             int i, iter;
15067             for (i = 0;
15068                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15069                  i++)
15070               if (syscall_number == iter)
15071                 return 1;
15072           }
15073         else
15074           return 1;
15075       }
15076
15077   return 0;
15078 }
15079
15080 /* Complete syscall names.  Used by "catch syscall".  */
15081 static VEC (char_ptr) *
15082 catch_syscall_completer (struct cmd_list_element *cmd,
15083                          const char *text, const char *word)
15084 {
15085   const char **list = get_syscall_names ();
15086   VEC (char_ptr) *retlist
15087     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15088
15089   xfree (list);
15090   return retlist;
15091 }
15092
15093 /* Tracepoint-specific operations.  */
15094
15095 /* Set tracepoint count to NUM.  */
15096 static void
15097 set_tracepoint_count (int num)
15098 {
15099   tracepoint_count = num;
15100   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15101 }
15102
15103 static void
15104 trace_command (char *arg, int from_tty)
15105 {
15106   struct breakpoint_ops *ops;
15107   const char *arg_cp = arg;
15108
15109   if (arg && probe_linespec_to_ops (&arg_cp))
15110     ops = &tracepoint_probe_breakpoint_ops;
15111   else
15112     ops = &tracepoint_breakpoint_ops;
15113
15114   create_breakpoint (get_current_arch (),
15115                      arg,
15116                      NULL, 0, NULL, 1 /* parse arg */,
15117                      0 /* tempflag */,
15118                      bp_tracepoint /* type_wanted */,
15119                      0 /* Ignore count */,
15120                      pending_break_support,
15121                      ops,
15122                      from_tty,
15123                      1 /* enabled */,
15124                      0 /* internal */, 0);
15125 }
15126
15127 static void
15128 ftrace_command (char *arg, int from_tty)
15129 {
15130   create_breakpoint (get_current_arch (),
15131                      arg,
15132                      NULL, 0, NULL, 1 /* parse arg */,
15133                      0 /* tempflag */,
15134                      bp_fast_tracepoint /* type_wanted */,
15135                      0 /* Ignore count */,
15136                      pending_break_support,
15137                      &tracepoint_breakpoint_ops,
15138                      from_tty,
15139                      1 /* enabled */,
15140                      0 /* internal */, 0);
15141 }
15142
15143 /* strace command implementation.  Creates a static tracepoint.  */
15144
15145 static void
15146 strace_command (char *arg, int from_tty)
15147 {
15148   struct breakpoint_ops *ops;
15149
15150   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15151      or with a normal static tracepoint.  */
15152   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15153     ops = &strace_marker_breakpoint_ops;
15154   else
15155     ops = &tracepoint_breakpoint_ops;
15156
15157   create_breakpoint (get_current_arch (),
15158                      arg,
15159                      NULL, 0, NULL, 1 /* parse arg */,
15160                      0 /* tempflag */,
15161                      bp_static_tracepoint /* type_wanted */,
15162                      0 /* Ignore count */,
15163                      pending_break_support,
15164                      ops,
15165                      from_tty,
15166                      1 /* enabled */,
15167                      0 /* internal */, 0);
15168 }
15169
15170 /* Set up a fake reader function that gets command lines from a linked
15171    list that was acquired during tracepoint uploading.  */
15172
15173 static struct uploaded_tp *this_utp;
15174 static int next_cmd;
15175
15176 static char *
15177 read_uploaded_action (void)
15178 {
15179   char *rslt;
15180
15181   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15182
15183   next_cmd++;
15184
15185   return rslt;
15186 }
15187
15188 /* Given information about a tracepoint as recorded on a target (which
15189    can be either a live system or a trace file), attempt to create an
15190    equivalent GDB tracepoint.  This is not a reliable process, since
15191    the target does not necessarily have all the information used when
15192    the tracepoint was originally defined.  */
15193   
15194 struct tracepoint *
15195 create_tracepoint_from_upload (struct uploaded_tp *utp)
15196 {
15197   char *addr_str, small_buf[100];
15198   struct tracepoint *tp;
15199
15200   if (utp->at_string)
15201     addr_str = utp->at_string;
15202   else
15203     {
15204       /* In the absence of a source location, fall back to raw
15205          address.  Since there is no way to confirm that the address
15206          means the same thing as when the trace was started, warn the
15207          user.  */
15208       warning (_("Uploaded tracepoint %d has no "
15209                  "source location, using raw address"),
15210                utp->number);
15211       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15212       addr_str = small_buf;
15213     }
15214
15215   /* There's not much we can do with a sequence of bytecodes.  */
15216   if (utp->cond && !utp->cond_string)
15217     warning (_("Uploaded tracepoint %d condition "
15218                "has no source form, ignoring it"),
15219              utp->number);
15220
15221   if (!create_breakpoint (get_current_arch (),
15222                           addr_str,
15223                           utp->cond_string, -1, NULL,
15224                           0 /* parse cond/thread */,
15225                           0 /* tempflag */,
15226                           utp->type /* type_wanted */,
15227                           0 /* Ignore count */,
15228                           pending_break_support,
15229                           &tracepoint_breakpoint_ops,
15230                           0 /* from_tty */,
15231                           utp->enabled /* enabled */,
15232                           0 /* internal */,
15233                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15234     return NULL;
15235
15236   /* Get the tracepoint we just created.  */
15237   tp = get_tracepoint (tracepoint_count);
15238   gdb_assert (tp != NULL);
15239
15240   if (utp->pass > 0)
15241     {
15242       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15243                  tp->base.number);
15244
15245       trace_pass_command (small_buf, 0);
15246     }
15247
15248   /* If we have uploaded versions of the original commands, set up a
15249      special-purpose "reader" function and call the usual command line
15250      reader, then pass the result to the breakpoint command-setting
15251      function.  */
15252   if (!VEC_empty (char_ptr, utp->cmd_strings))
15253     {
15254       struct command_line *cmd_list;
15255
15256       this_utp = utp;
15257       next_cmd = 0;
15258
15259       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15260
15261       breakpoint_set_commands (&tp->base, cmd_list);
15262     }
15263   else if (!VEC_empty (char_ptr, utp->actions)
15264            || !VEC_empty (char_ptr, utp->step_actions))
15265     warning (_("Uploaded tracepoint %d actions "
15266                "have no source form, ignoring them"),
15267              utp->number);
15268
15269   /* Copy any status information that might be available.  */
15270   tp->base.hit_count = utp->hit_count;
15271   tp->traceframe_usage = utp->traceframe_usage;
15272
15273   return tp;
15274 }
15275   
15276 /* Print information on tracepoint number TPNUM_EXP, or all if
15277    omitted.  */
15278
15279 static void
15280 tracepoints_info (char *args, int from_tty)
15281 {
15282   struct ui_out *uiout = current_uiout;
15283   int num_printed;
15284
15285   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15286
15287   if (num_printed == 0)
15288     {
15289       if (args == NULL || *args == '\0')
15290         ui_out_message (uiout, 0, "No tracepoints.\n");
15291       else
15292         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15293     }
15294
15295   default_collect_info ();
15296 }
15297
15298 /* The 'enable trace' command enables tracepoints.
15299    Not supported by all targets.  */
15300 static void
15301 enable_trace_command (char *args, int from_tty)
15302 {
15303   enable_command (args, from_tty);
15304 }
15305
15306 /* The 'disable trace' command disables tracepoints.
15307    Not supported by all targets.  */
15308 static void
15309 disable_trace_command (char *args, int from_tty)
15310 {
15311   disable_command (args, from_tty);
15312 }
15313
15314 /* Remove a tracepoint (or all if no argument).  */
15315 static void
15316 delete_trace_command (char *arg, int from_tty)
15317 {
15318   struct breakpoint *b, *b_tmp;
15319
15320   dont_repeat ();
15321
15322   if (arg == 0)
15323     {
15324       int breaks_to_delete = 0;
15325
15326       /* Delete all breakpoints if no argument.
15327          Do not delete internal or call-dummy breakpoints, these
15328          have to be deleted with an explicit breakpoint number 
15329          argument.  */
15330       ALL_TRACEPOINTS (b)
15331         if (is_tracepoint (b) && user_breakpoint_p (b))
15332           {
15333             breaks_to_delete = 1;
15334             break;
15335           }
15336
15337       /* Ask user only if there are some breakpoints to delete.  */
15338       if (!from_tty
15339           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15340         {
15341           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15342             if (is_tracepoint (b) && user_breakpoint_p (b))
15343               delete_breakpoint (b);
15344         }
15345     }
15346   else
15347     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15348 }
15349
15350 /* Helper function for trace_pass_command.  */
15351
15352 static void
15353 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15354 {
15355   tp->pass_count = count;
15356   observer_notify_breakpoint_modified (&tp->base);
15357   if (from_tty)
15358     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15359                      tp->base.number, count);
15360 }
15361
15362 /* Set passcount for tracepoint.
15363
15364    First command argument is passcount, second is tracepoint number.
15365    If tracepoint number omitted, apply to most recently defined.
15366    Also accepts special argument "all".  */
15367
15368 static void
15369 trace_pass_command (char *args, int from_tty)
15370 {
15371   struct tracepoint *t1;
15372   unsigned int count;
15373
15374   if (args == 0 || *args == 0)
15375     error (_("passcount command requires an "
15376              "argument (count + optional TP num)"));
15377
15378   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15379
15380   args = skip_spaces (args);
15381   if (*args && strncasecmp (args, "all", 3) == 0)
15382     {
15383       struct breakpoint *b;
15384
15385       args += 3;                        /* Skip special argument "all".  */
15386       if (*args)
15387         error (_("Junk at end of arguments."));
15388
15389       ALL_TRACEPOINTS (b)
15390       {
15391         t1 = (struct tracepoint *) b;
15392         trace_pass_set_count (t1, count, from_tty);
15393       }
15394     }
15395   else if (*args == '\0')
15396     {
15397       t1 = get_tracepoint_by_number (&args, NULL, 1);
15398       if (t1)
15399         trace_pass_set_count (t1, count, from_tty);
15400     }
15401   else
15402     {
15403       struct get_number_or_range_state state;
15404
15405       init_number_or_range (&state, args);
15406       while (!state.finished)
15407         {
15408           t1 = get_tracepoint_by_number (&args, &state, 1);
15409           if (t1)
15410             trace_pass_set_count (t1, count, from_tty);
15411         }
15412     }
15413 }
15414
15415 struct tracepoint *
15416 get_tracepoint (int num)
15417 {
15418   struct breakpoint *t;
15419
15420   ALL_TRACEPOINTS (t)
15421     if (t->number == num)
15422       return (struct tracepoint *) t;
15423
15424   return NULL;
15425 }
15426
15427 /* Find the tracepoint with the given target-side number (which may be
15428    different from the tracepoint number after disconnecting and
15429    reconnecting).  */
15430
15431 struct tracepoint *
15432 get_tracepoint_by_number_on_target (int num)
15433 {
15434   struct breakpoint *b;
15435
15436   ALL_TRACEPOINTS (b)
15437     {
15438       struct tracepoint *t = (struct tracepoint *) b;
15439
15440       if (t->number_on_target == num)
15441         return t;
15442     }
15443
15444   return NULL;
15445 }
15446
15447 /* Utility: parse a tracepoint number and look it up in the list.
15448    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15449    If OPTIONAL_P is true, then if the argument is missing, the most
15450    recent tracepoint (tracepoint_count) is returned.  */
15451 struct tracepoint *
15452 get_tracepoint_by_number (char **arg,
15453                           struct get_number_or_range_state *state,
15454                           int optional_p)
15455 {
15456   struct breakpoint *t;
15457   int tpnum;
15458   char *instring = arg == NULL ? NULL : *arg;
15459
15460   if (state)
15461     {
15462       gdb_assert (!state->finished);
15463       tpnum = get_number_or_range (state);
15464     }
15465   else if (arg == NULL || *arg == NULL || ! **arg)
15466     {
15467       if (optional_p)
15468         tpnum = tracepoint_count;
15469       else
15470         error_no_arg (_("tracepoint number"));
15471     }
15472   else
15473     tpnum = get_number (arg);
15474
15475   if (tpnum <= 0)
15476     {
15477       if (instring && *instring)
15478         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15479                          instring);
15480       else
15481         printf_filtered (_("Tracepoint argument missing "
15482                            "and no previous tracepoint\n"));
15483       return NULL;
15484     }
15485
15486   ALL_TRACEPOINTS (t)
15487     if (t->number == tpnum)
15488     {
15489       return (struct tracepoint *) t;
15490     }
15491
15492   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15493   return NULL;
15494 }
15495
15496 void
15497 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15498 {
15499   if (b->thread != -1)
15500     fprintf_unfiltered (fp, " thread %d", b->thread);
15501
15502   if (b->task != 0)
15503     fprintf_unfiltered (fp, " task %d", b->task);
15504
15505   fprintf_unfiltered (fp, "\n");
15506 }
15507
15508 /* Save information on user settable breakpoints (watchpoints, etc) to
15509    a new script file named FILENAME.  If FILTER is non-NULL, call it
15510    on each breakpoint and only include the ones for which it returns
15511    non-zero.  */
15512
15513 static void
15514 save_breakpoints (char *filename, int from_tty,
15515                   int (*filter) (const struct breakpoint *))
15516 {
15517   struct breakpoint *tp;
15518   int any = 0;
15519   struct cleanup *cleanup;
15520   struct ui_file *fp;
15521   int extra_trace_bits = 0;
15522
15523   if (filename == 0 || *filename == 0)
15524     error (_("Argument required (file name in which to save)"));
15525
15526   /* See if we have anything to save.  */
15527   ALL_BREAKPOINTS (tp)
15528   {
15529     /* Skip internal and momentary breakpoints.  */
15530     if (!user_breakpoint_p (tp))
15531       continue;
15532
15533     /* If we have a filter, only save the breakpoints it accepts.  */
15534     if (filter && !filter (tp))
15535       continue;
15536
15537     any = 1;
15538
15539     if (is_tracepoint (tp))
15540       {
15541         extra_trace_bits = 1;
15542
15543         /* We can stop searching.  */
15544         break;
15545       }
15546   }
15547
15548   if (!any)
15549     {
15550       warning (_("Nothing to save."));
15551       return;
15552     }
15553
15554   filename = tilde_expand (filename);
15555   cleanup = make_cleanup (xfree, filename);
15556   fp = gdb_fopen (filename, "w");
15557   if (!fp)
15558     error (_("Unable to open file '%s' for saving (%s)"),
15559            filename, safe_strerror (errno));
15560   make_cleanup_ui_file_delete (fp);
15561
15562   if (extra_trace_bits)
15563     save_trace_state_variables (fp);
15564
15565   ALL_BREAKPOINTS (tp)
15566   {
15567     /* Skip internal and momentary breakpoints.  */
15568     if (!user_breakpoint_p (tp))
15569       continue;
15570
15571     /* If we have a filter, only save the breakpoints it accepts.  */
15572     if (filter && !filter (tp))
15573       continue;
15574
15575     tp->ops->print_recreate (tp, fp);
15576
15577     /* Note, we can't rely on tp->number for anything, as we can't
15578        assume the recreated breakpoint numbers will match.  Use $bpnum
15579        instead.  */
15580
15581     if (tp->cond_string)
15582       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15583
15584     if (tp->ignore_count)
15585       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15586
15587     if (tp->type != bp_dprintf && tp->commands)
15588       {
15589         volatile struct gdb_exception ex;       
15590
15591         fprintf_unfiltered (fp, "  commands\n");
15592         
15593         ui_out_redirect (current_uiout, fp);
15594         TRY_CATCH (ex, RETURN_MASK_ALL)
15595           {
15596             print_command_lines (current_uiout, tp->commands->commands, 2);
15597           }
15598         ui_out_redirect (current_uiout, NULL);
15599
15600         if (ex.reason < 0)
15601           throw_exception (ex);
15602
15603         fprintf_unfiltered (fp, "  end\n");
15604       }
15605
15606     if (tp->enable_state == bp_disabled)
15607       fprintf_unfiltered (fp, "disable\n");
15608
15609     /* If this is a multi-location breakpoint, check if the locations
15610        should be individually disabled.  Watchpoint locations are
15611        special, and not user visible.  */
15612     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15613       {
15614         struct bp_location *loc;
15615         int n = 1;
15616
15617         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15618           if (!loc->enabled)
15619             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15620       }
15621   }
15622
15623   if (extra_trace_bits && *default_collect)
15624     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15625
15626   if (from_tty)
15627     printf_filtered (_("Saved to file '%s'.\n"), filename);
15628   do_cleanups (cleanup);
15629 }
15630
15631 /* The `save breakpoints' command.  */
15632
15633 static void
15634 save_breakpoints_command (char *args, int from_tty)
15635 {
15636   save_breakpoints (args, from_tty, NULL);
15637 }
15638
15639 /* The `save tracepoints' command.  */
15640
15641 static void
15642 save_tracepoints_command (char *args, int from_tty)
15643 {
15644   save_breakpoints (args, from_tty, is_tracepoint);
15645 }
15646
15647 /* Create a vector of all tracepoints.  */
15648
15649 VEC(breakpoint_p) *
15650 all_tracepoints (void)
15651 {
15652   VEC(breakpoint_p) *tp_vec = 0;
15653   struct breakpoint *tp;
15654
15655   ALL_TRACEPOINTS (tp)
15656   {
15657     VEC_safe_push (breakpoint_p, tp_vec, tp);
15658   }
15659
15660   return tp_vec;
15661 }
15662
15663 \f
15664 /* This help string is used for the break, hbreak, tbreak and thbreak
15665    commands.  It is defined as a macro to prevent duplication.
15666    COMMAND should be a string constant containing the name of the
15667    command.  */
15668 #define BREAK_ARGS_HELP(command) \
15669 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15670 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15671 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15672 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15673 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15674 If a line number is specified, break at start of code for that line.\n\
15675 If a function is specified, break at start of code for that function.\n\
15676 If an address is specified, break at that exact address.\n\
15677 With no LOCATION, uses current execution address of the selected\n\
15678 stack frame.  This is useful for breaking on return to a stack frame.\n\
15679 \n\
15680 THREADNUM is the number from \"info threads\".\n\
15681 CONDITION is a boolean expression.\n\
15682 \n\
15683 Multiple breakpoints at one place are permitted, and useful if their\n\
15684 conditions are different.\n\
15685 \n\
15686 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15687
15688 /* List of subcommands for "catch".  */
15689 static struct cmd_list_element *catch_cmdlist;
15690
15691 /* List of subcommands for "tcatch".  */
15692 static struct cmd_list_element *tcatch_cmdlist;
15693
15694 void
15695 add_catch_command (char *name, char *docstring,
15696                    void (*sfunc) (char *args, int from_tty,
15697                                   struct cmd_list_element *command),
15698                    completer_ftype *completer,
15699                    void *user_data_catch,
15700                    void *user_data_tcatch)
15701 {
15702   struct cmd_list_element *command;
15703
15704   command = add_cmd (name, class_breakpoint, NULL, docstring,
15705                      &catch_cmdlist);
15706   set_cmd_sfunc (command, sfunc);
15707   set_cmd_context (command, user_data_catch);
15708   set_cmd_completer (command, completer);
15709
15710   command = add_cmd (name, class_breakpoint, NULL, docstring,
15711                      &tcatch_cmdlist);
15712   set_cmd_sfunc (command, sfunc);
15713   set_cmd_context (command, user_data_tcatch);
15714   set_cmd_completer (command, completer);
15715 }
15716
15717 static void
15718 clear_syscall_counts (struct inferior *inf)
15719 {
15720   struct catch_syscall_inferior_data *inf_data
15721     = get_catch_syscall_inferior_data (inf);
15722
15723   inf_data->total_syscalls_count = 0;
15724   inf_data->any_syscall_count = 0;
15725   VEC_free (int, inf_data->syscalls_counts);
15726 }
15727
15728 static void
15729 save_command (char *arg, int from_tty)
15730 {
15731   printf_unfiltered (_("\"save\" must be followed by "
15732                        "the name of a save subcommand.\n"));
15733   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15734 }
15735
15736 struct breakpoint *
15737 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15738                           void *data)
15739 {
15740   struct breakpoint *b, *b_tmp;
15741
15742   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15743     {
15744       if ((*callback) (b, data))
15745         return b;
15746     }
15747
15748   return NULL;
15749 }
15750
15751 /* Zero if any of the breakpoint's locations could be a location where
15752    functions have been inlined, nonzero otherwise.  */
15753
15754 static int
15755 is_non_inline_function (struct breakpoint *b)
15756 {
15757   /* The shared library event breakpoint is set on the address of a
15758      non-inline function.  */
15759   if (b->type == bp_shlib_event)
15760     return 1;
15761
15762   return 0;
15763 }
15764
15765 /* Nonzero if the specified PC cannot be a location where functions
15766    have been inlined.  */
15767
15768 int
15769 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15770                            const struct target_waitstatus *ws)
15771 {
15772   struct breakpoint *b;
15773   struct bp_location *bl;
15774
15775   ALL_BREAKPOINTS (b)
15776     {
15777       if (!is_non_inline_function (b))
15778         continue;
15779
15780       for (bl = b->loc; bl != NULL; bl = bl->next)
15781         {
15782           if (!bl->shlib_disabled
15783               && bpstat_check_location (bl, aspace, pc, ws))
15784             return 1;
15785         }
15786     }
15787
15788   return 0;
15789 }
15790
15791 /* Remove any references to OBJFILE which is going to be freed.  */
15792
15793 void
15794 breakpoint_free_objfile (struct objfile *objfile)
15795 {
15796   struct bp_location **locp, *loc;
15797
15798   ALL_BP_LOCATIONS (loc, locp)
15799     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
15800       loc->symtab = NULL;
15801 }
15802
15803 void
15804 initialize_breakpoint_ops (void)
15805 {
15806   static int initialized = 0;
15807
15808   struct breakpoint_ops *ops;
15809
15810   if (initialized)
15811     return;
15812   initialized = 1;
15813
15814   /* The breakpoint_ops structure to be inherit by all kinds of
15815      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15816      internal and momentary breakpoints, etc.).  */
15817   ops = &bkpt_base_breakpoint_ops;
15818   *ops = base_breakpoint_ops;
15819   ops->re_set = bkpt_re_set;
15820   ops->insert_location = bkpt_insert_location;
15821   ops->remove_location = bkpt_remove_location;
15822   ops->breakpoint_hit = bkpt_breakpoint_hit;
15823   ops->create_sals_from_address = bkpt_create_sals_from_address;
15824   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15825   ops->decode_linespec = bkpt_decode_linespec;
15826
15827   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15828   ops = &bkpt_breakpoint_ops;
15829   *ops = bkpt_base_breakpoint_ops;
15830   ops->re_set = bkpt_re_set;
15831   ops->resources_needed = bkpt_resources_needed;
15832   ops->print_it = bkpt_print_it;
15833   ops->print_mention = bkpt_print_mention;
15834   ops->print_recreate = bkpt_print_recreate;
15835
15836   /* Ranged breakpoints.  */
15837   ops = &ranged_breakpoint_ops;
15838   *ops = bkpt_breakpoint_ops;
15839   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15840   ops->resources_needed = resources_needed_ranged_breakpoint;
15841   ops->print_it = print_it_ranged_breakpoint;
15842   ops->print_one = print_one_ranged_breakpoint;
15843   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15844   ops->print_mention = print_mention_ranged_breakpoint;
15845   ops->print_recreate = print_recreate_ranged_breakpoint;
15846
15847   /* Internal breakpoints.  */
15848   ops = &internal_breakpoint_ops;
15849   *ops = bkpt_base_breakpoint_ops;
15850   ops->re_set = internal_bkpt_re_set;
15851   ops->check_status = internal_bkpt_check_status;
15852   ops->print_it = internal_bkpt_print_it;
15853   ops->print_mention = internal_bkpt_print_mention;
15854
15855   /* Momentary breakpoints.  */
15856   ops = &momentary_breakpoint_ops;
15857   *ops = bkpt_base_breakpoint_ops;
15858   ops->re_set = momentary_bkpt_re_set;
15859   ops->check_status = momentary_bkpt_check_status;
15860   ops->print_it = momentary_bkpt_print_it;
15861   ops->print_mention = momentary_bkpt_print_mention;
15862
15863   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15864   ops = &longjmp_breakpoint_ops;
15865   *ops = momentary_breakpoint_ops;
15866   ops->dtor = longjmp_bkpt_dtor;
15867
15868   /* Probe breakpoints.  */
15869   ops = &bkpt_probe_breakpoint_ops;
15870   *ops = bkpt_breakpoint_ops;
15871   ops->insert_location = bkpt_probe_insert_location;
15872   ops->remove_location = bkpt_probe_remove_location;
15873   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15874   ops->decode_linespec = bkpt_probe_decode_linespec;
15875
15876   /* Watchpoints.  */
15877   ops = &watchpoint_breakpoint_ops;
15878   *ops = base_breakpoint_ops;
15879   ops->dtor = dtor_watchpoint;
15880   ops->re_set = re_set_watchpoint;
15881   ops->insert_location = insert_watchpoint;
15882   ops->remove_location = remove_watchpoint;
15883   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15884   ops->check_status = check_status_watchpoint;
15885   ops->resources_needed = resources_needed_watchpoint;
15886   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15887   ops->print_it = print_it_watchpoint;
15888   ops->print_mention = print_mention_watchpoint;
15889   ops->print_recreate = print_recreate_watchpoint;
15890   ops->explains_signal = explains_signal_watchpoint;
15891
15892   /* Masked watchpoints.  */
15893   ops = &masked_watchpoint_breakpoint_ops;
15894   *ops = watchpoint_breakpoint_ops;
15895   ops->insert_location = insert_masked_watchpoint;
15896   ops->remove_location = remove_masked_watchpoint;
15897   ops->resources_needed = resources_needed_masked_watchpoint;
15898   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15899   ops->print_it = print_it_masked_watchpoint;
15900   ops->print_one_detail = print_one_detail_masked_watchpoint;
15901   ops->print_mention = print_mention_masked_watchpoint;
15902   ops->print_recreate = print_recreate_masked_watchpoint;
15903
15904   /* Tracepoints.  */
15905   ops = &tracepoint_breakpoint_ops;
15906   *ops = base_breakpoint_ops;
15907   ops->re_set = tracepoint_re_set;
15908   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15909   ops->print_one_detail = tracepoint_print_one_detail;
15910   ops->print_mention = tracepoint_print_mention;
15911   ops->print_recreate = tracepoint_print_recreate;
15912   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15913   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15914   ops->decode_linespec = tracepoint_decode_linespec;
15915
15916   /* Probe tracepoints.  */
15917   ops = &tracepoint_probe_breakpoint_ops;
15918   *ops = tracepoint_breakpoint_ops;
15919   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15920   ops->decode_linespec = tracepoint_probe_decode_linespec;
15921
15922   /* Static tracepoints with marker (`-m').  */
15923   ops = &strace_marker_breakpoint_ops;
15924   *ops = tracepoint_breakpoint_ops;
15925   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15926   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15927   ops->decode_linespec = strace_marker_decode_linespec;
15928
15929   /* Fork catchpoints.  */
15930   ops = &catch_fork_breakpoint_ops;
15931   *ops = base_breakpoint_ops;
15932   ops->insert_location = insert_catch_fork;
15933   ops->remove_location = remove_catch_fork;
15934   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15935   ops->print_it = print_it_catch_fork;
15936   ops->print_one = print_one_catch_fork;
15937   ops->print_mention = print_mention_catch_fork;
15938   ops->print_recreate = print_recreate_catch_fork;
15939
15940   /* Vfork catchpoints.  */
15941   ops = &catch_vfork_breakpoint_ops;
15942   *ops = base_breakpoint_ops;
15943   ops->insert_location = insert_catch_vfork;
15944   ops->remove_location = remove_catch_vfork;
15945   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15946   ops->print_it = print_it_catch_vfork;
15947   ops->print_one = print_one_catch_vfork;
15948   ops->print_mention = print_mention_catch_vfork;
15949   ops->print_recreate = print_recreate_catch_vfork;
15950
15951   /* Exec catchpoints.  */
15952   ops = &catch_exec_breakpoint_ops;
15953   *ops = base_breakpoint_ops;
15954   ops->dtor = dtor_catch_exec;
15955   ops->insert_location = insert_catch_exec;
15956   ops->remove_location = remove_catch_exec;
15957   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15958   ops->print_it = print_it_catch_exec;
15959   ops->print_one = print_one_catch_exec;
15960   ops->print_mention = print_mention_catch_exec;
15961   ops->print_recreate = print_recreate_catch_exec;
15962
15963   /* Syscall catchpoints.  */
15964   ops = &catch_syscall_breakpoint_ops;
15965   *ops = base_breakpoint_ops;
15966   ops->dtor = dtor_catch_syscall;
15967   ops->insert_location = insert_catch_syscall;
15968   ops->remove_location = remove_catch_syscall;
15969   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15970   ops->print_it = print_it_catch_syscall;
15971   ops->print_one = print_one_catch_syscall;
15972   ops->print_mention = print_mention_catch_syscall;
15973   ops->print_recreate = print_recreate_catch_syscall;
15974
15975   /* Solib-related catchpoints.  */
15976   ops = &catch_solib_breakpoint_ops;
15977   *ops = base_breakpoint_ops;
15978   ops->dtor = dtor_catch_solib;
15979   ops->insert_location = insert_catch_solib;
15980   ops->remove_location = remove_catch_solib;
15981   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15982   ops->check_status = check_status_catch_solib;
15983   ops->print_it = print_it_catch_solib;
15984   ops->print_one = print_one_catch_solib;
15985   ops->print_mention = print_mention_catch_solib;
15986   ops->print_recreate = print_recreate_catch_solib;
15987
15988   ops = &dprintf_breakpoint_ops;
15989   *ops = bkpt_base_breakpoint_ops;
15990   ops->re_set = dprintf_re_set;
15991   ops->resources_needed = bkpt_resources_needed;
15992   ops->print_it = bkpt_print_it;
15993   ops->print_mention = bkpt_print_mention;
15994   ops->print_recreate = dprintf_print_recreate;
15995   ops->after_condition_true = dprintf_after_condition_true;
15996 }
15997
15998 /* Chain containing all defined "enable breakpoint" subcommands.  */
15999
16000 static struct cmd_list_element *enablebreaklist = NULL;
16001
16002 void
16003 _initialize_breakpoint (void)
16004 {
16005   struct cmd_list_element *c;
16006
16007   initialize_breakpoint_ops ();
16008
16009   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16010   observer_attach_inferior_exit (clear_syscall_counts);
16011   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16012
16013   breakpoint_objfile_key
16014     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16015
16016   catch_syscall_inferior_data
16017     = register_inferior_data_with_cleanup (NULL,
16018                                            catch_syscall_inferior_data_cleanup);
16019
16020   breakpoint_chain = 0;
16021   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16022      before a breakpoint is set.  */
16023   breakpoint_count = 0;
16024
16025   tracepoint_count = 0;
16026
16027   add_com ("ignore", class_breakpoint, ignore_command, _("\
16028 Set ignore-count of breakpoint number N to COUNT.\n\
16029 Usage is `ignore N COUNT'."));
16030   if (xdb_commands)
16031     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16032
16033   add_com ("commands", class_breakpoint, commands_command, _("\
16034 Set commands to be executed when a breakpoint is hit.\n\
16035 Give breakpoint number as argument after \"commands\".\n\
16036 With no argument, the targeted breakpoint is the last one set.\n\
16037 The commands themselves follow starting on the next line.\n\
16038 Type a line containing \"end\" to indicate the end of them.\n\
16039 Give \"silent\" as the first line to make the breakpoint silent;\n\
16040 then no output is printed when it is hit, except what the commands print."));
16041
16042   c = add_com ("condition", class_breakpoint, condition_command, _("\
16043 Specify breakpoint number N to break only if COND is true.\n\
16044 Usage is `condition N COND', where N is an integer and COND is an\n\
16045 expression to be evaluated whenever breakpoint N is reached."));
16046   set_cmd_completer (c, condition_completer);
16047
16048   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16049 Set a temporary breakpoint.\n\
16050 Like \"break\" except the breakpoint is only temporary,\n\
16051 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16052 by using \"enable delete\" on the breakpoint number.\n\
16053 \n"
16054 BREAK_ARGS_HELP ("tbreak")));
16055   set_cmd_completer (c, location_completer);
16056
16057   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16058 Set a hardware assisted breakpoint.\n\
16059 Like \"break\" except the breakpoint requires hardware support,\n\
16060 some target hardware may not have this support.\n\
16061 \n"
16062 BREAK_ARGS_HELP ("hbreak")));
16063   set_cmd_completer (c, location_completer);
16064
16065   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16066 Set a temporary hardware assisted breakpoint.\n\
16067 Like \"hbreak\" except the breakpoint is only temporary,\n\
16068 so it will be deleted when hit.\n\
16069 \n"
16070 BREAK_ARGS_HELP ("thbreak")));
16071   set_cmd_completer (c, location_completer);
16072
16073   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16074 Enable some breakpoints.\n\
16075 Give breakpoint numbers (separated by spaces) as arguments.\n\
16076 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16077 This is used to cancel the effect of the \"disable\" command.\n\
16078 With a subcommand you can enable temporarily."),
16079                   &enablelist, "enable ", 1, &cmdlist);
16080   if (xdb_commands)
16081     add_com ("ab", class_breakpoint, enable_command, _("\
16082 Enable some breakpoints.\n\
16083 Give breakpoint numbers (separated by spaces) as arguments.\n\
16084 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16085 This is used to cancel the effect of the \"disable\" command.\n\
16086 With a subcommand you can enable temporarily."));
16087
16088   add_com_alias ("en", "enable", class_breakpoint, 1);
16089
16090   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16091 Enable some breakpoints.\n\
16092 Give breakpoint numbers (separated by spaces) as arguments.\n\
16093 This is used to cancel the effect of the \"disable\" command.\n\
16094 May be abbreviated to simply \"enable\".\n"),
16095                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16096
16097   add_cmd ("once", no_class, enable_once_command, _("\
16098 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16099 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16100            &enablebreaklist);
16101
16102   add_cmd ("delete", no_class, enable_delete_command, _("\
16103 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16104 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16105            &enablebreaklist);
16106
16107   add_cmd ("count", no_class, enable_count_command, _("\
16108 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16109 If a breakpoint is hit while enabled in this fashion,\n\
16110 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16111            &enablebreaklist);
16112
16113   add_cmd ("delete", no_class, enable_delete_command, _("\
16114 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16115 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16116            &enablelist);
16117
16118   add_cmd ("once", no_class, enable_once_command, _("\
16119 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16120 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16121            &enablelist);
16122
16123   add_cmd ("count", no_class, enable_count_command, _("\
16124 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16125 If a breakpoint is hit while enabled in this fashion,\n\
16126 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16127            &enablelist);
16128
16129   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16130 Disable some breakpoints.\n\
16131 Arguments are breakpoint numbers with spaces in between.\n\
16132 To disable all breakpoints, give no argument.\n\
16133 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16134                   &disablelist, "disable ", 1, &cmdlist);
16135   add_com_alias ("dis", "disable", class_breakpoint, 1);
16136   add_com_alias ("disa", "disable", class_breakpoint, 1);
16137   if (xdb_commands)
16138     add_com ("sb", class_breakpoint, disable_command, _("\
16139 Disable some breakpoints.\n\
16140 Arguments are breakpoint numbers with spaces in between.\n\
16141 To disable all breakpoints, give no argument.\n\
16142 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16143
16144   add_cmd ("breakpoints", class_alias, disable_command, _("\
16145 Disable some breakpoints.\n\
16146 Arguments are breakpoint numbers with spaces in between.\n\
16147 To disable all breakpoints, give no argument.\n\
16148 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16149 This command may be abbreviated \"disable\"."),
16150            &disablelist);
16151
16152   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16153 Delete some breakpoints or auto-display expressions.\n\
16154 Arguments are breakpoint numbers with spaces in between.\n\
16155 To delete all breakpoints, give no argument.\n\
16156 \n\
16157 Also a prefix command for deletion of other GDB objects.\n\
16158 The \"unset\" command is also an alias for \"delete\"."),
16159                   &deletelist, "delete ", 1, &cmdlist);
16160   add_com_alias ("d", "delete", class_breakpoint, 1);
16161   add_com_alias ("del", "delete", class_breakpoint, 1);
16162   if (xdb_commands)
16163     add_com ("db", class_breakpoint, delete_command, _("\
16164 Delete some breakpoints.\n\
16165 Arguments are breakpoint numbers with spaces in between.\n\
16166 To delete all breakpoints, give no argument.\n"));
16167
16168   add_cmd ("breakpoints", class_alias, delete_command, _("\
16169 Delete some breakpoints or auto-display expressions.\n\
16170 Arguments are breakpoint numbers with spaces in between.\n\
16171 To delete all breakpoints, give no argument.\n\
16172 This command may be abbreviated \"delete\"."),
16173            &deletelist);
16174
16175   add_com ("clear", class_breakpoint, clear_command, _("\
16176 Clear breakpoint at specified line or function.\n\
16177 Argument may be line number, function name, or \"*\" and an address.\n\
16178 If line number is specified, all breakpoints in that line are cleared.\n\
16179 If function is specified, breakpoints at beginning of function are cleared.\n\
16180 If an address is specified, breakpoints at that address are cleared.\n\
16181 \n\
16182 With no argument, clears all breakpoints in the line that the selected frame\n\
16183 is executing in.\n\
16184 \n\
16185 See also the \"delete\" command which clears breakpoints by number."));
16186   add_com_alias ("cl", "clear", class_breakpoint, 1);
16187
16188   c = add_com ("break", class_breakpoint, break_command, _("\
16189 Set breakpoint at specified line or function.\n"
16190 BREAK_ARGS_HELP ("break")));
16191   set_cmd_completer (c, location_completer);
16192
16193   add_com_alias ("b", "break", class_run, 1);
16194   add_com_alias ("br", "break", class_run, 1);
16195   add_com_alias ("bre", "break", class_run, 1);
16196   add_com_alias ("brea", "break", class_run, 1);
16197
16198   if (xdb_commands)
16199    add_com_alias ("ba", "break", class_breakpoint, 1);
16200
16201   if (dbx_commands)
16202     {
16203       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16204 Break in function/address or break at a line in the current file."),
16205                              &stoplist, "stop ", 1, &cmdlist);
16206       add_cmd ("in", class_breakpoint, stopin_command,
16207                _("Break in function or address."), &stoplist);
16208       add_cmd ("at", class_breakpoint, stopat_command,
16209                _("Break at a line in the current file."), &stoplist);
16210       add_com ("status", class_info, breakpoints_info, _("\
16211 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16212 The \"Type\" column indicates one of:\n\
16213 \tbreakpoint     - normal breakpoint\n\
16214 \twatchpoint     - watchpoint\n\
16215 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16216 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16217 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16218 address and file/line number respectively.\n\
16219 \n\
16220 Convenience variable \"$_\" and default examine address for \"x\"\n\
16221 are set to the address of the last breakpoint listed unless the command\n\
16222 is prefixed with \"server \".\n\n\
16223 Convenience variable \"$bpnum\" contains the number of the last\n\
16224 breakpoint set."));
16225     }
16226
16227   add_info ("breakpoints", breakpoints_info, _("\
16228 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16229 The \"Type\" column indicates one of:\n\
16230 \tbreakpoint     - normal breakpoint\n\
16231 \twatchpoint     - watchpoint\n\
16232 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16233 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16234 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16235 address and file/line number respectively.\n\
16236 \n\
16237 Convenience variable \"$_\" and default examine address for \"x\"\n\
16238 are set to the address of the last breakpoint listed unless the command\n\
16239 is prefixed with \"server \".\n\n\
16240 Convenience variable \"$bpnum\" contains the number of the last\n\
16241 breakpoint set."));
16242
16243   add_info_alias ("b", "breakpoints", 1);
16244
16245   if (xdb_commands)
16246     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16247 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16248 The \"Type\" column indicates one of:\n\
16249 \tbreakpoint     - normal breakpoint\n\
16250 \twatchpoint     - watchpoint\n\
16251 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16252 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16253 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16254 address and file/line number respectively.\n\
16255 \n\
16256 Convenience variable \"$_\" and default examine address for \"x\"\n\
16257 are set to the address of the last breakpoint listed unless the command\n\
16258 is prefixed with \"server \".\n\n\
16259 Convenience variable \"$bpnum\" contains the number of the last\n\
16260 breakpoint set."));
16261
16262   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16263 Status of all breakpoints, or breakpoint number NUMBER.\n\
16264 The \"Type\" column indicates one of:\n\
16265 \tbreakpoint     - normal breakpoint\n\
16266 \twatchpoint     - watchpoint\n\
16267 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16268 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16269 \tuntil          - internal breakpoint used by the \"until\" command\n\
16270 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16271 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16272 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16273 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16274 address and file/line number respectively.\n\
16275 \n\
16276 Convenience variable \"$_\" and default examine address for \"x\"\n\
16277 are set to the address of the last breakpoint listed unless the command\n\
16278 is prefixed with \"server \".\n\n\
16279 Convenience variable \"$bpnum\" contains the number of the last\n\
16280 breakpoint set."),
16281            &maintenanceinfolist);
16282
16283   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16284 Set catchpoints to catch events."),
16285                   &catch_cmdlist, "catch ",
16286                   0/*allow-unknown*/, &cmdlist);
16287
16288   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16289 Set temporary catchpoints to catch events."),
16290                   &tcatch_cmdlist, "tcatch ",
16291                   0/*allow-unknown*/, &cmdlist);
16292
16293   add_catch_command ("fork", _("Catch calls to fork."),
16294                      catch_fork_command_1,
16295                      NULL,
16296                      (void *) (uintptr_t) catch_fork_permanent,
16297                      (void *) (uintptr_t) catch_fork_temporary);
16298   add_catch_command ("vfork", _("Catch calls to vfork."),
16299                      catch_fork_command_1,
16300                      NULL,
16301                      (void *) (uintptr_t) catch_vfork_permanent,
16302                      (void *) (uintptr_t) catch_vfork_temporary);
16303   add_catch_command ("exec", _("Catch calls to exec."),
16304                      catch_exec_command_1,
16305                      NULL,
16306                      CATCH_PERMANENT,
16307                      CATCH_TEMPORARY);
16308   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16309 Usage: catch load [REGEX]\n\
16310 If REGEX is given, only stop for libraries matching the regular expression."),
16311                      catch_load_command_1,
16312                      NULL,
16313                      CATCH_PERMANENT,
16314                      CATCH_TEMPORARY);
16315   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16316 Usage: catch unload [REGEX]\n\
16317 If REGEX is given, only stop for libraries matching the regular expression."),
16318                      catch_unload_command_1,
16319                      NULL,
16320                      CATCH_PERMANENT,
16321                      CATCH_TEMPORARY);
16322   add_catch_command ("syscall", _("\
16323 Catch system calls by their names and/or numbers.\n\
16324 Arguments say which system calls to catch.  If no arguments\n\
16325 are given, every system call will be caught.\n\
16326 Arguments, if given, should be one or more system call names\n\
16327 (if your system supports that), or system call numbers."),
16328                      catch_syscall_command_1,
16329                      catch_syscall_completer,
16330                      CATCH_PERMANENT,
16331                      CATCH_TEMPORARY);
16332
16333   c = add_com ("watch", class_breakpoint, watch_command, _("\
16334 Set a watchpoint for an expression.\n\
16335 Usage: watch [-l|-location] EXPRESSION\n\
16336 A watchpoint stops execution of your program whenever the value of\n\
16337 an expression changes.\n\
16338 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16339 the memory to which it refers."));
16340   set_cmd_completer (c, expression_completer);
16341
16342   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16343 Set a read watchpoint for an expression.\n\
16344 Usage: rwatch [-l|-location] EXPRESSION\n\
16345 A watchpoint stops execution of your program whenever the value of\n\
16346 an expression is read.\n\
16347 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16348 the memory to which it refers."));
16349   set_cmd_completer (c, expression_completer);
16350
16351   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16352 Set a watchpoint for an expression.\n\
16353 Usage: awatch [-l|-location] EXPRESSION\n\
16354 A watchpoint stops execution of your program whenever the value of\n\
16355 an expression is either read or written.\n\
16356 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16357 the memory to which it refers."));
16358   set_cmd_completer (c, expression_completer);
16359
16360   add_info ("watchpoints", watchpoints_info, _("\
16361 Status of specified watchpoints (all watchpoints if no argument)."));
16362
16363   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16364      respond to changes - contrary to the description.  */
16365   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16366                             &can_use_hw_watchpoints, _("\
16367 Set debugger's willingness to use watchpoint hardware."), _("\
16368 Show debugger's willingness to use watchpoint hardware."), _("\
16369 If zero, gdb will not use hardware for new watchpoints, even if\n\
16370 such is available.  (However, any hardware watchpoints that were\n\
16371 created before setting this to nonzero, will continue to use watchpoint\n\
16372 hardware.)"),
16373                             NULL,
16374                             show_can_use_hw_watchpoints,
16375                             &setlist, &showlist);
16376
16377   can_use_hw_watchpoints = 1;
16378
16379   /* Tracepoint manipulation commands.  */
16380
16381   c = add_com ("trace", class_breakpoint, trace_command, _("\
16382 Set a tracepoint at specified line or function.\n\
16383 \n"
16384 BREAK_ARGS_HELP ("trace") "\n\
16385 Do \"help tracepoints\" for info on other tracepoint commands."));
16386   set_cmd_completer (c, location_completer);
16387
16388   add_com_alias ("tp", "trace", class_alias, 0);
16389   add_com_alias ("tr", "trace", class_alias, 1);
16390   add_com_alias ("tra", "trace", class_alias, 1);
16391   add_com_alias ("trac", "trace", class_alias, 1);
16392
16393   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16394 Set a fast tracepoint at specified line or function.\n\
16395 \n"
16396 BREAK_ARGS_HELP ("ftrace") "\n\
16397 Do \"help tracepoints\" for info on other tracepoint commands."));
16398   set_cmd_completer (c, location_completer);
16399
16400   c = add_com ("strace", class_breakpoint, strace_command, _("\
16401 Set a static tracepoint at specified line, function or marker.\n\
16402 \n\
16403 strace [LOCATION] [if CONDITION]\n\
16404 LOCATION may be a line number, function name, \"*\" and an address,\n\
16405 or -m MARKER_ID.\n\
16406 If a line number is specified, probe the marker at start of code\n\
16407 for that line.  If a function is specified, probe the marker at start\n\
16408 of code for that function.  If an address is specified, probe the marker\n\
16409 at that exact address.  If a marker id is specified, probe the marker\n\
16410 with that name.  With no LOCATION, uses current execution address of\n\
16411 the selected stack frame.\n\
16412 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16413 This collects arbitrary user data passed in the probe point call to the\n\
16414 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16415 by printing the $_sdata variable like any other convenience variable.\n\
16416 \n\
16417 CONDITION is a boolean expression.\n\
16418 \n\
16419 Multiple tracepoints at one place are permitted, and useful if their\n\
16420 conditions are different.\n\
16421 \n\
16422 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16423 Do \"help tracepoints\" for info on other tracepoint commands."));
16424   set_cmd_completer (c, location_completer);
16425
16426   add_info ("tracepoints", tracepoints_info, _("\
16427 Status of specified tracepoints (all tracepoints if no argument).\n\
16428 Convenience variable \"$tpnum\" contains the number of the\n\
16429 last tracepoint set."));
16430
16431   add_info_alias ("tp", "tracepoints", 1);
16432
16433   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16434 Delete specified tracepoints.\n\
16435 Arguments are tracepoint numbers, separated by spaces.\n\
16436 No argument means delete all tracepoints."),
16437            &deletelist);
16438   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16439
16440   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16441 Disable specified tracepoints.\n\
16442 Arguments are tracepoint numbers, separated by spaces.\n\
16443 No argument means disable all tracepoints."),
16444            &disablelist);
16445   deprecate_cmd (c, "disable");
16446
16447   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16448 Enable specified tracepoints.\n\
16449 Arguments are tracepoint numbers, separated by spaces.\n\
16450 No argument means enable all tracepoints."),
16451            &enablelist);
16452   deprecate_cmd (c, "enable");
16453
16454   add_com ("passcount", class_trace, trace_pass_command, _("\
16455 Set the passcount for a tracepoint.\n\
16456 The trace will end when the tracepoint has been passed 'count' times.\n\
16457 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16458 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16459
16460   add_prefix_cmd ("save", class_breakpoint, save_command,
16461                   _("Save breakpoint definitions as a script."),
16462                   &save_cmdlist, "save ",
16463                   0/*allow-unknown*/, &cmdlist);
16464
16465   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16466 Save current breakpoint definitions as a script.\n\
16467 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16468 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16469 session to restore them."),
16470                &save_cmdlist);
16471   set_cmd_completer (c, filename_completer);
16472
16473   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16474 Save current tracepoint definitions as a script.\n\
16475 Use the 'source' command in another debug session to restore them."),
16476                &save_cmdlist);
16477   set_cmd_completer (c, filename_completer);
16478
16479   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16480   deprecate_cmd (c, "save tracepoints");
16481
16482   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16483 Breakpoint specific settings\n\
16484 Configure various breakpoint-specific variables such as\n\
16485 pending breakpoint behavior"),
16486                   &breakpoint_set_cmdlist, "set breakpoint ",
16487                   0/*allow-unknown*/, &setlist);
16488   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16489 Breakpoint specific settings\n\
16490 Configure various breakpoint-specific variables such as\n\
16491 pending breakpoint behavior"),
16492                   &breakpoint_show_cmdlist, "show breakpoint ",
16493                   0/*allow-unknown*/, &showlist);
16494
16495   add_setshow_auto_boolean_cmd ("pending", no_class,
16496                                 &pending_break_support, _("\
16497 Set debugger's behavior regarding pending breakpoints."), _("\
16498 Show debugger's behavior regarding pending breakpoints."), _("\
16499 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16500 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16501 an error.  If auto, an unrecognized breakpoint location results in a\n\
16502 user-query to see if a pending breakpoint should be created."),
16503                                 NULL,
16504                                 show_pending_break_support,
16505                                 &breakpoint_set_cmdlist,
16506                                 &breakpoint_show_cmdlist);
16507
16508   pending_break_support = AUTO_BOOLEAN_AUTO;
16509
16510   add_setshow_boolean_cmd ("auto-hw", no_class,
16511                            &automatic_hardware_breakpoints, _("\
16512 Set automatic usage of hardware breakpoints."), _("\
16513 Show automatic usage of hardware breakpoints."), _("\
16514 If set, the debugger will automatically use hardware breakpoints for\n\
16515 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16516 a warning will be emitted for such breakpoints."),
16517                            NULL,
16518                            show_automatic_hardware_breakpoints,
16519                            &breakpoint_set_cmdlist,
16520                            &breakpoint_show_cmdlist);
16521
16522   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16523                                 &always_inserted_mode, _("\
16524 Set mode for inserting breakpoints."), _("\
16525 Show mode for inserting breakpoints."), _("\
16526 When this mode is off, breakpoints are inserted in inferior when it is\n\
16527 resumed, and removed when execution stops.  When this mode is on,\n\
16528 breakpoints are inserted immediately and removed only when the user\n\
16529 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16530 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16531 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16532 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16533 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16534                                 NULL,
16535                                 &show_always_inserted_mode,
16536                                 &breakpoint_set_cmdlist,
16537                                 &breakpoint_show_cmdlist);
16538
16539   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16540                         condition_evaluation_enums,
16541                         &condition_evaluation_mode_1, _("\
16542 Set mode of breakpoint condition evaluation."), _("\
16543 Show mode of breakpoint condition evaluation."), _("\
16544 When this is set to \"host\", breakpoint conditions will be\n\
16545 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16546 breakpoint conditions will be downloaded to the target (if the target\n\
16547 supports such feature) and conditions will be evaluated on the target's side.\n\
16548 If this is set to \"auto\" (default), this will be automatically set to\n\
16549 \"target\" if it supports condition evaluation, otherwise it will\n\
16550 be set to \"gdb\""),
16551                            &set_condition_evaluation_mode,
16552                            &show_condition_evaluation_mode,
16553                            &breakpoint_set_cmdlist,
16554                            &breakpoint_show_cmdlist);
16555
16556   add_com ("break-range", class_breakpoint, break_range_command, _("\
16557 Set a breakpoint for an address range.\n\
16558 break-range START-LOCATION, END-LOCATION\n\
16559 where START-LOCATION and END-LOCATION can be one of the following:\n\
16560   LINENUM, for that line in the current file,\n\
16561   FILE:LINENUM, for that line in that file,\n\
16562   +OFFSET, for that number of lines after the current line\n\
16563            or the start of the range\n\
16564   FUNCTION, for the first line in that function,\n\
16565   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16566   *ADDRESS, for the instruction at that address.\n\
16567 \n\
16568 The breakpoint will stop execution of the inferior whenever it executes\n\
16569 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16570 range (including START-LOCATION and END-LOCATION)."));
16571
16572   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16573 Set a dynamic printf at specified line or function.\n\
16574 dprintf location,format string,arg1,arg2,...\n\
16575 location may be a line number, function name, or \"*\" and an address.\n\
16576 If a line number is specified, break at start of code for that line.\n\
16577 If a function is specified, break at start of code for that function."));
16578   set_cmd_completer (c, location_completer);
16579
16580   add_setshow_enum_cmd ("dprintf-style", class_support,
16581                         dprintf_style_enums, &dprintf_style, _("\
16582 Set the style of usage for dynamic printf."), _("\
16583 Show the style of usage for dynamic printf."), _("\
16584 This setting chooses how GDB will do a dynamic printf.\n\
16585 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16586 console, as with the \"printf\" command.\n\
16587 If the value is \"call\", the print is done by calling a function in your\n\
16588 program; by default printf(), but you can choose a different function or\n\
16589 output stream by setting dprintf-function and dprintf-channel."),
16590                         update_dprintf_commands, NULL,
16591                         &setlist, &showlist);
16592
16593   dprintf_function = xstrdup ("printf");
16594   add_setshow_string_cmd ("dprintf-function", class_support,
16595                           &dprintf_function, _("\
16596 Set the function to use for dynamic printf"), _("\
16597 Show the function to use for dynamic printf"), NULL,
16598                           update_dprintf_commands, NULL,
16599                           &setlist, &showlist);
16600
16601   dprintf_channel = xstrdup ("");
16602   add_setshow_string_cmd ("dprintf-channel", class_support,
16603                           &dprintf_channel, _("\
16604 Set the channel to use for dynamic printf"), _("\
16605 Show the channel to use for dynamic printf"), NULL,
16606                           update_dprintf_commands, NULL,
16607                           &setlist, &showlist);
16608
16609   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16610                            &disconnected_dprintf, _("\
16611 Set whether dprintf continues after GDB disconnects."), _("\
16612 Show whether dprintf continues after GDB disconnects."), _("\
16613 Use this to let dprintf commands continue to hit and produce output\n\
16614 even if GDB disconnects or detaches from the target."),
16615                            NULL,
16616                            NULL,
16617                            &setlist, &showlist);
16618
16619   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16620 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16621 (target agent only) This is useful for formatted output in user-defined commands."));
16622
16623   automatic_hardware_breakpoints = 1;
16624
16625   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16626   observer_attach_thread_exit (remove_threaded_breakpoints);
16627 }