Stop using errno values around target_xfer interfaces and memory errors.
[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     }
1804   else if (within_current_scope && b->exp)
1805     {
1806       int pc = 0;
1807       struct value *val_chain, *v, *result, *next;
1808       struct program_space *frame_pspace;
1809
1810       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1811
1812       /* Avoid setting b->val if it's already set.  The meaning of
1813          b->val is 'the last value' user saw, and we should update
1814          it only if we reported that last value to user.  As it
1815          happens, the code that reports it updates b->val directly.
1816          We don't keep track of the memory value for masked
1817          watchpoints.  */
1818       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1819         {
1820           b->val = v;
1821           b->val_valid = 1;
1822         }
1823
1824       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1825
1826       /* Look at each value on the value chain.  */
1827       for (v = val_chain; v; v = value_next (v))
1828         {
1829           /* If it's a memory location, and GDB actually needed
1830              its contents to evaluate the expression, then we
1831              must watch it.  If the first value returned is
1832              still lazy, that means an error occurred reading it;
1833              watch it anyway in case it becomes readable.  */
1834           if (VALUE_LVAL (v) == lval_memory
1835               && (v == val_chain || ! value_lazy (v)))
1836             {
1837               struct type *vtype = check_typedef (value_type (v));
1838
1839               /* We only watch structs and arrays if user asked
1840                  for it explicitly, never if they just happen to
1841                  appear in the middle of some value chain.  */
1842               if (v == result
1843                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1844                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1845                 {
1846                   CORE_ADDR addr;
1847                   int type;
1848                   struct bp_location *loc, **tmp;
1849
1850                   addr = value_address (v);
1851                   type = hw_write;
1852                   if (b->base.type == bp_read_watchpoint)
1853                     type = hw_read;
1854                   else if (b->base.type == bp_access_watchpoint)
1855                     type = hw_access;
1856
1857                   loc = allocate_bp_location (&b->base);
1858                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1859                     ;
1860                   *tmp = loc;
1861                   loc->gdbarch = get_type_arch (value_type (v));
1862
1863                   loc->pspace = frame_pspace;
1864                   loc->address = addr;
1865                   loc->length = TYPE_LENGTH (value_type (v));
1866                   loc->watchpoint_type = type;
1867                 }
1868             }
1869         }
1870
1871       /* Change the type of breakpoint between hardware assisted or
1872          an ordinary watchpoint depending on the hardware support
1873          and free hardware slots.  REPARSE is set when the inferior
1874          is started.  */
1875       if (reparse)
1876         {
1877           int reg_cnt;
1878           enum bp_loc_type loc_type;
1879           struct bp_location *bl;
1880
1881           reg_cnt = can_use_hardware_watchpoint (val_chain);
1882
1883           if (reg_cnt)
1884             {
1885               int i, target_resources_ok, other_type_used;
1886               enum bptype type;
1887
1888               /* Use an exact watchpoint when there's only one memory region to be
1889                  watched, and only one debug register is needed to watch it.  */
1890               b->exact = target_exact_watchpoints && reg_cnt == 1;
1891
1892               /* We need to determine how many resources are already
1893                  used for all other hardware watchpoints plus this one
1894                  to see if we still have enough resources to also fit
1895                  this watchpoint in as well.  */
1896
1897               /* If this is a software watchpoint, we try to turn it
1898                  to a hardware one -- count resources as if B was of
1899                  hardware watchpoint type.  */
1900               type = b->base.type;
1901               if (type == bp_watchpoint)
1902                 type = bp_hardware_watchpoint;
1903
1904               /* This watchpoint may or may not have been placed on
1905                  the list yet at this point (it won't be in the list
1906                  if we're trying to create it for the first time,
1907                  through watch_command), so always account for it
1908                  manually.  */
1909
1910               /* Count resources used by all watchpoints except B.  */
1911               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1912
1913               /* Add in the resources needed for B.  */
1914               i += hw_watchpoint_use_count (&b->base);
1915
1916               target_resources_ok
1917                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1918               if (target_resources_ok <= 0)
1919                 {
1920                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1921
1922                   if (target_resources_ok == 0 && !sw_mode)
1923                     error (_("Target does not support this type of "
1924                              "hardware watchpoint."));
1925                   else if (target_resources_ok < 0 && !sw_mode)
1926                     error (_("There are not enough available hardware "
1927                              "resources for this watchpoint."));
1928
1929                   /* Downgrade to software watchpoint.  */
1930                   b->base.type = bp_watchpoint;
1931                 }
1932               else
1933                 {
1934                   /* If this was a software watchpoint, we've just
1935                      found we have enough resources to turn it to a
1936                      hardware watchpoint.  Otherwise, this is a
1937                      nop.  */
1938                   b->base.type = type;
1939                 }
1940             }
1941           else if (!b->base.ops->works_in_software_mode (&b->base))
1942             error (_("Expression cannot be implemented with "
1943                      "read/access watchpoint."));
1944           else
1945             b->base.type = bp_watchpoint;
1946
1947           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1948                       : bp_loc_hardware_watchpoint);
1949           for (bl = b->base.loc; bl; bl = bl->next)
1950             bl->loc_type = loc_type;
1951         }
1952
1953       for (v = val_chain; v; v = next)
1954         {
1955           next = value_next (v);
1956           if (v != b->val)
1957             value_free (v);
1958         }
1959
1960       /* If a software watchpoint is not watching any memory, then the
1961          above left it without any location set up.  But,
1962          bpstat_stop_status requires a location to be able to report
1963          stops, so make sure there's at least a dummy one.  */
1964       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1965         {
1966           struct breakpoint *base = &b->base;
1967           base->loc = allocate_bp_location (base);
1968           base->loc->pspace = frame_pspace;
1969           base->loc->address = -1;
1970           base->loc->length = -1;
1971           base->loc->watchpoint_type = -1;
1972         }
1973     }
1974   else if (!within_current_scope)
1975     {
1976       printf_filtered (_("\
1977 Watchpoint %d deleted because the program has left the block\n\
1978 in which its expression is valid.\n"),
1979                        b->base.number);
1980       watchpoint_del_at_next_stop (b);
1981     }
1982
1983   /* Restore the selected frame.  */
1984   if (frame_saved)
1985     select_frame (frame_find_by_id (saved_frame_id));
1986 }
1987
1988
1989 /* Returns 1 iff breakpoint location should be
1990    inserted in the inferior.  We don't differentiate the type of BL's owner
1991    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1992    breakpoint_ops is not defined, because in insert_bp_location,
1993    tracepoint's insert_location will not be called.  */
1994 static int
1995 should_be_inserted (struct bp_location *bl)
1996 {
1997   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1998     return 0;
1999
2000   if (bl->owner->disposition == disp_del_at_next_stop)
2001     return 0;
2002
2003   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2004     return 0;
2005
2006   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2007     return 0;
2008
2009   /* This is set for example, when we're attached to the parent of a
2010      vfork, and have detached from the child.  The child is running
2011      free, and we expect it to do an exec or exit, at which point the
2012      OS makes the parent schedulable again (and the target reports
2013      that the vfork is done).  Until the child is done with the shared
2014      memory region, do not insert breakpoints in the parent, otherwise
2015      the child could still trip on the parent's breakpoints.  Since
2016      the parent is blocked anyway, it won't miss any breakpoint.  */
2017   if (bl->pspace->breakpoints_not_allowed)
2018     return 0;
2019
2020   return 1;
2021 }
2022
2023 /* Same as should_be_inserted but does the check assuming
2024    that the location is not duplicated.  */
2025
2026 static int
2027 unduplicated_should_be_inserted (struct bp_location *bl)
2028 {
2029   int result;
2030   const int save_duplicate = bl->duplicate;
2031
2032   bl->duplicate = 0;
2033   result = should_be_inserted (bl);
2034   bl->duplicate = save_duplicate;
2035   return result;
2036 }
2037
2038 /* Parses a conditional described by an expression COND into an
2039    agent expression bytecode suitable for evaluation
2040    by the bytecode interpreter.  Return NULL if there was
2041    any error during parsing.  */
2042
2043 static struct agent_expr *
2044 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2045 {
2046   struct agent_expr *aexpr = NULL;
2047   volatile struct gdb_exception ex;
2048
2049   if (!cond)
2050     return NULL;
2051
2052   /* We don't want to stop processing, so catch any errors
2053      that may show up.  */
2054   TRY_CATCH (ex, RETURN_MASK_ERROR)
2055     {
2056       aexpr = gen_eval_for_expr (scope, cond);
2057     }
2058
2059   if (ex.reason < 0)
2060     {
2061       /* If we got here, it means the condition could not be parsed to a valid
2062          bytecode expression and thus can't be evaluated on the target's side.
2063          It's no use iterating through the conditions.  */
2064       return NULL;
2065     }
2066
2067   /* We have a valid agent expression.  */
2068   return aexpr;
2069 }
2070
2071 /* Based on location BL, create a list of breakpoint conditions to be
2072    passed on to the target.  If we have duplicated locations with different
2073    conditions, we will add such conditions to the list.  The idea is that the
2074    target will evaluate the list of conditions and will only notify GDB when
2075    one of them is true.  */
2076
2077 static void
2078 build_target_condition_list (struct bp_location *bl)
2079 {
2080   struct bp_location **locp = NULL, **loc2p;
2081   int null_condition_or_parse_error = 0;
2082   int modified = bl->needs_update;
2083   struct bp_location *loc;
2084
2085   /* This is only meaningful if the target is
2086      evaluating conditions and if the user has
2087      opted for condition evaluation on the target's
2088      side.  */
2089   if (gdb_evaluates_breakpoint_condition_p ()
2090       || !target_supports_evaluation_of_breakpoint_conditions ())
2091     return;
2092
2093   /* Do a first pass to check for locations with no assigned
2094      conditions or conditions that fail to parse to a valid agent expression
2095      bytecode.  If any of these happen, then it's no use to send conditions
2096      to the target since this location will always trigger and generate a
2097      response back to GDB.  */
2098   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2099     {
2100       loc = (*loc2p);
2101       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2102         {
2103           if (modified)
2104             {
2105               struct agent_expr *aexpr;
2106
2107               /* Re-parse the conditions since something changed.  In that
2108                  case we already freed the condition bytecodes (see
2109                  force_breakpoint_reinsertion).  We just
2110                  need to parse the condition to bytecodes again.  */
2111               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2112               loc->cond_bytecode = aexpr;
2113
2114               /* Check if we managed to parse the conditional expression
2115                  correctly.  If not, we will not send this condition
2116                  to the target.  */
2117               if (aexpr)
2118                 continue;
2119             }
2120
2121           /* If we have a NULL bytecode expression, it means something
2122              went wrong or we have a null condition expression.  */
2123           if (!loc->cond_bytecode)
2124             {
2125               null_condition_or_parse_error = 1;
2126               break;
2127             }
2128         }
2129     }
2130
2131   /* If any of these happened, it means we will have to evaluate the conditions
2132      for the location's address on gdb's side.  It is no use keeping bytecodes
2133      for all the other duplicate locations, thus we free all of them here.
2134
2135      This is so we have a finer control over which locations' conditions are
2136      being evaluated by GDB or the remote stub.  */
2137   if (null_condition_or_parse_error)
2138     {
2139       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2140         {
2141           loc = (*loc2p);
2142           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2143             {
2144               /* Only go as far as the first NULL bytecode is
2145                  located.  */
2146               if (!loc->cond_bytecode)
2147                 return;
2148
2149               free_agent_expr (loc->cond_bytecode);
2150               loc->cond_bytecode = NULL;
2151             }
2152         }
2153     }
2154
2155   /* No NULL conditions or failed bytecode generation.  Build a condition list
2156      for this location's address.  */
2157   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2158     {
2159       loc = (*loc2p);
2160       if (loc->cond
2161           && is_breakpoint (loc->owner)
2162           && loc->pspace->num == bl->pspace->num
2163           && loc->owner->enable_state == bp_enabled
2164           && loc->enabled)
2165         /* Add the condition to the vector.  This will be used later to send the
2166            conditions to the target.  */
2167         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2168                        loc->cond_bytecode);
2169     }
2170
2171   return;
2172 }
2173
2174 /* Parses a command described by string CMD into an agent expression
2175    bytecode suitable for evaluation by the bytecode interpreter.
2176    Return NULL if there was any error during parsing.  */
2177
2178 static struct agent_expr *
2179 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2180 {
2181   struct cleanup *old_cleanups = 0;
2182   struct expression *expr, **argvec;
2183   struct agent_expr *aexpr = NULL;
2184   volatile struct gdb_exception ex;
2185   const char *cmdrest;
2186   const char *format_start, *format_end;
2187   struct format_piece *fpieces;
2188   int nargs;
2189   struct gdbarch *gdbarch = get_current_arch ();
2190
2191   if (!cmd)
2192     return NULL;
2193
2194   cmdrest = cmd;
2195
2196   if (*cmdrest == ',')
2197     ++cmdrest;
2198   cmdrest = skip_spaces_const (cmdrest);
2199
2200   if (*cmdrest++ != '"')
2201     error (_("No format string following the location"));
2202
2203   format_start = cmdrest;
2204
2205   fpieces = parse_format_string (&cmdrest);
2206
2207   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2208
2209   format_end = cmdrest;
2210
2211   if (*cmdrest++ != '"')
2212     error (_("Bad format string, non-terminated '\"'."));
2213   
2214   cmdrest = skip_spaces_const (cmdrest);
2215
2216   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2217     error (_("Invalid argument syntax"));
2218
2219   if (*cmdrest == ',')
2220     cmdrest++;
2221   cmdrest = skip_spaces_const (cmdrest);
2222
2223   /* For each argument, make an expression.  */
2224
2225   argvec = (struct expression **) alloca (strlen (cmd)
2226                                          * sizeof (struct expression *));
2227
2228   nargs = 0;
2229   while (*cmdrest != '\0')
2230     {
2231       const char *cmd1;
2232
2233       cmd1 = cmdrest;
2234       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2235       argvec[nargs++] = expr;
2236       cmdrest = cmd1;
2237       if (*cmdrest == ',')
2238         ++cmdrest;
2239     }
2240
2241   /* We don't want to stop processing, so catch any errors
2242      that may show up.  */
2243   TRY_CATCH (ex, RETURN_MASK_ERROR)
2244     {
2245       aexpr = gen_printf (scope, gdbarch, 0, 0,
2246                           format_start, format_end - format_start,
2247                           fpieces, nargs, argvec);
2248     }
2249
2250   do_cleanups (old_cleanups);
2251
2252   if (ex.reason < 0)
2253     {
2254       /* If we got here, it means the command could not be parsed to a valid
2255          bytecode expression and thus can't be evaluated on the target's side.
2256          It's no use iterating through the other commands.  */
2257       return NULL;
2258     }
2259
2260   /* We have a valid agent expression, return it.  */
2261   return aexpr;
2262 }
2263
2264 /* Based on location BL, create a list of breakpoint commands to be
2265    passed on to the target.  If we have duplicated locations with
2266    different commands, we will add any such to the list.  */
2267
2268 static void
2269 build_target_command_list (struct bp_location *bl)
2270 {
2271   struct bp_location **locp = NULL, **loc2p;
2272   int null_command_or_parse_error = 0;
2273   int modified = bl->needs_update;
2274   struct bp_location *loc;
2275
2276   /* For now, limit to agent-style dprintf breakpoints.  */
2277   if (bl->owner->type != bp_dprintf
2278       || strcmp (dprintf_style, dprintf_style_agent) != 0)
2279     return;
2280
2281   if (!target_can_run_breakpoint_commands ())
2282     return;
2283
2284   /* Do a first pass to check for locations with no assigned
2285      conditions or conditions that fail to parse to a valid agent expression
2286      bytecode.  If any of these happen, then it's no use to send conditions
2287      to the target since this location will always trigger and generate a
2288      response back to GDB.  */
2289   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2290     {
2291       loc = (*loc2p);
2292       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2293         {
2294           if (modified)
2295             {
2296               struct agent_expr *aexpr;
2297
2298               /* Re-parse the commands since something changed.  In that
2299                  case we already freed the command bytecodes (see
2300                  force_breakpoint_reinsertion).  We just
2301                  need to parse the command to bytecodes again.  */
2302               aexpr = parse_cmd_to_aexpr (bl->address,
2303                                           loc->owner->extra_string);
2304               loc->cmd_bytecode = aexpr;
2305
2306               if (!aexpr)
2307                 continue;
2308             }
2309
2310           /* If we have a NULL bytecode expression, it means something
2311              went wrong or we have a null command expression.  */
2312           if (!loc->cmd_bytecode)
2313             {
2314               null_command_or_parse_error = 1;
2315               break;
2316             }
2317         }
2318     }
2319
2320   /* If anything failed, then we're not doing target-side commands,
2321      and so clean up.  */
2322   if (null_command_or_parse_error)
2323     {
2324       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2325         {
2326           loc = (*loc2p);
2327           if (is_breakpoint (loc->owner)
2328               && loc->pspace->num == bl->pspace->num)
2329             {
2330               /* Only go as far as the first NULL bytecode is
2331                  located.  */
2332               if (loc->cmd_bytecode == NULL)
2333                 return;
2334
2335               free_agent_expr (loc->cmd_bytecode);
2336               loc->cmd_bytecode = NULL;
2337             }
2338         }
2339     }
2340
2341   /* No NULL commands or failed bytecode generation.  Build a command list
2342      for this location's address.  */
2343   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2344     {
2345       loc = (*loc2p);
2346       if (loc->owner->extra_string
2347           && is_breakpoint (loc->owner)
2348           && loc->pspace->num == bl->pspace->num
2349           && loc->owner->enable_state == bp_enabled
2350           && loc->enabled)
2351         /* Add the command to the vector.  This will be used later
2352            to send the commands to the target.  */
2353         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2354                        loc->cmd_bytecode);
2355     }
2356
2357   bl->target_info.persist = 0;
2358   /* Maybe flag this location as persistent.  */
2359   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2360     bl->target_info.persist = 1;
2361 }
2362
2363 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2364    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2365    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2366    Returns 0 for success, 1 if the bp_location type is not supported or
2367    -1 for failure.
2368
2369    NOTE drow/2003-09-09: This routine could be broken down to an
2370    object-style method for each breakpoint or catchpoint type.  */
2371 static int
2372 insert_bp_location (struct bp_location *bl,
2373                     struct ui_file *tmp_error_stream,
2374                     int *disabled_breaks,
2375                     int *hw_breakpoint_error,
2376                     int *hw_bp_error_explained_already)
2377 {
2378   int val = 0;
2379   char *hw_bp_err_string = NULL;
2380   struct gdb_exception e;
2381
2382   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2383     return 0;
2384
2385   /* Note we don't initialize bl->target_info, as that wipes out
2386      the breakpoint location's shadow_contents if the breakpoint
2387      is still inserted at that location.  This in turn breaks
2388      target_read_memory which depends on these buffers when
2389      a memory read is requested at the breakpoint location:
2390      Once the target_info has been wiped, we fail to see that
2391      we have a breakpoint inserted at that address and thus
2392      read the breakpoint instead of returning the data saved in
2393      the breakpoint location's shadow contents.  */
2394   bl->target_info.placed_address = bl->address;
2395   bl->target_info.placed_address_space = bl->pspace->aspace;
2396   bl->target_info.length = bl->length;
2397
2398   /* When working with target-side conditions, we must pass all the conditions
2399      for the same breakpoint address down to the target since GDB will not
2400      insert those locations.  With a list of breakpoint conditions, the target
2401      can decide when to stop and notify GDB.  */
2402
2403   if (is_breakpoint (bl->owner))
2404     {
2405       build_target_condition_list (bl);
2406       build_target_command_list (bl);
2407       /* Reset the modification marker.  */
2408       bl->needs_update = 0;
2409     }
2410
2411   if (bl->loc_type == bp_loc_software_breakpoint
2412       || bl->loc_type == bp_loc_hardware_breakpoint)
2413     {
2414       if (bl->owner->type != bp_hardware_breakpoint)
2415         {
2416           /* If the explicitly specified breakpoint type
2417              is not hardware breakpoint, check the memory map to see
2418              if the breakpoint address is in read only memory or not.
2419
2420              Two important cases are:
2421              - location type is not hardware breakpoint, memory
2422              is readonly.  We change the type of the location to
2423              hardware breakpoint.
2424              - location type is hardware breakpoint, memory is
2425              read-write.  This means we've previously made the
2426              location hardware one, but then the memory map changed,
2427              so we undo.
2428              
2429              When breakpoints are removed, remove_breakpoints will use
2430              location types we've just set here, the only possible
2431              problem is that memory map has changed during running
2432              program, but it's not going to work anyway with current
2433              gdb.  */
2434           struct mem_region *mr 
2435             = lookup_mem_region (bl->target_info.placed_address);
2436           
2437           if (mr)
2438             {
2439               if (automatic_hardware_breakpoints)
2440                 {
2441                   enum bp_loc_type new_type;
2442                   
2443                   if (mr->attrib.mode != MEM_RW)
2444                     new_type = bp_loc_hardware_breakpoint;
2445                   else 
2446                     new_type = bp_loc_software_breakpoint;
2447                   
2448                   if (new_type != bl->loc_type)
2449                     {
2450                       static int said = 0;
2451
2452                       bl->loc_type = new_type;
2453                       if (!said)
2454                         {
2455                           fprintf_filtered (gdb_stdout,
2456                                             _("Note: automatically using "
2457                                               "hardware breakpoints for "
2458                                               "read-only addresses.\n"));
2459                           said = 1;
2460                         }
2461                     }
2462                 }
2463               else if (bl->loc_type == bp_loc_software_breakpoint
2464                        && mr->attrib.mode != MEM_RW)        
2465                 warning (_("cannot set software breakpoint "
2466                            "at readonly address %s"),
2467                          paddress (bl->gdbarch, bl->address));
2468             }
2469         }
2470         
2471       /* First check to see if we have to handle an overlay.  */
2472       if (overlay_debugging == ovly_off
2473           || bl->section == NULL
2474           || !(section_is_overlay (bl->section)))
2475         {
2476           /* No overlay handling: just set the breakpoint.  */
2477           TRY_CATCH (e, RETURN_MASK_ALL)
2478             {
2479               val = bl->owner->ops->insert_location (bl);
2480             }
2481           if (e.reason < 0)
2482             {
2483               val = 1;
2484               hw_bp_err_string = (char *) e.message;
2485             }
2486         }
2487       else
2488         {
2489           /* This breakpoint is in an overlay section.
2490              Shall we set a breakpoint at the LMA?  */
2491           if (!overlay_events_enabled)
2492             {
2493               /* Yes -- overlay event support is not active, 
2494                  so we must try to set a breakpoint at the LMA.
2495                  This will not work for a hardware breakpoint.  */
2496               if (bl->loc_type == bp_loc_hardware_breakpoint)
2497                 warning (_("hardware breakpoint %d not supported in overlay!"),
2498                          bl->owner->number);
2499               else
2500                 {
2501                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2502                                                              bl->section);
2503                   /* Set a software (trap) breakpoint at the LMA.  */
2504                   bl->overlay_target_info = bl->target_info;
2505                   bl->overlay_target_info.placed_address = addr;
2506                   val = target_insert_breakpoint (bl->gdbarch,
2507                                                   &bl->overlay_target_info);
2508                   if (val != 0)
2509                     fprintf_unfiltered (tmp_error_stream,
2510                                         "Overlay breakpoint %d "
2511                                         "failed: in ROM?\n",
2512                                         bl->owner->number);
2513                 }
2514             }
2515           /* Shall we set a breakpoint at the VMA? */
2516           if (section_is_mapped (bl->section))
2517             {
2518               /* Yes.  This overlay section is mapped into memory.  */
2519               TRY_CATCH (e, RETURN_MASK_ALL)
2520                 {
2521                   val = bl->owner->ops->insert_location (bl);
2522                 }
2523               if (e.reason < 0)
2524                 {
2525                   val = 1;
2526                   hw_bp_err_string = (char *) e.message;
2527                 }
2528             }
2529           else
2530             {
2531               /* No.  This breakpoint will not be inserted.  
2532                  No error, but do not mark the bp as 'inserted'.  */
2533               return 0;
2534             }
2535         }
2536
2537       if (val)
2538         {
2539           /* Can't set the breakpoint.  */
2540           if (solib_name_from_address (bl->pspace, bl->address))
2541             {
2542               /* See also: disable_breakpoints_in_shlibs.  */
2543               val = 0;
2544               bl->shlib_disabled = 1;
2545               observer_notify_breakpoint_modified (bl->owner);
2546               if (!*disabled_breaks)
2547                 {
2548                   fprintf_unfiltered (tmp_error_stream, 
2549                                       "Cannot insert breakpoint %d.\n", 
2550                                       bl->owner->number);
2551                   fprintf_unfiltered (tmp_error_stream, 
2552                                       "Temporarily disabling shared "
2553                                       "library breakpoints:\n");
2554                 }
2555               *disabled_breaks = 1;
2556               fprintf_unfiltered (tmp_error_stream,
2557                                   "breakpoint #%d\n", bl->owner->number);
2558             }
2559           else
2560             {
2561               if (bl->loc_type == bp_loc_hardware_breakpoint)
2562                 {
2563                   *hw_breakpoint_error = 1;
2564                   *hw_bp_error_explained_already = hw_bp_err_string != NULL;
2565                   fprintf_unfiltered (tmp_error_stream,
2566                                       "Cannot insert hardware breakpoint %d%s",
2567                                       bl->owner->number, hw_bp_err_string ? ":" : ".\n");
2568                   if (hw_bp_err_string)
2569                     fprintf_unfiltered (tmp_error_stream, "%s.\n", hw_bp_err_string);
2570                 }
2571               else
2572                 {
2573                   char *message = memory_error_message (TARGET_XFER_E_IO,
2574                                                         bl->gdbarch, bl->address);
2575                   struct cleanup *old_chain = make_cleanup (xfree, message);
2576
2577                   fprintf_unfiltered (tmp_error_stream, 
2578                                       "Cannot insert breakpoint %d.\n"
2579                                       "%s\n",
2580                                       bl->owner->number, message);
2581
2582                   do_cleanups (old_chain);
2583                 }
2584
2585             }
2586         }
2587       else
2588         bl->inserted = 1;
2589
2590       return val;
2591     }
2592
2593   else if (bl->loc_type == bp_loc_hardware_watchpoint
2594            /* NOTE drow/2003-09-08: This state only exists for removing
2595               watchpoints.  It's not clear that it's necessary...  */
2596            && bl->owner->disposition != disp_del_at_next_stop)
2597     {
2598       gdb_assert (bl->owner->ops != NULL
2599                   && bl->owner->ops->insert_location != NULL);
2600
2601       val = bl->owner->ops->insert_location (bl);
2602
2603       /* If trying to set a read-watchpoint, and it turns out it's not
2604          supported, try emulating one with an access watchpoint.  */
2605       if (val == 1 && bl->watchpoint_type == hw_read)
2606         {
2607           struct bp_location *loc, **loc_temp;
2608
2609           /* But don't try to insert it, if there's already another
2610              hw_access location that would be considered a duplicate
2611              of this one.  */
2612           ALL_BP_LOCATIONS (loc, loc_temp)
2613             if (loc != bl
2614                 && loc->watchpoint_type == hw_access
2615                 && watchpoint_locations_match (bl, loc))
2616               {
2617                 bl->duplicate = 1;
2618                 bl->inserted = 1;
2619                 bl->target_info = loc->target_info;
2620                 bl->watchpoint_type = hw_access;
2621                 val = 0;
2622                 break;
2623               }
2624
2625           if (val == 1)
2626             {
2627               bl->watchpoint_type = hw_access;
2628               val = bl->owner->ops->insert_location (bl);
2629
2630               if (val)
2631                 /* Back to the original value.  */
2632                 bl->watchpoint_type = hw_read;
2633             }
2634         }
2635
2636       bl->inserted = (val == 0);
2637     }
2638
2639   else if (bl->owner->type == bp_catchpoint)
2640     {
2641       gdb_assert (bl->owner->ops != NULL
2642                   && bl->owner->ops->insert_location != NULL);
2643
2644       val = bl->owner->ops->insert_location (bl);
2645       if (val)
2646         {
2647           bl->owner->enable_state = bp_disabled;
2648
2649           if (val == 1)
2650             warning (_("\
2651 Error inserting catchpoint %d: Your system does not support this type\n\
2652 of catchpoint."), bl->owner->number);
2653           else
2654             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2655         }
2656
2657       bl->inserted = (val == 0);
2658
2659       /* We've already printed an error message if there was a problem
2660          inserting this catchpoint, and we've disabled the catchpoint,
2661          so just return success.  */
2662       return 0;
2663     }
2664
2665   return 0;
2666 }
2667
2668 /* This function is called when program space PSPACE is about to be
2669    deleted.  It takes care of updating breakpoints to not reference
2670    PSPACE anymore.  */
2671
2672 void
2673 breakpoint_program_space_exit (struct program_space *pspace)
2674 {
2675   struct breakpoint *b, *b_temp;
2676   struct bp_location *loc, **loc_temp;
2677
2678   /* Remove any breakpoint that was set through this program space.  */
2679   ALL_BREAKPOINTS_SAFE (b, b_temp)
2680     {
2681       if (b->pspace == pspace)
2682         delete_breakpoint (b);
2683     }
2684
2685   /* Breakpoints set through other program spaces could have locations
2686      bound to PSPACE as well.  Remove those.  */
2687   ALL_BP_LOCATIONS (loc, loc_temp)
2688     {
2689       struct bp_location *tmp;
2690
2691       if (loc->pspace == pspace)
2692         {
2693           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2694           if (loc->owner->loc == loc)
2695             loc->owner->loc = loc->next;
2696           else
2697             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2698               if (tmp->next == loc)
2699                 {
2700                   tmp->next = loc->next;
2701                   break;
2702                 }
2703         }
2704     }
2705
2706   /* Now update the global location list to permanently delete the
2707      removed locations above.  */
2708   update_global_location_list (0);
2709 }
2710
2711 /* Make sure all breakpoints are inserted in inferior.
2712    Throws exception on any error.
2713    A breakpoint that is already inserted won't be inserted
2714    again, so calling this function twice is safe.  */
2715 void
2716 insert_breakpoints (void)
2717 {
2718   struct breakpoint *bpt;
2719
2720   ALL_BREAKPOINTS (bpt)
2721     if (is_hardware_watchpoint (bpt))
2722       {
2723         struct watchpoint *w = (struct watchpoint *) bpt;
2724
2725         update_watchpoint (w, 0 /* don't reparse.  */);
2726       }
2727
2728   update_global_location_list (1);
2729
2730   /* update_global_location_list does not insert breakpoints when
2731      always_inserted_mode is not enabled.  Explicitly insert them
2732      now.  */
2733   if (!breakpoints_always_inserted_mode ())
2734     insert_breakpoint_locations ();
2735 }
2736
2737 /* Invoke CALLBACK for each of bp_location.  */
2738
2739 void
2740 iterate_over_bp_locations (walk_bp_location_callback callback)
2741 {
2742   struct bp_location *loc, **loc_tmp;
2743
2744   ALL_BP_LOCATIONS (loc, loc_tmp)
2745     {
2746       callback (loc, NULL);
2747     }
2748 }
2749
2750 /* This is used when we need to synch breakpoint conditions between GDB and the
2751    target.  It is the case with deleting and disabling of breakpoints when using
2752    always-inserted mode.  */
2753
2754 static void
2755 update_inserted_breakpoint_locations (void)
2756 {
2757   struct bp_location *bl, **blp_tmp;
2758   int error_flag = 0;
2759   int val = 0;
2760   int disabled_breaks = 0;
2761   int hw_breakpoint_error = 0;
2762   int hw_bp_details_reported = 0;
2763
2764   struct ui_file *tmp_error_stream = mem_fileopen ();
2765   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2766
2767   /* Explicitly mark the warning -- this will only be printed if
2768      there was an error.  */
2769   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2770
2771   save_current_space_and_thread ();
2772
2773   ALL_BP_LOCATIONS (bl, blp_tmp)
2774     {
2775       /* We only want to update software breakpoints and hardware
2776          breakpoints.  */
2777       if (!is_breakpoint (bl->owner))
2778         continue;
2779
2780       /* We only want to update locations that are already inserted
2781          and need updating.  This is to avoid unwanted insertion during
2782          deletion of breakpoints.  */
2783       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2784         continue;
2785
2786       switch_to_program_space_and_thread (bl->pspace);
2787
2788       /* For targets that support global breakpoints, there's no need
2789          to select an inferior to insert breakpoint to.  In fact, even
2790          if we aren't attached to any process yet, we should still
2791          insert breakpoints.  */
2792       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2793           && ptid_equal (inferior_ptid, null_ptid))
2794         continue;
2795
2796       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2797                                     &hw_breakpoint_error, &hw_bp_details_reported);
2798       if (val)
2799         error_flag = val;
2800     }
2801
2802   if (error_flag)
2803     {
2804       target_terminal_ours_for_output ();
2805       error_stream (tmp_error_stream);
2806     }
2807
2808   do_cleanups (cleanups);
2809 }
2810
2811 /* Used when starting or continuing the program.  */
2812
2813 static void
2814 insert_breakpoint_locations (void)
2815 {
2816   struct breakpoint *bpt;
2817   struct bp_location *bl, **blp_tmp;
2818   int error_flag = 0;
2819   int val = 0;
2820   int disabled_breaks = 0;
2821   int hw_breakpoint_error = 0;
2822   int hw_bp_error_explained_already = 0;
2823
2824   struct ui_file *tmp_error_stream = mem_fileopen ();
2825   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2826   
2827   /* Explicitly mark the warning -- this will only be printed if
2828      there was an error.  */
2829   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2830
2831   save_current_space_and_thread ();
2832
2833   ALL_BP_LOCATIONS (bl, blp_tmp)
2834     {
2835       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2836         continue;
2837
2838       /* There is no point inserting thread-specific breakpoints if
2839          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2840          has BL->OWNER always non-NULL.  */
2841       if (bl->owner->thread != -1
2842           && !valid_thread_id (bl->owner->thread))
2843         continue;
2844
2845       switch_to_program_space_and_thread (bl->pspace);
2846
2847       /* For targets that support global breakpoints, there's no need
2848          to select an inferior to insert breakpoint to.  In fact, even
2849          if we aren't attached to any process yet, we should still
2850          insert breakpoints.  */
2851       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2852           && ptid_equal (inferior_ptid, null_ptid))
2853         continue;
2854
2855       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2856                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2857       if (val)
2858         error_flag = val;
2859     }
2860
2861   /* If we failed to insert all locations of a watchpoint, remove
2862      them, as half-inserted watchpoint is of limited use.  */
2863   ALL_BREAKPOINTS (bpt)  
2864     {
2865       int some_failed = 0;
2866       struct bp_location *loc;
2867
2868       if (!is_hardware_watchpoint (bpt))
2869         continue;
2870
2871       if (!breakpoint_enabled (bpt))
2872         continue;
2873
2874       if (bpt->disposition == disp_del_at_next_stop)
2875         continue;
2876       
2877       for (loc = bpt->loc; loc; loc = loc->next)
2878         if (!loc->inserted && should_be_inserted (loc))
2879           {
2880             some_failed = 1;
2881             break;
2882           }
2883       if (some_failed)
2884         {
2885           for (loc = bpt->loc; loc; loc = loc->next)
2886             if (loc->inserted)
2887               remove_breakpoint (loc, mark_uninserted);
2888
2889           hw_breakpoint_error = 1;
2890           fprintf_unfiltered (tmp_error_stream,
2891                               "Could not insert hardware watchpoint %d.\n", 
2892                               bpt->number);
2893           error_flag = -1;
2894         }
2895     }
2896
2897   if (error_flag)
2898     {
2899       /* If a hardware breakpoint or watchpoint was inserted, add a
2900          message about possibly exhausted resources.  */
2901       if (hw_breakpoint_error && !hw_bp_error_explained_already)
2902         {
2903           fprintf_unfiltered (tmp_error_stream, 
2904                               "Could not insert hardware breakpoints:\n\
2905 You may have requested too many hardware breakpoints/watchpoints.\n");
2906         }
2907       target_terminal_ours_for_output ();
2908       error_stream (tmp_error_stream);
2909     }
2910
2911   do_cleanups (cleanups);
2912 }
2913
2914 /* Used when the program stops.
2915    Returns zero if successful, or non-zero if there was a problem
2916    removing a breakpoint location.  */
2917
2918 int
2919 remove_breakpoints (void)
2920 {
2921   struct bp_location *bl, **blp_tmp;
2922   int val = 0;
2923
2924   ALL_BP_LOCATIONS (bl, blp_tmp)
2925   {
2926     if (bl->inserted && !is_tracepoint (bl->owner))
2927       val |= remove_breakpoint (bl, mark_uninserted);
2928   }
2929   return val;
2930 }
2931
2932 /* When a thread exits, remove breakpoints that are related to
2933    that thread.  */
2934
2935 static void
2936 remove_threaded_breakpoints (struct thread_info *tp, int silent)
2937 {
2938   struct breakpoint *b, *b_tmp;
2939
2940   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2941     {
2942       if (b->thread == tp->num && user_breakpoint_p (b))
2943         {
2944           b->disposition = disp_del_at_next_stop;
2945
2946           printf_filtered (_("\
2947 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
2948                           b->number, tp->num);
2949
2950           /* Hide it from the user.  */
2951           b->number = 0;
2952        }
2953     }
2954 }
2955
2956 /* Remove breakpoints of process PID.  */
2957
2958 int
2959 remove_breakpoints_pid (int pid)
2960 {
2961   struct bp_location *bl, **blp_tmp;
2962   int val;
2963   struct inferior *inf = find_inferior_pid (pid);
2964
2965   ALL_BP_LOCATIONS (bl, blp_tmp)
2966   {
2967     if (bl->pspace != inf->pspace)
2968       continue;
2969
2970     if (bl->owner->type == bp_dprintf)
2971       continue;
2972
2973     if (bl->inserted)
2974       {
2975         val = remove_breakpoint (bl, mark_uninserted);
2976         if (val != 0)
2977           return val;
2978       }
2979   }
2980   return 0;
2981 }
2982
2983 int
2984 reattach_breakpoints (int pid)
2985 {
2986   struct cleanup *old_chain;
2987   struct bp_location *bl, **blp_tmp;
2988   int val;
2989   struct ui_file *tmp_error_stream;
2990   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
2991   struct inferior *inf;
2992   struct thread_info *tp;
2993
2994   tp = any_live_thread_of_process (pid);
2995   if (tp == NULL)
2996     return 1;
2997
2998   inf = find_inferior_pid (pid);
2999   old_chain = save_inferior_ptid ();
3000
3001   inferior_ptid = tp->ptid;
3002
3003   tmp_error_stream = mem_fileopen ();
3004   make_cleanup_ui_file_delete (tmp_error_stream);
3005
3006   ALL_BP_LOCATIONS (bl, blp_tmp)
3007   {
3008     if (bl->pspace != inf->pspace)
3009       continue;
3010
3011     if (bl->inserted)
3012       {
3013         bl->inserted = 0;
3014         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3015         if (val != 0)
3016           {
3017             do_cleanups (old_chain);
3018             return val;
3019           }
3020       }
3021   }
3022   do_cleanups (old_chain);
3023   return 0;
3024 }
3025
3026 static int internal_breakpoint_number = -1;
3027
3028 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3029    If INTERNAL is non-zero, the breakpoint number will be populated
3030    from internal_breakpoint_number and that variable decremented.
3031    Otherwise the breakpoint number will be populated from
3032    breakpoint_count and that value incremented.  Internal breakpoints
3033    do not set the internal var bpnum.  */
3034 static void
3035 set_breakpoint_number (int internal, struct breakpoint *b)
3036 {
3037   if (internal)
3038     b->number = internal_breakpoint_number--;
3039   else
3040     {
3041       set_breakpoint_count (breakpoint_count + 1);
3042       b->number = breakpoint_count;
3043     }
3044 }
3045
3046 static struct breakpoint *
3047 create_internal_breakpoint (struct gdbarch *gdbarch,
3048                             CORE_ADDR address, enum bptype type,
3049                             const struct breakpoint_ops *ops)
3050 {
3051   struct symtab_and_line sal;
3052   struct breakpoint *b;
3053
3054   init_sal (&sal);              /* Initialize to zeroes.  */
3055
3056   sal.pc = address;
3057   sal.section = find_pc_overlay (sal.pc);
3058   sal.pspace = current_program_space;
3059
3060   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3061   b->number = internal_breakpoint_number--;
3062   b->disposition = disp_donttouch;
3063
3064   return b;
3065 }
3066
3067 static const char *const longjmp_names[] =
3068   {
3069     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3070   };
3071 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3072
3073 /* Per-objfile data private to breakpoint.c.  */
3074 struct breakpoint_objfile_data
3075 {
3076   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3077   struct minimal_symbol *overlay_msym;
3078
3079   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3080   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
3081
3082   /* True if we have looked for longjmp probes.  */
3083   int longjmp_searched;
3084
3085   /* SystemTap probe points for longjmp (if any).  */
3086   VEC (probe_p) *longjmp_probes;
3087
3088   /* Minimal symbol for "std::terminate()" (if any).  */
3089   struct minimal_symbol *terminate_msym;
3090
3091   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3092   struct minimal_symbol *exception_msym;
3093
3094   /* True if we have looked for exception probes.  */
3095   int exception_searched;
3096
3097   /* SystemTap probe points for unwinding (if any).  */
3098   VEC (probe_p) *exception_probes;
3099 };
3100
3101 static const struct objfile_data *breakpoint_objfile_key;
3102
3103 /* Minimal symbol not found sentinel.  */
3104 static struct minimal_symbol msym_not_found;
3105
3106 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3107
3108 static int
3109 msym_not_found_p (const struct minimal_symbol *msym)
3110 {
3111   return msym == &msym_not_found;
3112 }
3113
3114 /* Return per-objfile data needed by breakpoint.c.
3115    Allocate the data if necessary.  */
3116
3117 static struct breakpoint_objfile_data *
3118 get_breakpoint_objfile_data (struct objfile *objfile)
3119 {
3120   struct breakpoint_objfile_data *bp_objfile_data;
3121
3122   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3123   if (bp_objfile_data == NULL)
3124     {
3125       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3126                                        sizeof (*bp_objfile_data));
3127
3128       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3129       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3130     }
3131   return bp_objfile_data;
3132 }
3133
3134 static void
3135 free_breakpoint_probes (struct objfile *obj, void *data)
3136 {
3137   struct breakpoint_objfile_data *bp_objfile_data = data;
3138
3139   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3140   VEC_free (probe_p, bp_objfile_data->exception_probes);
3141 }
3142
3143 static void
3144 create_overlay_event_breakpoint (void)
3145 {
3146   struct objfile *objfile;
3147   const char *const func_name = "_ovly_debug_event";
3148
3149   ALL_OBJFILES (objfile)
3150     {
3151       struct breakpoint *b;
3152       struct breakpoint_objfile_data *bp_objfile_data;
3153       CORE_ADDR addr;
3154
3155       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3156
3157       if (msym_not_found_p (bp_objfile_data->overlay_msym))
3158         continue;
3159
3160       if (bp_objfile_data->overlay_msym == NULL)
3161         {
3162           struct minimal_symbol *m;
3163
3164           m = lookup_minimal_symbol_text (func_name, objfile);
3165           if (m == NULL)
3166             {
3167               /* Avoid future lookups in this objfile.  */
3168               bp_objfile_data->overlay_msym = &msym_not_found;
3169               continue;
3170             }
3171           bp_objfile_data->overlay_msym = m;
3172         }
3173
3174       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3175       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3176                                       bp_overlay_event,
3177                                       &internal_breakpoint_ops);
3178       b->addr_string = xstrdup (func_name);
3179
3180       if (overlay_debugging == ovly_auto)
3181         {
3182           b->enable_state = bp_enabled;
3183           overlay_events_enabled = 1;
3184         }
3185       else
3186        {
3187          b->enable_state = bp_disabled;
3188          overlay_events_enabled = 0;
3189        }
3190     }
3191   update_global_location_list (1);
3192 }
3193
3194 static void
3195 create_longjmp_master_breakpoint (void)
3196 {
3197   struct program_space *pspace;
3198   struct cleanup *old_chain;
3199
3200   old_chain = save_current_program_space ();
3201
3202   ALL_PSPACES (pspace)
3203   {
3204     struct objfile *objfile;
3205
3206     set_current_program_space (pspace);
3207
3208     ALL_OBJFILES (objfile)
3209     {
3210       int i;
3211       struct gdbarch *gdbarch;
3212       struct breakpoint_objfile_data *bp_objfile_data;
3213
3214       gdbarch = get_objfile_arch (objfile);
3215       if (!gdbarch_get_longjmp_target_p (gdbarch))
3216         continue;
3217
3218       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3219
3220       if (!bp_objfile_data->longjmp_searched)
3221         {
3222           VEC (probe_p) *ret;
3223
3224           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3225           if (ret != NULL)
3226             {
3227               /* We are only interested in checking one element.  */
3228               struct probe *p = VEC_index (probe_p, ret, 0);
3229
3230               if (!can_evaluate_probe_arguments (p))
3231                 {
3232                   /* We cannot use the probe interface here, because it does
3233                      not know how to evaluate arguments.  */
3234                   VEC_free (probe_p, ret);
3235                   ret = NULL;
3236                 }
3237             }
3238           bp_objfile_data->longjmp_probes = ret;
3239           bp_objfile_data->longjmp_searched = 1;
3240         }
3241
3242       if (bp_objfile_data->longjmp_probes != NULL)
3243         {
3244           int i;
3245           struct probe *probe;
3246           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3247
3248           for (i = 0;
3249                VEC_iterate (probe_p,
3250                             bp_objfile_data->longjmp_probes,
3251                             i, probe);
3252                ++i)
3253             {
3254               struct breakpoint *b;
3255
3256               b = create_internal_breakpoint (gdbarch, probe->address,
3257                                               bp_longjmp_master,
3258                                               &internal_breakpoint_ops);
3259               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3260               b->enable_state = bp_disabled;
3261             }
3262
3263           continue;
3264         }
3265
3266       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3267         {
3268           struct breakpoint *b;
3269           const char *func_name;
3270           CORE_ADDR addr;
3271
3272           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
3273             continue;
3274
3275           func_name = longjmp_names[i];
3276           if (bp_objfile_data->longjmp_msym[i] == NULL)
3277             {
3278               struct minimal_symbol *m;
3279
3280               m = lookup_minimal_symbol_text (func_name, objfile);
3281               if (m == NULL)
3282                 {
3283                   /* Prevent future lookups in this objfile.  */
3284                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
3285                   continue;
3286                 }
3287               bp_objfile_data->longjmp_msym[i] = m;
3288             }
3289
3290           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3291           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3292                                           &internal_breakpoint_ops);
3293           b->addr_string = xstrdup (func_name);
3294           b->enable_state = bp_disabled;
3295         }
3296     }
3297   }
3298   update_global_location_list (1);
3299
3300   do_cleanups (old_chain);
3301 }
3302
3303 /* Create a master std::terminate breakpoint.  */
3304 static void
3305 create_std_terminate_master_breakpoint (void)
3306 {
3307   struct program_space *pspace;
3308   struct cleanup *old_chain;
3309   const char *const func_name = "std::terminate()";
3310
3311   old_chain = save_current_program_space ();
3312
3313   ALL_PSPACES (pspace)
3314   {
3315     struct objfile *objfile;
3316     CORE_ADDR addr;
3317
3318     set_current_program_space (pspace);
3319
3320     ALL_OBJFILES (objfile)
3321     {
3322       struct breakpoint *b;
3323       struct breakpoint_objfile_data *bp_objfile_data;
3324
3325       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3326
3327       if (msym_not_found_p (bp_objfile_data->terminate_msym))
3328         continue;
3329
3330       if (bp_objfile_data->terminate_msym == NULL)
3331         {
3332           struct minimal_symbol *m;
3333
3334           m = lookup_minimal_symbol (func_name, NULL, objfile);
3335           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
3336                             && MSYMBOL_TYPE (m) != mst_file_text))
3337             {
3338               /* Prevent future lookups in this objfile.  */
3339               bp_objfile_data->terminate_msym = &msym_not_found;
3340               continue;
3341             }
3342           bp_objfile_data->terminate_msym = m;
3343         }
3344
3345       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3346       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3347                                       bp_std_terminate_master,
3348                                       &internal_breakpoint_ops);
3349       b->addr_string = xstrdup (func_name);
3350       b->enable_state = bp_disabled;
3351     }
3352   }
3353
3354   update_global_location_list (1);
3355
3356   do_cleanups (old_chain);
3357 }
3358
3359 /* Install a master breakpoint on the unwinder's debug hook.  */
3360
3361 static void
3362 create_exception_master_breakpoint (void)
3363 {
3364   struct objfile *objfile;
3365   const char *const func_name = "_Unwind_DebugHook";
3366
3367   ALL_OBJFILES (objfile)
3368     {
3369       struct breakpoint *b;
3370       struct gdbarch *gdbarch;
3371       struct breakpoint_objfile_data *bp_objfile_data;
3372       CORE_ADDR addr;
3373
3374       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3375
3376       /* We prefer the SystemTap probe point if it exists.  */
3377       if (!bp_objfile_data->exception_searched)
3378         {
3379           VEC (probe_p) *ret;
3380
3381           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3382
3383           if (ret != NULL)
3384             {
3385               /* We are only interested in checking one element.  */
3386               struct probe *p = VEC_index (probe_p, ret, 0);
3387
3388               if (!can_evaluate_probe_arguments (p))
3389                 {
3390                   /* We cannot use the probe interface here, because it does
3391                      not know how to evaluate arguments.  */
3392                   VEC_free (probe_p, ret);
3393                   ret = NULL;
3394                 }
3395             }
3396           bp_objfile_data->exception_probes = ret;
3397           bp_objfile_data->exception_searched = 1;
3398         }
3399
3400       if (bp_objfile_data->exception_probes != NULL)
3401         {
3402           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3403           int i;
3404           struct probe *probe;
3405
3406           for (i = 0;
3407                VEC_iterate (probe_p,
3408                             bp_objfile_data->exception_probes,
3409                             i, probe);
3410                ++i)
3411             {
3412               struct breakpoint *b;
3413
3414               b = create_internal_breakpoint (gdbarch, probe->address,
3415                                               bp_exception_master,
3416                                               &internal_breakpoint_ops);
3417               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3418               b->enable_state = bp_disabled;
3419             }
3420
3421           continue;
3422         }
3423
3424       /* Otherwise, try the hook function.  */
3425
3426       if (msym_not_found_p (bp_objfile_data->exception_msym))
3427         continue;
3428
3429       gdbarch = get_objfile_arch (objfile);
3430
3431       if (bp_objfile_data->exception_msym == NULL)
3432         {
3433           struct minimal_symbol *debug_hook;
3434
3435           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3436           if (debug_hook == NULL)
3437             {
3438               bp_objfile_data->exception_msym = &msym_not_found;
3439               continue;
3440             }
3441
3442           bp_objfile_data->exception_msym = debug_hook;
3443         }
3444
3445       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3446       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3447                                                  &current_target);
3448       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3449                                       &internal_breakpoint_ops);
3450       b->addr_string = xstrdup (func_name);
3451       b->enable_state = bp_disabled;
3452     }
3453
3454   update_global_location_list (1);
3455 }
3456
3457 void
3458 update_breakpoints_after_exec (void)
3459 {
3460   struct breakpoint *b, *b_tmp;
3461   struct bp_location *bploc, **bplocp_tmp;
3462
3463   /* We're about to delete breakpoints from GDB's lists.  If the
3464      INSERTED flag is true, GDB will try to lift the breakpoints by
3465      writing the breakpoints' "shadow contents" back into memory.  The
3466      "shadow contents" are NOT valid after an exec, so GDB should not
3467      do that.  Instead, the target is responsible from marking
3468      breakpoints out as soon as it detects an exec.  We don't do that
3469      here instead, because there may be other attempts to delete
3470      breakpoints after detecting an exec and before reaching here.  */
3471   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3472     if (bploc->pspace == current_program_space)
3473       gdb_assert (!bploc->inserted);
3474
3475   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3476   {
3477     if (b->pspace != current_program_space)
3478       continue;
3479
3480     /* Solib breakpoints must be explicitly reset after an exec().  */
3481     if (b->type == bp_shlib_event)
3482       {
3483         delete_breakpoint (b);
3484         continue;
3485       }
3486
3487     /* JIT breakpoints must be explicitly reset after an exec().  */
3488     if (b->type == bp_jit_event)
3489       {
3490         delete_breakpoint (b);
3491         continue;
3492       }
3493
3494     /* Thread event breakpoints must be set anew after an exec(),
3495        as must overlay event and longjmp master breakpoints.  */
3496     if (b->type == bp_thread_event || b->type == bp_overlay_event
3497         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3498         || b->type == bp_exception_master)
3499       {
3500         delete_breakpoint (b);
3501         continue;
3502       }
3503
3504     /* Step-resume breakpoints are meaningless after an exec().  */
3505     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3506       {
3507         delete_breakpoint (b);
3508         continue;
3509       }
3510
3511     /* Longjmp and longjmp-resume breakpoints are also meaningless
3512        after an exec.  */
3513     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3514         || b->type == bp_longjmp_call_dummy
3515         || b->type == bp_exception || b->type == bp_exception_resume)
3516       {
3517         delete_breakpoint (b);
3518         continue;
3519       }
3520
3521     if (b->type == bp_catchpoint)
3522       {
3523         /* For now, none of the bp_catchpoint breakpoints need to
3524            do anything at this point.  In the future, if some of
3525            the catchpoints need to something, we will need to add
3526            a new method, and call this method from here.  */
3527         continue;
3528       }
3529
3530     /* bp_finish is a special case.  The only way we ought to be able
3531        to see one of these when an exec() has happened, is if the user
3532        caught a vfork, and then said "finish".  Ordinarily a finish just
3533        carries them to the call-site of the current callee, by setting
3534        a temporary bp there and resuming.  But in this case, the finish
3535        will carry them entirely through the vfork & exec.
3536
3537        We don't want to allow a bp_finish to remain inserted now.  But
3538        we can't safely delete it, 'cause finish_command has a handle to
3539        the bp on a bpstat, and will later want to delete it.  There's a
3540        chance (and I've seen it happen) that if we delete the bp_finish
3541        here, that its storage will get reused by the time finish_command
3542        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3543        We really must allow finish_command to delete a bp_finish.
3544
3545        In the absence of a general solution for the "how do we know
3546        it's safe to delete something others may have handles to?"
3547        problem, what we'll do here is just uninsert the bp_finish, and
3548        let finish_command delete it.
3549
3550        (We know the bp_finish is "doomed" in the sense that it's
3551        momentary, and will be deleted as soon as finish_command sees
3552        the inferior stopped.  So it doesn't matter that the bp's
3553        address is probably bogus in the new a.out, unlike e.g., the
3554        solib breakpoints.)  */
3555
3556     if (b->type == bp_finish)
3557       {
3558         continue;
3559       }
3560
3561     /* Without a symbolic address, we have little hope of the
3562        pre-exec() address meaning the same thing in the post-exec()
3563        a.out.  */
3564     if (b->addr_string == NULL)
3565       {
3566         delete_breakpoint (b);
3567         continue;
3568       }
3569   }
3570   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3571   create_overlay_event_breakpoint ();
3572   create_longjmp_master_breakpoint ();
3573   create_std_terminate_master_breakpoint ();
3574   create_exception_master_breakpoint ();
3575 }
3576
3577 int
3578 detach_breakpoints (ptid_t ptid)
3579 {
3580   struct bp_location *bl, **blp_tmp;
3581   int val = 0;
3582   struct cleanup *old_chain = save_inferior_ptid ();
3583   struct inferior *inf = current_inferior ();
3584
3585   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3586     error (_("Cannot detach breakpoints of inferior_ptid"));
3587
3588   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3589   inferior_ptid = ptid;
3590   ALL_BP_LOCATIONS (bl, blp_tmp)
3591   {
3592     if (bl->pspace != inf->pspace)
3593       continue;
3594
3595     /* This function must physically remove breakpoints locations
3596        from the specified ptid, without modifying the breakpoint
3597        package's state.  Locations of type bp_loc_other are only
3598        maintained at GDB side.  So, there is no need to remove
3599        these bp_loc_other locations.  Moreover, removing these
3600        would modify the breakpoint package's state.  */
3601     if (bl->loc_type == bp_loc_other)
3602       continue;
3603
3604     if (bl->inserted)
3605       val |= remove_breakpoint_1 (bl, mark_inserted);
3606   }
3607
3608   /* Detach single-step breakpoints as well.  */
3609   detach_single_step_breakpoints ();
3610
3611   do_cleanups (old_chain);
3612   return val;
3613 }
3614
3615 /* Remove the breakpoint location BL from the current address space.
3616    Note that this is used to detach breakpoints from a child fork.
3617    When we get here, the child isn't in the inferior list, and neither
3618    do we have objects to represent its address space --- we should
3619    *not* look at bl->pspace->aspace here.  */
3620
3621 static int
3622 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3623 {
3624   int val;
3625
3626   /* BL is never in moribund_locations by our callers.  */
3627   gdb_assert (bl->owner != NULL);
3628
3629   if (bl->owner->enable_state == bp_permanent)
3630     /* Permanent breakpoints cannot be inserted or removed.  */
3631     return 0;
3632
3633   /* The type of none suggests that owner is actually deleted.
3634      This should not ever happen.  */
3635   gdb_assert (bl->owner->type != bp_none);
3636
3637   if (bl->loc_type == bp_loc_software_breakpoint
3638       || bl->loc_type == bp_loc_hardware_breakpoint)
3639     {
3640       /* "Normal" instruction breakpoint: either the standard
3641          trap-instruction bp (bp_breakpoint), or a
3642          bp_hardware_breakpoint.  */
3643
3644       /* First check to see if we have to handle an overlay.  */
3645       if (overlay_debugging == ovly_off
3646           || bl->section == NULL
3647           || !(section_is_overlay (bl->section)))
3648         {
3649           /* No overlay handling: just remove the breakpoint.  */
3650           val = bl->owner->ops->remove_location (bl);
3651         }
3652       else
3653         {
3654           /* This breakpoint is in an overlay section.
3655              Did we set a breakpoint at the LMA?  */
3656           if (!overlay_events_enabled)
3657               {
3658                 /* Yes -- overlay event support is not active, so we
3659                    should have set a breakpoint at the LMA.  Remove it.  
3660                 */
3661                 /* Ignore any failures: if the LMA is in ROM, we will
3662                    have already warned when we failed to insert it.  */
3663                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3664                   target_remove_hw_breakpoint (bl->gdbarch,
3665                                                &bl->overlay_target_info);
3666                 else
3667                   target_remove_breakpoint (bl->gdbarch,
3668                                             &bl->overlay_target_info);
3669               }
3670           /* Did we set a breakpoint at the VMA? 
3671              If so, we will have marked the breakpoint 'inserted'.  */
3672           if (bl->inserted)
3673             {
3674               /* Yes -- remove it.  Previously we did not bother to
3675                  remove the breakpoint if the section had been
3676                  unmapped, but let's not rely on that being safe.  We
3677                  don't know what the overlay manager might do.  */
3678
3679               /* However, we should remove *software* breakpoints only
3680                  if the section is still mapped, or else we overwrite
3681                  wrong code with the saved shadow contents.  */
3682               if (bl->loc_type == bp_loc_hardware_breakpoint
3683                   || section_is_mapped (bl->section))
3684                 val = bl->owner->ops->remove_location (bl);
3685               else
3686                 val = 0;
3687             }
3688           else
3689             {
3690               /* No -- not inserted, so no need to remove.  No error.  */
3691               val = 0;
3692             }
3693         }
3694
3695       /* In some cases, we might not be able to remove a breakpoint
3696          in a shared library that has already been removed, but we
3697          have not yet processed the shlib unload event.  */
3698       if (val && solib_name_from_address (bl->pspace, bl->address))
3699         val = 0;
3700
3701       if (val)
3702         return val;
3703       bl->inserted = (is == mark_inserted);
3704     }
3705   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3706     {
3707       gdb_assert (bl->owner->ops != NULL
3708                   && bl->owner->ops->remove_location != NULL);
3709
3710       bl->inserted = (is == mark_inserted);
3711       bl->owner->ops->remove_location (bl);
3712
3713       /* Failure to remove any of the hardware watchpoints comes here.  */
3714       if ((is == mark_uninserted) && (bl->inserted))
3715         warning (_("Could not remove hardware watchpoint %d."),
3716                  bl->owner->number);
3717     }
3718   else if (bl->owner->type == bp_catchpoint
3719            && breakpoint_enabled (bl->owner)
3720            && !bl->duplicate)
3721     {
3722       gdb_assert (bl->owner->ops != NULL
3723                   && bl->owner->ops->remove_location != NULL);
3724
3725       val = bl->owner->ops->remove_location (bl);
3726       if (val)
3727         return val;
3728
3729       bl->inserted = (is == mark_inserted);
3730     }
3731
3732   return 0;
3733 }
3734
3735 static int
3736 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3737 {
3738   int ret;
3739   struct cleanup *old_chain;
3740
3741   /* BL is never in moribund_locations by our callers.  */
3742   gdb_assert (bl->owner != NULL);
3743
3744   if (bl->owner->enable_state == bp_permanent)
3745     /* Permanent breakpoints cannot be inserted or removed.  */
3746     return 0;
3747
3748   /* The type of none suggests that owner is actually deleted.
3749      This should not ever happen.  */
3750   gdb_assert (bl->owner->type != bp_none);
3751
3752   old_chain = save_current_space_and_thread ();
3753
3754   switch_to_program_space_and_thread (bl->pspace);
3755
3756   ret = remove_breakpoint_1 (bl, is);
3757
3758   do_cleanups (old_chain);
3759   return ret;
3760 }
3761
3762 /* Clear the "inserted" flag in all breakpoints.  */
3763
3764 void
3765 mark_breakpoints_out (void)
3766 {
3767   struct bp_location *bl, **blp_tmp;
3768
3769   ALL_BP_LOCATIONS (bl, blp_tmp)
3770     if (bl->pspace == current_program_space)
3771       bl->inserted = 0;
3772 }
3773
3774 /* Clear the "inserted" flag in all breakpoints and delete any
3775    breakpoints which should go away between runs of the program.
3776
3777    Plus other such housekeeping that has to be done for breakpoints
3778    between runs.
3779
3780    Note: this function gets called at the end of a run (by
3781    generic_mourn_inferior) and when a run begins (by
3782    init_wait_for_inferior).  */
3783
3784
3785
3786 void
3787 breakpoint_init_inferior (enum inf_context context)
3788 {
3789   struct breakpoint *b, *b_tmp;
3790   struct bp_location *bl, **blp_tmp;
3791   int ix;
3792   struct program_space *pspace = current_program_space;
3793
3794   /* If breakpoint locations are shared across processes, then there's
3795      nothing to do.  */
3796   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3797     return;
3798
3799   ALL_BP_LOCATIONS (bl, blp_tmp)
3800   {
3801     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3802     if (bl->pspace == pspace
3803         && bl->owner->enable_state != bp_permanent)
3804       bl->inserted = 0;
3805   }
3806
3807   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3808   {
3809     if (b->loc && b->loc->pspace != pspace)
3810       continue;
3811
3812     switch (b->type)
3813       {
3814       case bp_call_dummy:
3815       case bp_longjmp_call_dummy:
3816
3817         /* If the call dummy breakpoint is at the entry point it will
3818            cause problems when the inferior is rerun, so we better get
3819            rid of it.  */
3820
3821       case bp_watchpoint_scope:
3822
3823         /* Also get rid of scope breakpoints.  */
3824
3825       case bp_shlib_event:
3826
3827         /* Also remove solib event breakpoints.  Their addresses may
3828            have changed since the last time we ran the program.
3829            Actually we may now be debugging against different target;
3830            and so the solib backend that installed this breakpoint may
3831            not be used in by the target.  E.g.,
3832
3833            (gdb) file prog-linux
3834            (gdb) run               # native linux target
3835            ...
3836            (gdb) kill
3837            (gdb) file prog-win.exe
3838            (gdb) tar rem :9999     # remote Windows gdbserver.
3839         */
3840
3841       case bp_step_resume:
3842
3843         /* Also remove step-resume breakpoints.  */
3844
3845         delete_breakpoint (b);
3846         break;
3847
3848       case bp_watchpoint:
3849       case bp_hardware_watchpoint:
3850       case bp_read_watchpoint:
3851       case bp_access_watchpoint:
3852         {
3853           struct watchpoint *w = (struct watchpoint *) b;
3854
3855           /* Likewise for watchpoints on local expressions.  */
3856           if (w->exp_valid_block != NULL)
3857             delete_breakpoint (b);
3858           else if (context == inf_starting)
3859             {
3860               /* Reset val field to force reread of starting value in
3861                  insert_breakpoints.  */
3862               if (w->val)
3863                 value_free (w->val);
3864               w->val = NULL;
3865               w->val_valid = 0;
3866           }
3867         }
3868         break;
3869       default:
3870         break;
3871       }
3872   }
3873
3874   /* Get rid of the moribund locations.  */
3875   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3876     decref_bp_location (&bl);
3877   VEC_free (bp_location_p, moribund_locations);
3878 }
3879
3880 /* These functions concern about actual breakpoints inserted in the
3881    target --- to e.g. check if we need to do decr_pc adjustment or if
3882    we need to hop over the bkpt --- so we check for address space
3883    match, not program space.  */
3884
3885 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3886    exists at PC.  It returns ordinary_breakpoint_here if it's an
3887    ordinary breakpoint, or permanent_breakpoint_here if it's a
3888    permanent breakpoint.
3889    - When continuing from a location with an ordinary breakpoint, we
3890      actually single step once before calling insert_breakpoints.
3891    - When continuing from a location with a permanent breakpoint, we
3892      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3893      the target, to advance the PC past the breakpoint.  */
3894
3895 enum breakpoint_here
3896 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3897 {
3898   struct bp_location *bl, **blp_tmp;
3899   int any_breakpoint_here = 0;
3900
3901   ALL_BP_LOCATIONS (bl, blp_tmp)
3902     {
3903       if (bl->loc_type != bp_loc_software_breakpoint
3904           && bl->loc_type != bp_loc_hardware_breakpoint)
3905         continue;
3906
3907       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3908       if ((breakpoint_enabled (bl->owner)
3909            || bl->owner->enable_state == bp_permanent)
3910           && breakpoint_location_address_match (bl, aspace, pc))
3911         {
3912           if (overlay_debugging 
3913               && section_is_overlay (bl->section)
3914               && !section_is_mapped (bl->section))
3915             continue;           /* unmapped overlay -- can't be a match */
3916           else if (bl->owner->enable_state == bp_permanent)
3917             return permanent_breakpoint_here;
3918           else
3919             any_breakpoint_here = 1;
3920         }
3921     }
3922
3923   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3924 }
3925
3926 /* Return true if there's a moribund breakpoint at PC.  */
3927
3928 int
3929 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3930 {
3931   struct bp_location *loc;
3932   int ix;
3933
3934   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3935     if (breakpoint_location_address_match (loc, aspace, pc))
3936       return 1;
3937
3938   return 0;
3939 }
3940
3941 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3942    inserted using regular breakpoint_chain / bp_location array
3943    mechanism.  This does not check for single-step breakpoints, which
3944    are inserted and removed using direct target manipulation.  */
3945
3946 int
3947 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3948                                     CORE_ADDR pc)
3949 {
3950   struct bp_location *bl, **blp_tmp;
3951
3952   ALL_BP_LOCATIONS (bl, blp_tmp)
3953     {
3954       if (bl->loc_type != bp_loc_software_breakpoint
3955           && bl->loc_type != bp_loc_hardware_breakpoint)
3956         continue;
3957
3958       if (bl->inserted
3959           && breakpoint_location_address_match (bl, aspace, pc))
3960         {
3961           if (overlay_debugging 
3962               && section_is_overlay (bl->section)
3963               && !section_is_mapped (bl->section))
3964             continue;           /* unmapped overlay -- can't be a match */
3965           else
3966             return 1;
3967         }
3968     }
3969   return 0;
3970 }
3971
3972 /* Returns non-zero iff there's either regular breakpoint
3973    or a single step breakpoint inserted at PC.  */
3974
3975 int
3976 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3977 {
3978   if (regular_breakpoint_inserted_here_p (aspace, pc))
3979     return 1;
3980
3981   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3982     return 1;
3983
3984   return 0;
3985 }
3986
3987 /* This function returns non-zero iff there is a software breakpoint
3988    inserted at PC.  */
3989
3990 int
3991 software_breakpoint_inserted_here_p (struct address_space *aspace,
3992                                      CORE_ADDR pc)
3993 {
3994   struct bp_location *bl, **blp_tmp;
3995
3996   ALL_BP_LOCATIONS (bl, blp_tmp)
3997     {
3998       if (bl->loc_type != bp_loc_software_breakpoint)
3999         continue;
4000
4001       if (bl->inserted
4002           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4003                                        aspace, pc))
4004         {
4005           if (overlay_debugging 
4006               && section_is_overlay (bl->section)
4007               && !section_is_mapped (bl->section))
4008             continue;           /* unmapped overlay -- can't be a match */
4009           else
4010             return 1;
4011         }
4012     }
4013
4014   /* Also check for software single-step breakpoints.  */
4015   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4016     return 1;
4017
4018   return 0;
4019 }
4020
4021 int
4022 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4023                                        CORE_ADDR addr, ULONGEST len)
4024 {
4025   struct breakpoint *bpt;
4026
4027   ALL_BREAKPOINTS (bpt)
4028     {
4029       struct bp_location *loc;
4030
4031       if (bpt->type != bp_hardware_watchpoint
4032           && bpt->type != bp_access_watchpoint)
4033         continue;
4034
4035       if (!breakpoint_enabled (bpt))
4036         continue;
4037
4038       for (loc = bpt->loc; loc; loc = loc->next)
4039         if (loc->pspace->aspace == aspace && loc->inserted)
4040           {
4041             CORE_ADDR l, h;
4042
4043             /* Check for intersection.  */
4044             l = max (loc->address, addr);
4045             h = min (loc->address + loc->length, addr + len);
4046             if (l < h)
4047               return 1;
4048           }
4049     }
4050   return 0;
4051 }
4052
4053 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4054    PC is valid for process/thread PTID.  */
4055
4056 int
4057 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4058                          ptid_t ptid)
4059 {
4060   struct bp_location *bl, **blp_tmp;
4061   /* The thread and task IDs associated to PTID, computed lazily.  */
4062   int thread = -1;
4063   int task = 0;
4064   
4065   ALL_BP_LOCATIONS (bl, blp_tmp)
4066     {
4067       if (bl->loc_type != bp_loc_software_breakpoint
4068           && bl->loc_type != bp_loc_hardware_breakpoint)
4069         continue;
4070
4071       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4072       if (!breakpoint_enabled (bl->owner)
4073           && bl->owner->enable_state != bp_permanent)
4074         continue;
4075
4076       if (!breakpoint_location_address_match (bl, aspace, pc))
4077         continue;
4078
4079       if (bl->owner->thread != -1)
4080         {
4081           /* This is a thread-specific breakpoint.  Check that ptid
4082              matches that thread.  If thread hasn't been computed yet,
4083              it is now time to do so.  */
4084           if (thread == -1)
4085             thread = pid_to_thread_id (ptid);
4086           if (bl->owner->thread != thread)
4087             continue;
4088         }
4089
4090       if (bl->owner->task != 0)
4091         {
4092           /* This is a task-specific breakpoint.  Check that ptid
4093              matches that task.  If task hasn't been computed yet,
4094              it is now time to do so.  */
4095           if (task == 0)
4096             task = ada_get_task_number (ptid);
4097           if (bl->owner->task != task)
4098             continue;
4099         }
4100
4101       if (overlay_debugging 
4102           && section_is_overlay (bl->section)
4103           && !section_is_mapped (bl->section))
4104         continue;           /* unmapped overlay -- can't be a match */
4105
4106       return 1;
4107     }
4108
4109   return 0;
4110 }
4111 \f
4112
4113 /* bpstat stuff.  External routines' interfaces are documented
4114    in breakpoint.h.  */
4115
4116 int
4117 is_catchpoint (struct breakpoint *ep)
4118 {
4119   return (ep->type == bp_catchpoint);
4120 }
4121
4122 /* Frees any storage that is part of a bpstat.  Does not walk the
4123    'next' chain.  */
4124
4125 static void
4126 bpstat_free (bpstat bs)
4127 {
4128   if (bs->old_val != NULL)
4129     value_free (bs->old_val);
4130   decref_counted_command_line (&bs->commands);
4131   decref_bp_location (&bs->bp_location_at);
4132   xfree (bs);
4133 }
4134
4135 /* Clear a bpstat so that it says we are not at any breakpoint.
4136    Also free any storage that is part of a bpstat.  */
4137
4138 void
4139 bpstat_clear (bpstat *bsp)
4140 {
4141   bpstat p;
4142   bpstat q;
4143
4144   if (bsp == 0)
4145     return;
4146   p = *bsp;
4147   while (p != NULL)
4148     {
4149       q = p->next;
4150       bpstat_free (p);
4151       p = q;
4152     }
4153   *bsp = NULL;
4154 }
4155
4156 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4157    is part of the bpstat is copied as well.  */
4158
4159 bpstat
4160 bpstat_copy (bpstat bs)
4161 {
4162   bpstat p = NULL;
4163   bpstat tmp;
4164   bpstat retval = NULL;
4165
4166   if (bs == NULL)
4167     return bs;
4168
4169   for (; bs != NULL; bs = bs->next)
4170     {
4171       tmp = (bpstat) xmalloc (sizeof (*tmp));
4172       memcpy (tmp, bs, sizeof (*tmp));
4173       incref_counted_command_line (tmp->commands);
4174       incref_bp_location (tmp->bp_location_at);
4175       if (bs->old_val != NULL)
4176         {
4177           tmp->old_val = value_copy (bs->old_val);
4178           release_value (tmp->old_val);
4179         }
4180
4181       if (p == NULL)
4182         /* This is the first thing in the chain.  */
4183         retval = tmp;
4184       else
4185         p->next = tmp;
4186       p = tmp;
4187     }
4188   p->next = NULL;
4189   return retval;
4190 }
4191
4192 /* Find the bpstat associated with this breakpoint.  */
4193
4194 bpstat
4195 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4196 {
4197   if (bsp == NULL)
4198     return NULL;
4199
4200   for (; bsp != NULL; bsp = bsp->next)
4201     {
4202       if (bsp->breakpoint_at == breakpoint)
4203         return bsp;
4204     }
4205   return NULL;
4206 }
4207
4208 /* See breakpoint.h.  */
4209
4210 enum bpstat_signal_value
4211 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4212 {
4213   enum bpstat_signal_value result = BPSTAT_SIGNAL_NO;
4214
4215   for (; bsp != NULL; bsp = bsp->next)
4216     {
4217       /* Ensure that, if we ever entered this loop, then we at least
4218          return BPSTAT_SIGNAL_HIDE.  */
4219       enum bpstat_signal_value newval;
4220
4221       if (bsp->breakpoint_at == NULL)
4222         {
4223           /* A moribund location can never explain a signal other than
4224              GDB_SIGNAL_TRAP.  */
4225           if (sig == GDB_SIGNAL_TRAP)
4226             newval = BPSTAT_SIGNAL_HIDE;
4227           else
4228             newval = BPSTAT_SIGNAL_NO;
4229         }
4230       else
4231         newval = bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4232                                                            sig);
4233
4234       if (newval > result)
4235         result = newval;
4236     }
4237
4238   return result;
4239 }
4240
4241 /* Put in *NUM the breakpoint number of the first breakpoint we are
4242    stopped at.  *BSP upon return is a bpstat which points to the
4243    remaining breakpoints stopped at (but which is not guaranteed to be
4244    good for anything but further calls to bpstat_num).
4245
4246    Return 0 if passed a bpstat which does not indicate any breakpoints.
4247    Return -1 if stopped at a breakpoint that has been deleted since
4248    we set it.
4249    Return 1 otherwise.  */
4250
4251 int
4252 bpstat_num (bpstat *bsp, int *num)
4253 {
4254   struct breakpoint *b;
4255
4256   if ((*bsp) == NULL)
4257     return 0;                   /* No more breakpoint values */
4258
4259   /* We assume we'll never have several bpstats that correspond to a
4260      single breakpoint -- otherwise, this function might return the
4261      same number more than once and this will look ugly.  */
4262   b = (*bsp)->breakpoint_at;
4263   *bsp = (*bsp)->next;
4264   if (b == NULL)
4265     return -1;                  /* breakpoint that's been deleted since */
4266
4267   *num = b->number;             /* We have its number */
4268   return 1;
4269 }
4270
4271 /* See breakpoint.h.  */
4272
4273 void
4274 bpstat_clear_actions (void)
4275 {
4276   struct thread_info *tp;
4277   bpstat bs;
4278
4279   if (ptid_equal (inferior_ptid, null_ptid))
4280     return;
4281
4282   tp = find_thread_ptid (inferior_ptid);
4283   if (tp == NULL)
4284     return;
4285
4286   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4287     {
4288       decref_counted_command_line (&bs->commands);
4289
4290       if (bs->old_val != NULL)
4291         {
4292           value_free (bs->old_val);
4293           bs->old_val = NULL;
4294         }
4295     }
4296 }
4297
4298 /* Called when a command is about to proceed the inferior.  */
4299
4300 static void
4301 breakpoint_about_to_proceed (void)
4302 {
4303   if (!ptid_equal (inferior_ptid, null_ptid))
4304     {
4305       struct thread_info *tp = inferior_thread ();
4306
4307       /* Allow inferior function calls in breakpoint commands to not
4308          interrupt the command list.  When the call finishes
4309          successfully, the inferior will be standing at the same
4310          breakpoint as if nothing happened.  */
4311       if (tp->control.in_infcall)
4312         return;
4313     }
4314
4315   breakpoint_proceeded = 1;
4316 }
4317
4318 /* Stub for cleaning up our state if we error-out of a breakpoint
4319    command.  */
4320 static void
4321 cleanup_executing_breakpoints (void *ignore)
4322 {
4323   executing_breakpoint_commands = 0;
4324 }
4325
4326 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4327    or its equivalent.  */
4328
4329 static int
4330 command_line_is_silent (struct command_line *cmd)
4331 {
4332   return cmd && (strcmp ("silent", cmd->line) == 0
4333                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4334 }
4335
4336 /* Execute all the commands associated with all the breakpoints at
4337    this location.  Any of these commands could cause the process to
4338    proceed beyond this point, etc.  We look out for such changes by
4339    checking the global "breakpoint_proceeded" after each command.
4340
4341    Returns true if a breakpoint command resumed the inferior.  In that
4342    case, it is the caller's responsibility to recall it again with the
4343    bpstat of the current thread.  */
4344
4345 static int
4346 bpstat_do_actions_1 (bpstat *bsp)
4347 {
4348   bpstat bs;
4349   struct cleanup *old_chain;
4350   int again = 0;
4351
4352   /* Avoid endless recursion if a `source' command is contained
4353      in bs->commands.  */
4354   if (executing_breakpoint_commands)
4355     return 0;
4356
4357   executing_breakpoint_commands = 1;
4358   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4359
4360   prevent_dont_repeat ();
4361
4362   /* This pointer will iterate over the list of bpstat's.  */
4363   bs = *bsp;
4364
4365   breakpoint_proceeded = 0;
4366   for (; bs != NULL; bs = bs->next)
4367     {
4368       struct counted_command_line *ccmd;
4369       struct command_line *cmd;
4370       struct cleanup *this_cmd_tree_chain;
4371
4372       /* Take ownership of the BSP's command tree, if it has one.
4373
4374          The command tree could legitimately contain commands like
4375          'step' and 'next', which call clear_proceed_status, which
4376          frees stop_bpstat's command tree.  To make sure this doesn't
4377          free the tree we're executing out from under us, we need to
4378          take ownership of the tree ourselves.  Since a given bpstat's
4379          commands are only executed once, we don't need to copy it; we
4380          can clear the pointer in the bpstat, and make sure we free
4381          the tree when we're done.  */
4382       ccmd = bs->commands;
4383       bs->commands = NULL;
4384       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4385       cmd = ccmd ? ccmd->commands : NULL;
4386       if (command_line_is_silent (cmd))
4387         {
4388           /* The action has been already done by bpstat_stop_status.  */
4389           cmd = cmd->next;
4390         }
4391
4392       while (cmd != NULL)
4393         {
4394           execute_control_command (cmd);
4395
4396           if (breakpoint_proceeded)
4397             break;
4398           else
4399             cmd = cmd->next;
4400         }
4401
4402       /* We can free this command tree now.  */
4403       do_cleanups (this_cmd_tree_chain);
4404
4405       if (breakpoint_proceeded)
4406         {
4407           if (target_can_async_p ())
4408             /* If we are in async mode, then the target might be still
4409                running, not stopped at any breakpoint, so nothing for
4410                us to do here -- just return to the event loop.  */
4411             ;
4412           else
4413             /* In sync mode, when execute_control_command returns
4414                we're already standing on the next breakpoint.
4415                Breakpoint commands for that stop were not run, since
4416                execute_command does not run breakpoint commands --
4417                only command_line_handler does, but that one is not
4418                involved in execution of breakpoint commands.  So, we
4419                can now execute breakpoint commands.  It should be
4420                noted that making execute_command do bpstat actions is
4421                not an option -- in this case we'll have recursive
4422                invocation of bpstat for each breakpoint with a
4423                command, and can easily blow up GDB stack.  Instead, we
4424                return true, which will trigger the caller to recall us
4425                with the new stop_bpstat.  */
4426             again = 1;
4427           break;
4428         }
4429     }
4430   do_cleanups (old_chain);
4431   return again;
4432 }
4433
4434 void
4435 bpstat_do_actions (void)
4436 {
4437   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4438
4439   /* Do any commands attached to breakpoint we are stopped at.  */
4440   while (!ptid_equal (inferior_ptid, null_ptid)
4441          && target_has_execution
4442          && !is_exited (inferior_ptid)
4443          && !is_executing (inferior_ptid))
4444     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4445        and only return when it is stopped at the next breakpoint, we
4446        keep doing breakpoint actions until it returns false to
4447        indicate the inferior was not resumed.  */
4448     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4449       break;
4450
4451   discard_cleanups (cleanup_if_error);
4452 }
4453
4454 /* Print out the (old or new) value associated with a watchpoint.  */
4455
4456 static void
4457 watchpoint_value_print (struct value *val, struct ui_file *stream)
4458 {
4459   if (val == NULL)
4460     fprintf_unfiltered (stream, _("<unreadable>"));
4461   else
4462     {
4463       struct value_print_options opts;
4464       get_user_print_options (&opts);
4465       value_print (val, stream, &opts);
4466     }
4467 }
4468
4469 /* Generic routine for printing messages indicating why we
4470    stopped.  The behavior of this function depends on the value
4471    'print_it' in the bpstat structure.  Under some circumstances we
4472    may decide not to print anything here and delegate the task to
4473    normal_stop().  */
4474
4475 static enum print_stop_action
4476 print_bp_stop_message (bpstat bs)
4477 {
4478   switch (bs->print_it)
4479     {
4480     case print_it_noop:
4481       /* Nothing should be printed for this bpstat entry.  */
4482       return PRINT_UNKNOWN;
4483       break;
4484
4485     case print_it_done:
4486       /* We still want to print the frame, but we already printed the
4487          relevant messages.  */
4488       return PRINT_SRC_AND_LOC;
4489       break;
4490
4491     case print_it_normal:
4492       {
4493         struct breakpoint *b = bs->breakpoint_at;
4494
4495         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4496            which has since been deleted.  */
4497         if (b == NULL)
4498           return PRINT_UNKNOWN;
4499
4500         /* Normal case.  Call the breakpoint's print_it method.  */
4501         return b->ops->print_it (bs);
4502       }
4503       break;
4504
4505     default:
4506       internal_error (__FILE__, __LINE__,
4507                       _("print_bp_stop_message: unrecognized enum value"));
4508       break;
4509     }
4510 }
4511
4512 /* A helper function that prints a shared library stopped event.  */
4513
4514 static void
4515 print_solib_event (int is_catchpoint)
4516 {
4517   int any_deleted
4518     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4519   int any_added
4520     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4521
4522   if (!is_catchpoint)
4523     {
4524       if (any_added || any_deleted)
4525         ui_out_text (current_uiout,
4526                      _("Stopped due to shared library event:\n"));
4527       else
4528         ui_out_text (current_uiout,
4529                      _("Stopped due to shared library event (no "
4530                        "libraries added or removed)\n"));
4531     }
4532
4533   if (ui_out_is_mi_like_p (current_uiout))
4534     ui_out_field_string (current_uiout, "reason",
4535                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4536
4537   if (any_deleted)
4538     {
4539       struct cleanup *cleanup;
4540       char *name;
4541       int ix;
4542
4543       ui_out_text (current_uiout, _("  Inferior unloaded "));
4544       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4545                                                     "removed");
4546       for (ix = 0;
4547            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4548                         ix, name);
4549            ++ix)
4550         {
4551           if (ix > 0)
4552             ui_out_text (current_uiout, "    ");
4553           ui_out_field_string (current_uiout, "library", name);
4554           ui_out_text (current_uiout, "\n");
4555         }
4556
4557       do_cleanups (cleanup);
4558     }
4559
4560   if (any_added)
4561     {
4562       struct so_list *iter;
4563       int ix;
4564       struct cleanup *cleanup;
4565
4566       ui_out_text (current_uiout, _("  Inferior loaded "));
4567       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4568                                                     "added");
4569       for (ix = 0;
4570            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4571                         ix, iter);
4572            ++ix)
4573         {
4574           if (ix > 0)
4575             ui_out_text (current_uiout, "    ");
4576           ui_out_field_string (current_uiout, "library", iter->so_name);
4577           ui_out_text (current_uiout, "\n");
4578         }
4579
4580       do_cleanups (cleanup);
4581     }
4582 }
4583
4584 /* Print a message indicating what happened.  This is called from
4585    normal_stop().  The input to this routine is the head of the bpstat
4586    list - a list of the eventpoints that caused this stop.  KIND is
4587    the target_waitkind for the stopping event.  This
4588    routine calls the generic print routine for printing a message
4589    about reasons for stopping.  This will print (for example) the
4590    "Breakpoint n," part of the output.  The return value of this
4591    routine is one of:
4592
4593    PRINT_UNKNOWN: Means we printed nothing.
4594    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4595    code to print the location.  An example is 
4596    "Breakpoint 1, " which should be followed by
4597    the location.
4598    PRINT_SRC_ONLY: Means we printed something, but there is no need
4599    to also print the location part of the message.
4600    An example is the catch/throw messages, which
4601    don't require a location appended to the end.
4602    PRINT_NOTHING: We have done some printing and we don't need any 
4603    further info to be printed.  */
4604
4605 enum print_stop_action
4606 bpstat_print (bpstat bs, int kind)
4607 {
4608   int val;
4609
4610   /* Maybe another breakpoint in the chain caused us to stop.
4611      (Currently all watchpoints go on the bpstat whether hit or not.
4612      That probably could (should) be changed, provided care is taken
4613      with respect to bpstat_explains_signal).  */
4614   for (; bs; bs = bs->next)
4615     {
4616       val = print_bp_stop_message (bs);
4617       if (val == PRINT_SRC_ONLY 
4618           || val == PRINT_SRC_AND_LOC 
4619           || val == PRINT_NOTHING)
4620         return val;
4621     }
4622
4623   /* If we had hit a shared library event breakpoint,
4624      print_bp_stop_message would print out this message.  If we hit an
4625      OS-level shared library event, do the same thing.  */
4626   if (kind == TARGET_WAITKIND_LOADED)
4627     {
4628       print_solib_event (0);
4629       return PRINT_NOTHING;
4630     }
4631
4632   /* We reached the end of the chain, or we got a null BS to start
4633      with and nothing was printed.  */
4634   return PRINT_UNKNOWN;
4635 }
4636
4637 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4638    used inside a catch_errors to evaluate the breakpoint condition.
4639    The argument is a "struct expression *" that has been cast to a
4640    "char *" to make it pass through catch_errors.  */
4641
4642 static int
4643 breakpoint_cond_eval (void *exp)
4644 {
4645   struct value *mark = value_mark ();
4646   int i = !value_true (evaluate_expression ((struct expression *) exp));
4647
4648   value_free_to_mark (mark);
4649   return i;
4650 }
4651
4652 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4653
4654 static bpstat
4655 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4656 {
4657   bpstat bs;
4658
4659   bs = (bpstat) xmalloc (sizeof (*bs));
4660   bs->next = NULL;
4661   **bs_link_pointer = bs;
4662   *bs_link_pointer = &bs->next;
4663   bs->breakpoint_at = bl->owner;
4664   bs->bp_location_at = bl;
4665   incref_bp_location (bl);
4666   /* If the condition is false, etc., don't do the commands.  */
4667   bs->commands = NULL;
4668   bs->old_val = NULL;
4669   bs->print_it = print_it_normal;
4670   return bs;
4671 }
4672 \f
4673 /* The target has stopped with waitstatus WS.  Check if any hardware
4674    watchpoints have triggered, according to the target.  */
4675
4676 int
4677 watchpoints_triggered (struct target_waitstatus *ws)
4678 {
4679   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4680   CORE_ADDR addr;
4681   struct breakpoint *b;
4682
4683   if (!stopped_by_watchpoint)
4684     {
4685       /* We were not stopped by a watchpoint.  Mark all watchpoints
4686          as not triggered.  */
4687       ALL_BREAKPOINTS (b)
4688         if (is_hardware_watchpoint (b))
4689           {
4690             struct watchpoint *w = (struct watchpoint *) b;
4691
4692             w->watchpoint_triggered = watch_triggered_no;
4693           }
4694
4695       return 0;
4696     }
4697
4698   if (!target_stopped_data_address (&current_target, &addr))
4699     {
4700       /* We were stopped by a watchpoint, but we don't know where.
4701          Mark all watchpoints as unknown.  */
4702       ALL_BREAKPOINTS (b)
4703         if (is_hardware_watchpoint (b))
4704           {
4705             struct watchpoint *w = (struct watchpoint *) b;
4706
4707             w->watchpoint_triggered = watch_triggered_unknown;
4708           }
4709
4710       return stopped_by_watchpoint;
4711     }
4712
4713   /* The target could report the data address.  Mark watchpoints
4714      affected by this data address as triggered, and all others as not
4715      triggered.  */
4716
4717   ALL_BREAKPOINTS (b)
4718     if (is_hardware_watchpoint (b))
4719       {
4720         struct watchpoint *w = (struct watchpoint *) b;
4721         struct bp_location *loc;
4722
4723         w->watchpoint_triggered = watch_triggered_no;
4724         for (loc = b->loc; loc; loc = loc->next)
4725           {
4726             if (is_masked_watchpoint (b))
4727               {
4728                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4729                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4730
4731                 if (newaddr == start)
4732                   {
4733                     w->watchpoint_triggered = watch_triggered_yes;
4734                     break;
4735                   }
4736               }
4737             /* Exact match not required.  Within range is sufficient.  */
4738             else if (target_watchpoint_addr_within_range (&current_target,
4739                                                          addr, loc->address,
4740                                                          loc->length))
4741               {
4742                 w->watchpoint_triggered = watch_triggered_yes;
4743                 break;
4744               }
4745           }
4746       }
4747
4748   return 1;
4749 }
4750
4751 /* Possible return values for watchpoint_check (this can't be an enum
4752    because of check_errors).  */
4753 /* The watchpoint has been deleted.  */
4754 #define WP_DELETED 1
4755 /* The value has changed.  */
4756 #define WP_VALUE_CHANGED 2
4757 /* The value has not changed.  */
4758 #define WP_VALUE_NOT_CHANGED 3
4759 /* Ignore this watchpoint, no matter if the value changed or not.  */
4760 #define WP_IGNORE 4
4761
4762 #define BP_TEMPFLAG 1
4763 #define BP_HARDWAREFLAG 2
4764
4765 /* Evaluate watchpoint condition expression and check if its value
4766    changed.
4767
4768    P should be a pointer to struct bpstat, but is defined as a void *
4769    in order for this function to be usable with catch_errors.  */
4770
4771 static int
4772 watchpoint_check (void *p)
4773 {
4774   bpstat bs = (bpstat) p;
4775   struct watchpoint *b;
4776   struct frame_info *fr;
4777   int within_current_scope;
4778
4779   /* BS is built from an existing struct breakpoint.  */
4780   gdb_assert (bs->breakpoint_at != NULL);
4781   b = (struct watchpoint *) bs->breakpoint_at;
4782
4783   /* If this is a local watchpoint, we only want to check if the
4784      watchpoint frame is in scope if the current thread is the thread
4785      that was used to create the watchpoint.  */
4786   if (!watchpoint_in_thread_scope (b))
4787     return WP_IGNORE;
4788
4789   if (b->exp_valid_block == NULL)
4790     within_current_scope = 1;
4791   else
4792     {
4793       struct frame_info *frame = get_current_frame ();
4794       struct gdbarch *frame_arch = get_frame_arch (frame);
4795       CORE_ADDR frame_pc = get_frame_pc (frame);
4796
4797       /* in_function_epilogue_p() returns a non-zero value if we're
4798          still in the function but the stack frame has already been
4799          invalidated.  Since we can't rely on the values of local
4800          variables after the stack has been destroyed, we are treating
4801          the watchpoint in that state as `not changed' without further
4802          checking.  Don't mark watchpoints as changed if the current
4803          frame is in an epilogue - even if they are in some other
4804          frame, our view of the stack is likely to be wrong and
4805          frame_find_by_id could error out.  */
4806       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4807         return WP_IGNORE;
4808
4809       fr = frame_find_by_id (b->watchpoint_frame);
4810       within_current_scope = (fr != NULL);
4811
4812       /* If we've gotten confused in the unwinder, we might have
4813          returned a frame that can't describe this variable.  */
4814       if (within_current_scope)
4815         {
4816           struct symbol *function;
4817
4818           function = get_frame_function (fr);
4819           if (function == NULL
4820               || !contained_in (b->exp_valid_block,
4821                                 SYMBOL_BLOCK_VALUE (function)))
4822             within_current_scope = 0;
4823         }
4824
4825       if (within_current_scope)
4826         /* If we end up stopping, the current frame will get selected
4827            in normal_stop.  So this call to select_frame won't affect
4828            the user.  */
4829         select_frame (fr);
4830     }
4831
4832   if (within_current_scope)
4833     {
4834       /* We use value_{,free_to_}mark because it could be a *long*
4835          time before we return to the command level and call
4836          free_all_values.  We can't call free_all_values because we
4837          might be in the middle of evaluating a function call.  */
4838
4839       int pc = 0;
4840       struct value *mark;
4841       struct value *new_val;
4842
4843       if (is_masked_watchpoint (&b->base))
4844         /* Since we don't know the exact trigger address (from
4845            stopped_data_address), just tell the user we've triggered
4846            a mask watchpoint.  */
4847         return WP_VALUE_CHANGED;
4848
4849       mark = value_mark ();
4850       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
4851
4852       /* We use value_equal_contents instead of value_equal because
4853          the latter coerces an array to a pointer, thus comparing just
4854          the address of the array instead of its contents.  This is
4855          not what we want.  */
4856       if ((b->val != NULL) != (new_val != NULL)
4857           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4858         {
4859           if (new_val != NULL)
4860             {
4861               release_value (new_val);
4862               value_free_to_mark (mark);
4863             }
4864           bs->old_val = b->val;
4865           b->val = new_val;
4866           b->val_valid = 1;
4867           return WP_VALUE_CHANGED;
4868         }
4869       else
4870         {
4871           /* Nothing changed.  */
4872           value_free_to_mark (mark);
4873           return WP_VALUE_NOT_CHANGED;
4874         }
4875     }
4876   else
4877     {
4878       struct ui_out *uiout = current_uiout;
4879
4880       /* This seems like the only logical thing to do because
4881          if we temporarily ignored the watchpoint, then when
4882          we reenter the block in which it is valid it contains
4883          garbage (in the case of a function, it may have two
4884          garbage values, one before and one after the prologue).
4885          So we can't even detect the first assignment to it and
4886          watch after that (since the garbage may or may not equal
4887          the first value assigned).  */
4888       /* We print all the stop information in
4889          breakpoint_ops->print_it, but in this case, by the time we
4890          call breakpoint_ops->print_it this bp will be deleted
4891          already.  So we have no choice but print the information
4892          here.  */
4893       if (ui_out_is_mi_like_p (uiout))
4894         ui_out_field_string
4895           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4896       ui_out_text (uiout, "\nWatchpoint ");
4897       ui_out_field_int (uiout, "wpnum", b->base.number);
4898       ui_out_text (uiout,
4899                    " deleted because the program has left the block in\n\
4900 which its expression is valid.\n");     
4901
4902       /* Make sure the watchpoint's commands aren't executed.  */
4903       decref_counted_command_line (&b->base.commands);
4904       watchpoint_del_at_next_stop (b);
4905
4906       return WP_DELETED;
4907     }
4908 }
4909
4910 /* Return true if it looks like target has stopped due to hitting
4911    breakpoint location BL.  This function does not check if we should
4912    stop, only if BL explains the stop.  */
4913
4914 static int
4915 bpstat_check_location (const struct bp_location *bl,
4916                        struct address_space *aspace, CORE_ADDR bp_addr,
4917                        const struct target_waitstatus *ws)
4918 {
4919   struct breakpoint *b = bl->owner;
4920
4921   /* BL is from an existing breakpoint.  */
4922   gdb_assert (b != NULL);
4923
4924   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4925 }
4926
4927 /* Determine if the watched values have actually changed, and we
4928    should stop.  If not, set BS->stop to 0.  */
4929
4930 static void
4931 bpstat_check_watchpoint (bpstat bs)
4932 {
4933   const struct bp_location *bl;
4934   struct watchpoint *b;
4935
4936   /* BS is built for existing struct breakpoint.  */
4937   bl = bs->bp_location_at;
4938   gdb_assert (bl != NULL);
4939   b = (struct watchpoint *) bs->breakpoint_at;
4940   gdb_assert (b != NULL);
4941
4942     {
4943       int must_check_value = 0;
4944       
4945       if (b->base.type == bp_watchpoint)
4946         /* For a software watchpoint, we must always check the
4947            watched value.  */
4948         must_check_value = 1;
4949       else if (b->watchpoint_triggered == watch_triggered_yes)
4950         /* We have a hardware watchpoint (read, write, or access)
4951            and the target earlier reported an address watched by
4952            this watchpoint.  */
4953         must_check_value = 1;
4954       else if (b->watchpoint_triggered == watch_triggered_unknown
4955                && b->base.type == bp_hardware_watchpoint)
4956         /* We were stopped by a hardware watchpoint, but the target could
4957            not report the data address.  We must check the watchpoint's
4958            value.  Access and read watchpoints are out of luck; without
4959            a data address, we can't figure it out.  */
4960         must_check_value = 1;
4961
4962       if (must_check_value)
4963         {
4964           char *message
4965             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4966                           b->base.number);
4967           struct cleanup *cleanups = make_cleanup (xfree, message);
4968           int e = catch_errors (watchpoint_check, bs, message,
4969                                 RETURN_MASK_ALL);
4970           do_cleanups (cleanups);
4971           switch (e)
4972             {
4973             case WP_DELETED:
4974               /* We've already printed what needs to be printed.  */
4975               bs->print_it = print_it_done;
4976               /* Stop.  */
4977               break;
4978             case WP_IGNORE:
4979               bs->print_it = print_it_noop;
4980               bs->stop = 0;
4981               break;
4982             case WP_VALUE_CHANGED:
4983               if (b->base.type == bp_read_watchpoint)
4984                 {
4985                   /* There are two cases to consider here:
4986
4987                      1. We're watching the triggered memory for reads.
4988                      In that case, trust the target, and always report
4989                      the watchpoint hit to the user.  Even though
4990                      reads don't cause value changes, the value may
4991                      have changed since the last time it was read, and
4992                      since we're not trapping writes, we will not see
4993                      those, and as such we should ignore our notion of
4994                      old value.
4995
4996                      2. We're watching the triggered memory for both
4997                      reads and writes.  There are two ways this may
4998                      happen:
4999
5000                      2.1. This is a target that can't break on data
5001                      reads only, but can break on accesses (reads or
5002                      writes), such as e.g., x86.  We detect this case
5003                      at the time we try to insert read watchpoints.
5004
5005                      2.2. Otherwise, the target supports read
5006                      watchpoints, but, the user set an access or write
5007                      watchpoint watching the same memory as this read
5008                      watchpoint.
5009
5010                      If we're watching memory writes as well as reads,
5011                      ignore watchpoint hits when we find that the
5012                      value hasn't changed, as reads don't cause
5013                      changes.  This still gives false positives when
5014                      the program writes the same value to memory as
5015                      what there was already in memory (we will confuse
5016                      it for a read), but it's much better than
5017                      nothing.  */
5018
5019                   int other_write_watchpoint = 0;
5020
5021                   if (bl->watchpoint_type == hw_read)
5022                     {
5023                       struct breakpoint *other_b;
5024
5025                       ALL_BREAKPOINTS (other_b)
5026                         if (other_b->type == bp_hardware_watchpoint
5027                             || other_b->type == bp_access_watchpoint)
5028                           {
5029                             struct watchpoint *other_w =
5030                               (struct watchpoint *) other_b;
5031
5032                             if (other_w->watchpoint_triggered
5033                                 == watch_triggered_yes)
5034                               {
5035                                 other_write_watchpoint = 1;
5036                                 break;
5037                               }
5038                           }
5039                     }
5040
5041                   if (other_write_watchpoint
5042                       || bl->watchpoint_type == hw_access)
5043                     {
5044                       /* We're watching the same memory for writes,
5045                          and the value changed since the last time we
5046                          updated it, so this trap must be for a write.
5047                          Ignore it.  */
5048                       bs->print_it = print_it_noop;
5049                       bs->stop = 0;
5050                     }
5051                 }
5052               break;
5053             case WP_VALUE_NOT_CHANGED:
5054               if (b->base.type == bp_hardware_watchpoint
5055                   || b->base.type == bp_watchpoint)
5056                 {
5057                   /* Don't stop: write watchpoints shouldn't fire if
5058                      the value hasn't changed.  */
5059                   bs->print_it = print_it_noop;
5060                   bs->stop = 0;
5061                 }
5062               /* Stop.  */
5063               break;
5064             default:
5065               /* Can't happen.  */
5066             case 0:
5067               /* Error from catch_errors.  */
5068               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5069               watchpoint_del_at_next_stop (b);
5070               /* We've already printed what needs to be printed.  */
5071               bs->print_it = print_it_done;
5072               break;
5073             }
5074         }
5075       else      /* must_check_value == 0 */
5076         {
5077           /* This is a case where some watchpoint(s) triggered, but
5078              not at the address of this watchpoint, or else no
5079              watchpoint triggered after all.  So don't print
5080              anything for this watchpoint.  */
5081           bs->print_it = print_it_noop;
5082           bs->stop = 0;
5083         }
5084     }
5085 }
5086
5087
5088 /* Check conditions (condition proper, frame, thread and ignore count)
5089    of breakpoint referred to by BS.  If we should not stop for this
5090    breakpoint, set BS->stop to 0.  */
5091
5092 static void
5093 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5094 {
5095   int thread_id = pid_to_thread_id (ptid);
5096   const struct bp_location *bl;
5097   struct breakpoint *b;
5098
5099   /* BS is built for existing struct breakpoint.  */
5100   bl = bs->bp_location_at;
5101   gdb_assert (bl != NULL);
5102   b = bs->breakpoint_at;
5103   gdb_assert (b != NULL);
5104
5105   /* Even if the target evaluated the condition on its end and notified GDB, we
5106      need to do so again since GDB does not know if we stopped due to a
5107      breakpoint or a single step breakpoint.  */
5108
5109   if (frame_id_p (b->frame_id)
5110       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5111     bs->stop = 0;
5112   else if (bs->stop)
5113     {
5114       int value_is_zero = 0;
5115       struct expression *cond;
5116
5117       /* Evaluate Python breakpoints that have a "stop"
5118          method implemented.  */
5119       if (b->py_bp_object)
5120         bs->stop = gdbpy_should_stop (b->py_bp_object);
5121
5122       if (is_watchpoint (b))
5123         {
5124           struct watchpoint *w = (struct watchpoint *) b;
5125
5126           cond = w->cond_exp;
5127         }
5128       else
5129         cond = bl->cond;
5130
5131       if (cond && b->disposition != disp_del_at_next_stop)
5132         {
5133           int within_current_scope = 1;
5134           struct watchpoint * w;
5135
5136           /* We use value_mark and value_free_to_mark because it could
5137              be a long time before we return to the command level and
5138              call free_all_values.  We can't call free_all_values
5139              because we might be in the middle of evaluating a
5140              function call.  */
5141           struct value *mark = value_mark ();
5142
5143           if (is_watchpoint (b))
5144             w = (struct watchpoint *) b;
5145           else
5146             w = NULL;
5147
5148           /* Need to select the frame, with all that implies so that
5149              the conditions will have the right context.  Because we
5150              use the frame, we will not see an inlined function's
5151              variables when we arrive at a breakpoint at the start
5152              of the inlined function; the current frame will be the
5153              call site.  */
5154           if (w == NULL || w->cond_exp_valid_block == NULL)
5155             select_frame (get_current_frame ());
5156           else
5157             {
5158               struct frame_info *frame;
5159
5160               /* For local watchpoint expressions, which particular
5161                  instance of a local is being watched matters, so we
5162                  keep track of the frame to evaluate the expression
5163                  in.  To evaluate the condition however, it doesn't
5164                  really matter which instantiation of the function
5165                  where the condition makes sense triggers the
5166                  watchpoint.  This allows an expression like "watch
5167                  global if q > 10" set in `func', catch writes to
5168                  global on all threads that call `func', or catch
5169                  writes on all recursive calls of `func' by a single
5170                  thread.  We simply always evaluate the condition in
5171                  the innermost frame that's executing where it makes
5172                  sense to evaluate the condition.  It seems
5173                  intuitive.  */
5174               frame = block_innermost_frame (w->cond_exp_valid_block);
5175               if (frame != NULL)
5176                 select_frame (frame);
5177               else
5178                 within_current_scope = 0;
5179             }
5180           if (within_current_scope)
5181             value_is_zero
5182               = catch_errors (breakpoint_cond_eval, cond,
5183                               "Error in testing breakpoint condition:\n",
5184                               RETURN_MASK_ALL);
5185           else
5186             {
5187               warning (_("Watchpoint condition cannot be tested "
5188                          "in the current scope"));
5189               /* If we failed to set the right context for this
5190                  watchpoint, unconditionally report it.  */
5191               value_is_zero = 0;
5192             }
5193           /* FIXME-someday, should give breakpoint #.  */
5194           value_free_to_mark (mark);
5195         }
5196
5197       if (cond && value_is_zero)
5198         {
5199           bs->stop = 0;
5200         }
5201       else if (b->thread != -1 && b->thread != thread_id)
5202         {
5203           bs->stop = 0;
5204         }
5205       else if (b->ignore_count > 0)
5206         {
5207           b->ignore_count--;
5208           bs->stop = 0;
5209           /* Increase the hit count even though we don't stop.  */
5210           ++(b->hit_count);
5211           observer_notify_breakpoint_modified (b);
5212         }       
5213     }
5214 }
5215
5216
5217 /* Get a bpstat associated with having just stopped at address
5218    BP_ADDR in thread PTID.
5219
5220    Determine whether we stopped at a breakpoint, etc, or whether we
5221    don't understand this stop.  Result is a chain of bpstat's such
5222    that:
5223
5224    if we don't understand the stop, the result is a null pointer.
5225
5226    if we understand why we stopped, the result is not null.
5227
5228    Each element of the chain refers to a particular breakpoint or
5229    watchpoint at which we have stopped.  (We may have stopped for
5230    several reasons concurrently.)
5231
5232    Each element of the chain has valid next, breakpoint_at,
5233    commands, FIXME??? fields.  */
5234
5235 bpstat
5236 bpstat_stop_status (struct address_space *aspace,
5237                     CORE_ADDR bp_addr, ptid_t ptid,
5238                     const struct target_waitstatus *ws)
5239 {
5240   struct breakpoint *b = NULL;
5241   struct bp_location *bl;
5242   struct bp_location *loc;
5243   /* First item of allocated bpstat's.  */
5244   bpstat bs_head = NULL, *bs_link = &bs_head;
5245   /* Pointer to the last thing in the chain currently.  */
5246   bpstat bs;
5247   int ix;
5248   int need_remove_insert;
5249   int removed_any;
5250
5251   /* First, build the bpstat chain with locations that explain a
5252      target stop, while being careful to not set the target running,
5253      as that may invalidate locations (in particular watchpoint
5254      locations are recreated).  Resuming will happen here with
5255      breakpoint conditions or watchpoint expressions that include
5256      inferior function calls.  */
5257
5258   ALL_BREAKPOINTS (b)
5259     {
5260       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5261         continue;
5262
5263       for (bl = b->loc; bl != NULL; bl = bl->next)
5264         {
5265           /* For hardware watchpoints, we look only at the first
5266              location.  The watchpoint_check function will work on the
5267              entire expression, not the individual locations.  For
5268              read watchpoints, the watchpoints_triggered function has
5269              checked all locations already.  */
5270           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5271             break;
5272
5273           if (!bl->enabled || bl->shlib_disabled)
5274             continue;
5275
5276           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5277             continue;
5278
5279           /* Come here if it's a watchpoint, or if the break address
5280              matches.  */
5281
5282           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5283                                                    explain stop.  */
5284
5285           /* Assume we stop.  Should we find a watchpoint that is not
5286              actually triggered, or if the condition of the breakpoint
5287              evaluates as false, we'll reset 'stop' to 0.  */
5288           bs->stop = 1;
5289           bs->print = 1;
5290
5291           /* If this is a scope breakpoint, mark the associated
5292              watchpoint as triggered so that we will handle the
5293              out-of-scope event.  We'll get to the watchpoint next
5294              iteration.  */
5295           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5296             {
5297               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5298
5299               w->watchpoint_triggered = watch_triggered_yes;
5300             }
5301         }
5302     }
5303
5304   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5305     {
5306       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5307         {
5308           bs = bpstat_alloc (loc, &bs_link);
5309           /* For hits of moribund locations, we should just proceed.  */
5310           bs->stop = 0;
5311           bs->print = 0;
5312           bs->print_it = print_it_noop;
5313         }
5314     }
5315
5316   /* A bit of special processing for shlib breakpoints.  We need to
5317      process solib loading here, so that the lists of loaded and
5318      unloaded libraries are correct before we handle "catch load" and
5319      "catch unload".  */
5320   for (bs = bs_head; bs != NULL; bs = bs->next)
5321     {
5322       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5323         {
5324           handle_solib_event ();
5325           break;
5326         }
5327     }
5328
5329   /* Now go through the locations that caused the target to stop, and
5330      check whether we're interested in reporting this stop to higher
5331      layers, or whether we should resume the target transparently.  */
5332
5333   removed_any = 0;
5334
5335   for (bs = bs_head; bs != NULL; bs = bs->next)
5336     {
5337       if (!bs->stop)
5338         continue;
5339
5340       b = bs->breakpoint_at;
5341       b->ops->check_status (bs);
5342       if (bs->stop)
5343         {
5344           bpstat_check_breakpoint_conditions (bs, ptid);
5345
5346           if (bs->stop)
5347             {
5348               ++(b->hit_count);
5349               observer_notify_breakpoint_modified (b);
5350
5351               /* We will stop here.  */
5352               if (b->disposition == disp_disable)
5353                 {
5354                   --(b->enable_count);
5355                   if (b->enable_count <= 0
5356                       && b->enable_state != bp_permanent)
5357                     b->enable_state = bp_disabled;
5358                   removed_any = 1;
5359                 }
5360               if (b->silent)
5361                 bs->print = 0;
5362               bs->commands = b->commands;
5363               incref_counted_command_line (bs->commands);
5364               if (command_line_is_silent (bs->commands
5365                                           ? bs->commands->commands : NULL))
5366                 bs->print = 0;
5367
5368               b->ops->after_condition_true (bs);
5369             }
5370
5371         }
5372
5373       /* Print nothing for this entry if we don't stop or don't
5374          print.  */
5375       if (!bs->stop || !bs->print)
5376         bs->print_it = print_it_noop;
5377     }
5378
5379   /* If we aren't stopping, the value of some hardware watchpoint may
5380      not have changed, but the intermediate memory locations we are
5381      watching may have.  Don't bother if we're stopping; this will get
5382      done later.  */
5383   need_remove_insert = 0;
5384   if (! bpstat_causes_stop (bs_head))
5385     for (bs = bs_head; bs != NULL; bs = bs->next)
5386       if (!bs->stop
5387           && bs->breakpoint_at
5388           && is_hardware_watchpoint (bs->breakpoint_at))
5389         {
5390           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5391
5392           update_watchpoint (w, 0 /* don't reparse.  */);
5393           need_remove_insert = 1;
5394         }
5395
5396   if (need_remove_insert)
5397     update_global_location_list (1);
5398   else if (removed_any)
5399     update_global_location_list (0);
5400
5401   return bs_head;
5402 }
5403
5404 static void
5405 handle_jit_event (void)
5406 {
5407   struct frame_info *frame;
5408   struct gdbarch *gdbarch;
5409
5410   /* Switch terminal for any messages produced by
5411      breakpoint_re_set.  */
5412   target_terminal_ours_for_output ();
5413
5414   frame = get_current_frame ();
5415   gdbarch = get_frame_arch (frame);
5416
5417   jit_event_handler (gdbarch);
5418
5419   target_terminal_inferior ();
5420 }
5421
5422 /* Prepare WHAT final decision for infrun.  */
5423
5424 /* Decide what infrun needs to do with this bpstat.  */
5425
5426 struct bpstat_what
5427 bpstat_what (bpstat bs_head)
5428 {
5429   struct bpstat_what retval;
5430   int jit_event = 0;
5431   bpstat bs;
5432
5433   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5434   retval.call_dummy = STOP_NONE;
5435   retval.is_longjmp = 0;
5436
5437   for (bs = bs_head; bs != NULL; bs = bs->next)
5438     {
5439       /* Extract this BS's action.  After processing each BS, we check
5440          if its action overrides all we've seem so far.  */
5441       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5442       enum bptype bptype;
5443
5444       if (bs->breakpoint_at == NULL)
5445         {
5446           /* I suspect this can happen if it was a momentary
5447              breakpoint which has since been deleted.  */
5448           bptype = bp_none;
5449         }
5450       else
5451         bptype = bs->breakpoint_at->type;
5452
5453       switch (bptype)
5454         {
5455         case bp_none:
5456           break;
5457         case bp_breakpoint:
5458         case bp_hardware_breakpoint:
5459         case bp_until:
5460         case bp_finish:
5461         case bp_shlib_event:
5462           if (bs->stop)
5463             {
5464               if (bs->print)
5465                 this_action = BPSTAT_WHAT_STOP_NOISY;
5466               else
5467                 this_action = BPSTAT_WHAT_STOP_SILENT;
5468             }
5469           else
5470             this_action = BPSTAT_WHAT_SINGLE;
5471           break;
5472         case bp_watchpoint:
5473         case bp_hardware_watchpoint:
5474         case bp_read_watchpoint:
5475         case bp_access_watchpoint:
5476           if (bs->stop)
5477             {
5478               if (bs->print)
5479                 this_action = BPSTAT_WHAT_STOP_NOISY;
5480               else
5481                 this_action = BPSTAT_WHAT_STOP_SILENT;
5482             }
5483           else
5484             {
5485               /* There was a watchpoint, but we're not stopping.
5486                  This requires no further action.  */
5487             }
5488           break;
5489         case bp_longjmp:
5490         case bp_longjmp_call_dummy:
5491         case bp_exception:
5492           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5493           retval.is_longjmp = bptype != bp_exception;
5494           break;
5495         case bp_longjmp_resume:
5496         case bp_exception_resume:
5497           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5498           retval.is_longjmp = bptype == bp_longjmp_resume;
5499           break;
5500         case bp_step_resume:
5501           if (bs->stop)
5502             this_action = BPSTAT_WHAT_STEP_RESUME;
5503           else
5504             {
5505               /* It is for the wrong frame.  */
5506               this_action = BPSTAT_WHAT_SINGLE;
5507             }
5508           break;
5509         case bp_hp_step_resume:
5510           if (bs->stop)
5511             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5512           else
5513             {
5514               /* It is for the wrong frame.  */
5515               this_action = BPSTAT_WHAT_SINGLE;
5516             }
5517           break;
5518         case bp_watchpoint_scope:
5519         case bp_thread_event:
5520         case bp_overlay_event:
5521         case bp_longjmp_master:
5522         case bp_std_terminate_master:
5523         case bp_exception_master:
5524           this_action = BPSTAT_WHAT_SINGLE;
5525           break;
5526         case bp_catchpoint:
5527           if (bs->stop)
5528             {
5529               if (bs->print)
5530                 this_action = BPSTAT_WHAT_STOP_NOISY;
5531               else
5532                 this_action = BPSTAT_WHAT_STOP_SILENT;
5533             }
5534           else
5535             {
5536               /* There was a catchpoint, but we're not stopping.
5537                  This requires no further action.  */
5538             }
5539           break;
5540         case bp_jit_event:
5541           jit_event = 1;
5542           this_action = BPSTAT_WHAT_SINGLE;
5543           break;
5544         case bp_call_dummy:
5545           /* Make sure the action is stop (silent or noisy),
5546              so infrun.c pops the dummy frame.  */
5547           retval.call_dummy = STOP_STACK_DUMMY;
5548           this_action = BPSTAT_WHAT_STOP_SILENT;
5549           break;
5550         case bp_std_terminate:
5551           /* Make sure the action is stop (silent or noisy),
5552              so infrun.c pops the dummy frame.  */
5553           retval.call_dummy = STOP_STD_TERMINATE;
5554           this_action = BPSTAT_WHAT_STOP_SILENT;
5555           break;
5556         case bp_tracepoint:
5557         case bp_fast_tracepoint:
5558         case bp_static_tracepoint:
5559           /* Tracepoint hits should not be reported back to GDB, and
5560              if one got through somehow, it should have been filtered
5561              out already.  */
5562           internal_error (__FILE__, __LINE__,
5563                           _("bpstat_what: tracepoint encountered"));
5564           break;
5565         case bp_gnu_ifunc_resolver:
5566           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5567           this_action = BPSTAT_WHAT_SINGLE;
5568           break;
5569         case bp_gnu_ifunc_resolver_return:
5570           /* The breakpoint will be removed, execution will restart from the
5571              PC of the former breakpoint.  */
5572           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5573           break;
5574
5575         case bp_dprintf:
5576           if (bs->stop)
5577             this_action = BPSTAT_WHAT_STOP_SILENT;
5578           else
5579             this_action = BPSTAT_WHAT_SINGLE;
5580           break;
5581
5582         default:
5583           internal_error (__FILE__, __LINE__,
5584                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5585         }
5586
5587       retval.main_action = max (retval.main_action, this_action);
5588     }
5589
5590   /* These operations may affect the bs->breakpoint_at state so they are
5591      delayed after MAIN_ACTION is decided above.  */
5592
5593   if (jit_event)
5594     {
5595       if (debug_infrun)
5596         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5597
5598       handle_jit_event ();
5599     }
5600
5601   for (bs = bs_head; bs != NULL; bs = bs->next)
5602     {
5603       struct breakpoint *b = bs->breakpoint_at;
5604
5605       if (b == NULL)
5606         continue;
5607       switch (b->type)
5608         {
5609         case bp_gnu_ifunc_resolver:
5610           gnu_ifunc_resolver_stop (b);
5611           break;
5612         case bp_gnu_ifunc_resolver_return:
5613           gnu_ifunc_resolver_return_stop (b);
5614           break;
5615         }
5616     }
5617
5618   return retval;
5619 }
5620
5621 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5622    without hardware support).  This isn't related to a specific bpstat,
5623    just to things like whether watchpoints are set.  */
5624
5625 int
5626 bpstat_should_step (void)
5627 {
5628   struct breakpoint *b;
5629
5630   ALL_BREAKPOINTS (b)
5631     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5632       return 1;
5633   return 0;
5634 }
5635
5636 int
5637 bpstat_causes_stop (bpstat bs)
5638 {
5639   for (; bs != NULL; bs = bs->next)
5640     if (bs->stop)
5641       return 1;
5642
5643   return 0;
5644 }
5645
5646 \f
5647
5648 /* Compute a string of spaces suitable to indent the next line
5649    so it starts at the position corresponding to the table column
5650    named COL_NAME in the currently active table of UIOUT.  */
5651
5652 static char *
5653 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5654 {
5655   static char wrap_indent[80];
5656   int i, total_width, width, align;
5657   char *text;
5658
5659   total_width = 0;
5660   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5661     {
5662       if (strcmp (text, col_name) == 0)
5663         {
5664           gdb_assert (total_width < sizeof wrap_indent);
5665           memset (wrap_indent, ' ', total_width);
5666           wrap_indent[total_width] = 0;
5667
5668           return wrap_indent;
5669         }
5670
5671       total_width += width + 1;
5672     }
5673
5674   return NULL;
5675 }
5676
5677 /* Determine if the locations of this breakpoint will have their conditions
5678    evaluated by the target, host or a mix of both.  Returns the following:
5679
5680     "host": Host evals condition.
5681     "host or target": Host or Target evals condition.
5682     "target": Target evals condition.
5683 */
5684
5685 static const char *
5686 bp_condition_evaluator (struct breakpoint *b)
5687 {
5688   struct bp_location *bl;
5689   char host_evals = 0;
5690   char target_evals = 0;
5691
5692   if (!b)
5693     return NULL;
5694
5695   if (!is_breakpoint (b))
5696     return NULL;
5697
5698   if (gdb_evaluates_breakpoint_condition_p ()
5699       || !target_supports_evaluation_of_breakpoint_conditions ())
5700     return condition_evaluation_host;
5701
5702   for (bl = b->loc; bl; bl = bl->next)
5703     {
5704       if (bl->cond_bytecode)
5705         target_evals++;
5706       else
5707         host_evals++;
5708     }
5709
5710   if (host_evals && target_evals)
5711     return condition_evaluation_both;
5712   else if (target_evals)
5713     return condition_evaluation_target;
5714   else
5715     return condition_evaluation_host;
5716 }
5717
5718 /* Determine the breakpoint location's condition evaluator.  This is
5719    similar to bp_condition_evaluator, but for locations.  */
5720
5721 static const char *
5722 bp_location_condition_evaluator (struct bp_location *bl)
5723 {
5724   if (bl && !is_breakpoint (bl->owner))
5725     return NULL;
5726
5727   if (gdb_evaluates_breakpoint_condition_p ()
5728       || !target_supports_evaluation_of_breakpoint_conditions ())
5729     return condition_evaluation_host;
5730
5731   if (bl && bl->cond_bytecode)
5732     return condition_evaluation_target;
5733   else
5734     return condition_evaluation_host;
5735 }
5736
5737 /* Print the LOC location out of the list of B->LOC locations.  */
5738
5739 static void
5740 print_breakpoint_location (struct breakpoint *b,
5741                            struct bp_location *loc)
5742 {
5743   struct ui_out *uiout = current_uiout;
5744   struct cleanup *old_chain = save_current_program_space ();
5745
5746   if (loc != NULL && loc->shlib_disabled)
5747     loc = NULL;
5748
5749   if (loc != NULL)
5750     set_current_program_space (loc->pspace);
5751
5752   if (b->display_canonical)
5753     ui_out_field_string (uiout, "what", b->addr_string);
5754   else if (loc && loc->symtab)
5755     {
5756       struct symbol *sym 
5757         = find_pc_sect_function (loc->address, loc->section);
5758       if (sym)
5759         {
5760           ui_out_text (uiout, "in ");
5761           ui_out_field_string (uiout, "func",
5762                                SYMBOL_PRINT_NAME (sym));
5763           ui_out_text (uiout, " ");
5764           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5765           ui_out_text (uiout, "at ");
5766         }
5767       ui_out_field_string (uiout, "file",
5768                            symtab_to_filename_for_display (loc->symtab));
5769       ui_out_text (uiout, ":");
5770
5771       if (ui_out_is_mi_like_p (uiout))
5772         ui_out_field_string (uiout, "fullname",
5773                              symtab_to_fullname (loc->symtab));
5774       
5775       ui_out_field_int (uiout, "line", loc->line_number);
5776     }
5777   else if (loc)
5778     {
5779       struct ui_file *stb = mem_fileopen ();
5780       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5781
5782       print_address_symbolic (loc->gdbarch, loc->address, stb,
5783                               demangle, "");
5784       ui_out_field_stream (uiout, "at", stb);
5785
5786       do_cleanups (stb_chain);
5787     }
5788   else
5789     ui_out_field_string (uiout, "pending", b->addr_string);
5790
5791   if (loc && is_breakpoint (b)
5792       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5793       && bp_condition_evaluator (b) == condition_evaluation_both)
5794     {
5795       ui_out_text (uiout, " (");
5796       ui_out_field_string (uiout, "evaluated-by",
5797                            bp_location_condition_evaluator (loc));
5798       ui_out_text (uiout, ")");
5799     }
5800
5801   do_cleanups (old_chain);
5802 }
5803
5804 static const char *
5805 bptype_string (enum bptype type)
5806 {
5807   struct ep_type_description
5808     {
5809       enum bptype type;
5810       char *description;
5811     };
5812   static struct ep_type_description bptypes[] =
5813   {
5814     {bp_none, "?deleted?"},
5815     {bp_breakpoint, "breakpoint"},
5816     {bp_hardware_breakpoint, "hw breakpoint"},
5817     {bp_until, "until"},
5818     {bp_finish, "finish"},
5819     {bp_watchpoint, "watchpoint"},
5820     {bp_hardware_watchpoint, "hw watchpoint"},
5821     {bp_read_watchpoint, "read watchpoint"},
5822     {bp_access_watchpoint, "acc watchpoint"},
5823     {bp_longjmp, "longjmp"},
5824     {bp_longjmp_resume, "longjmp resume"},
5825     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5826     {bp_exception, "exception"},
5827     {bp_exception_resume, "exception resume"},
5828     {bp_step_resume, "step resume"},
5829     {bp_hp_step_resume, "high-priority step resume"},
5830     {bp_watchpoint_scope, "watchpoint scope"},
5831     {bp_call_dummy, "call dummy"},
5832     {bp_std_terminate, "std::terminate"},
5833     {bp_shlib_event, "shlib events"},
5834     {bp_thread_event, "thread events"},
5835     {bp_overlay_event, "overlay events"},
5836     {bp_longjmp_master, "longjmp master"},
5837     {bp_std_terminate_master, "std::terminate master"},
5838     {bp_exception_master, "exception master"},
5839     {bp_catchpoint, "catchpoint"},
5840     {bp_tracepoint, "tracepoint"},
5841     {bp_fast_tracepoint, "fast tracepoint"},
5842     {bp_static_tracepoint, "static tracepoint"},
5843     {bp_dprintf, "dprintf"},
5844     {bp_jit_event, "jit events"},
5845     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5846     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5847   };
5848
5849   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5850       || ((int) type != bptypes[(int) type].type))
5851     internal_error (__FILE__, __LINE__,
5852                     _("bptypes table does not describe type #%d."),
5853                     (int) type);
5854
5855   return bptypes[(int) type].description;
5856 }
5857
5858 /* For MI, output a field named 'thread-groups' with a list as the value.
5859    For CLI, prefix the list with the string 'inf'. */
5860
5861 static void
5862 output_thread_groups (struct ui_out *uiout,
5863                       const char *field_name,
5864                       VEC(int) *inf_num,
5865                       int mi_only)
5866 {
5867   struct cleanup *back_to;
5868   int is_mi = ui_out_is_mi_like_p (uiout);
5869   int inf;
5870   int i;
5871
5872   /* For backward compatibility, don't display inferiors in CLI unless
5873      there are several.  Always display them for MI. */
5874   if (!is_mi && mi_only)
5875     return;
5876
5877   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
5878
5879   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
5880     {
5881       if (is_mi)
5882         {
5883           char mi_group[10];
5884
5885           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
5886           ui_out_field_string (uiout, NULL, mi_group);
5887         }
5888       else
5889         {
5890           if (i == 0)
5891             ui_out_text (uiout, " inf ");
5892           else
5893             ui_out_text (uiout, ", ");
5894         
5895           ui_out_text (uiout, plongest (inf));
5896         }
5897     }
5898
5899   do_cleanups (back_to);
5900 }
5901
5902 /* Print B to gdb_stdout.  */
5903
5904 static void
5905 print_one_breakpoint_location (struct breakpoint *b,
5906                                struct bp_location *loc,
5907                                int loc_number,
5908                                struct bp_location **last_loc,
5909                                int allflag)
5910 {
5911   struct command_line *l;
5912   static char bpenables[] = "nynny";
5913
5914   struct ui_out *uiout = current_uiout;
5915   int header_of_multiple = 0;
5916   int part_of_multiple = (loc != NULL);
5917   struct value_print_options opts;
5918
5919   get_user_print_options (&opts);
5920
5921   gdb_assert (!loc || loc_number != 0);
5922   /* See comment in print_one_breakpoint concerning treatment of
5923      breakpoints with single disabled location.  */
5924   if (loc == NULL 
5925       && (b->loc != NULL 
5926           && (b->loc->next != NULL || !b->loc->enabled)))
5927     header_of_multiple = 1;
5928   if (loc == NULL)
5929     loc = b->loc;
5930
5931   annotate_record ();
5932
5933   /* 1 */
5934   annotate_field (0);
5935   if (part_of_multiple)
5936     {
5937       char *formatted;
5938       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5939       ui_out_field_string (uiout, "number", formatted);
5940       xfree (formatted);
5941     }
5942   else
5943     {
5944       ui_out_field_int (uiout, "number", b->number);
5945     }
5946
5947   /* 2 */
5948   annotate_field (1);
5949   if (part_of_multiple)
5950     ui_out_field_skip (uiout, "type");
5951   else
5952     ui_out_field_string (uiout, "type", bptype_string (b->type));
5953
5954   /* 3 */
5955   annotate_field (2);
5956   if (part_of_multiple)
5957     ui_out_field_skip (uiout, "disp");
5958   else
5959     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5960
5961
5962   /* 4 */
5963   annotate_field (3);
5964   if (part_of_multiple)
5965     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5966   else
5967     ui_out_field_fmt (uiout, "enabled", "%c", 
5968                       bpenables[(int) b->enable_state]);
5969   ui_out_spaces (uiout, 2);
5970
5971   
5972   /* 5 and 6 */
5973   if (b->ops != NULL && b->ops->print_one != NULL)
5974     {
5975       /* Although the print_one can possibly print all locations,
5976          calling it here is not likely to get any nice result.  So,
5977          make sure there's just one location.  */
5978       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5979       b->ops->print_one (b, last_loc);
5980     }
5981   else
5982     switch (b->type)
5983       {
5984       case bp_none:
5985         internal_error (__FILE__, __LINE__,
5986                         _("print_one_breakpoint: bp_none encountered\n"));
5987         break;
5988
5989       case bp_watchpoint:
5990       case bp_hardware_watchpoint:
5991       case bp_read_watchpoint:
5992       case bp_access_watchpoint:
5993         {
5994           struct watchpoint *w = (struct watchpoint *) b;
5995
5996           /* Field 4, the address, is omitted (which makes the columns
5997              not line up too nicely with the headers, but the effect
5998              is relatively readable).  */
5999           if (opts.addressprint)
6000             ui_out_field_skip (uiout, "addr");
6001           annotate_field (5);
6002           ui_out_field_string (uiout, "what", w->exp_string);
6003         }
6004         break;
6005
6006       case bp_breakpoint:
6007       case bp_hardware_breakpoint:
6008       case bp_until:
6009       case bp_finish:
6010       case bp_longjmp:
6011       case bp_longjmp_resume:
6012       case bp_longjmp_call_dummy:
6013       case bp_exception:
6014       case bp_exception_resume:
6015       case bp_step_resume:
6016       case bp_hp_step_resume:
6017       case bp_watchpoint_scope:
6018       case bp_call_dummy:
6019       case bp_std_terminate:
6020       case bp_shlib_event:
6021       case bp_thread_event:
6022       case bp_overlay_event:
6023       case bp_longjmp_master:
6024       case bp_std_terminate_master:
6025       case bp_exception_master:
6026       case bp_tracepoint:
6027       case bp_fast_tracepoint:
6028       case bp_static_tracepoint:
6029       case bp_dprintf:
6030       case bp_jit_event:
6031       case bp_gnu_ifunc_resolver:
6032       case bp_gnu_ifunc_resolver_return:
6033         if (opts.addressprint)
6034           {
6035             annotate_field (4);
6036             if (header_of_multiple)
6037               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6038             else if (b->loc == NULL || loc->shlib_disabled)
6039               ui_out_field_string (uiout, "addr", "<PENDING>");
6040             else
6041               ui_out_field_core_addr (uiout, "addr",
6042                                       loc->gdbarch, loc->address);
6043           }
6044         annotate_field (5);
6045         if (!header_of_multiple)
6046           print_breakpoint_location (b, loc);
6047         if (b->loc)
6048           *last_loc = b->loc;
6049         break;
6050       }
6051
6052
6053   if (loc != NULL && !header_of_multiple)
6054     {
6055       struct inferior *inf;
6056       VEC(int) *inf_num = NULL;
6057       int mi_only = 1;
6058
6059       ALL_INFERIORS (inf)
6060         {
6061           if (inf->pspace == loc->pspace)
6062             VEC_safe_push (int, inf_num, inf->num);
6063         }
6064
6065         /* For backward compatibility, don't display inferiors in CLI unless
6066            there are several.  Always display for MI. */
6067         if (allflag
6068             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6069                 && (number_of_program_spaces () > 1
6070                     || number_of_inferiors () > 1)
6071                 /* LOC is for existing B, it cannot be in
6072                    moribund_locations and thus having NULL OWNER.  */
6073                 && loc->owner->type != bp_catchpoint))
6074         mi_only = 0;
6075       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6076       VEC_free (int, inf_num);
6077     }
6078
6079   if (!part_of_multiple)
6080     {
6081       if (b->thread != -1)
6082         {
6083           /* FIXME: This seems to be redundant and lost here; see the
6084              "stop only in" line a little further down.  */
6085           ui_out_text (uiout, " thread ");
6086           ui_out_field_int (uiout, "thread", b->thread);
6087         }
6088       else if (b->task != 0)
6089         {
6090           ui_out_text (uiout, " task ");
6091           ui_out_field_int (uiout, "task", b->task);
6092         }
6093     }
6094
6095   ui_out_text (uiout, "\n");
6096
6097   if (!part_of_multiple)
6098     b->ops->print_one_detail (b, uiout);
6099
6100   if (part_of_multiple && frame_id_p (b->frame_id))
6101     {
6102       annotate_field (6);
6103       ui_out_text (uiout, "\tstop only in stack frame at ");
6104       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6105          the frame ID.  */
6106       ui_out_field_core_addr (uiout, "frame",
6107                               b->gdbarch, b->frame_id.stack_addr);
6108       ui_out_text (uiout, "\n");
6109     }
6110   
6111   if (!part_of_multiple && b->cond_string)
6112     {
6113       annotate_field (7);
6114       if (is_tracepoint (b))
6115         ui_out_text (uiout, "\ttrace only if ");
6116       else
6117         ui_out_text (uiout, "\tstop only if ");
6118       ui_out_field_string (uiout, "cond", b->cond_string);
6119
6120       /* Print whether the target is doing the breakpoint's condition
6121          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6122       if (is_breakpoint (b)
6123           && breakpoint_condition_evaluation_mode ()
6124           == condition_evaluation_target)
6125         {
6126           ui_out_text (uiout, " (");
6127           ui_out_field_string (uiout, "evaluated-by",
6128                                bp_condition_evaluator (b));
6129           ui_out_text (uiout, " evals)");
6130         }
6131       ui_out_text (uiout, "\n");
6132     }
6133
6134   if (!part_of_multiple && b->thread != -1)
6135     {
6136       /* FIXME should make an annotation for this.  */
6137       ui_out_text (uiout, "\tstop only in thread ");
6138       ui_out_field_int (uiout, "thread", b->thread);
6139       ui_out_text (uiout, "\n");
6140     }
6141   
6142   if (!part_of_multiple)
6143     {
6144       if (b->hit_count)
6145         {
6146           /* FIXME should make an annotation for this.  */
6147           if (is_catchpoint (b))
6148             ui_out_text (uiout, "\tcatchpoint");
6149           else if (is_tracepoint (b))
6150             ui_out_text (uiout, "\ttracepoint");
6151           else
6152             ui_out_text (uiout, "\tbreakpoint");
6153           ui_out_text (uiout, " already hit ");
6154           ui_out_field_int (uiout, "times", b->hit_count);
6155           if (b->hit_count == 1)
6156             ui_out_text (uiout, " time\n");
6157           else
6158             ui_out_text (uiout, " times\n");
6159         }
6160       else
6161         {
6162           /* Output the count also if it is zero, but only if this is mi.  */
6163           if (ui_out_is_mi_like_p (uiout))
6164             ui_out_field_int (uiout, "times", b->hit_count);
6165         }
6166     }
6167
6168   if (!part_of_multiple && b->ignore_count)
6169     {
6170       annotate_field (8);
6171       ui_out_text (uiout, "\tignore next ");
6172       ui_out_field_int (uiout, "ignore", b->ignore_count);
6173       ui_out_text (uiout, " hits\n");
6174     }
6175
6176   /* Note that an enable count of 1 corresponds to "enable once"
6177      behavior, which is reported by the combination of enablement and
6178      disposition, so we don't need to mention it here.  */
6179   if (!part_of_multiple && b->enable_count > 1)
6180     {
6181       annotate_field (8);
6182       ui_out_text (uiout, "\tdisable after ");
6183       /* Tweak the wording to clarify that ignore and enable counts
6184          are distinct, and have additive effect.  */
6185       if (b->ignore_count)
6186         ui_out_text (uiout, "additional ");
6187       else
6188         ui_out_text (uiout, "next ");
6189       ui_out_field_int (uiout, "enable", b->enable_count);
6190       ui_out_text (uiout, " hits\n");
6191     }
6192
6193   if (!part_of_multiple && is_tracepoint (b))
6194     {
6195       struct tracepoint *tp = (struct tracepoint *) b;
6196
6197       if (tp->traceframe_usage)
6198         {
6199           ui_out_text (uiout, "\ttrace buffer usage ");
6200           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6201           ui_out_text (uiout, " bytes\n");
6202         }
6203     }
6204
6205   l = b->commands ? b->commands->commands : NULL;
6206   if (!part_of_multiple && l)
6207     {
6208       struct cleanup *script_chain;
6209
6210       annotate_field (9);
6211       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6212       print_command_lines (uiout, l, 4);
6213       do_cleanups (script_chain);
6214     }
6215
6216   if (is_tracepoint (b))
6217     {
6218       struct tracepoint *t = (struct tracepoint *) b;
6219
6220       if (!part_of_multiple && t->pass_count)
6221         {
6222           annotate_field (10);
6223           ui_out_text (uiout, "\tpass count ");
6224           ui_out_field_int (uiout, "pass", t->pass_count);
6225           ui_out_text (uiout, " \n");
6226         }
6227
6228       /* Don't display it when tracepoint or tracepoint location is
6229          pending.   */
6230       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6231         {
6232           annotate_field (11);
6233
6234           if (ui_out_is_mi_like_p (uiout))
6235             ui_out_field_string (uiout, "installed",
6236                                  loc->inserted ? "y" : "n");
6237           else
6238             {
6239               if (loc->inserted)
6240                 ui_out_text (uiout, "\t");
6241               else
6242                 ui_out_text (uiout, "\tnot ");
6243               ui_out_text (uiout, "installed on target\n");
6244             }
6245         }
6246     }
6247
6248   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6249     {
6250       if (is_watchpoint (b))
6251         {
6252           struct watchpoint *w = (struct watchpoint *) b;
6253
6254           ui_out_field_string (uiout, "original-location", w->exp_string);
6255         }
6256       else if (b->addr_string)
6257         ui_out_field_string (uiout, "original-location", b->addr_string);
6258     }
6259 }
6260
6261 static void
6262 print_one_breakpoint (struct breakpoint *b,
6263                       struct bp_location **last_loc, 
6264                       int allflag)
6265 {
6266   struct cleanup *bkpt_chain;
6267   struct ui_out *uiout = current_uiout;
6268
6269   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6270
6271   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6272   do_cleanups (bkpt_chain);
6273
6274   /* If this breakpoint has custom print function,
6275      it's already printed.  Otherwise, print individual
6276      locations, if any.  */
6277   if (b->ops == NULL || b->ops->print_one == NULL)
6278     {
6279       /* If breakpoint has a single location that is disabled, we
6280          print it as if it had several locations, since otherwise it's
6281          hard to represent "breakpoint enabled, location disabled"
6282          situation.
6283
6284          Note that while hardware watchpoints have several locations
6285          internally, that's not a property exposed to user.  */
6286       if (b->loc 
6287           && !is_hardware_watchpoint (b)
6288           && (b->loc->next || !b->loc->enabled))
6289         {
6290           struct bp_location *loc;
6291           int n = 1;
6292
6293           for (loc = b->loc; loc; loc = loc->next, ++n)
6294             {
6295               struct cleanup *inner2 =
6296                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6297               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6298               do_cleanups (inner2);
6299             }
6300         }
6301     }
6302 }
6303
6304 static int
6305 breakpoint_address_bits (struct breakpoint *b)
6306 {
6307   int print_address_bits = 0;
6308   struct bp_location *loc;
6309
6310   for (loc = b->loc; loc; loc = loc->next)
6311     {
6312       int addr_bit;
6313
6314       /* Software watchpoints that aren't watching memory don't have
6315          an address to print.  */
6316       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6317         continue;
6318
6319       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6320       if (addr_bit > print_address_bits)
6321         print_address_bits = addr_bit;
6322     }
6323
6324   return print_address_bits;
6325 }
6326
6327 struct captured_breakpoint_query_args
6328   {
6329     int bnum;
6330   };
6331
6332 static int
6333 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6334 {
6335   struct captured_breakpoint_query_args *args = data;
6336   struct breakpoint *b;
6337   struct bp_location *dummy_loc = NULL;
6338
6339   ALL_BREAKPOINTS (b)
6340     {
6341       if (args->bnum == b->number)
6342         {
6343           print_one_breakpoint (b, &dummy_loc, 0);
6344           return GDB_RC_OK;
6345         }
6346     }
6347   return GDB_RC_NONE;
6348 }
6349
6350 enum gdb_rc
6351 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6352                       char **error_message)
6353 {
6354   struct captured_breakpoint_query_args args;
6355
6356   args.bnum = bnum;
6357   /* For the moment we don't trust print_one_breakpoint() to not throw
6358      an error.  */
6359   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6360                                  error_message, RETURN_MASK_ALL) < 0)
6361     return GDB_RC_FAIL;
6362   else
6363     return GDB_RC_OK;
6364 }
6365
6366 /* Return true if this breakpoint was set by the user, false if it is
6367    internal or momentary.  */
6368
6369 int
6370 user_breakpoint_p (struct breakpoint *b)
6371 {
6372   return b->number > 0;
6373 }
6374
6375 /* Print information on user settable breakpoint (watchpoint, etc)
6376    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6377    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6378    FILTER is non-NULL, call it on each breakpoint and only include the
6379    ones for which it returns non-zero.  Return the total number of
6380    breakpoints listed.  */
6381
6382 static int
6383 breakpoint_1 (char *args, int allflag, 
6384               int (*filter) (const struct breakpoint *))
6385 {
6386   struct breakpoint *b;
6387   struct bp_location *last_loc = NULL;
6388   int nr_printable_breakpoints;
6389   struct cleanup *bkpttbl_chain;
6390   struct value_print_options opts;
6391   int print_address_bits = 0;
6392   int print_type_col_width = 14;
6393   struct ui_out *uiout = current_uiout;
6394
6395   get_user_print_options (&opts);
6396
6397   /* Compute the number of rows in the table, as well as the size
6398      required for address fields.  */
6399   nr_printable_breakpoints = 0;
6400   ALL_BREAKPOINTS (b)
6401     {
6402       /* If we have a filter, only list the breakpoints it accepts.  */
6403       if (filter && !filter (b))
6404         continue;
6405
6406       /* If we have an "args" string, it is a list of breakpoints to 
6407          accept.  Skip the others.  */
6408       if (args != NULL && *args != '\0')
6409         {
6410           if (allflag && parse_and_eval_long (args) != b->number)
6411             continue;
6412           if (!allflag && !number_is_in_list (args, b->number))
6413             continue;
6414         }
6415
6416       if (allflag || user_breakpoint_p (b))
6417         {
6418           int addr_bit, type_len;
6419
6420           addr_bit = breakpoint_address_bits (b);
6421           if (addr_bit > print_address_bits)
6422             print_address_bits = addr_bit;
6423
6424           type_len = strlen (bptype_string (b->type));
6425           if (type_len > print_type_col_width)
6426             print_type_col_width = type_len;
6427
6428           nr_printable_breakpoints++;
6429         }
6430     }
6431
6432   if (opts.addressprint)
6433     bkpttbl_chain 
6434       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6435                                              nr_printable_breakpoints,
6436                                              "BreakpointTable");
6437   else
6438     bkpttbl_chain 
6439       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6440                                              nr_printable_breakpoints,
6441                                              "BreakpointTable");
6442
6443   if (nr_printable_breakpoints > 0)
6444     annotate_breakpoints_headers ();
6445   if (nr_printable_breakpoints > 0)
6446     annotate_field (0);
6447   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6448   if (nr_printable_breakpoints > 0)
6449     annotate_field (1);
6450   ui_out_table_header (uiout, print_type_col_width, ui_left,
6451                        "type", "Type");                         /* 2 */
6452   if (nr_printable_breakpoints > 0)
6453     annotate_field (2);
6454   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6455   if (nr_printable_breakpoints > 0)
6456     annotate_field (3);
6457   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6458   if (opts.addressprint)
6459     {
6460       if (nr_printable_breakpoints > 0)
6461         annotate_field (4);
6462       if (print_address_bits <= 32)
6463         ui_out_table_header (uiout, 10, ui_left, 
6464                              "addr", "Address");                /* 5 */
6465       else
6466         ui_out_table_header (uiout, 18, ui_left, 
6467                              "addr", "Address");                /* 5 */
6468     }
6469   if (nr_printable_breakpoints > 0)
6470     annotate_field (5);
6471   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6472   ui_out_table_body (uiout);
6473   if (nr_printable_breakpoints > 0)
6474     annotate_breakpoints_table ();
6475
6476   ALL_BREAKPOINTS (b)
6477     {
6478       QUIT;
6479       /* If we have a filter, only list the breakpoints it accepts.  */
6480       if (filter && !filter (b))
6481         continue;
6482
6483       /* If we have an "args" string, it is a list of breakpoints to 
6484          accept.  Skip the others.  */
6485
6486       if (args != NULL && *args != '\0')
6487         {
6488           if (allflag)  /* maintenance info breakpoint */
6489             {
6490               if (parse_and_eval_long (args) != b->number)
6491                 continue;
6492             }
6493           else          /* all others */
6494             {
6495               if (!number_is_in_list (args, b->number))
6496                 continue;
6497             }
6498         }
6499       /* We only print out user settable breakpoints unless the
6500          allflag is set.  */
6501       if (allflag || user_breakpoint_p (b))
6502         print_one_breakpoint (b, &last_loc, allflag);
6503     }
6504
6505   do_cleanups (bkpttbl_chain);
6506
6507   if (nr_printable_breakpoints == 0)
6508     {
6509       /* If there's a filter, let the caller decide how to report
6510          empty list.  */
6511       if (!filter)
6512         {
6513           if (args == NULL || *args == '\0')
6514             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6515           else
6516             ui_out_message (uiout, 0, 
6517                             "No breakpoint or watchpoint matching '%s'.\n",
6518                             args);
6519         }
6520     }
6521   else
6522     {
6523       if (last_loc && !server_command)
6524         set_next_address (last_loc->gdbarch, last_loc->address);
6525     }
6526
6527   /* FIXME?  Should this be moved up so that it is only called when
6528      there have been breakpoints? */
6529   annotate_breakpoints_table_end ();
6530
6531   return nr_printable_breakpoints;
6532 }
6533
6534 /* Display the value of default-collect in a way that is generally
6535    compatible with the breakpoint list.  */
6536
6537 static void
6538 default_collect_info (void)
6539 {
6540   struct ui_out *uiout = current_uiout;
6541
6542   /* If it has no value (which is frequently the case), say nothing; a
6543      message like "No default-collect." gets in user's face when it's
6544      not wanted.  */
6545   if (!*default_collect)
6546     return;
6547
6548   /* The following phrase lines up nicely with per-tracepoint collect
6549      actions.  */
6550   ui_out_text (uiout, "default collect ");
6551   ui_out_field_string (uiout, "default-collect", default_collect);
6552   ui_out_text (uiout, " \n");
6553 }
6554   
6555 static void
6556 breakpoints_info (char *args, int from_tty)
6557 {
6558   breakpoint_1 (args, 0, NULL);
6559
6560   default_collect_info ();
6561 }
6562
6563 static void
6564 watchpoints_info (char *args, int from_tty)
6565 {
6566   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6567   struct ui_out *uiout = current_uiout;
6568
6569   if (num_printed == 0)
6570     {
6571       if (args == NULL || *args == '\0')
6572         ui_out_message (uiout, 0, "No watchpoints.\n");
6573       else
6574         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6575     }
6576 }
6577
6578 static void
6579 maintenance_info_breakpoints (char *args, int from_tty)
6580 {
6581   breakpoint_1 (args, 1, NULL);
6582
6583   default_collect_info ();
6584 }
6585
6586 static int
6587 breakpoint_has_pc (struct breakpoint *b,
6588                    struct program_space *pspace,
6589                    CORE_ADDR pc, struct obj_section *section)
6590 {
6591   struct bp_location *bl = b->loc;
6592
6593   for (; bl; bl = bl->next)
6594     {
6595       if (bl->pspace == pspace
6596           && bl->address == pc
6597           && (!overlay_debugging || bl->section == section))
6598         return 1;         
6599     }
6600   return 0;
6601 }
6602
6603 /* Print a message describing any user-breakpoints set at PC.  This
6604    concerns with logical breakpoints, so we match program spaces, not
6605    address spaces.  */
6606
6607 static void
6608 describe_other_breakpoints (struct gdbarch *gdbarch,
6609                             struct program_space *pspace, CORE_ADDR pc,
6610                             struct obj_section *section, int thread)
6611 {
6612   int others = 0;
6613   struct breakpoint *b;
6614
6615   ALL_BREAKPOINTS (b)
6616     others += (user_breakpoint_p (b)
6617                && breakpoint_has_pc (b, pspace, pc, section));
6618   if (others > 0)
6619     {
6620       if (others == 1)
6621         printf_filtered (_("Note: breakpoint "));
6622       else /* if (others == ???) */
6623         printf_filtered (_("Note: breakpoints "));
6624       ALL_BREAKPOINTS (b)
6625         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6626           {
6627             others--;
6628             printf_filtered ("%d", b->number);
6629             if (b->thread == -1 && thread != -1)
6630               printf_filtered (" (all threads)");
6631             else if (b->thread != -1)
6632               printf_filtered (" (thread %d)", b->thread);
6633             printf_filtered ("%s%s ",
6634                              ((b->enable_state == bp_disabled
6635                                || b->enable_state == bp_call_disabled)
6636                               ? " (disabled)"
6637                               : b->enable_state == bp_permanent 
6638                               ? " (permanent)"
6639                               : ""),
6640                              (others > 1) ? "," 
6641                              : ((others == 1) ? " and" : ""));
6642           }
6643       printf_filtered (_("also set at pc "));
6644       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6645       printf_filtered (".\n");
6646     }
6647 }
6648 \f
6649
6650 /* Return true iff it is meaningful to use the address member of
6651    BPT.  For some breakpoint types, the address member is irrelevant
6652    and it makes no sense to attempt to compare it to other addresses
6653    (or use it for any other purpose either).
6654
6655    More specifically, each of the following breakpoint types will
6656    always have a zero valued address and we don't want to mark
6657    breakpoints of any of these types to be a duplicate of an actual
6658    breakpoint at address zero:
6659
6660       bp_watchpoint
6661       bp_catchpoint
6662
6663 */
6664
6665 static int
6666 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6667 {
6668   enum bptype type = bpt->type;
6669
6670   return (type != bp_watchpoint && type != bp_catchpoint);
6671 }
6672
6673 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6674    true if LOC1 and LOC2 represent the same watchpoint location.  */
6675
6676 static int
6677 watchpoint_locations_match (struct bp_location *loc1, 
6678                             struct bp_location *loc2)
6679 {
6680   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6681   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6682
6683   /* Both of them must exist.  */
6684   gdb_assert (w1 != NULL);
6685   gdb_assert (w2 != NULL);
6686
6687   /* If the target can evaluate the condition expression in hardware,
6688      then we we need to insert both watchpoints even if they are at
6689      the same place.  Otherwise the watchpoint will only trigger when
6690      the condition of whichever watchpoint was inserted evaluates to
6691      true, not giving a chance for GDB to check the condition of the
6692      other watchpoint.  */
6693   if ((w1->cond_exp
6694        && target_can_accel_watchpoint_condition (loc1->address, 
6695                                                  loc1->length,
6696                                                  loc1->watchpoint_type,
6697                                                  w1->cond_exp))
6698       || (w2->cond_exp
6699           && target_can_accel_watchpoint_condition (loc2->address, 
6700                                                     loc2->length,
6701                                                     loc2->watchpoint_type,
6702                                                     w2->cond_exp)))
6703     return 0;
6704
6705   /* Note that this checks the owner's type, not the location's.  In
6706      case the target does not support read watchpoints, but does
6707      support access watchpoints, we'll have bp_read_watchpoint
6708      watchpoints with hw_access locations.  Those should be considered
6709      duplicates of hw_read locations.  The hw_read locations will
6710      become hw_access locations later.  */
6711   return (loc1->owner->type == loc2->owner->type
6712           && loc1->pspace->aspace == loc2->pspace->aspace
6713           && loc1->address == loc2->address
6714           && loc1->length == loc2->length);
6715 }
6716
6717 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6718    same breakpoint location.  In most targets, this can only be true
6719    if ASPACE1 matches ASPACE2.  On targets that have global
6720    breakpoints, the address space doesn't really matter.  */
6721
6722 static int
6723 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6724                           struct address_space *aspace2, CORE_ADDR addr2)
6725 {
6726   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6727            || aspace1 == aspace2)
6728           && addr1 == addr2);
6729 }
6730
6731 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6732    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6733    matches ASPACE2.  On targets that have global breakpoints, the address
6734    space doesn't really matter.  */
6735
6736 static int
6737 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6738                                 int len1, struct address_space *aspace2,
6739                                 CORE_ADDR addr2)
6740 {
6741   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6742            || aspace1 == aspace2)
6743           && addr2 >= addr1 && addr2 < addr1 + len1);
6744 }
6745
6746 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6747    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6748    matches the breakpoint's address space.  On targets that have global
6749    breakpoints, the address space doesn't really matter.  */
6750
6751 static int
6752 breakpoint_location_address_match (struct bp_location *bl,
6753                                    struct address_space *aspace,
6754                                    CORE_ADDR addr)
6755 {
6756   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6757                                     aspace, addr)
6758           || (bl->length
6759               && breakpoint_address_match_range (bl->pspace->aspace,
6760                                                  bl->address, bl->length,
6761                                                  aspace, addr)));
6762 }
6763
6764 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6765    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6766    true, otherwise returns false.  */
6767
6768 static int
6769 tracepoint_locations_match (struct bp_location *loc1,
6770                             struct bp_location *loc2)
6771 {
6772   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6773     /* Since tracepoint locations are never duplicated with others', tracepoint
6774        locations at the same address of different tracepoints are regarded as
6775        different locations.  */
6776     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6777   else
6778     return 0;
6779 }
6780
6781 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6782    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6783    represent the same location.  */
6784
6785 static int
6786 breakpoint_locations_match (struct bp_location *loc1, 
6787                             struct bp_location *loc2)
6788 {
6789   int hw_point1, hw_point2;
6790
6791   /* Both of them must not be in moribund_locations.  */
6792   gdb_assert (loc1->owner != NULL);
6793   gdb_assert (loc2->owner != NULL);
6794
6795   hw_point1 = is_hardware_watchpoint (loc1->owner);
6796   hw_point2 = is_hardware_watchpoint (loc2->owner);
6797
6798   if (hw_point1 != hw_point2)
6799     return 0;
6800   else if (hw_point1)
6801     return watchpoint_locations_match (loc1, loc2);
6802   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6803     return tracepoint_locations_match (loc1, loc2);
6804   else
6805     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6806     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6807                                      loc2->pspace->aspace, loc2->address)
6808             && loc1->length == loc2->length);
6809 }
6810
6811 static void
6812 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6813                                int bnum, int have_bnum)
6814 {
6815   /* The longest string possibly returned by hex_string_custom
6816      is 50 chars.  These must be at least that big for safety.  */
6817   char astr1[64];
6818   char astr2[64];
6819
6820   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6821   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6822   if (have_bnum)
6823     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6824              bnum, astr1, astr2);
6825   else
6826     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6827 }
6828
6829 /* Adjust a breakpoint's address to account for architectural
6830    constraints on breakpoint placement.  Return the adjusted address.
6831    Note: Very few targets require this kind of adjustment.  For most
6832    targets, this function is simply the identity function.  */
6833
6834 static CORE_ADDR
6835 adjust_breakpoint_address (struct gdbarch *gdbarch,
6836                            CORE_ADDR bpaddr, enum bptype bptype)
6837 {
6838   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6839     {
6840       /* Very few targets need any kind of breakpoint adjustment.  */
6841       return bpaddr;
6842     }
6843   else if (bptype == bp_watchpoint
6844            || bptype == bp_hardware_watchpoint
6845            || bptype == bp_read_watchpoint
6846            || bptype == bp_access_watchpoint
6847            || bptype == bp_catchpoint)
6848     {
6849       /* Watchpoints and the various bp_catch_* eventpoints should not
6850          have their addresses modified.  */
6851       return bpaddr;
6852     }
6853   else
6854     {
6855       CORE_ADDR adjusted_bpaddr;
6856
6857       /* Some targets have architectural constraints on the placement
6858          of breakpoint instructions.  Obtain the adjusted address.  */
6859       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6860
6861       /* An adjusted breakpoint address can significantly alter
6862          a user's expectations.  Print a warning if an adjustment
6863          is required.  */
6864       if (adjusted_bpaddr != bpaddr)
6865         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6866
6867       return adjusted_bpaddr;
6868     }
6869 }
6870
6871 void
6872 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6873                   struct breakpoint *owner)
6874 {
6875   memset (loc, 0, sizeof (*loc));
6876
6877   gdb_assert (ops != NULL);
6878
6879   loc->ops = ops;
6880   loc->owner = owner;
6881   loc->cond = NULL;
6882   loc->cond_bytecode = NULL;
6883   loc->shlib_disabled = 0;
6884   loc->enabled = 1;
6885
6886   switch (owner->type)
6887     {
6888     case bp_breakpoint:
6889     case bp_until:
6890     case bp_finish:
6891     case bp_longjmp:
6892     case bp_longjmp_resume:
6893     case bp_longjmp_call_dummy:
6894     case bp_exception:
6895     case bp_exception_resume:
6896     case bp_step_resume:
6897     case bp_hp_step_resume:
6898     case bp_watchpoint_scope:
6899     case bp_call_dummy:
6900     case bp_std_terminate:
6901     case bp_shlib_event:
6902     case bp_thread_event:
6903     case bp_overlay_event:
6904     case bp_jit_event:
6905     case bp_longjmp_master:
6906     case bp_std_terminate_master:
6907     case bp_exception_master:
6908     case bp_gnu_ifunc_resolver:
6909     case bp_gnu_ifunc_resolver_return:
6910     case bp_dprintf:
6911       loc->loc_type = bp_loc_software_breakpoint;
6912       mark_breakpoint_location_modified (loc);
6913       break;
6914     case bp_hardware_breakpoint:
6915       loc->loc_type = bp_loc_hardware_breakpoint;
6916       mark_breakpoint_location_modified (loc);
6917       break;
6918     case bp_hardware_watchpoint:
6919     case bp_read_watchpoint:
6920     case bp_access_watchpoint:
6921       loc->loc_type = bp_loc_hardware_watchpoint;
6922       break;
6923     case bp_watchpoint:
6924     case bp_catchpoint:
6925     case bp_tracepoint:
6926     case bp_fast_tracepoint:
6927     case bp_static_tracepoint:
6928       loc->loc_type = bp_loc_other;
6929       break;
6930     default:
6931       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6932     }
6933
6934   loc->refc = 1;
6935 }
6936
6937 /* Allocate a struct bp_location.  */
6938
6939 static struct bp_location *
6940 allocate_bp_location (struct breakpoint *bpt)
6941 {
6942   return bpt->ops->allocate_location (bpt);
6943 }
6944
6945 static void
6946 free_bp_location (struct bp_location *loc)
6947 {
6948   loc->ops->dtor (loc);
6949   xfree (loc);
6950 }
6951
6952 /* Increment reference count.  */
6953
6954 static void
6955 incref_bp_location (struct bp_location *bl)
6956 {
6957   ++bl->refc;
6958 }
6959
6960 /* Decrement reference count.  If the reference count reaches 0,
6961    destroy the bp_location.  Sets *BLP to NULL.  */
6962
6963 static void
6964 decref_bp_location (struct bp_location **blp)
6965 {
6966   gdb_assert ((*blp)->refc > 0);
6967
6968   if (--(*blp)->refc == 0)
6969     free_bp_location (*blp);
6970   *blp = NULL;
6971 }
6972
6973 /* Add breakpoint B at the end of the global breakpoint chain.  */
6974
6975 static void
6976 add_to_breakpoint_chain (struct breakpoint *b)
6977 {
6978   struct breakpoint *b1;
6979
6980   /* Add this breakpoint to the end of the chain so that a list of
6981      breakpoints will come out in order of increasing numbers.  */
6982
6983   b1 = breakpoint_chain;
6984   if (b1 == 0)
6985     breakpoint_chain = b;
6986   else
6987     {
6988       while (b1->next)
6989         b1 = b1->next;
6990       b1->next = b;
6991     }
6992 }
6993
6994 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6995
6996 static void
6997 init_raw_breakpoint_without_location (struct breakpoint *b,
6998                                       struct gdbarch *gdbarch,
6999                                       enum bptype bptype,
7000                                       const struct breakpoint_ops *ops)
7001 {
7002   memset (b, 0, sizeof (*b));
7003
7004   gdb_assert (ops != NULL);
7005
7006   b->ops = ops;
7007   b->type = bptype;
7008   b->gdbarch = gdbarch;
7009   b->language = current_language->la_language;
7010   b->input_radix = input_radix;
7011   b->thread = -1;
7012   b->enable_state = bp_enabled;
7013   b->next = 0;
7014   b->silent = 0;
7015   b->ignore_count = 0;
7016   b->commands = NULL;
7017   b->frame_id = null_frame_id;
7018   b->condition_not_parsed = 0;
7019   b->py_bp_object = NULL;
7020   b->related_breakpoint = b;
7021 }
7022
7023 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7024    that has type BPTYPE and has no locations as yet.  */
7025
7026 static struct breakpoint *
7027 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7028                                      enum bptype bptype,
7029                                      const struct breakpoint_ops *ops)
7030 {
7031   struct breakpoint *b = XNEW (struct breakpoint);
7032
7033   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7034   add_to_breakpoint_chain (b);
7035   return b;
7036 }
7037
7038 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7039    resolutions should be made as the user specified the location explicitly
7040    enough.  */
7041
7042 static void
7043 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7044 {
7045   gdb_assert (loc->owner != NULL);
7046
7047   if (loc->owner->type == bp_breakpoint
7048       || loc->owner->type == bp_hardware_breakpoint
7049       || is_tracepoint (loc->owner))
7050     {
7051       int is_gnu_ifunc;
7052       const char *function_name;
7053       CORE_ADDR func_addr;
7054
7055       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7056                                           &func_addr, NULL, &is_gnu_ifunc);
7057
7058       if (is_gnu_ifunc && !explicit_loc)
7059         {
7060           struct breakpoint *b = loc->owner;
7061
7062           gdb_assert (loc->pspace == current_program_space);
7063           if (gnu_ifunc_resolve_name (function_name,
7064                                       &loc->requested_address))
7065             {
7066               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7067               loc->address = adjust_breakpoint_address (loc->gdbarch,
7068                                                         loc->requested_address,
7069                                                         b->type);
7070             }
7071           else if (b->type == bp_breakpoint && b->loc == loc
7072                    && loc->next == NULL && b->related_breakpoint == b)
7073             {
7074               /* Create only the whole new breakpoint of this type but do not
7075                  mess more complicated breakpoints with multiple locations.  */
7076               b->type = bp_gnu_ifunc_resolver;
7077               /* Remember the resolver's address for use by the return
7078                  breakpoint.  */
7079               loc->related_address = func_addr;
7080             }
7081         }
7082
7083       if (function_name)
7084         loc->function_name = xstrdup (function_name);
7085     }
7086 }
7087
7088 /* Attempt to determine architecture of location identified by SAL.  */
7089 struct gdbarch *
7090 get_sal_arch (struct symtab_and_line sal)
7091 {
7092   if (sal.section)
7093     return get_objfile_arch (sal.section->objfile);
7094   if (sal.symtab)
7095     return get_objfile_arch (sal.symtab->objfile);
7096
7097   return NULL;
7098 }
7099
7100 /* Low level routine for partially initializing a breakpoint of type
7101    BPTYPE.  The newly created breakpoint's address, section, source
7102    file name, and line number are provided by SAL.
7103
7104    It is expected that the caller will complete the initialization of
7105    the newly created breakpoint struct as well as output any status
7106    information regarding the creation of a new breakpoint.  */
7107
7108 static void
7109 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7110                      struct symtab_and_line sal, enum bptype bptype,
7111                      const struct breakpoint_ops *ops)
7112 {
7113   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7114
7115   add_location_to_breakpoint (b, &sal);
7116
7117   if (bptype != bp_catchpoint)
7118     gdb_assert (sal.pspace != NULL);
7119
7120   /* Store the program space that was used to set the breakpoint,
7121      except for ordinary breakpoints, which are independent of the
7122      program space.  */
7123   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7124     b->pspace = sal.pspace;
7125 }
7126
7127 /* set_raw_breakpoint is a low level routine for allocating and
7128    partially initializing a breakpoint of type BPTYPE.  The newly
7129    created breakpoint's address, section, source file name, and line
7130    number are provided by SAL.  The newly created and partially
7131    initialized breakpoint is added to the breakpoint chain and
7132    is also returned as the value of this function.
7133
7134    It is expected that the caller will complete the initialization of
7135    the newly created breakpoint struct as well as output any status
7136    information regarding the creation of a new breakpoint.  In
7137    particular, set_raw_breakpoint does NOT set the breakpoint
7138    number!  Care should be taken to not allow an error to occur
7139    prior to completing the initialization of the breakpoint.  If this
7140    should happen, a bogus breakpoint will be left on the chain.  */
7141
7142 struct breakpoint *
7143 set_raw_breakpoint (struct gdbarch *gdbarch,
7144                     struct symtab_and_line sal, enum bptype bptype,
7145                     const struct breakpoint_ops *ops)
7146 {
7147   struct breakpoint *b = XNEW (struct breakpoint);
7148
7149   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7150   add_to_breakpoint_chain (b);
7151   return b;
7152 }
7153
7154
7155 /* Note that the breakpoint object B describes a permanent breakpoint
7156    instruction, hard-wired into the inferior's code.  */
7157 void
7158 make_breakpoint_permanent (struct breakpoint *b)
7159 {
7160   struct bp_location *bl;
7161
7162   b->enable_state = bp_permanent;
7163
7164   /* By definition, permanent breakpoints are already present in the
7165      code.  Mark all locations as inserted.  For now,
7166      make_breakpoint_permanent is called in just one place, so it's
7167      hard to say if it's reasonable to have permanent breakpoint with
7168      multiple locations or not, but it's easy to implement.  */
7169   for (bl = b->loc; bl; bl = bl->next)
7170     bl->inserted = 1;
7171 }
7172
7173 /* Call this routine when stepping and nexting to enable a breakpoint
7174    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7175    initiated the operation.  */
7176
7177 void
7178 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7179 {
7180   struct breakpoint *b, *b_tmp;
7181   int thread = tp->num;
7182
7183   /* To avoid having to rescan all objfile symbols at every step,
7184      we maintain a list of continually-inserted but always disabled
7185      longjmp "master" breakpoints.  Here, we simply create momentary
7186      clones of those and enable them for the requested thread.  */
7187   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7188     if (b->pspace == current_program_space
7189         && (b->type == bp_longjmp_master
7190             || b->type == bp_exception_master))
7191       {
7192         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7193         struct breakpoint *clone;
7194
7195         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7196            after their removal.  */
7197         clone = momentary_breakpoint_from_master (b, type,
7198                                                   &longjmp_breakpoint_ops);
7199         clone->thread = thread;
7200       }
7201
7202   tp->initiating_frame = frame;
7203 }
7204
7205 /* Delete all longjmp breakpoints from THREAD.  */
7206 void
7207 delete_longjmp_breakpoint (int thread)
7208 {
7209   struct breakpoint *b, *b_tmp;
7210
7211   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7212     if (b->type == bp_longjmp || b->type == bp_exception)
7213       {
7214         if (b->thread == thread)
7215           delete_breakpoint (b);
7216       }
7217 }
7218
7219 void
7220 delete_longjmp_breakpoint_at_next_stop (int thread)
7221 {
7222   struct breakpoint *b, *b_tmp;
7223
7224   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7225     if (b->type == bp_longjmp || b->type == bp_exception)
7226       {
7227         if (b->thread == thread)
7228           b->disposition = disp_del_at_next_stop;
7229       }
7230 }
7231
7232 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7233    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7234    pointer to any of them.  Return NULL if this system cannot place longjmp
7235    breakpoints.  */
7236
7237 struct breakpoint *
7238 set_longjmp_breakpoint_for_call_dummy (void)
7239 {
7240   struct breakpoint *b, *retval = NULL;
7241
7242   ALL_BREAKPOINTS (b)
7243     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7244       {
7245         struct breakpoint *new_b;
7246
7247         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7248                                                   &momentary_breakpoint_ops);
7249         new_b->thread = pid_to_thread_id (inferior_ptid);
7250
7251         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7252
7253         gdb_assert (new_b->related_breakpoint == new_b);
7254         if (retval == NULL)
7255           retval = new_b;
7256         new_b->related_breakpoint = retval;
7257         while (retval->related_breakpoint != new_b->related_breakpoint)
7258           retval = retval->related_breakpoint;
7259         retval->related_breakpoint = new_b;
7260       }
7261
7262   return retval;
7263 }
7264
7265 /* Verify all existing dummy frames and their associated breakpoints for
7266    THREAD.  Remove those which can no longer be found in the current frame
7267    stack.
7268
7269    You should call this function only at places where it is safe to currently
7270    unwind the whole stack.  Failed stack unwind would discard live dummy
7271    frames.  */
7272
7273 void
7274 check_longjmp_breakpoint_for_call_dummy (int thread)
7275 {
7276   struct breakpoint *b, *b_tmp;
7277
7278   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7279     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7280       {
7281         struct breakpoint *dummy_b = b->related_breakpoint;
7282
7283         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7284           dummy_b = dummy_b->related_breakpoint;
7285         if (dummy_b->type != bp_call_dummy
7286             || frame_find_by_id (dummy_b->frame_id) != NULL)
7287           continue;
7288         
7289         dummy_frame_discard (dummy_b->frame_id);
7290
7291         while (b->related_breakpoint != b)
7292           {
7293             if (b_tmp == b->related_breakpoint)
7294               b_tmp = b->related_breakpoint->next;
7295             delete_breakpoint (b->related_breakpoint);
7296           }
7297         delete_breakpoint (b);
7298       }
7299 }
7300
7301 void
7302 enable_overlay_breakpoints (void)
7303 {
7304   struct breakpoint *b;
7305
7306   ALL_BREAKPOINTS (b)
7307     if (b->type == bp_overlay_event)
7308     {
7309       b->enable_state = bp_enabled;
7310       update_global_location_list (1);
7311       overlay_events_enabled = 1;
7312     }
7313 }
7314
7315 void
7316 disable_overlay_breakpoints (void)
7317 {
7318   struct breakpoint *b;
7319
7320   ALL_BREAKPOINTS (b)
7321     if (b->type == bp_overlay_event)
7322     {
7323       b->enable_state = bp_disabled;
7324       update_global_location_list (0);
7325       overlay_events_enabled = 0;
7326     }
7327 }
7328
7329 /* Set an active std::terminate breakpoint for each std::terminate
7330    master breakpoint.  */
7331 void
7332 set_std_terminate_breakpoint (void)
7333 {
7334   struct breakpoint *b, *b_tmp;
7335
7336   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7337     if (b->pspace == current_program_space
7338         && b->type == bp_std_terminate_master)
7339       {
7340         momentary_breakpoint_from_master (b, bp_std_terminate,
7341                                           &momentary_breakpoint_ops);
7342       }
7343 }
7344
7345 /* Delete all the std::terminate breakpoints.  */
7346 void
7347 delete_std_terminate_breakpoint (void)
7348 {
7349   struct breakpoint *b, *b_tmp;
7350
7351   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7352     if (b->type == bp_std_terminate)
7353       delete_breakpoint (b);
7354 }
7355
7356 struct breakpoint *
7357 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7358 {
7359   struct breakpoint *b;
7360
7361   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7362                                   &internal_breakpoint_ops);
7363
7364   b->enable_state = bp_enabled;
7365   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7366   b->addr_string
7367     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7368
7369   update_global_location_list_nothrow (1);
7370
7371   return b;
7372 }
7373
7374 void
7375 remove_thread_event_breakpoints (void)
7376 {
7377   struct breakpoint *b, *b_tmp;
7378
7379   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7380     if (b->type == bp_thread_event
7381         && b->loc->pspace == current_program_space)
7382       delete_breakpoint (b);
7383 }
7384
7385 struct lang_and_radix
7386   {
7387     enum language lang;
7388     int radix;
7389   };
7390
7391 /* Create a breakpoint for JIT code registration and unregistration.  */
7392
7393 struct breakpoint *
7394 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7395 {
7396   struct breakpoint *b;
7397
7398   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7399                                   &internal_breakpoint_ops);
7400   update_global_location_list_nothrow (1);
7401   return b;
7402 }
7403
7404 /* Remove JIT code registration and unregistration breakpoint(s).  */
7405
7406 void
7407 remove_jit_event_breakpoints (void)
7408 {
7409   struct breakpoint *b, *b_tmp;
7410
7411   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7412     if (b->type == bp_jit_event
7413         && b->loc->pspace == current_program_space)
7414       delete_breakpoint (b);
7415 }
7416
7417 void
7418 remove_solib_event_breakpoints (void)
7419 {
7420   struct breakpoint *b, *b_tmp;
7421
7422   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7423     if (b->type == bp_shlib_event
7424         && b->loc->pspace == current_program_space)
7425       delete_breakpoint (b);
7426 }
7427
7428 struct breakpoint *
7429 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7430 {
7431   struct breakpoint *b;
7432
7433   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7434                                   &internal_breakpoint_ops);
7435   update_global_location_list_nothrow (1);
7436   return b;
7437 }
7438
7439 /* Disable any breakpoints that are on code in shared libraries.  Only
7440    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7441
7442 void
7443 disable_breakpoints_in_shlibs (void)
7444 {
7445   struct bp_location *loc, **locp_tmp;
7446
7447   ALL_BP_LOCATIONS (loc, locp_tmp)
7448   {
7449     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7450     struct breakpoint *b = loc->owner;
7451
7452     /* We apply the check to all breakpoints, including disabled for
7453        those with loc->duplicate set.  This is so that when breakpoint
7454        becomes enabled, or the duplicate is removed, gdb will try to
7455        insert all breakpoints.  If we don't set shlib_disabled here,
7456        we'll try to insert those breakpoints and fail.  */
7457     if (((b->type == bp_breakpoint)
7458          || (b->type == bp_jit_event)
7459          || (b->type == bp_hardware_breakpoint)
7460          || (is_tracepoint (b)))
7461         && loc->pspace == current_program_space
7462         && !loc->shlib_disabled
7463         && solib_name_from_address (loc->pspace, loc->address)
7464         )
7465       {
7466         loc->shlib_disabled = 1;
7467       }
7468   }
7469 }
7470
7471 /* Disable any breakpoints and tracepoints that are in an unloaded shared
7472    library.  Only apply to enabled breakpoints, disabled ones can just stay
7473    disabled.  */
7474
7475 static void
7476 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7477 {
7478   struct bp_location *loc, **locp_tmp;
7479   int disabled_shlib_breaks = 0;
7480
7481   /* SunOS a.out shared libraries are always mapped, so do not
7482      disable breakpoints; they will only be reported as unloaded
7483      through clear_solib when GDB discards its shared library
7484      list.  See clear_solib for more information.  */
7485   if (exec_bfd != NULL
7486       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7487     return;
7488
7489   ALL_BP_LOCATIONS (loc, locp_tmp)
7490   {
7491     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7492     struct breakpoint *b = loc->owner;
7493
7494     if (solib->pspace == loc->pspace
7495         && !loc->shlib_disabled
7496         && (((b->type == bp_breakpoint
7497               || b->type == bp_jit_event
7498               || b->type == bp_hardware_breakpoint)
7499              && (loc->loc_type == bp_loc_hardware_breakpoint
7500                  || loc->loc_type == bp_loc_software_breakpoint))
7501             || is_tracepoint (b))
7502         && solib_contains_address_p (solib, loc->address))
7503       {
7504         loc->shlib_disabled = 1;
7505         /* At this point, we cannot rely on remove_breakpoint
7506            succeeding so we must mark the breakpoint as not inserted
7507            to prevent future errors occurring in remove_breakpoints.  */
7508         loc->inserted = 0;
7509
7510         /* This may cause duplicate notifications for the same breakpoint.  */
7511         observer_notify_breakpoint_modified (b);
7512
7513         if (!disabled_shlib_breaks)
7514           {
7515             target_terminal_ours_for_output ();
7516             warning (_("Temporarily disabling breakpoints "
7517                        "for unloaded shared library \"%s\""),
7518                      solib->so_name);
7519           }
7520         disabled_shlib_breaks = 1;
7521       }
7522   }
7523 }
7524
7525 /* FORK & VFORK catchpoints.  */
7526
7527 /* An instance of this type is used to represent a fork or vfork
7528    catchpoint.  It includes a "struct breakpoint" as a kind of base
7529    class; users downcast to "struct breakpoint *" when needed.  A
7530    breakpoint is really of this type iff its ops pointer points to
7531    CATCH_FORK_BREAKPOINT_OPS.  */
7532
7533 struct fork_catchpoint
7534 {
7535   /* The base class.  */
7536   struct breakpoint base;
7537
7538   /* Process id of a child process whose forking triggered this
7539      catchpoint.  This field is only valid immediately after this
7540      catchpoint has triggered.  */
7541   ptid_t forked_inferior_pid;
7542 };
7543
7544 /* Implement the "insert" breakpoint_ops method for fork
7545    catchpoints.  */
7546
7547 static int
7548 insert_catch_fork (struct bp_location *bl)
7549 {
7550   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7551 }
7552
7553 /* Implement the "remove" breakpoint_ops method for fork
7554    catchpoints.  */
7555
7556 static int
7557 remove_catch_fork (struct bp_location *bl)
7558 {
7559   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7560 }
7561
7562 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7563    catchpoints.  */
7564
7565 static int
7566 breakpoint_hit_catch_fork (const struct bp_location *bl,
7567                            struct address_space *aspace, CORE_ADDR bp_addr,
7568                            const struct target_waitstatus *ws)
7569 {
7570   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7571
7572   if (ws->kind != TARGET_WAITKIND_FORKED)
7573     return 0;
7574
7575   c->forked_inferior_pid = ws->value.related_pid;
7576   return 1;
7577 }
7578
7579 /* Implement the "print_it" breakpoint_ops method for fork
7580    catchpoints.  */
7581
7582 static enum print_stop_action
7583 print_it_catch_fork (bpstat bs)
7584 {
7585   struct ui_out *uiout = current_uiout;
7586   struct breakpoint *b = bs->breakpoint_at;
7587   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7588
7589   annotate_catchpoint (b->number);
7590   if (b->disposition == disp_del)
7591     ui_out_text (uiout, "\nTemporary catchpoint ");
7592   else
7593     ui_out_text (uiout, "\nCatchpoint ");
7594   if (ui_out_is_mi_like_p (uiout))
7595     {
7596       ui_out_field_string (uiout, "reason",
7597                            async_reason_lookup (EXEC_ASYNC_FORK));
7598       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7599     }
7600   ui_out_field_int (uiout, "bkptno", b->number);
7601   ui_out_text (uiout, " (forked process ");
7602   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7603   ui_out_text (uiout, "), ");
7604   return PRINT_SRC_AND_LOC;
7605 }
7606
7607 /* Implement the "print_one" breakpoint_ops method for fork
7608    catchpoints.  */
7609
7610 static void
7611 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7612 {
7613   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7614   struct value_print_options opts;
7615   struct ui_out *uiout = current_uiout;
7616
7617   get_user_print_options (&opts);
7618
7619   /* Field 4, the address, is omitted (which makes the columns not
7620      line up too nicely with the headers, but the effect is relatively
7621      readable).  */
7622   if (opts.addressprint)
7623     ui_out_field_skip (uiout, "addr");
7624   annotate_field (5);
7625   ui_out_text (uiout, "fork");
7626   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7627     {
7628       ui_out_text (uiout, ", process ");
7629       ui_out_field_int (uiout, "what",
7630                         ptid_get_pid (c->forked_inferior_pid));
7631       ui_out_spaces (uiout, 1);
7632     }
7633
7634   if (ui_out_is_mi_like_p (uiout))
7635     ui_out_field_string (uiout, "catch-type", "fork");
7636 }
7637
7638 /* Implement the "print_mention" breakpoint_ops method for fork
7639    catchpoints.  */
7640
7641 static void
7642 print_mention_catch_fork (struct breakpoint *b)
7643 {
7644   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7645 }
7646
7647 /* Implement the "print_recreate" breakpoint_ops method for fork
7648    catchpoints.  */
7649
7650 static void
7651 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7652 {
7653   fprintf_unfiltered (fp, "catch fork");
7654   print_recreate_thread (b, fp);
7655 }
7656
7657 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7658
7659 static struct breakpoint_ops catch_fork_breakpoint_ops;
7660
7661 /* Implement the "insert" breakpoint_ops method for vfork
7662    catchpoints.  */
7663
7664 static int
7665 insert_catch_vfork (struct bp_location *bl)
7666 {
7667   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7668 }
7669
7670 /* Implement the "remove" breakpoint_ops method for vfork
7671    catchpoints.  */
7672
7673 static int
7674 remove_catch_vfork (struct bp_location *bl)
7675 {
7676   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7677 }
7678
7679 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7680    catchpoints.  */
7681
7682 static int
7683 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7684                             struct address_space *aspace, CORE_ADDR bp_addr,
7685                             const struct target_waitstatus *ws)
7686 {
7687   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7688
7689   if (ws->kind != TARGET_WAITKIND_VFORKED)
7690     return 0;
7691
7692   c->forked_inferior_pid = ws->value.related_pid;
7693   return 1;
7694 }
7695
7696 /* Implement the "print_it" breakpoint_ops method for vfork
7697    catchpoints.  */
7698
7699 static enum print_stop_action
7700 print_it_catch_vfork (bpstat bs)
7701 {
7702   struct ui_out *uiout = current_uiout;
7703   struct breakpoint *b = bs->breakpoint_at;
7704   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7705
7706   annotate_catchpoint (b->number);
7707   if (b->disposition == disp_del)
7708     ui_out_text (uiout, "\nTemporary catchpoint ");
7709   else
7710     ui_out_text (uiout, "\nCatchpoint ");
7711   if (ui_out_is_mi_like_p (uiout))
7712     {
7713       ui_out_field_string (uiout, "reason",
7714                            async_reason_lookup (EXEC_ASYNC_VFORK));
7715       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7716     }
7717   ui_out_field_int (uiout, "bkptno", b->number);
7718   ui_out_text (uiout, " (vforked process ");
7719   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7720   ui_out_text (uiout, "), ");
7721   return PRINT_SRC_AND_LOC;
7722 }
7723
7724 /* Implement the "print_one" breakpoint_ops method for vfork
7725    catchpoints.  */
7726
7727 static void
7728 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7729 {
7730   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7731   struct value_print_options opts;
7732   struct ui_out *uiout = current_uiout;
7733
7734   get_user_print_options (&opts);
7735   /* Field 4, the address, is omitted (which makes the columns not
7736      line up too nicely with the headers, but the effect is relatively
7737      readable).  */
7738   if (opts.addressprint)
7739     ui_out_field_skip (uiout, "addr");
7740   annotate_field (5);
7741   ui_out_text (uiout, "vfork");
7742   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7743     {
7744       ui_out_text (uiout, ", process ");
7745       ui_out_field_int (uiout, "what",
7746                         ptid_get_pid (c->forked_inferior_pid));
7747       ui_out_spaces (uiout, 1);
7748     }
7749
7750   if (ui_out_is_mi_like_p (uiout))
7751     ui_out_field_string (uiout, "catch-type", "vfork");
7752 }
7753
7754 /* Implement the "print_mention" breakpoint_ops method for vfork
7755    catchpoints.  */
7756
7757 static void
7758 print_mention_catch_vfork (struct breakpoint *b)
7759 {
7760   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7761 }
7762
7763 /* Implement the "print_recreate" breakpoint_ops method for vfork
7764    catchpoints.  */
7765
7766 static void
7767 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7768 {
7769   fprintf_unfiltered (fp, "catch vfork");
7770   print_recreate_thread (b, fp);
7771 }
7772
7773 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7774
7775 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7776
7777 /* An instance of this type is used to represent an solib catchpoint.
7778    It includes a "struct breakpoint" as a kind of base class; users
7779    downcast to "struct breakpoint *" when needed.  A breakpoint is
7780    really of this type iff its ops pointer points to
7781    CATCH_SOLIB_BREAKPOINT_OPS.  */
7782
7783 struct solib_catchpoint
7784 {
7785   /* The base class.  */
7786   struct breakpoint base;
7787
7788   /* True for "catch load", false for "catch unload".  */
7789   unsigned char is_load;
7790
7791   /* Regular expression to match, if any.  COMPILED is only valid when
7792      REGEX is non-NULL.  */
7793   char *regex;
7794   regex_t compiled;
7795 };
7796
7797 static void
7798 dtor_catch_solib (struct breakpoint *b)
7799 {
7800   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7801
7802   if (self->regex)
7803     regfree (&self->compiled);
7804   xfree (self->regex);
7805
7806   base_breakpoint_ops.dtor (b);
7807 }
7808
7809 static int
7810 insert_catch_solib (struct bp_location *ignore)
7811 {
7812   return 0;
7813 }
7814
7815 static int
7816 remove_catch_solib (struct bp_location *ignore)
7817 {
7818   return 0;
7819 }
7820
7821 static int
7822 breakpoint_hit_catch_solib (const struct bp_location *bl,
7823                             struct address_space *aspace,
7824                             CORE_ADDR bp_addr,
7825                             const struct target_waitstatus *ws)
7826 {
7827   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7828   struct breakpoint *other;
7829
7830   if (ws->kind == TARGET_WAITKIND_LOADED)
7831     return 1;
7832
7833   ALL_BREAKPOINTS (other)
7834   {
7835     struct bp_location *other_bl;
7836
7837     if (other == bl->owner)
7838       continue;
7839
7840     if (other->type != bp_shlib_event)
7841       continue;
7842
7843     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7844       continue;
7845
7846     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7847       {
7848         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7849           return 1;
7850       }
7851   }
7852
7853   return 0;
7854 }
7855
7856 static void
7857 check_status_catch_solib (struct bpstats *bs)
7858 {
7859   struct solib_catchpoint *self
7860     = (struct solib_catchpoint *) bs->breakpoint_at;
7861   int ix;
7862
7863   if (self->is_load)
7864     {
7865       struct so_list *iter;
7866
7867       for (ix = 0;
7868            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7869                         ix, iter);
7870            ++ix)
7871         {
7872           if (!self->regex
7873               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7874             return;
7875         }
7876     }
7877   else
7878     {
7879       char *iter;
7880
7881       for (ix = 0;
7882            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7883                         ix, iter);
7884            ++ix)
7885         {
7886           if (!self->regex
7887               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7888             return;
7889         }
7890     }
7891
7892   bs->stop = 0;
7893   bs->print_it = print_it_noop;
7894 }
7895
7896 static enum print_stop_action
7897 print_it_catch_solib (bpstat bs)
7898 {
7899   struct breakpoint *b = bs->breakpoint_at;
7900   struct ui_out *uiout = current_uiout;
7901
7902   annotate_catchpoint (b->number);
7903   if (b->disposition == disp_del)
7904     ui_out_text (uiout, "\nTemporary catchpoint ");
7905   else
7906     ui_out_text (uiout, "\nCatchpoint ");
7907   ui_out_field_int (uiout, "bkptno", b->number);
7908   ui_out_text (uiout, "\n");
7909   if (ui_out_is_mi_like_p (uiout))
7910     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7911   print_solib_event (1);
7912   return PRINT_SRC_AND_LOC;
7913 }
7914
7915 static void
7916 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7917 {
7918   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7919   struct value_print_options opts;
7920   struct ui_out *uiout = current_uiout;
7921   char *msg;
7922
7923   get_user_print_options (&opts);
7924   /* Field 4, the address, is omitted (which makes the columns not
7925      line up too nicely with the headers, but the effect is relatively
7926      readable).  */
7927   if (opts.addressprint)
7928     {
7929       annotate_field (4);
7930       ui_out_field_skip (uiout, "addr");
7931     }
7932
7933   annotate_field (5);
7934   if (self->is_load)
7935     {
7936       if (self->regex)
7937         msg = xstrprintf (_("load of library matching %s"), self->regex);
7938       else
7939         msg = xstrdup (_("load of library"));
7940     }
7941   else
7942     {
7943       if (self->regex)
7944         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7945       else
7946         msg = xstrdup (_("unload of library"));
7947     }
7948   ui_out_field_string (uiout, "what", msg);
7949   xfree (msg);
7950
7951   if (ui_out_is_mi_like_p (uiout))
7952     ui_out_field_string (uiout, "catch-type",
7953                          self->is_load ? "load" : "unload");
7954 }
7955
7956 static void
7957 print_mention_catch_solib (struct breakpoint *b)
7958 {
7959   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7960
7961   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7962                    self->is_load ? "load" : "unload");
7963 }
7964
7965 static void
7966 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7967 {
7968   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7969
7970   fprintf_unfiltered (fp, "%s %s",
7971                       b->disposition == disp_del ? "tcatch" : "catch",
7972                       self->is_load ? "load" : "unload");
7973   if (self->regex)
7974     fprintf_unfiltered (fp, " %s", self->regex);
7975   fprintf_unfiltered (fp, "\n");
7976 }
7977
7978 static struct breakpoint_ops catch_solib_breakpoint_ops;
7979
7980 /* Shared helper function (MI and CLI) for creating and installing
7981    a shared object event catchpoint.  If IS_LOAD is non-zero then
7982    the events to be caught are load events, otherwise they are
7983    unload events.  If IS_TEMP is non-zero the catchpoint is a
7984    temporary one.  If ENABLED is non-zero the catchpoint is
7985    created in an enabled state.  */
7986
7987 void
7988 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
7989 {
7990   struct solib_catchpoint *c;
7991   struct gdbarch *gdbarch = get_current_arch ();
7992   struct cleanup *cleanup;
7993
7994   if (!arg)
7995     arg = "";
7996   arg = skip_spaces (arg);
7997
7998   c = XCNEW (struct solib_catchpoint);
7999   cleanup = make_cleanup (xfree, c);
8000
8001   if (*arg != '\0')
8002     {
8003       int errcode;
8004
8005       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8006       if (errcode != 0)
8007         {
8008           char *err = get_regcomp_error (errcode, &c->compiled);
8009
8010           make_cleanup (xfree, err);
8011           error (_("Invalid regexp (%s): %s"), err, arg);
8012         }
8013       c->regex = xstrdup (arg);
8014     }
8015
8016   c->is_load = is_load;
8017   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8018                    &catch_solib_breakpoint_ops);
8019
8020   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8021
8022   discard_cleanups (cleanup);
8023   install_breakpoint (0, &c->base, 1);
8024 }
8025
8026 /* A helper function that does all the work for "catch load" and
8027    "catch unload".  */
8028
8029 static void
8030 catch_load_or_unload (char *arg, int from_tty, int is_load,
8031                       struct cmd_list_element *command)
8032 {
8033   int tempflag;
8034   const int enabled = 1;
8035
8036   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8037
8038   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8039 }
8040
8041 static void
8042 catch_load_command_1 (char *arg, int from_tty,
8043                       struct cmd_list_element *command)
8044 {
8045   catch_load_or_unload (arg, from_tty, 1, command);
8046 }
8047
8048 static void
8049 catch_unload_command_1 (char *arg, int from_tty,
8050                         struct cmd_list_element *command)
8051 {
8052   catch_load_or_unload (arg, from_tty, 0, command);
8053 }
8054
8055 /* An instance of this type is used to represent a syscall catchpoint.
8056    It includes a "struct breakpoint" as a kind of base class; users
8057    downcast to "struct breakpoint *" when needed.  A breakpoint is
8058    really of this type iff its ops pointer points to
8059    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8060
8061 struct syscall_catchpoint
8062 {
8063   /* The base class.  */
8064   struct breakpoint base;
8065
8066   /* Syscall numbers used for the 'catch syscall' feature.  If no
8067      syscall has been specified for filtering, its value is NULL.
8068      Otherwise, it holds a list of all syscalls to be caught.  The
8069      list elements are allocated with xmalloc.  */
8070   VEC(int) *syscalls_to_be_caught;
8071 };
8072
8073 /* Implement the "dtor" breakpoint_ops method for syscall
8074    catchpoints.  */
8075
8076 static void
8077 dtor_catch_syscall (struct breakpoint *b)
8078 {
8079   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8080
8081   VEC_free (int, c->syscalls_to_be_caught);
8082
8083   base_breakpoint_ops.dtor (b);
8084 }
8085
8086 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8087
8088 struct catch_syscall_inferior_data
8089 {
8090   /* We keep a count of the number of times the user has requested a
8091      particular syscall to be tracked, and pass this information to the
8092      target.  This lets capable targets implement filtering directly.  */
8093
8094   /* Number of times that "any" syscall is requested.  */
8095   int any_syscall_count;
8096
8097   /* Count of each system call.  */
8098   VEC(int) *syscalls_counts;
8099
8100   /* This counts all syscall catch requests, so we can readily determine
8101      if any catching is necessary.  */
8102   int total_syscalls_count;
8103 };
8104
8105 static struct catch_syscall_inferior_data*
8106 get_catch_syscall_inferior_data (struct inferior *inf)
8107 {
8108   struct catch_syscall_inferior_data *inf_data;
8109
8110   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8111   if (inf_data == NULL)
8112     {
8113       inf_data = XZALLOC (struct catch_syscall_inferior_data);
8114       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8115     }
8116
8117   return inf_data;
8118 }
8119
8120 static void
8121 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8122 {
8123   xfree (arg);
8124 }
8125
8126
8127 /* Implement the "insert" breakpoint_ops method for syscall
8128    catchpoints.  */
8129
8130 static int
8131 insert_catch_syscall (struct bp_location *bl)
8132 {
8133   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8134   struct inferior *inf = current_inferior ();
8135   struct catch_syscall_inferior_data *inf_data
8136     = get_catch_syscall_inferior_data (inf);
8137
8138   ++inf_data->total_syscalls_count;
8139   if (!c->syscalls_to_be_caught)
8140     ++inf_data->any_syscall_count;
8141   else
8142     {
8143       int i, iter;
8144
8145       for (i = 0;
8146            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8147            i++)
8148         {
8149           int elem;
8150
8151           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8152             {
8153               int old_size = VEC_length (int, inf_data->syscalls_counts);
8154               uintptr_t vec_addr_offset
8155                 = old_size * ((uintptr_t) sizeof (int));
8156               uintptr_t vec_addr;
8157               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8158               vec_addr = ((uintptr_t) VEC_address (int,
8159                                                   inf_data->syscalls_counts)
8160                           + vec_addr_offset);
8161               memset ((void *) vec_addr, 0,
8162                       (iter + 1 - old_size) * sizeof (int));
8163             }
8164           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8165           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8166         }
8167     }
8168
8169   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8170                                         inf_data->total_syscalls_count != 0,
8171                                         inf_data->any_syscall_count,
8172                                         VEC_length (int,
8173                                                     inf_data->syscalls_counts),
8174                                         VEC_address (int,
8175                                                      inf_data->syscalls_counts));
8176 }
8177
8178 /* Implement the "remove" breakpoint_ops method for syscall
8179    catchpoints.  */
8180
8181 static int
8182 remove_catch_syscall (struct bp_location *bl)
8183 {
8184   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8185   struct inferior *inf = current_inferior ();
8186   struct catch_syscall_inferior_data *inf_data
8187     = get_catch_syscall_inferior_data (inf);
8188
8189   --inf_data->total_syscalls_count;
8190   if (!c->syscalls_to_be_caught)
8191     --inf_data->any_syscall_count;
8192   else
8193     {
8194       int i, iter;
8195
8196       for (i = 0;
8197            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8198            i++)
8199         {
8200           int elem;
8201           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8202             /* Shouldn't happen.  */
8203             continue;
8204           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8205           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8206         }
8207     }
8208
8209   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8210                                         inf_data->total_syscalls_count != 0,
8211                                         inf_data->any_syscall_count,
8212                                         VEC_length (int,
8213                                                     inf_data->syscalls_counts),
8214                                         VEC_address (int,
8215                                                      inf_data->syscalls_counts));
8216 }
8217
8218 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8219    catchpoints.  */
8220
8221 static int
8222 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8223                               struct address_space *aspace, CORE_ADDR bp_addr,
8224                               const struct target_waitstatus *ws)
8225 {
8226   /* We must check if we are catching specific syscalls in this
8227      breakpoint.  If we are, then we must guarantee that the called
8228      syscall is the same syscall we are catching.  */
8229   int syscall_number = 0;
8230   const struct syscall_catchpoint *c
8231     = (const struct syscall_catchpoint *) bl->owner;
8232
8233   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8234       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8235     return 0;
8236
8237   syscall_number = ws->value.syscall_number;
8238
8239   /* Now, checking if the syscall is the same.  */
8240   if (c->syscalls_to_be_caught)
8241     {
8242       int i, iter;
8243
8244       for (i = 0;
8245            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8246            i++)
8247         if (syscall_number == iter)
8248           break;
8249       /* Not the same.  */
8250       if (!iter)
8251         return 0;
8252     }
8253
8254   return 1;
8255 }
8256
8257 /* Implement the "print_it" breakpoint_ops method for syscall
8258    catchpoints.  */
8259
8260 static enum print_stop_action
8261 print_it_catch_syscall (bpstat bs)
8262 {
8263   struct ui_out *uiout = current_uiout;
8264   struct breakpoint *b = bs->breakpoint_at;
8265   /* These are needed because we want to know in which state a
8266      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8267      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8268      must print "called syscall" or "returned from syscall".  */
8269   ptid_t ptid;
8270   struct target_waitstatus last;
8271   struct syscall s;
8272
8273   get_last_target_status (&ptid, &last);
8274
8275   get_syscall_by_number (last.value.syscall_number, &s);
8276
8277   annotate_catchpoint (b->number);
8278
8279   if (b->disposition == disp_del)
8280     ui_out_text (uiout, "\nTemporary catchpoint ");
8281   else
8282     ui_out_text (uiout, "\nCatchpoint ");
8283   if (ui_out_is_mi_like_p (uiout))
8284     {
8285       ui_out_field_string (uiout, "reason",
8286                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8287                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8288                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8289       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8290     }
8291   ui_out_field_int (uiout, "bkptno", b->number);
8292
8293   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8294     ui_out_text (uiout, " (call to syscall ");
8295   else
8296     ui_out_text (uiout, " (returned from syscall ");
8297
8298   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8299     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8300   if (s.name != NULL)
8301     ui_out_field_string (uiout, "syscall-name", s.name);
8302
8303   ui_out_text (uiout, "), ");
8304
8305   return PRINT_SRC_AND_LOC;
8306 }
8307
8308 /* Implement the "print_one" breakpoint_ops method for syscall
8309    catchpoints.  */
8310
8311 static void
8312 print_one_catch_syscall (struct breakpoint *b,
8313                          struct bp_location **last_loc)
8314 {
8315   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8316   struct value_print_options opts;
8317   struct ui_out *uiout = current_uiout;
8318
8319   get_user_print_options (&opts);
8320   /* Field 4, the address, is omitted (which makes the columns not
8321      line up too nicely with the headers, but the effect is relatively
8322      readable).  */
8323   if (opts.addressprint)
8324     ui_out_field_skip (uiout, "addr");
8325   annotate_field (5);
8326
8327   if (c->syscalls_to_be_caught
8328       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8329     ui_out_text (uiout, "syscalls \"");
8330   else
8331     ui_out_text (uiout, "syscall \"");
8332
8333   if (c->syscalls_to_be_caught)
8334     {
8335       int i, iter;
8336       char *text = xstrprintf ("%s", "");
8337
8338       for (i = 0;
8339            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8340            i++)
8341         {
8342           char *x = text;
8343           struct syscall s;
8344           get_syscall_by_number (iter, &s);
8345
8346           if (s.name != NULL)
8347             text = xstrprintf ("%s%s, ", text, s.name);
8348           else
8349             text = xstrprintf ("%s%d, ", text, iter);
8350
8351           /* We have to xfree the last 'text' (now stored at 'x')
8352              because xstrprintf dynamically allocates new space for it
8353              on every call.  */
8354           xfree (x);
8355         }
8356       /* Remove the last comma.  */
8357       text[strlen (text) - 2] = '\0';
8358       ui_out_field_string (uiout, "what", text);
8359     }
8360   else
8361     ui_out_field_string (uiout, "what", "<any syscall>");
8362   ui_out_text (uiout, "\" ");
8363
8364   if (ui_out_is_mi_like_p (uiout))
8365     ui_out_field_string (uiout, "catch-type", "syscall");
8366 }
8367
8368 /* Implement the "print_mention" breakpoint_ops method for syscall
8369    catchpoints.  */
8370
8371 static void
8372 print_mention_catch_syscall (struct breakpoint *b)
8373 {
8374   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8375
8376   if (c->syscalls_to_be_caught)
8377     {
8378       int i, iter;
8379
8380       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8381         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8382       else
8383         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8384
8385       for (i = 0;
8386            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8387            i++)
8388         {
8389           struct syscall s;
8390           get_syscall_by_number (iter, &s);
8391
8392           if (s.name)
8393             printf_filtered (" '%s' [%d]", s.name, s.number);
8394           else
8395             printf_filtered (" %d", s.number);
8396         }
8397       printf_filtered (")");
8398     }
8399   else
8400     printf_filtered (_("Catchpoint %d (any syscall)"),
8401                      b->number);
8402 }
8403
8404 /* Implement the "print_recreate" breakpoint_ops method for syscall
8405    catchpoints.  */
8406
8407 static void
8408 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8409 {
8410   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8411
8412   fprintf_unfiltered (fp, "catch syscall");
8413
8414   if (c->syscalls_to_be_caught)
8415     {
8416       int i, iter;
8417
8418       for (i = 0;
8419            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8420            i++)
8421         {
8422           struct syscall s;
8423
8424           get_syscall_by_number (iter, &s);
8425           if (s.name)
8426             fprintf_unfiltered (fp, " %s", s.name);
8427           else
8428             fprintf_unfiltered (fp, " %d", s.number);
8429         }
8430     }
8431   print_recreate_thread (b, fp);
8432 }
8433
8434 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8435
8436 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8437
8438 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8439
8440 static int
8441 syscall_catchpoint_p (struct breakpoint *b)
8442 {
8443   return (b->ops == &catch_syscall_breakpoint_ops);
8444 }
8445
8446 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8447    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8448    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8449    the breakpoint_ops structure associated to the catchpoint.  */
8450
8451 void
8452 init_catchpoint (struct breakpoint *b,
8453                  struct gdbarch *gdbarch, int tempflag,
8454                  char *cond_string,
8455                  const struct breakpoint_ops *ops)
8456 {
8457   struct symtab_and_line sal;
8458
8459   init_sal (&sal);
8460   sal.pspace = current_program_space;
8461
8462   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8463
8464   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8465   b->disposition = tempflag ? disp_del : disp_donttouch;
8466 }
8467
8468 void
8469 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8470 {
8471   add_to_breakpoint_chain (b);
8472   set_breakpoint_number (internal, b);
8473   if (is_tracepoint (b))
8474     set_tracepoint_count (breakpoint_count);
8475   if (!internal)
8476     mention (b);
8477   observer_notify_breakpoint_created (b);
8478
8479   if (update_gll)
8480     update_global_location_list (1);
8481 }
8482
8483 static void
8484 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8485                                     int tempflag, char *cond_string,
8486                                     const struct breakpoint_ops *ops)
8487 {
8488   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8489
8490   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8491
8492   c->forked_inferior_pid = null_ptid;
8493
8494   install_breakpoint (0, &c->base, 1);
8495 }
8496
8497 /* Exec catchpoints.  */
8498
8499 /* An instance of this type is used to represent an exec catchpoint.
8500    It includes a "struct breakpoint" as a kind of base class; users
8501    downcast to "struct breakpoint *" when needed.  A breakpoint is
8502    really of this type iff its ops pointer points to
8503    CATCH_EXEC_BREAKPOINT_OPS.  */
8504
8505 struct exec_catchpoint
8506 {
8507   /* The base class.  */
8508   struct breakpoint base;
8509
8510   /* Filename of a program whose exec triggered this catchpoint.
8511      This field is only valid immediately after this catchpoint has
8512      triggered.  */
8513   char *exec_pathname;
8514 };
8515
8516 /* Implement the "dtor" breakpoint_ops method for exec
8517    catchpoints.  */
8518
8519 static void
8520 dtor_catch_exec (struct breakpoint *b)
8521 {
8522   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8523
8524   xfree (c->exec_pathname);
8525
8526   base_breakpoint_ops.dtor (b);
8527 }
8528
8529 static int
8530 insert_catch_exec (struct bp_location *bl)
8531 {
8532   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8533 }
8534
8535 static int
8536 remove_catch_exec (struct bp_location *bl)
8537 {
8538   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8539 }
8540
8541 static int
8542 breakpoint_hit_catch_exec (const struct bp_location *bl,
8543                            struct address_space *aspace, CORE_ADDR bp_addr,
8544                            const struct target_waitstatus *ws)
8545 {
8546   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8547
8548   if (ws->kind != TARGET_WAITKIND_EXECD)
8549     return 0;
8550
8551   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8552   return 1;
8553 }
8554
8555 static enum print_stop_action
8556 print_it_catch_exec (bpstat bs)
8557 {
8558   struct ui_out *uiout = current_uiout;
8559   struct breakpoint *b = bs->breakpoint_at;
8560   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8561
8562   annotate_catchpoint (b->number);
8563   if (b->disposition == disp_del)
8564     ui_out_text (uiout, "\nTemporary catchpoint ");
8565   else
8566     ui_out_text (uiout, "\nCatchpoint ");
8567   if (ui_out_is_mi_like_p (uiout))
8568     {
8569       ui_out_field_string (uiout, "reason",
8570                            async_reason_lookup (EXEC_ASYNC_EXEC));
8571       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8572     }
8573   ui_out_field_int (uiout, "bkptno", b->number);
8574   ui_out_text (uiout, " (exec'd ");
8575   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8576   ui_out_text (uiout, "), ");
8577
8578   return PRINT_SRC_AND_LOC;
8579 }
8580
8581 static void
8582 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8583 {
8584   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8585   struct value_print_options opts;
8586   struct ui_out *uiout = current_uiout;
8587
8588   get_user_print_options (&opts);
8589
8590   /* Field 4, the address, is omitted (which makes the columns
8591      not line up too nicely with the headers, but the effect
8592      is relatively readable).  */
8593   if (opts.addressprint)
8594     ui_out_field_skip (uiout, "addr");
8595   annotate_field (5);
8596   ui_out_text (uiout, "exec");
8597   if (c->exec_pathname != NULL)
8598     {
8599       ui_out_text (uiout, ", program \"");
8600       ui_out_field_string (uiout, "what", c->exec_pathname);
8601       ui_out_text (uiout, "\" ");
8602     }
8603
8604   if (ui_out_is_mi_like_p (uiout))
8605     ui_out_field_string (uiout, "catch-type", "exec");
8606 }
8607
8608 static void
8609 print_mention_catch_exec (struct breakpoint *b)
8610 {
8611   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8612 }
8613
8614 /* Implement the "print_recreate" breakpoint_ops method for exec
8615    catchpoints.  */
8616
8617 static void
8618 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8619 {
8620   fprintf_unfiltered (fp, "catch exec");
8621   print_recreate_thread (b, fp);
8622 }
8623
8624 static struct breakpoint_ops catch_exec_breakpoint_ops;
8625
8626 static void
8627 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8628                                  const struct breakpoint_ops *ops)
8629 {
8630   struct syscall_catchpoint *c;
8631   struct gdbarch *gdbarch = get_current_arch ();
8632
8633   c = XNEW (struct syscall_catchpoint);
8634   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8635   c->syscalls_to_be_caught = filter;
8636
8637   install_breakpoint (0, &c->base, 1);
8638 }
8639
8640 static int
8641 hw_breakpoint_used_count (void)
8642 {
8643   int i = 0;
8644   struct breakpoint *b;
8645   struct bp_location *bl;
8646
8647   ALL_BREAKPOINTS (b)
8648   {
8649     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8650       for (bl = b->loc; bl; bl = bl->next)
8651         {
8652           /* Special types of hardware breakpoints may use more than
8653              one register.  */
8654           i += b->ops->resources_needed (bl);
8655         }
8656   }
8657
8658   return i;
8659 }
8660
8661 /* Returns the resources B would use if it were a hardware
8662    watchpoint.  */
8663
8664 static int
8665 hw_watchpoint_use_count (struct breakpoint *b)
8666 {
8667   int i = 0;
8668   struct bp_location *bl;
8669
8670   if (!breakpoint_enabled (b))
8671     return 0;
8672
8673   for (bl = b->loc; bl; bl = bl->next)
8674     {
8675       /* Special types of hardware watchpoints may use more than
8676          one register.  */
8677       i += b->ops->resources_needed (bl);
8678     }
8679
8680   return i;
8681 }
8682
8683 /* Returns the sum the used resources of all hardware watchpoints of
8684    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8685    the sum of the used resources of all hardware watchpoints of other
8686    types _not_ TYPE.  */
8687
8688 static int
8689 hw_watchpoint_used_count_others (struct breakpoint *except,
8690                                  enum bptype type, int *other_type_used)
8691 {
8692   int i = 0;
8693   struct breakpoint *b;
8694
8695   *other_type_used = 0;
8696   ALL_BREAKPOINTS (b)
8697     {
8698       if (b == except)
8699         continue;
8700       if (!breakpoint_enabled (b))
8701         continue;
8702
8703       if (b->type == type)
8704         i += hw_watchpoint_use_count (b);
8705       else if (is_hardware_watchpoint (b))
8706         *other_type_used = 1;
8707     }
8708
8709   return i;
8710 }
8711
8712 void
8713 disable_watchpoints_before_interactive_call_start (void)
8714 {
8715   struct breakpoint *b;
8716
8717   ALL_BREAKPOINTS (b)
8718   {
8719     if (is_watchpoint (b) && breakpoint_enabled (b))
8720       {
8721         b->enable_state = bp_call_disabled;
8722         update_global_location_list (0);
8723       }
8724   }
8725 }
8726
8727 void
8728 enable_watchpoints_after_interactive_call_stop (void)
8729 {
8730   struct breakpoint *b;
8731
8732   ALL_BREAKPOINTS (b)
8733   {
8734     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8735       {
8736         b->enable_state = bp_enabled;
8737         update_global_location_list (1);
8738       }
8739   }
8740 }
8741
8742 void
8743 disable_breakpoints_before_startup (void)
8744 {
8745   current_program_space->executing_startup = 1;
8746   update_global_location_list (0);
8747 }
8748
8749 void
8750 enable_breakpoints_after_startup (void)
8751 {
8752   current_program_space->executing_startup = 0;
8753   breakpoint_re_set ();
8754 }
8755
8756
8757 /* Set a breakpoint that will evaporate an end of command
8758    at address specified by SAL.
8759    Restrict it to frame FRAME if FRAME is nonzero.  */
8760
8761 struct breakpoint *
8762 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8763                           struct frame_id frame_id, enum bptype type)
8764 {
8765   struct breakpoint *b;
8766
8767   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8768      tail-called one.  */
8769   gdb_assert (!frame_id_artificial_p (frame_id));
8770
8771   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8772   b->enable_state = bp_enabled;
8773   b->disposition = disp_donttouch;
8774   b->frame_id = frame_id;
8775
8776   /* If we're debugging a multi-threaded program, then we want
8777      momentary breakpoints to be active in only a single thread of
8778      control.  */
8779   if (in_thread_list (inferior_ptid))
8780     b->thread = pid_to_thread_id (inferior_ptid);
8781
8782   update_global_location_list_nothrow (1);
8783
8784   return b;
8785 }
8786
8787 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8788    The new breakpoint will have type TYPE, and use OPS as it
8789    breakpoint_ops.  */
8790
8791 static struct breakpoint *
8792 momentary_breakpoint_from_master (struct breakpoint *orig,
8793                                   enum bptype type,
8794                                   const struct breakpoint_ops *ops)
8795 {
8796   struct breakpoint *copy;
8797
8798   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8799   copy->loc = allocate_bp_location (copy);
8800   set_breakpoint_location_function (copy->loc, 1);
8801
8802   copy->loc->gdbarch = orig->loc->gdbarch;
8803   copy->loc->requested_address = orig->loc->requested_address;
8804   copy->loc->address = orig->loc->address;
8805   copy->loc->section = orig->loc->section;
8806   copy->loc->pspace = orig->loc->pspace;
8807   copy->loc->probe = orig->loc->probe;
8808   copy->loc->line_number = orig->loc->line_number;
8809   copy->loc->symtab = orig->loc->symtab;
8810   copy->frame_id = orig->frame_id;
8811   copy->thread = orig->thread;
8812   copy->pspace = orig->pspace;
8813
8814   copy->enable_state = bp_enabled;
8815   copy->disposition = disp_donttouch;
8816   copy->number = internal_breakpoint_number--;
8817
8818   update_global_location_list_nothrow (0);
8819   return copy;
8820 }
8821
8822 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8823    ORIG is NULL.  */
8824
8825 struct breakpoint *
8826 clone_momentary_breakpoint (struct breakpoint *orig)
8827 {
8828   /* If there's nothing to clone, then return nothing.  */
8829   if (orig == NULL)
8830     return NULL;
8831
8832   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8833 }
8834
8835 struct breakpoint *
8836 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8837                                 enum bptype type)
8838 {
8839   struct symtab_and_line sal;
8840
8841   sal = find_pc_line (pc, 0);
8842   sal.pc = pc;
8843   sal.section = find_pc_overlay (pc);
8844   sal.explicit_pc = 1;
8845
8846   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8847 }
8848 \f
8849
8850 /* Tell the user we have just set a breakpoint B.  */
8851
8852 static void
8853 mention (struct breakpoint *b)
8854 {
8855   b->ops->print_mention (b);
8856   if (ui_out_is_mi_like_p (current_uiout))
8857     return;
8858   printf_filtered ("\n");
8859 }
8860 \f
8861
8862 static struct bp_location *
8863 add_location_to_breakpoint (struct breakpoint *b,
8864                             const struct symtab_and_line *sal)
8865 {
8866   struct bp_location *loc, **tmp;
8867   CORE_ADDR adjusted_address;
8868   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8869
8870   if (loc_gdbarch == NULL)
8871     loc_gdbarch = b->gdbarch;
8872
8873   /* Adjust the breakpoint's address prior to allocating a location.
8874      Once we call allocate_bp_location(), that mostly uninitialized
8875      location will be placed on the location chain.  Adjustment of the
8876      breakpoint may cause target_read_memory() to be called and we do
8877      not want its scan of the location chain to find a breakpoint and
8878      location that's only been partially initialized.  */
8879   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8880                                                 sal->pc, b->type);
8881
8882   /* Sort the locations by their ADDRESS.  */
8883   loc = allocate_bp_location (b);
8884   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8885        tmp = &((*tmp)->next))
8886     ;
8887   loc->next = *tmp;
8888   *tmp = loc;
8889
8890   loc->requested_address = sal->pc;
8891   loc->address = adjusted_address;
8892   loc->pspace = sal->pspace;
8893   loc->probe = sal->probe;
8894   gdb_assert (loc->pspace != NULL);
8895   loc->section = sal->section;
8896   loc->gdbarch = loc_gdbarch;
8897   loc->line_number = sal->line;
8898   loc->symtab = sal->symtab;
8899
8900   set_breakpoint_location_function (loc,
8901                                     sal->explicit_pc || sal->explicit_line);
8902   return loc;
8903 }
8904 \f
8905
8906 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8907    return 0 otherwise.  */
8908
8909 static int
8910 bp_loc_is_permanent (struct bp_location *loc)
8911 {
8912   int len;
8913   CORE_ADDR addr;
8914   const gdb_byte *bpoint;
8915   gdb_byte *target_mem;
8916   struct cleanup *cleanup;
8917   int retval = 0;
8918
8919   gdb_assert (loc != NULL);
8920
8921   addr = loc->address;
8922   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8923
8924   /* Software breakpoints unsupported?  */
8925   if (bpoint == NULL)
8926     return 0;
8927
8928   target_mem = alloca (len);
8929
8930   /* Enable the automatic memory restoration from breakpoints while
8931      we read the memory.  Otherwise we could say about our temporary
8932      breakpoints they are permanent.  */
8933   cleanup = save_current_space_and_thread ();
8934
8935   switch_to_program_space_and_thread (loc->pspace);
8936   make_show_memory_breakpoints_cleanup (0);
8937
8938   if (target_read_memory (loc->address, target_mem, len) == 0
8939       && memcmp (target_mem, bpoint, len) == 0)
8940     retval = 1;
8941
8942   do_cleanups (cleanup);
8943
8944   return retval;
8945 }
8946
8947 /* Build a command list for the dprintf corresponding to the current
8948    settings of the dprintf style options.  */
8949
8950 static void
8951 update_dprintf_command_list (struct breakpoint *b)
8952 {
8953   char *dprintf_args = b->extra_string;
8954   char *printf_line = NULL;
8955
8956   if (!dprintf_args)
8957     return;
8958
8959   dprintf_args = skip_spaces (dprintf_args);
8960
8961   /* Allow a comma, as it may have terminated a location, but don't
8962      insist on it.  */
8963   if (*dprintf_args == ',')
8964     ++dprintf_args;
8965   dprintf_args = skip_spaces (dprintf_args);
8966
8967   if (*dprintf_args != '"')
8968     error (_("Bad format string, missing '\"'."));
8969
8970   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8971     printf_line = xstrprintf ("printf %s", dprintf_args);
8972   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8973     {
8974       if (!dprintf_function)
8975         error (_("No function supplied for dprintf call"));
8976
8977       if (dprintf_channel && strlen (dprintf_channel) > 0)
8978         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8979                                   dprintf_function,
8980                                   dprintf_channel,
8981                                   dprintf_args);
8982       else
8983         printf_line = xstrprintf ("call (void) %s (%s)",
8984                                   dprintf_function,
8985                                   dprintf_args);
8986     }
8987   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8988     {
8989       if (target_can_run_breakpoint_commands ())
8990         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8991       else
8992         {
8993           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8994           printf_line = xstrprintf ("printf %s", dprintf_args);
8995         }
8996     }
8997   else
8998     internal_error (__FILE__, __LINE__,
8999                     _("Invalid dprintf style."));
9000
9001   gdb_assert (printf_line != NULL);
9002   /* Manufacture a printf sequence.  */
9003   {
9004     struct command_line *printf_cmd_line
9005       = xmalloc (sizeof (struct command_line));
9006
9007     printf_cmd_line = xmalloc (sizeof (struct command_line));
9008     printf_cmd_line->control_type = simple_control;
9009     printf_cmd_line->body_count = 0;
9010     printf_cmd_line->body_list = NULL;
9011     printf_cmd_line->next = NULL;
9012     printf_cmd_line->line = printf_line;
9013
9014     breakpoint_set_commands (b, printf_cmd_line);
9015   }
9016 }
9017
9018 /* Update all dprintf commands, making their command lists reflect
9019    current style settings.  */
9020
9021 static void
9022 update_dprintf_commands (char *args, int from_tty,
9023                          struct cmd_list_element *c)
9024 {
9025   struct breakpoint *b;
9026
9027   ALL_BREAKPOINTS (b)
9028     {
9029       if (b->type == bp_dprintf)
9030         update_dprintf_command_list (b);
9031     }
9032 }
9033
9034 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9035    as textual description of the location, and COND_STRING
9036    as condition expression.  */
9037
9038 static void
9039 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9040                      struct symtabs_and_lines sals, char *addr_string,
9041                      char *filter, char *cond_string,
9042                      char *extra_string,
9043                      enum bptype type, enum bpdisp disposition,
9044                      int thread, int task, int ignore_count,
9045                      const struct breakpoint_ops *ops, int from_tty,
9046                      int enabled, int internal, unsigned flags,
9047                      int display_canonical)
9048 {
9049   int i;
9050
9051   if (type == bp_hardware_breakpoint)
9052     {
9053       int target_resources_ok;
9054
9055       i = hw_breakpoint_used_count ();
9056       target_resources_ok =
9057         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9058                                             i + 1, 0);
9059       if (target_resources_ok == 0)
9060         error (_("No hardware breakpoint support in the target."));
9061       else if (target_resources_ok < 0)
9062         error (_("Hardware breakpoints used exceeds limit."));
9063     }
9064
9065   gdb_assert (sals.nelts > 0);
9066
9067   for (i = 0; i < sals.nelts; ++i)
9068     {
9069       struct symtab_and_line sal = sals.sals[i];
9070       struct bp_location *loc;
9071
9072       if (from_tty)
9073         {
9074           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9075           if (!loc_gdbarch)
9076             loc_gdbarch = gdbarch;
9077
9078           describe_other_breakpoints (loc_gdbarch,
9079                                       sal.pspace, sal.pc, sal.section, thread);
9080         }
9081
9082       if (i == 0)
9083         {
9084           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9085           b->thread = thread;
9086           b->task = task;
9087
9088           b->cond_string = cond_string;
9089           b->extra_string = extra_string;
9090           b->ignore_count = ignore_count;
9091           b->enable_state = enabled ? bp_enabled : bp_disabled;
9092           b->disposition = disposition;
9093
9094           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9095             b->loc->inserted = 1;
9096
9097           if (type == bp_static_tracepoint)
9098             {
9099               struct tracepoint *t = (struct tracepoint *) b;
9100               struct static_tracepoint_marker marker;
9101
9102               if (strace_marker_p (b))
9103                 {
9104                   /* We already know the marker exists, otherwise, we
9105                      wouldn't see a sal for it.  */
9106                   char *p = &addr_string[3];
9107                   char *endp;
9108                   char *marker_str;
9109
9110                   p = skip_spaces (p);
9111
9112                   endp = skip_to_space (p);
9113
9114                   marker_str = savestring (p, endp - p);
9115                   t->static_trace_marker_id = marker_str;
9116
9117                   printf_filtered (_("Probed static tracepoint "
9118                                      "marker \"%s\"\n"),
9119                                    t->static_trace_marker_id);
9120                 }
9121               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9122                 {
9123                   t->static_trace_marker_id = xstrdup (marker.str_id);
9124                   release_static_tracepoint_marker (&marker);
9125
9126                   printf_filtered (_("Probed static tracepoint "
9127                                      "marker \"%s\"\n"),
9128                                    t->static_trace_marker_id);
9129                 }
9130               else
9131                 warning (_("Couldn't determine the static "
9132                            "tracepoint marker to probe"));
9133             }
9134
9135           loc = b->loc;
9136         }
9137       else
9138         {
9139           loc = add_location_to_breakpoint (b, &sal);
9140           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9141             loc->inserted = 1;
9142         }
9143
9144       if (bp_loc_is_permanent (loc))
9145         make_breakpoint_permanent (b);
9146
9147       if (b->cond_string)
9148         {
9149           const char *arg = b->cond_string;
9150
9151           loc->cond = parse_exp_1 (&arg, loc->address,
9152                                    block_for_pc (loc->address), 0);
9153           if (*arg)
9154               error (_("Garbage '%s' follows condition"), arg);
9155         }
9156
9157       /* Dynamic printf requires and uses additional arguments on the
9158          command line, otherwise it's an error.  */
9159       if (type == bp_dprintf)
9160         {
9161           if (b->extra_string)
9162             update_dprintf_command_list (b);
9163           else
9164             error (_("Format string required"));
9165         }
9166       else if (b->extra_string)
9167         error (_("Garbage '%s' at end of command"), b->extra_string);
9168     }
9169
9170   b->display_canonical = display_canonical;
9171   if (addr_string)
9172     b->addr_string = addr_string;
9173   else
9174     /* addr_string has to be used or breakpoint_re_set will delete
9175        me.  */
9176     b->addr_string
9177       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9178   b->filter = filter;
9179 }
9180
9181 static void
9182 create_breakpoint_sal (struct gdbarch *gdbarch,
9183                        struct symtabs_and_lines sals, char *addr_string,
9184                        char *filter, char *cond_string,
9185                        char *extra_string,
9186                        enum bptype type, enum bpdisp disposition,
9187                        int thread, int task, int ignore_count,
9188                        const struct breakpoint_ops *ops, int from_tty,
9189                        int enabled, int internal, unsigned flags,
9190                        int display_canonical)
9191 {
9192   struct breakpoint *b;
9193   struct cleanup *old_chain;
9194
9195   if (is_tracepoint_type (type))
9196     {
9197       struct tracepoint *t;
9198
9199       t = XCNEW (struct tracepoint);
9200       b = &t->base;
9201     }
9202   else
9203     b = XNEW (struct breakpoint);
9204
9205   old_chain = make_cleanup (xfree, b);
9206
9207   init_breakpoint_sal (b, gdbarch,
9208                        sals, addr_string,
9209                        filter, cond_string, extra_string,
9210                        type, disposition,
9211                        thread, task, ignore_count,
9212                        ops, from_tty,
9213                        enabled, internal, flags,
9214                        display_canonical);
9215   discard_cleanups (old_chain);
9216
9217   install_breakpoint (internal, b, 0);
9218 }
9219
9220 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9221    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9222    value.  COND_STRING, if not NULL, specified the condition to be
9223    used for all breakpoints.  Essentially the only case where
9224    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9225    function.  In that case, it's still not possible to specify
9226    separate conditions for different overloaded functions, so
9227    we take just a single condition string.
9228    
9229    NOTE: If the function succeeds, the caller is expected to cleanup
9230    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9231    array contents).  If the function fails (error() is called), the
9232    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9233    COND and SALS arrays and each of those arrays contents.  */
9234
9235 static void
9236 create_breakpoints_sal (struct gdbarch *gdbarch,
9237                         struct linespec_result *canonical,
9238                         char *cond_string, char *extra_string,
9239                         enum bptype type, enum bpdisp disposition,
9240                         int thread, int task, int ignore_count,
9241                         const struct breakpoint_ops *ops, int from_tty,
9242                         int enabled, int internal, unsigned flags)
9243 {
9244   int i;
9245   struct linespec_sals *lsal;
9246
9247   if (canonical->pre_expanded)
9248     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9249
9250   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9251     {
9252       /* Note that 'addr_string' can be NULL in the case of a plain
9253          'break', without arguments.  */
9254       char *addr_string = (canonical->addr_string
9255                            ? xstrdup (canonical->addr_string)
9256                            : NULL);
9257       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9258       struct cleanup *inner = make_cleanup (xfree, addr_string);
9259
9260       make_cleanup (xfree, filter_string);
9261       create_breakpoint_sal (gdbarch, lsal->sals,
9262                              addr_string,
9263                              filter_string,
9264                              cond_string, extra_string,
9265                              type, disposition,
9266                              thread, task, ignore_count, ops,
9267                              from_tty, enabled, internal, flags,
9268                              canonical->special_display);
9269       discard_cleanups (inner);
9270     }
9271 }
9272
9273 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9274    followed by conditionals.  On return, SALS contains an array of SAL
9275    addresses found.  ADDR_STRING contains a vector of (canonical)
9276    address strings.  ADDRESS points to the end of the SAL.
9277
9278    The array and the line spec strings are allocated on the heap, it is
9279    the caller's responsibility to free them.  */
9280
9281 static void
9282 parse_breakpoint_sals (char **address,
9283                        struct linespec_result *canonical)
9284 {
9285   /* If no arg given, or if first arg is 'if ', use the default
9286      breakpoint.  */
9287   if ((*address) == NULL
9288       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9289     {
9290       /* The last displayed codepoint, if it's valid, is our default breakpoint
9291          address.  */
9292       if (last_displayed_sal_is_valid ())
9293         {
9294           struct linespec_sals lsal;
9295           struct symtab_and_line sal;
9296           CORE_ADDR pc;
9297
9298           init_sal (&sal);              /* Initialize to zeroes.  */
9299           lsal.sals.sals = (struct symtab_and_line *)
9300             xmalloc (sizeof (struct symtab_and_line));
9301
9302           /* Set sal's pspace, pc, symtab, and line to the values
9303              corresponding to the last call to print_frame_info.
9304              Be sure to reinitialize LINE with NOTCURRENT == 0
9305              as the breakpoint line number is inappropriate otherwise.
9306              find_pc_line would adjust PC, re-set it back.  */
9307           get_last_displayed_sal (&sal);
9308           pc = sal.pc;
9309           sal = find_pc_line (pc, 0);
9310
9311           /* "break" without arguments is equivalent to "break *PC"
9312              where PC is the last displayed codepoint's address.  So
9313              make sure to set sal.explicit_pc to prevent GDB from
9314              trying to expand the list of sals to include all other
9315              instances with the same symtab and line.  */
9316           sal.pc = pc;
9317           sal.explicit_pc = 1;
9318
9319           lsal.sals.sals[0] = sal;
9320           lsal.sals.nelts = 1;
9321           lsal.canonical = NULL;
9322
9323           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9324         }
9325       else
9326         error (_("No default breakpoint address now."));
9327     }
9328   else
9329     {
9330       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9331
9332       /* Force almost all breakpoints to be in terms of the
9333          current_source_symtab (which is decode_line_1's default).
9334          This should produce the results we want almost all of the
9335          time while leaving default_breakpoint_* alone.
9336
9337          ObjC: However, don't match an Objective-C method name which
9338          may have a '+' or '-' succeeded by a '['.  */
9339       if (last_displayed_sal_is_valid ()
9340           && (!cursal.symtab
9341               || ((strchr ("+-", (*address)[0]) != NULL)
9342                   && ((*address)[1] != '['))))
9343         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9344                           get_last_displayed_symtab (),
9345                           get_last_displayed_line (),
9346                           canonical, NULL, NULL);
9347       else
9348         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9349                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9350     }
9351 }
9352
9353
9354 /* Convert each SAL into a real PC.  Verify that the PC can be
9355    inserted as a breakpoint.  If it can't throw an error.  */
9356
9357 static void
9358 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9359 {    
9360   int i;
9361
9362   for (i = 0; i < sals->nelts; i++)
9363     resolve_sal_pc (&sals->sals[i]);
9364 }
9365
9366 /* Fast tracepoints may have restrictions on valid locations.  For
9367    instance, a fast tracepoint using a jump instead of a trap will
9368    likely have to overwrite more bytes than a trap would, and so can
9369    only be placed where the instruction is longer than the jump, or a
9370    multi-instruction sequence does not have a jump into the middle of
9371    it, etc.  */
9372
9373 static void
9374 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9375                             struct symtabs_and_lines *sals)
9376 {
9377   int i, rslt;
9378   struct symtab_and_line *sal;
9379   char *msg;
9380   struct cleanup *old_chain;
9381
9382   for (i = 0; i < sals->nelts; i++)
9383     {
9384       struct gdbarch *sarch;
9385
9386       sal = &sals->sals[i];
9387
9388       sarch = get_sal_arch (*sal);
9389       /* We fall back to GDBARCH if there is no architecture
9390          associated with SAL.  */
9391       if (sarch == NULL)
9392         sarch = gdbarch;
9393       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9394                                                NULL, &msg);
9395       old_chain = make_cleanup (xfree, msg);
9396
9397       if (!rslt)
9398         error (_("May not have a fast tracepoint at 0x%s%s"),
9399                paddress (sarch, sal->pc), (msg ? msg : ""));
9400
9401       do_cleanups (old_chain);
9402     }
9403 }
9404
9405 /* Issue an invalid thread ID error.  */
9406
9407 static void ATTRIBUTE_NORETURN
9408 invalid_thread_id_error (int id)
9409 {
9410   error (_("Unknown thread %d."), id);
9411 }
9412
9413 /* Given TOK, a string specification of condition and thread, as
9414    accepted by the 'break' command, extract the condition
9415    string and thread number and set *COND_STRING and *THREAD.
9416    PC identifies the context at which the condition should be parsed.
9417    If no condition is found, *COND_STRING is set to NULL.
9418    If no thread is found, *THREAD is set to -1.  */
9419
9420 static void
9421 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9422                            char **cond_string, int *thread, int *task,
9423                            char **rest)
9424 {
9425   *cond_string = NULL;
9426   *thread = -1;
9427   *task = 0;
9428   *rest = NULL;
9429
9430   while (tok && *tok)
9431     {
9432       const char *end_tok;
9433       int toklen;
9434       const char *cond_start = NULL;
9435       const char *cond_end = NULL;
9436
9437       tok = skip_spaces_const (tok);
9438
9439       if ((*tok == '"' || *tok == ',') && rest)
9440         {
9441           *rest = savestring (tok, strlen (tok));
9442           return;
9443         }
9444
9445       end_tok = skip_to_space_const (tok);
9446
9447       toklen = end_tok - tok;
9448
9449       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9450         {
9451           struct expression *expr;
9452
9453           tok = cond_start = end_tok + 1;
9454           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9455           xfree (expr);
9456           cond_end = tok;
9457           *cond_string = savestring (cond_start, cond_end - cond_start);
9458         }
9459       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9460         {
9461           char *tmptok;
9462
9463           tok = end_tok + 1;
9464           *thread = strtol (tok, &tmptok, 0);
9465           if (tok == tmptok)
9466             error (_("Junk after thread keyword."));
9467           if (!valid_thread_id (*thread))
9468             invalid_thread_id_error (*thread);
9469           tok = tmptok;
9470         }
9471       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9472         {
9473           char *tmptok;
9474
9475           tok = end_tok + 1;
9476           *task = strtol (tok, &tmptok, 0);
9477           if (tok == tmptok)
9478             error (_("Junk after task keyword."));
9479           if (!valid_task_id (*task))
9480             error (_("Unknown task %d."), *task);
9481           tok = tmptok;
9482         }
9483       else if (rest)
9484         {
9485           *rest = savestring (tok, strlen (tok));
9486           return;
9487         }
9488       else
9489         error (_("Junk at end of arguments."));
9490     }
9491 }
9492
9493 /* Decode a static tracepoint marker spec.  */
9494
9495 static struct symtabs_and_lines
9496 decode_static_tracepoint_spec (char **arg_p)
9497 {
9498   VEC(static_tracepoint_marker_p) *markers = NULL;
9499   struct symtabs_and_lines sals;
9500   struct cleanup *old_chain;
9501   char *p = &(*arg_p)[3];
9502   char *endp;
9503   char *marker_str;
9504   int i;
9505
9506   p = skip_spaces (p);
9507
9508   endp = skip_to_space (p);
9509
9510   marker_str = savestring (p, endp - p);
9511   old_chain = make_cleanup (xfree, marker_str);
9512
9513   markers = target_static_tracepoint_markers_by_strid (marker_str);
9514   if (VEC_empty(static_tracepoint_marker_p, markers))
9515     error (_("No known static tracepoint marker named %s"), marker_str);
9516
9517   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9518   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9519
9520   for (i = 0; i < sals.nelts; i++)
9521     {
9522       struct static_tracepoint_marker *marker;
9523
9524       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9525
9526       init_sal (&sals.sals[i]);
9527
9528       sals.sals[i] = find_pc_line (marker->address, 0);
9529       sals.sals[i].pc = marker->address;
9530
9531       release_static_tracepoint_marker (marker);
9532     }
9533
9534   do_cleanups (old_chain);
9535
9536   *arg_p = endp;
9537   return sals;
9538 }
9539
9540 /* Set a breakpoint.  This function is shared between CLI and MI
9541    functions for setting a breakpoint.  This function has two major
9542    modes of operations, selected by the PARSE_ARG parameter.  If
9543    non-zero, the function will parse ARG, extracting location,
9544    condition, thread and extra string.  Otherwise, ARG is just the
9545    breakpoint's location, with condition, thread, and extra string
9546    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9547    If INTERNAL is non-zero, the breakpoint number will be allocated
9548    from the internal breakpoint count.  Returns true if any breakpoint
9549    was created; false otherwise.  */
9550
9551 int
9552 create_breakpoint (struct gdbarch *gdbarch,
9553                    char *arg, char *cond_string,
9554                    int thread, char *extra_string,
9555                    int parse_arg,
9556                    int tempflag, enum bptype type_wanted,
9557                    int ignore_count,
9558                    enum auto_boolean pending_break_support,
9559                    const struct breakpoint_ops *ops,
9560                    int from_tty, int enabled, int internal,
9561                    unsigned flags)
9562 {
9563   volatile struct gdb_exception e;
9564   char *copy_arg = NULL;
9565   char *addr_start = arg;
9566   struct linespec_result canonical;
9567   struct cleanup *old_chain;
9568   struct cleanup *bkpt_chain = NULL;
9569   int pending = 0;
9570   int task = 0;
9571   int prev_bkpt_count = breakpoint_count;
9572
9573   gdb_assert (ops != NULL);
9574
9575   init_linespec_result (&canonical);
9576
9577   TRY_CATCH (e, RETURN_MASK_ALL)
9578     {
9579       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9580                                      addr_start, &copy_arg);
9581     }
9582
9583   /* If caller is interested in rc value from parse, set value.  */
9584   switch (e.reason)
9585     {
9586     case GDB_NO_ERROR:
9587       if (VEC_empty (linespec_sals, canonical.sals))
9588         return 0;
9589       break;
9590     case RETURN_ERROR:
9591       switch (e.error)
9592         {
9593         case NOT_FOUND_ERROR:
9594
9595           /* If pending breakpoint support is turned off, throw
9596              error.  */
9597
9598           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9599             throw_exception (e);
9600
9601           exception_print (gdb_stderr, e);
9602
9603           /* If pending breakpoint support is auto query and the user
9604              selects no, then simply return the error code.  */
9605           if (pending_break_support == AUTO_BOOLEAN_AUTO
9606               && !nquery (_("Make %s pending on future shared library load? "),
9607                           bptype_string (type_wanted)))
9608             return 0;
9609
9610           /* At this point, either the user was queried about setting
9611              a pending breakpoint and selected yes, or pending
9612              breakpoint behavior is on and thus a pending breakpoint
9613              is defaulted on behalf of the user.  */
9614           {
9615             struct linespec_sals lsal;
9616
9617             copy_arg = xstrdup (addr_start);
9618             lsal.canonical = xstrdup (copy_arg);
9619             lsal.sals.nelts = 1;
9620             lsal.sals.sals = XNEW (struct symtab_and_line);
9621             init_sal (&lsal.sals.sals[0]);
9622             pending = 1;
9623             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9624           }
9625           break;
9626         default:
9627           throw_exception (e);
9628         }
9629       break;
9630     default:
9631       throw_exception (e);
9632     }
9633
9634   /* Create a chain of things that always need to be cleaned up.  */
9635   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9636
9637   /* ----------------------------- SNIP -----------------------------
9638      Anything added to the cleanup chain beyond this point is assumed
9639      to be part of a breakpoint.  If the breakpoint create succeeds
9640      then the memory is not reclaimed.  */
9641   bkpt_chain = make_cleanup (null_cleanup, 0);
9642
9643   /* Resolve all line numbers to PC's and verify that the addresses
9644      are ok for the target.  */
9645   if (!pending)
9646     {
9647       int ix;
9648       struct linespec_sals *iter;
9649
9650       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9651         breakpoint_sals_to_pc (&iter->sals);
9652     }
9653
9654   /* Fast tracepoints may have additional restrictions on location.  */
9655   if (!pending && type_wanted == bp_fast_tracepoint)
9656     {
9657       int ix;
9658       struct linespec_sals *iter;
9659
9660       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9661         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9662     }
9663
9664   /* Verify that condition can be parsed, before setting any
9665      breakpoints.  Allocate a separate condition expression for each
9666      breakpoint.  */
9667   if (!pending)
9668     {
9669       if (parse_arg)
9670         {
9671           char *rest;
9672           struct linespec_sals *lsal;
9673
9674           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9675
9676           /* Here we only parse 'arg' to separate condition
9677              from thread number, so parsing in context of first
9678              sal is OK.  When setting the breakpoint we'll
9679              re-parse it in context of each sal.  */
9680
9681           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9682                                      &thread, &task, &rest);
9683           if (cond_string)
9684             make_cleanup (xfree, cond_string);
9685           if (rest)
9686             make_cleanup (xfree, rest);
9687           if (rest)
9688             extra_string = rest;
9689         }
9690       else
9691         {
9692           if (*arg != '\0')
9693             error (_("Garbage '%s' at end of location"), arg);
9694
9695           /* Create a private copy of condition string.  */
9696           if (cond_string)
9697             {
9698               cond_string = xstrdup (cond_string);
9699               make_cleanup (xfree, cond_string);
9700             }
9701           /* Create a private copy of any extra string.  */
9702           if (extra_string)
9703             {
9704               extra_string = xstrdup (extra_string);
9705               make_cleanup (xfree, extra_string);
9706             }
9707         }
9708
9709       ops->create_breakpoints_sal (gdbarch, &canonical,
9710                                    cond_string, extra_string, type_wanted,
9711                                    tempflag ? disp_del : disp_donttouch,
9712                                    thread, task, ignore_count, ops,
9713                                    from_tty, enabled, internal, flags);
9714     }
9715   else
9716     {
9717       struct breakpoint *b;
9718
9719       make_cleanup (xfree, copy_arg);
9720
9721       if (is_tracepoint_type (type_wanted))
9722         {
9723           struct tracepoint *t;
9724
9725           t = XCNEW (struct tracepoint);
9726           b = &t->base;
9727         }
9728       else
9729         b = XNEW (struct breakpoint);
9730
9731       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9732
9733       b->addr_string = copy_arg;
9734       if (parse_arg)
9735         b->cond_string = NULL;
9736       else
9737         {
9738           /* Create a private copy of condition string.  */
9739           if (cond_string)
9740             {
9741               cond_string = xstrdup (cond_string);
9742               make_cleanup (xfree, cond_string);
9743             }
9744           b->cond_string = cond_string;
9745         }
9746       b->extra_string = NULL;
9747       b->ignore_count = ignore_count;
9748       b->disposition = tempflag ? disp_del : disp_donttouch;
9749       b->condition_not_parsed = 1;
9750       b->enable_state = enabled ? bp_enabled : bp_disabled;
9751       if ((type_wanted != bp_breakpoint
9752            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9753         b->pspace = current_program_space;
9754
9755       install_breakpoint (internal, b, 0);
9756     }
9757   
9758   if (VEC_length (linespec_sals, canonical.sals) > 1)
9759     {
9760       warning (_("Multiple breakpoints were set.\nUse the "
9761                  "\"delete\" command to delete unwanted breakpoints."));
9762       prev_breakpoint_count = prev_bkpt_count;
9763     }
9764
9765   /* That's it.  Discard the cleanups for data inserted into the
9766      breakpoint.  */
9767   discard_cleanups (bkpt_chain);
9768   /* But cleanup everything else.  */
9769   do_cleanups (old_chain);
9770
9771   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9772   update_global_location_list (1);
9773
9774   return 1;
9775 }
9776
9777 /* Set a breakpoint.
9778    ARG is a string describing breakpoint address,
9779    condition, and thread.
9780    FLAG specifies if a breakpoint is hardware on,
9781    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9782    and BP_TEMPFLAG.  */
9783
9784 static void
9785 break_command_1 (char *arg, int flag, int from_tty)
9786 {
9787   int tempflag = flag & BP_TEMPFLAG;
9788   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9789                              ? bp_hardware_breakpoint
9790                              : bp_breakpoint);
9791   struct breakpoint_ops *ops;
9792   const char *arg_cp = arg;
9793
9794   /* Matching breakpoints on probes.  */
9795   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9796     ops = &bkpt_probe_breakpoint_ops;
9797   else
9798     ops = &bkpt_breakpoint_ops;
9799
9800   create_breakpoint (get_current_arch (),
9801                      arg,
9802                      NULL, 0, NULL, 1 /* parse arg */,
9803                      tempflag, type_wanted,
9804                      0 /* Ignore count */,
9805                      pending_break_support,
9806                      ops,
9807                      from_tty,
9808                      1 /* enabled */,
9809                      0 /* internal */,
9810                      0);
9811 }
9812
9813 /* Helper function for break_command_1 and disassemble_command.  */
9814
9815 void
9816 resolve_sal_pc (struct symtab_and_line *sal)
9817 {
9818   CORE_ADDR pc;
9819
9820   if (sal->pc == 0 && sal->symtab != NULL)
9821     {
9822       if (!find_line_pc (sal->symtab, sal->line, &pc))
9823         error (_("No line %d in file \"%s\"."),
9824                sal->line, symtab_to_filename_for_display (sal->symtab));
9825       sal->pc = pc;
9826
9827       /* If this SAL corresponds to a breakpoint inserted using a line
9828          number, then skip the function prologue if necessary.  */
9829       if (sal->explicit_line)
9830         skip_prologue_sal (sal);
9831     }
9832
9833   if (sal->section == 0 && sal->symtab != NULL)
9834     {
9835       struct blockvector *bv;
9836       struct block *b;
9837       struct symbol *sym;
9838
9839       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9840       if (bv != NULL)
9841         {
9842           sym = block_linkage_function (b);
9843           if (sym != NULL)
9844             {
9845               fixup_symbol_section (sym, sal->symtab->objfile);
9846               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
9847             }
9848           else
9849             {
9850               /* It really is worthwhile to have the section, so we'll
9851                  just have to look harder. This case can be executed
9852                  if we have line numbers but no functions (as can
9853                  happen in assembly source).  */
9854
9855               struct bound_minimal_symbol msym;
9856               struct cleanup *old_chain = save_current_space_and_thread ();
9857
9858               switch_to_program_space_and_thread (sal->pspace);
9859
9860               msym = lookup_minimal_symbol_by_pc (sal->pc);
9861               if (msym.minsym)
9862                 sal->section = SYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9863
9864               do_cleanups (old_chain);
9865             }
9866         }
9867     }
9868 }
9869
9870 void
9871 break_command (char *arg, int from_tty)
9872 {
9873   break_command_1 (arg, 0, from_tty);
9874 }
9875
9876 void
9877 tbreak_command (char *arg, int from_tty)
9878 {
9879   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9880 }
9881
9882 static void
9883 hbreak_command (char *arg, int from_tty)
9884 {
9885   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9886 }
9887
9888 static void
9889 thbreak_command (char *arg, int from_tty)
9890 {
9891   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9892 }
9893
9894 static void
9895 stop_command (char *arg, int from_tty)
9896 {
9897   printf_filtered (_("Specify the type of breakpoint to set.\n\
9898 Usage: stop in <function | address>\n\
9899        stop at <line>\n"));
9900 }
9901
9902 static void
9903 stopin_command (char *arg, int from_tty)
9904 {
9905   int badInput = 0;
9906
9907   if (arg == (char *) NULL)
9908     badInput = 1;
9909   else if (*arg != '*')
9910     {
9911       char *argptr = arg;
9912       int hasColon = 0;
9913
9914       /* Look for a ':'.  If this is a line number specification, then
9915          say it is bad, otherwise, it should be an address or
9916          function/method name.  */
9917       while (*argptr && !hasColon)
9918         {
9919           hasColon = (*argptr == ':');
9920           argptr++;
9921         }
9922
9923       if (hasColon)
9924         badInput = (*argptr != ':');    /* Not a class::method */
9925       else
9926         badInput = isdigit (*arg);      /* a simple line number */
9927     }
9928
9929   if (badInput)
9930     printf_filtered (_("Usage: stop in <function | address>\n"));
9931   else
9932     break_command_1 (arg, 0, from_tty);
9933 }
9934
9935 static void
9936 stopat_command (char *arg, int from_tty)
9937 {
9938   int badInput = 0;
9939
9940   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9941     badInput = 1;
9942   else
9943     {
9944       char *argptr = arg;
9945       int hasColon = 0;
9946
9947       /* Look for a ':'.  If there is a '::' then get out, otherwise
9948          it is probably a line number.  */
9949       while (*argptr && !hasColon)
9950         {
9951           hasColon = (*argptr == ':');
9952           argptr++;
9953         }
9954
9955       if (hasColon)
9956         badInput = (*argptr == ':');    /* we have class::method */
9957       else
9958         badInput = !isdigit (*arg);     /* not a line number */
9959     }
9960
9961   if (badInput)
9962     printf_filtered (_("Usage: stop at <line>\n"));
9963   else
9964     break_command_1 (arg, 0, from_tty);
9965 }
9966
9967 /* The dynamic printf command is mostly like a regular breakpoint, but
9968    with a prewired command list consisting of a single output command,
9969    built from extra arguments supplied on the dprintf command
9970    line.  */
9971
9972 static void
9973 dprintf_command (char *arg, int from_tty)
9974 {
9975   create_breakpoint (get_current_arch (),
9976                      arg,
9977                      NULL, 0, NULL, 1 /* parse arg */,
9978                      0, bp_dprintf,
9979                      0 /* Ignore count */,
9980                      pending_break_support,
9981                      &dprintf_breakpoint_ops,
9982                      from_tty,
9983                      1 /* enabled */,
9984                      0 /* internal */,
9985                      0);
9986 }
9987
9988 static void
9989 agent_printf_command (char *arg, int from_tty)
9990 {
9991   error (_("May only run agent-printf on the target"));
9992 }
9993
9994 /* Implement the "breakpoint_hit" breakpoint_ops method for
9995    ranged breakpoints.  */
9996
9997 static int
9998 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9999                                   struct address_space *aspace,
10000                                   CORE_ADDR bp_addr,
10001                                   const struct target_waitstatus *ws)
10002 {
10003   if (ws->kind != TARGET_WAITKIND_STOPPED
10004       || ws->value.sig != GDB_SIGNAL_TRAP)
10005     return 0;
10006
10007   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10008                                          bl->length, aspace, bp_addr);
10009 }
10010
10011 /* Implement the "resources_needed" breakpoint_ops method for
10012    ranged breakpoints.  */
10013
10014 static int
10015 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10016 {
10017   return target_ranged_break_num_registers ();
10018 }
10019
10020 /* Implement the "print_it" breakpoint_ops method for
10021    ranged breakpoints.  */
10022
10023 static enum print_stop_action
10024 print_it_ranged_breakpoint (bpstat bs)
10025 {
10026   struct breakpoint *b = bs->breakpoint_at;
10027   struct bp_location *bl = b->loc;
10028   struct ui_out *uiout = current_uiout;
10029
10030   gdb_assert (b->type == bp_hardware_breakpoint);
10031
10032   /* Ranged breakpoints have only one location.  */
10033   gdb_assert (bl && bl->next == NULL);
10034
10035   annotate_breakpoint (b->number);
10036   if (b->disposition == disp_del)
10037     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10038   else
10039     ui_out_text (uiout, "\nRanged breakpoint ");
10040   if (ui_out_is_mi_like_p (uiout))
10041     {
10042       ui_out_field_string (uiout, "reason",
10043                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10044       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10045     }
10046   ui_out_field_int (uiout, "bkptno", b->number);
10047   ui_out_text (uiout, ", ");
10048
10049   return PRINT_SRC_AND_LOC;
10050 }
10051
10052 /* Implement the "print_one" breakpoint_ops method for
10053    ranged breakpoints.  */
10054
10055 static void
10056 print_one_ranged_breakpoint (struct breakpoint *b,
10057                              struct bp_location **last_loc)
10058 {
10059   struct bp_location *bl = b->loc;
10060   struct value_print_options opts;
10061   struct ui_out *uiout = current_uiout;
10062
10063   /* Ranged breakpoints have only one location.  */
10064   gdb_assert (bl && bl->next == NULL);
10065
10066   get_user_print_options (&opts);
10067
10068   if (opts.addressprint)
10069     /* We don't print the address range here, it will be printed later
10070        by print_one_detail_ranged_breakpoint.  */
10071     ui_out_field_skip (uiout, "addr");
10072   annotate_field (5);
10073   print_breakpoint_location (b, bl);
10074   *last_loc = bl;
10075 }
10076
10077 /* Implement the "print_one_detail" breakpoint_ops method for
10078    ranged breakpoints.  */
10079
10080 static void
10081 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10082                                     struct ui_out *uiout)
10083 {
10084   CORE_ADDR address_start, address_end;
10085   struct bp_location *bl = b->loc;
10086   struct ui_file *stb = mem_fileopen ();
10087   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10088
10089   gdb_assert (bl);
10090
10091   address_start = bl->address;
10092   address_end = address_start + bl->length - 1;
10093
10094   ui_out_text (uiout, "\taddress range: ");
10095   fprintf_unfiltered (stb, "[%s, %s]",
10096                       print_core_address (bl->gdbarch, address_start),
10097                       print_core_address (bl->gdbarch, address_end));
10098   ui_out_field_stream (uiout, "addr", stb);
10099   ui_out_text (uiout, "\n");
10100
10101   do_cleanups (cleanup);
10102 }
10103
10104 /* Implement the "print_mention" breakpoint_ops method for
10105    ranged breakpoints.  */
10106
10107 static void
10108 print_mention_ranged_breakpoint (struct breakpoint *b)
10109 {
10110   struct bp_location *bl = b->loc;
10111   struct ui_out *uiout = current_uiout;
10112
10113   gdb_assert (bl);
10114   gdb_assert (b->type == bp_hardware_breakpoint);
10115
10116   if (ui_out_is_mi_like_p (uiout))
10117     return;
10118
10119   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10120                    b->number, paddress (bl->gdbarch, bl->address),
10121                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10122 }
10123
10124 /* Implement the "print_recreate" breakpoint_ops method for
10125    ranged breakpoints.  */
10126
10127 static void
10128 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10129 {
10130   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10131                       b->addr_string_range_end);
10132   print_recreate_thread (b, fp);
10133 }
10134
10135 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10136
10137 static struct breakpoint_ops ranged_breakpoint_ops;
10138
10139 /* Find the address where the end of the breakpoint range should be
10140    placed, given the SAL of the end of the range.  This is so that if
10141    the user provides a line number, the end of the range is set to the
10142    last instruction of the given line.  */
10143
10144 static CORE_ADDR
10145 find_breakpoint_range_end (struct symtab_and_line sal)
10146 {
10147   CORE_ADDR end;
10148
10149   /* If the user provided a PC value, use it.  Otherwise,
10150      find the address of the end of the given location.  */
10151   if (sal.explicit_pc)
10152     end = sal.pc;
10153   else
10154     {
10155       int ret;
10156       CORE_ADDR start;
10157
10158       ret = find_line_pc_range (sal, &start, &end);
10159       if (!ret)
10160         error (_("Could not find location of the end of the range."));
10161
10162       /* find_line_pc_range returns the start of the next line.  */
10163       end--;
10164     }
10165
10166   return end;
10167 }
10168
10169 /* Implement the "break-range" CLI command.  */
10170
10171 static void
10172 break_range_command (char *arg, int from_tty)
10173 {
10174   char *arg_start, *addr_string_start, *addr_string_end;
10175   struct linespec_result canonical_start, canonical_end;
10176   int bp_count, can_use_bp, length;
10177   CORE_ADDR end;
10178   struct breakpoint *b;
10179   struct symtab_and_line sal_start, sal_end;
10180   struct cleanup *cleanup_bkpt;
10181   struct linespec_sals *lsal_start, *lsal_end;
10182
10183   /* We don't support software ranged breakpoints.  */
10184   if (target_ranged_break_num_registers () < 0)
10185     error (_("This target does not support hardware ranged breakpoints."));
10186
10187   bp_count = hw_breakpoint_used_count ();
10188   bp_count += target_ranged_break_num_registers ();
10189   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10190                                                    bp_count, 0);
10191   if (can_use_bp < 0)
10192     error (_("Hardware breakpoints used exceeds limit."));
10193
10194   arg = skip_spaces (arg);
10195   if (arg == NULL || arg[0] == '\0')
10196     error(_("No address range specified."));
10197
10198   init_linespec_result (&canonical_start);
10199
10200   arg_start = arg;
10201   parse_breakpoint_sals (&arg, &canonical_start);
10202
10203   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10204
10205   if (arg[0] != ',')
10206     error (_("Too few arguments."));
10207   else if (VEC_empty (linespec_sals, canonical_start.sals))
10208     error (_("Could not find location of the beginning of the range."));
10209
10210   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10211
10212   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10213       || lsal_start->sals.nelts != 1)
10214     error (_("Cannot create a ranged breakpoint with multiple locations."));
10215
10216   sal_start = lsal_start->sals.sals[0];
10217   addr_string_start = savestring (arg_start, arg - arg_start);
10218   make_cleanup (xfree, addr_string_start);
10219
10220   arg++;        /* Skip the comma.  */
10221   arg = skip_spaces (arg);
10222
10223   /* Parse the end location.  */
10224
10225   init_linespec_result (&canonical_end);
10226   arg_start = arg;
10227
10228   /* We call decode_line_full directly here instead of using
10229      parse_breakpoint_sals because we need to specify the start location's
10230      symtab and line as the default symtab and line for the end of the
10231      range.  This makes it possible to have ranges like "foo.c:27, +14",
10232      where +14 means 14 lines from the start location.  */
10233   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10234                     sal_start.symtab, sal_start.line,
10235                     &canonical_end, NULL, NULL);
10236
10237   make_cleanup_destroy_linespec_result (&canonical_end);
10238
10239   if (VEC_empty (linespec_sals, canonical_end.sals))
10240     error (_("Could not find location of the end of the range."));
10241
10242   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10243   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10244       || lsal_end->sals.nelts != 1)
10245     error (_("Cannot create a ranged breakpoint with multiple locations."));
10246
10247   sal_end = lsal_end->sals.sals[0];
10248   addr_string_end = savestring (arg_start, arg - arg_start);
10249   make_cleanup (xfree, addr_string_end);
10250
10251   end = find_breakpoint_range_end (sal_end);
10252   if (sal_start.pc > end)
10253     error (_("Invalid address range, end precedes start."));
10254
10255   length = end - sal_start.pc + 1;
10256   if (length < 0)
10257     /* Length overflowed.  */
10258     error (_("Address range too large."));
10259   else if (length == 1)
10260     {
10261       /* This range is simple enough to be handled by
10262          the `hbreak' command.  */
10263       hbreak_command (addr_string_start, 1);
10264
10265       do_cleanups (cleanup_bkpt);
10266
10267       return;
10268     }
10269
10270   /* Now set up the breakpoint.  */
10271   b = set_raw_breakpoint (get_current_arch (), sal_start,
10272                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10273   set_breakpoint_count (breakpoint_count + 1);
10274   b->number = breakpoint_count;
10275   b->disposition = disp_donttouch;
10276   b->addr_string = xstrdup (addr_string_start);
10277   b->addr_string_range_end = xstrdup (addr_string_end);
10278   b->loc->length = length;
10279
10280   do_cleanups (cleanup_bkpt);
10281
10282   mention (b);
10283   observer_notify_breakpoint_created (b);
10284   update_global_location_list (1);
10285 }
10286
10287 /*  Return non-zero if EXP is verified as constant.  Returned zero
10288     means EXP is variable.  Also the constant detection may fail for
10289     some constant expressions and in such case still falsely return
10290     zero.  */
10291
10292 static int
10293 watchpoint_exp_is_const (const struct expression *exp)
10294 {
10295   int i = exp->nelts;
10296
10297   while (i > 0)
10298     {
10299       int oplenp, argsp;
10300
10301       /* We are only interested in the descriptor of each element.  */
10302       operator_length (exp, i, &oplenp, &argsp);
10303       i -= oplenp;
10304
10305       switch (exp->elts[i].opcode)
10306         {
10307         case BINOP_ADD:
10308         case BINOP_SUB:
10309         case BINOP_MUL:
10310         case BINOP_DIV:
10311         case BINOP_REM:
10312         case BINOP_MOD:
10313         case BINOP_LSH:
10314         case BINOP_RSH:
10315         case BINOP_LOGICAL_AND:
10316         case BINOP_LOGICAL_OR:
10317         case BINOP_BITWISE_AND:
10318         case BINOP_BITWISE_IOR:
10319         case BINOP_BITWISE_XOR:
10320         case BINOP_EQUAL:
10321         case BINOP_NOTEQUAL:
10322         case BINOP_LESS:
10323         case BINOP_GTR:
10324         case BINOP_LEQ:
10325         case BINOP_GEQ:
10326         case BINOP_REPEAT:
10327         case BINOP_COMMA:
10328         case BINOP_EXP:
10329         case BINOP_MIN:
10330         case BINOP_MAX:
10331         case BINOP_INTDIV:
10332         case BINOP_CONCAT:
10333         case BINOP_IN:
10334         case BINOP_RANGE:
10335         case TERNOP_COND:
10336         case TERNOP_SLICE:
10337
10338         case OP_LONG:
10339         case OP_DOUBLE:
10340         case OP_DECFLOAT:
10341         case OP_LAST:
10342         case OP_COMPLEX:
10343         case OP_STRING:
10344         case OP_ARRAY:
10345         case OP_TYPE:
10346         case OP_TYPEOF:
10347         case OP_DECLTYPE:
10348         case OP_TYPEID:
10349         case OP_NAME:
10350         case OP_OBJC_NSSTRING:
10351
10352         case UNOP_NEG:
10353         case UNOP_LOGICAL_NOT:
10354         case UNOP_COMPLEMENT:
10355         case UNOP_ADDR:
10356         case UNOP_HIGH:
10357         case UNOP_CAST:
10358
10359         case UNOP_CAST_TYPE:
10360         case UNOP_REINTERPRET_CAST:
10361         case UNOP_DYNAMIC_CAST:
10362           /* Unary, binary and ternary operators: We have to check
10363              their operands.  If they are constant, then so is the
10364              result of that operation.  For instance, if A and B are
10365              determined to be constants, then so is "A + B".
10366
10367              UNOP_IND is one exception to the rule above, because the
10368              value of *ADDR is not necessarily a constant, even when
10369              ADDR is.  */
10370           break;
10371
10372         case OP_VAR_VALUE:
10373           /* Check whether the associated symbol is a constant.
10374
10375              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10376              possible that a buggy compiler could mark a variable as
10377              constant even when it is not, and TYPE_CONST would return
10378              true in this case, while SYMBOL_CLASS wouldn't.
10379
10380              We also have to check for function symbols because they
10381              are always constant.  */
10382           {
10383             struct symbol *s = exp->elts[i + 2].symbol;
10384
10385             if (SYMBOL_CLASS (s) != LOC_BLOCK
10386                 && SYMBOL_CLASS (s) != LOC_CONST
10387                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10388               return 0;
10389             break;
10390           }
10391
10392         /* The default action is to return 0 because we are using
10393            the optimistic approach here: If we don't know something,
10394            then it is not a constant.  */
10395         default:
10396           return 0;
10397         }
10398     }
10399
10400   return 1;
10401 }
10402
10403 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10404
10405 static void
10406 dtor_watchpoint (struct breakpoint *self)
10407 {
10408   struct watchpoint *w = (struct watchpoint *) self;
10409
10410   xfree (w->cond_exp);
10411   xfree (w->exp);
10412   xfree (w->exp_string);
10413   xfree (w->exp_string_reparse);
10414   value_free (w->val);
10415
10416   base_breakpoint_ops.dtor (self);
10417 }
10418
10419 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10420
10421 static void
10422 re_set_watchpoint (struct breakpoint *b)
10423 {
10424   struct watchpoint *w = (struct watchpoint *) b;
10425
10426   /* Watchpoint can be either on expression using entirely global
10427      variables, or it can be on local variables.
10428
10429      Watchpoints of the first kind are never auto-deleted, and even
10430      persist across program restarts.  Since they can use variables
10431      from shared libraries, we need to reparse expression as libraries
10432      are loaded and unloaded.
10433
10434      Watchpoints on local variables can also change meaning as result
10435      of solib event.  For example, if a watchpoint uses both a local
10436      and a global variables in expression, it's a local watchpoint,
10437      but unloading of a shared library will make the expression
10438      invalid.  This is not a very common use case, but we still
10439      re-evaluate expression, to avoid surprises to the user.
10440
10441      Note that for local watchpoints, we re-evaluate it only if
10442      watchpoints frame id is still valid.  If it's not, it means the
10443      watchpoint is out of scope and will be deleted soon.  In fact,
10444      I'm not sure we'll ever be called in this case.
10445
10446      If a local watchpoint's frame id is still valid, then
10447      w->exp_valid_block is likewise valid, and we can safely use it.
10448
10449      Don't do anything about disabled watchpoints, since they will be
10450      reevaluated again when enabled.  */
10451   update_watchpoint (w, 1 /* reparse */);
10452 }
10453
10454 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10455
10456 static int
10457 insert_watchpoint (struct bp_location *bl)
10458 {
10459   struct watchpoint *w = (struct watchpoint *) bl->owner;
10460   int length = w->exact ? 1 : bl->length;
10461
10462   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10463                                    w->cond_exp);
10464 }
10465
10466 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10467
10468 static int
10469 remove_watchpoint (struct bp_location *bl)
10470 {
10471   struct watchpoint *w = (struct watchpoint *) bl->owner;
10472   int length = w->exact ? 1 : bl->length;
10473
10474   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10475                                    w->cond_exp);
10476 }
10477
10478 static int
10479 breakpoint_hit_watchpoint (const struct bp_location *bl,
10480                            struct address_space *aspace, CORE_ADDR bp_addr,
10481                            const struct target_waitstatus *ws)
10482 {
10483   struct breakpoint *b = bl->owner;
10484   struct watchpoint *w = (struct watchpoint *) b;
10485
10486   /* Continuable hardware watchpoints are treated as non-existent if the
10487      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10488      some data address).  Otherwise gdb won't stop on a break instruction
10489      in the code (not from a breakpoint) when a hardware watchpoint has
10490      been defined.  Also skip watchpoints which we know did not trigger
10491      (did not match the data address).  */
10492   if (is_hardware_watchpoint (b)
10493       && w->watchpoint_triggered == watch_triggered_no)
10494     return 0;
10495
10496   return 1;
10497 }
10498
10499 static void
10500 check_status_watchpoint (bpstat bs)
10501 {
10502   gdb_assert (is_watchpoint (bs->breakpoint_at));
10503
10504   bpstat_check_watchpoint (bs);
10505 }
10506
10507 /* Implement the "resources_needed" breakpoint_ops method for
10508    hardware watchpoints.  */
10509
10510 static int
10511 resources_needed_watchpoint (const struct bp_location *bl)
10512 {
10513   struct watchpoint *w = (struct watchpoint *) bl->owner;
10514   int length = w->exact? 1 : bl->length;
10515
10516   return target_region_ok_for_hw_watchpoint (bl->address, length);
10517 }
10518
10519 /* Implement the "works_in_software_mode" breakpoint_ops method for
10520    hardware watchpoints.  */
10521
10522 static int
10523 works_in_software_mode_watchpoint (const struct breakpoint *b)
10524 {
10525   /* Read and access watchpoints only work with hardware support.  */
10526   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10527 }
10528
10529 static enum print_stop_action
10530 print_it_watchpoint (bpstat bs)
10531 {
10532   struct cleanup *old_chain;
10533   struct breakpoint *b;
10534   struct ui_file *stb;
10535   enum print_stop_action result;
10536   struct watchpoint *w;
10537   struct ui_out *uiout = current_uiout;
10538
10539   gdb_assert (bs->bp_location_at != NULL);
10540
10541   b = bs->breakpoint_at;
10542   w = (struct watchpoint *) b;
10543
10544   stb = mem_fileopen ();
10545   old_chain = make_cleanup_ui_file_delete (stb);
10546
10547   switch (b->type)
10548     {
10549     case bp_watchpoint:
10550     case bp_hardware_watchpoint:
10551       annotate_watchpoint (b->number);
10552       if (ui_out_is_mi_like_p (uiout))
10553         ui_out_field_string
10554           (uiout, "reason",
10555            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10556       mention (b);
10557       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10558       ui_out_text (uiout, "\nOld value = ");
10559       watchpoint_value_print (bs->old_val, stb);
10560       ui_out_field_stream (uiout, "old", stb);
10561       ui_out_text (uiout, "\nNew value = ");
10562       watchpoint_value_print (w->val, stb);
10563       ui_out_field_stream (uiout, "new", stb);
10564       ui_out_text (uiout, "\n");
10565       /* More than one watchpoint may have been triggered.  */
10566       result = PRINT_UNKNOWN;
10567       break;
10568
10569     case bp_read_watchpoint:
10570       if (ui_out_is_mi_like_p (uiout))
10571         ui_out_field_string
10572           (uiout, "reason",
10573            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10574       mention (b);
10575       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10576       ui_out_text (uiout, "\nValue = ");
10577       watchpoint_value_print (w->val, stb);
10578       ui_out_field_stream (uiout, "value", stb);
10579       ui_out_text (uiout, "\n");
10580       result = PRINT_UNKNOWN;
10581       break;
10582
10583     case bp_access_watchpoint:
10584       if (bs->old_val != NULL)
10585         {
10586           annotate_watchpoint (b->number);
10587           if (ui_out_is_mi_like_p (uiout))
10588             ui_out_field_string
10589               (uiout, "reason",
10590                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10591           mention (b);
10592           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10593           ui_out_text (uiout, "\nOld value = ");
10594           watchpoint_value_print (bs->old_val, stb);
10595           ui_out_field_stream (uiout, "old", stb);
10596           ui_out_text (uiout, "\nNew value = ");
10597         }
10598       else
10599         {
10600           mention (b);
10601           if (ui_out_is_mi_like_p (uiout))
10602             ui_out_field_string
10603               (uiout, "reason",
10604                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10605           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10606           ui_out_text (uiout, "\nValue = ");
10607         }
10608       watchpoint_value_print (w->val, stb);
10609       ui_out_field_stream (uiout, "new", stb);
10610       ui_out_text (uiout, "\n");
10611       result = PRINT_UNKNOWN;
10612       break;
10613     default:
10614       result = PRINT_UNKNOWN;
10615     }
10616
10617   do_cleanups (old_chain);
10618   return result;
10619 }
10620
10621 /* Implement the "print_mention" breakpoint_ops method for hardware
10622    watchpoints.  */
10623
10624 static void
10625 print_mention_watchpoint (struct breakpoint *b)
10626 {
10627   struct cleanup *ui_out_chain;
10628   struct watchpoint *w = (struct watchpoint *) b;
10629   struct ui_out *uiout = current_uiout;
10630
10631   switch (b->type)
10632     {
10633     case bp_watchpoint:
10634       ui_out_text (uiout, "Watchpoint ");
10635       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10636       break;
10637     case bp_hardware_watchpoint:
10638       ui_out_text (uiout, "Hardware watchpoint ");
10639       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10640       break;
10641     case bp_read_watchpoint:
10642       ui_out_text (uiout, "Hardware read watchpoint ");
10643       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10644       break;
10645     case bp_access_watchpoint:
10646       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10647       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10648       break;
10649     default:
10650       internal_error (__FILE__, __LINE__,
10651                       _("Invalid hardware watchpoint type."));
10652     }
10653
10654   ui_out_field_int (uiout, "number", b->number);
10655   ui_out_text (uiout, ": ");
10656   ui_out_field_string (uiout, "exp", w->exp_string);
10657   do_cleanups (ui_out_chain);
10658 }
10659
10660 /* Implement the "print_recreate" breakpoint_ops method for
10661    watchpoints.  */
10662
10663 static void
10664 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10665 {
10666   struct watchpoint *w = (struct watchpoint *) b;
10667
10668   switch (b->type)
10669     {
10670     case bp_watchpoint:
10671     case bp_hardware_watchpoint:
10672       fprintf_unfiltered (fp, "watch");
10673       break;
10674     case bp_read_watchpoint:
10675       fprintf_unfiltered (fp, "rwatch");
10676       break;
10677     case bp_access_watchpoint:
10678       fprintf_unfiltered (fp, "awatch");
10679       break;
10680     default:
10681       internal_error (__FILE__, __LINE__,
10682                       _("Invalid watchpoint type."));
10683     }
10684
10685   fprintf_unfiltered (fp, " %s", w->exp_string);
10686   print_recreate_thread (b, fp);
10687 }
10688
10689 /* Implement the "explains_signal" breakpoint_ops method for
10690    watchpoints.  */
10691
10692 static enum bpstat_signal_value
10693 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10694 {
10695   /* A software watchpoint cannot cause a signal other than
10696      GDB_SIGNAL_TRAP.  */
10697   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10698     return BPSTAT_SIGNAL_NO;
10699
10700   return BPSTAT_SIGNAL_HIDE;
10701 }
10702
10703 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10704
10705 static struct breakpoint_ops watchpoint_breakpoint_ops;
10706
10707 /* Implement the "insert" breakpoint_ops method for
10708    masked hardware watchpoints.  */
10709
10710 static int
10711 insert_masked_watchpoint (struct bp_location *bl)
10712 {
10713   struct watchpoint *w = (struct watchpoint *) bl->owner;
10714
10715   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10716                                         bl->watchpoint_type);
10717 }
10718
10719 /* Implement the "remove" breakpoint_ops method for
10720    masked hardware watchpoints.  */
10721
10722 static int
10723 remove_masked_watchpoint (struct bp_location *bl)
10724 {
10725   struct watchpoint *w = (struct watchpoint *) bl->owner;
10726
10727   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10728                                         bl->watchpoint_type);
10729 }
10730
10731 /* Implement the "resources_needed" breakpoint_ops method for
10732    masked hardware watchpoints.  */
10733
10734 static int
10735 resources_needed_masked_watchpoint (const struct bp_location *bl)
10736 {
10737   struct watchpoint *w = (struct watchpoint *) bl->owner;
10738
10739   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10740 }
10741
10742 /* Implement the "works_in_software_mode" breakpoint_ops method for
10743    masked hardware watchpoints.  */
10744
10745 static int
10746 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10747 {
10748   return 0;
10749 }
10750
10751 /* Implement the "print_it" breakpoint_ops method for
10752    masked hardware watchpoints.  */
10753
10754 static enum print_stop_action
10755 print_it_masked_watchpoint (bpstat bs)
10756 {
10757   struct breakpoint *b = bs->breakpoint_at;
10758   struct ui_out *uiout = current_uiout;
10759
10760   /* Masked watchpoints have only one location.  */
10761   gdb_assert (b->loc && b->loc->next == NULL);
10762
10763   switch (b->type)
10764     {
10765     case bp_hardware_watchpoint:
10766       annotate_watchpoint (b->number);
10767       if (ui_out_is_mi_like_p (uiout))
10768         ui_out_field_string
10769           (uiout, "reason",
10770            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10771       break;
10772
10773     case bp_read_watchpoint:
10774       if (ui_out_is_mi_like_p (uiout))
10775         ui_out_field_string
10776           (uiout, "reason",
10777            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10778       break;
10779
10780     case bp_access_watchpoint:
10781       if (ui_out_is_mi_like_p (uiout))
10782         ui_out_field_string
10783           (uiout, "reason",
10784            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10785       break;
10786     default:
10787       internal_error (__FILE__, __LINE__,
10788                       _("Invalid hardware watchpoint type."));
10789     }
10790
10791   mention (b);
10792   ui_out_text (uiout, _("\n\
10793 Check the underlying instruction at PC for the memory\n\
10794 address and value which triggered this watchpoint.\n"));
10795   ui_out_text (uiout, "\n");
10796
10797   /* More than one watchpoint may have been triggered.  */
10798   return PRINT_UNKNOWN;
10799 }
10800
10801 /* Implement the "print_one_detail" breakpoint_ops method for
10802    masked hardware watchpoints.  */
10803
10804 static void
10805 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10806                                     struct ui_out *uiout)
10807 {
10808   struct watchpoint *w = (struct watchpoint *) b;
10809
10810   /* Masked watchpoints have only one location.  */
10811   gdb_assert (b->loc && b->loc->next == NULL);
10812
10813   ui_out_text (uiout, "\tmask ");
10814   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10815   ui_out_text (uiout, "\n");
10816 }
10817
10818 /* Implement the "print_mention" breakpoint_ops method for
10819    masked hardware watchpoints.  */
10820
10821 static void
10822 print_mention_masked_watchpoint (struct breakpoint *b)
10823 {
10824   struct watchpoint *w = (struct watchpoint *) b;
10825   struct ui_out *uiout = current_uiout;
10826   struct cleanup *ui_out_chain;
10827
10828   switch (b->type)
10829     {
10830     case bp_hardware_watchpoint:
10831       ui_out_text (uiout, "Masked hardware watchpoint ");
10832       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10833       break;
10834     case bp_read_watchpoint:
10835       ui_out_text (uiout, "Masked hardware read watchpoint ");
10836       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10837       break;
10838     case bp_access_watchpoint:
10839       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10840       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10841       break;
10842     default:
10843       internal_error (__FILE__, __LINE__,
10844                       _("Invalid hardware watchpoint type."));
10845     }
10846
10847   ui_out_field_int (uiout, "number", b->number);
10848   ui_out_text (uiout, ": ");
10849   ui_out_field_string (uiout, "exp", w->exp_string);
10850   do_cleanups (ui_out_chain);
10851 }
10852
10853 /* Implement the "print_recreate" breakpoint_ops method for
10854    masked hardware watchpoints.  */
10855
10856 static void
10857 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10858 {
10859   struct watchpoint *w = (struct watchpoint *) b;
10860   char tmp[40];
10861
10862   switch (b->type)
10863     {
10864     case bp_hardware_watchpoint:
10865       fprintf_unfiltered (fp, "watch");
10866       break;
10867     case bp_read_watchpoint:
10868       fprintf_unfiltered (fp, "rwatch");
10869       break;
10870     case bp_access_watchpoint:
10871       fprintf_unfiltered (fp, "awatch");
10872       break;
10873     default:
10874       internal_error (__FILE__, __LINE__,
10875                       _("Invalid hardware watchpoint type."));
10876     }
10877
10878   sprintf_vma (tmp, w->hw_wp_mask);
10879   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10880   print_recreate_thread (b, fp);
10881 }
10882
10883 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10884
10885 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10886
10887 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10888
10889 static int
10890 is_masked_watchpoint (const struct breakpoint *b)
10891 {
10892   return b->ops == &masked_watchpoint_breakpoint_ops;
10893 }
10894
10895 /* accessflag:  hw_write:  watch write, 
10896                 hw_read:   watch read, 
10897                 hw_access: watch access (read or write) */
10898 static void
10899 watch_command_1 (const char *arg, int accessflag, int from_tty,
10900                  int just_location, int internal)
10901 {
10902   volatile struct gdb_exception e;
10903   struct breakpoint *b, *scope_breakpoint = NULL;
10904   struct expression *exp;
10905   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10906   struct value *val, *mark, *result;
10907   struct frame_info *frame;
10908   const char *exp_start = NULL;
10909   const char *exp_end = NULL;
10910   const char *tok, *end_tok;
10911   int toklen = -1;
10912   const char *cond_start = NULL;
10913   const char *cond_end = NULL;
10914   enum bptype bp_type;
10915   int thread = -1;
10916   int pc = 0;
10917   /* Flag to indicate whether we are going to use masks for
10918      the hardware watchpoint.  */
10919   int use_mask = 0;
10920   CORE_ADDR mask = 0;
10921   struct watchpoint *w;
10922   char *expression;
10923   struct cleanup *back_to;
10924
10925   /* Make sure that we actually have parameters to parse.  */
10926   if (arg != NULL && arg[0] != '\0')
10927     {
10928       const char *value_start;
10929
10930       exp_end = arg + strlen (arg);
10931
10932       /* Look for "parameter value" pairs at the end
10933          of the arguments string.  */
10934       for (tok = exp_end - 1; tok > arg; tok--)
10935         {
10936           /* Skip whitespace at the end of the argument list.  */
10937           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10938             tok--;
10939
10940           /* Find the beginning of the last token.
10941              This is the value of the parameter.  */
10942           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10943             tok--;
10944           value_start = tok + 1;
10945
10946           /* Skip whitespace.  */
10947           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10948             tok--;
10949
10950           end_tok = tok;
10951
10952           /* Find the beginning of the second to last token.
10953              This is the parameter itself.  */
10954           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10955             tok--;
10956           tok++;
10957           toklen = end_tok - tok + 1;
10958
10959           if (toklen == 6 && !strncmp (tok, "thread", 6))
10960             {
10961               /* At this point we've found a "thread" token, which means
10962                  the user is trying to set a watchpoint that triggers
10963                  only in a specific thread.  */
10964               char *endp;
10965
10966               if (thread != -1)
10967                 error(_("You can specify only one thread."));
10968
10969               /* Extract the thread ID from the next token.  */
10970               thread = strtol (value_start, &endp, 0);
10971
10972               /* Check if the user provided a valid numeric value for the
10973                  thread ID.  */
10974               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10975                 error (_("Invalid thread ID specification %s."), value_start);
10976
10977               /* Check if the thread actually exists.  */
10978               if (!valid_thread_id (thread))
10979                 invalid_thread_id_error (thread);
10980             }
10981           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10982             {
10983               /* We've found a "mask" token, which means the user wants to
10984                  create a hardware watchpoint that is going to have the mask
10985                  facility.  */
10986               struct value *mask_value, *mark;
10987
10988               if (use_mask)
10989                 error(_("You can specify only one mask."));
10990
10991               use_mask = just_location = 1;
10992
10993               mark = value_mark ();
10994               mask_value = parse_to_comma_and_eval (&value_start);
10995               mask = value_as_address (mask_value);
10996               value_free_to_mark (mark);
10997             }
10998           else
10999             /* We didn't recognize what we found.  We should stop here.  */
11000             break;
11001
11002           /* Truncate the string and get rid of the "parameter value" pair before
11003              the arguments string is parsed by the parse_exp_1 function.  */
11004           exp_end = tok;
11005         }
11006     }
11007   else
11008     exp_end = arg;
11009
11010   /* Parse the rest of the arguments.  From here on out, everything
11011      is in terms of a newly allocated string instead of the original
11012      ARG.  */
11013   innermost_block = NULL;
11014   expression = savestring (arg, exp_end - arg);
11015   back_to = make_cleanup (xfree, expression);
11016   exp_start = arg = expression;
11017   exp = parse_exp_1 (&arg, 0, 0, 0);
11018   exp_end = arg;
11019   /* Remove trailing whitespace from the expression before saving it.
11020      This makes the eventual display of the expression string a bit
11021      prettier.  */
11022   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11023     --exp_end;
11024
11025   /* Checking if the expression is not constant.  */
11026   if (watchpoint_exp_is_const (exp))
11027     {
11028       int len;
11029
11030       len = exp_end - exp_start;
11031       while (len > 0 && isspace (exp_start[len - 1]))
11032         len--;
11033       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11034     }
11035
11036   exp_valid_block = innermost_block;
11037   mark = value_mark ();
11038   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11039
11040   if (just_location)
11041     {
11042       int ret;
11043
11044       exp_valid_block = NULL;
11045       val = value_addr (result);
11046       release_value (val);
11047       value_free_to_mark (mark);
11048
11049       if (use_mask)
11050         {
11051           ret = target_masked_watch_num_registers (value_as_address (val),
11052                                                    mask);
11053           if (ret == -1)
11054             error (_("This target does not support masked watchpoints."));
11055           else if (ret == -2)
11056             error (_("Invalid mask or memory region."));
11057         }
11058     }
11059   else if (val != NULL)
11060     release_value (val);
11061
11062   tok = skip_spaces_const (arg);
11063   end_tok = skip_to_space_const (tok);
11064
11065   toklen = end_tok - tok;
11066   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11067     {
11068       struct expression *cond;
11069
11070       innermost_block = NULL;
11071       tok = cond_start = end_tok + 1;
11072       cond = parse_exp_1 (&tok, 0, 0, 0);
11073
11074       /* The watchpoint expression may not be local, but the condition
11075          may still be.  E.g.: `watch global if local > 0'.  */
11076       cond_exp_valid_block = innermost_block;
11077
11078       xfree (cond);
11079       cond_end = tok;
11080     }
11081   if (*tok)
11082     error (_("Junk at end of command."));
11083
11084   if (accessflag == hw_read)
11085     bp_type = bp_read_watchpoint;
11086   else if (accessflag == hw_access)
11087     bp_type = bp_access_watchpoint;
11088   else
11089     bp_type = bp_hardware_watchpoint;
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.  */
11128
11129   w = XCNEW (struct watchpoint);
11130   b = &w->base;
11131   if (use_mask)
11132     init_raw_breakpoint_without_location (b, NULL, bp_type,
11133                                           &masked_watchpoint_breakpoint_ops);
11134   else
11135     init_raw_breakpoint_without_location (b, NULL, bp_type,
11136                                           &watchpoint_breakpoint_ops);
11137   b->thread = thread;
11138   b->disposition = disp_donttouch;
11139   b->pspace = current_program_space;
11140   w->exp = exp;
11141   w->exp_valid_block = exp_valid_block;
11142   w->cond_exp_valid_block = cond_exp_valid_block;
11143   if (just_location)
11144     {
11145       struct type *t = value_type (val);
11146       CORE_ADDR addr = value_as_address (val);
11147       char *name;
11148
11149       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11150       name = type_to_string (t);
11151
11152       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11153                                           core_addr_to_string (addr));
11154       xfree (name);
11155
11156       w->exp_string = xstrprintf ("-location %.*s",
11157                                   (int) (exp_end - exp_start), exp_start);
11158
11159       /* The above expression is in C.  */
11160       b->language = language_c;
11161     }
11162   else
11163     w->exp_string = savestring (exp_start, exp_end - exp_start);
11164
11165   if (use_mask)
11166     {
11167       w->hw_wp_mask = mask;
11168     }
11169   else
11170     {
11171       w->val = val;
11172       w->val_valid = 1;
11173     }
11174
11175   if (cond_start)
11176     b->cond_string = savestring (cond_start, cond_end - cond_start);
11177   else
11178     b->cond_string = 0;
11179
11180   if (frame)
11181     {
11182       w->watchpoint_frame = get_frame_id (frame);
11183       w->watchpoint_thread = inferior_ptid;
11184     }
11185   else
11186     {
11187       w->watchpoint_frame = null_frame_id;
11188       w->watchpoint_thread = null_ptid;
11189     }
11190
11191   if (scope_breakpoint != NULL)
11192     {
11193       /* The scope breakpoint is related to the watchpoint.  We will
11194          need to act on them together.  */
11195       b->related_breakpoint = scope_breakpoint;
11196       scope_breakpoint->related_breakpoint = b;
11197     }
11198
11199   if (!just_location)
11200     value_free_to_mark (mark);
11201
11202   TRY_CATCH (e, RETURN_MASK_ALL)
11203     {
11204       /* Finally update the new watchpoint.  This creates the locations
11205          that should be inserted.  */
11206       update_watchpoint (w, 1);
11207     }
11208   if (e.reason < 0)
11209     {
11210       delete_breakpoint (b);
11211       throw_exception (e);
11212     }
11213
11214   install_breakpoint (internal, b, 1);
11215   do_cleanups (back_to);
11216 }
11217
11218 /* Return count of debug registers needed to watch the given expression.
11219    If the watchpoint cannot be handled in hardware return zero.  */
11220
11221 static int
11222 can_use_hardware_watchpoint (struct value *v)
11223 {
11224   int found_memory_cnt = 0;
11225   struct value *head = v;
11226
11227   /* Did the user specifically forbid us to use hardware watchpoints? */
11228   if (!can_use_hw_watchpoints)
11229     return 0;
11230
11231   /* Make sure that the value of the expression depends only upon
11232      memory contents, and values computed from them within GDB.  If we
11233      find any register references or function calls, we can't use a
11234      hardware watchpoint.
11235
11236      The idea here is that evaluating an expression generates a series
11237      of values, one holding the value of every subexpression.  (The
11238      expression a*b+c has five subexpressions: a, b, a*b, c, and
11239      a*b+c.)  GDB's values hold almost enough information to establish
11240      the criteria given above --- they identify memory lvalues,
11241      register lvalues, computed values, etcetera.  So we can evaluate
11242      the expression, and then scan the chain of values that leaves
11243      behind to decide whether we can detect any possible change to the
11244      expression's final value using only hardware watchpoints.
11245
11246      However, I don't think that the values returned by inferior
11247      function calls are special in any way.  So this function may not
11248      notice that an expression involving an inferior function call
11249      can't be watched with hardware watchpoints.  FIXME.  */
11250   for (; v; v = value_next (v))
11251     {
11252       if (VALUE_LVAL (v) == lval_memory)
11253         {
11254           if (v != head && value_lazy (v))
11255             /* A lazy memory lvalue in the chain is one that GDB never
11256                needed to fetch; we either just used its address (e.g.,
11257                `a' in `a.b') or we never needed it at all (e.g., `a'
11258                in `a,b').  This doesn't apply to HEAD; if that is
11259                lazy then it was not readable, but watch it anyway.  */
11260             ;
11261           else
11262             {
11263               /* Ahh, memory we actually used!  Check if we can cover
11264                  it with hardware watchpoints.  */
11265               struct type *vtype = check_typedef (value_type (v));
11266
11267               /* We only watch structs and arrays if user asked for it
11268                  explicitly, never if they just happen to appear in a
11269                  middle of some value chain.  */
11270               if (v == head
11271                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11272                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11273                 {
11274                   CORE_ADDR vaddr = value_address (v);
11275                   int len;
11276                   int num_regs;
11277
11278                   len = (target_exact_watchpoints
11279                          && is_scalar_type_recursive (vtype))?
11280                     1 : TYPE_LENGTH (value_type (v));
11281
11282                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11283                   if (!num_regs)
11284                     return 0;
11285                   else
11286                     found_memory_cnt += num_regs;
11287                 }
11288             }
11289         }
11290       else if (VALUE_LVAL (v) != not_lval
11291                && deprecated_value_modifiable (v) == 0)
11292         return 0;       /* These are values from the history (e.g., $1).  */
11293       else if (VALUE_LVAL (v) == lval_register)
11294         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11295     }
11296
11297   /* The expression itself looks suitable for using a hardware
11298      watchpoint, but give the target machine a chance to reject it.  */
11299   return found_memory_cnt;
11300 }
11301
11302 void
11303 watch_command_wrapper (char *arg, int from_tty, int internal)
11304 {
11305   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11306 }
11307
11308 /* A helper function that looks for the "-location" argument and then
11309    calls watch_command_1.  */
11310
11311 static void
11312 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11313 {
11314   int just_location = 0;
11315
11316   if (arg
11317       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11318           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11319     {
11320       arg = skip_spaces (arg);
11321       just_location = 1;
11322     }
11323
11324   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11325 }
11326
11327 static void
11328 watch_command (char *arg, int from_tty)
11329 {
11330   watch_maybe_just_location (arg, hw_write, from_tty);
11331 }
11332
11333 void
11334 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11335 {
11336   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11337 }
11338
11339 static void
11340 rwatch_command (char *arg, int from_tty)
11341 {
11342   watch_maybe_just_location (arg, hw_read, from_tty);
11343 }
11344
11345 void
11346 awatch_command_wrapper (char *arg, int from_tty, int internal)
11347 {
11348   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11349 }
11350
11351 static void
11352 awatch_command (char *arg, int from_tty)
11353 {
11354   watch_maybe_just_location (arg, hw_access, from_tty);
11355 }
11356 \f
11357
11358 /* Helper routines for the until_command routine in infcmd.c.  Here
11359    because it uses the mechanisms of breakpoints.  */
11360
11361 struct until_break_command_continuation_args
11362 {
11363   struct breakpoint *breakpoint;
11364   struct breakpoint *breakpoint2;
11365   int thread_num;
11366 };
11367
11368 /* This function is called by fetch_inferior_event via the
11369    cmd_continuation pointer, to complete the until command.  It takes
11370    care of cleaning up the temporary breakpoints set up by the until
11371    command.  */
11372 static void
11373 until_break_command_continuation (void *arg, int err)
11374 {
11375   struct until_break_command_continuation_args *a = arg;
11376
11377   delete_breakpoint (a->breakpoint);
11378   if (a->breakpoint2)
11379     delete_breakpoint (a->breakpoint2);
11380   delete_longjmp_breakpoint (a->thread_num);
11381 }
11382
11383 void
11384 until_break_command (char *arg, int from_tty, int anywhere)
11385 {
11386   struct symtabs_and_lines sals;
11387   struct symtab_and_line sal;
11388   struct frame_info *frame;
11389   struct gdbarch *frame_gdbarch;
11390   struct frame_id stack_frame_id;
11391   struct frame_id caller_frame_id;
11392   struct breakpoint *breakpoint;
11393   struct breakpoint *breakpoint2 = NULL;
11394   struct cleanup *old_chain;
11395   int thread;
11396   struct thread_info *tp;
11397
11398   clear_proceed_status ();
11399
11400   /* Set a breakpoint where the user wants it and at return from
11401      this function.  */
11402
11403   if (last_displayed_sal_is_valid ())
11404     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11405                           get_last_displayed_symtab (),
11406                           get_last_displayed_line ());
11407   else
11408     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11409                           (struct symtab *) NULL, 0);
11410
11411   if (sals.nelts != 1)
11412     error (_("Couldn't get information on specified line."));
11413
11414   sal = sals.sals[0];
11415   xfree (sals.sals);    /* malloc'd, so freed.  */
11416
11417   if (*arg)
11418     error (_("Junk at end of arguments."));
11419
11420   resolve_sal_pc (&sal);
11421
11422   tp = inferior_thread ();
11423   thread = tp->num;
11424
11425   old_chain = make_cleanup (null_cleanup, NULL);
11426
11427   /* Note linespec handling above invalidates the frame chain.
11428      Installing a breakpoint also invalidates the frame chain (as it
11429      may need to switch threads), so do any frame handling before
11430      that.  */
11431
11432   frame = get_selected_frame (NULL);
11433   frame_gdbarch = get_frame_arch (frame);
11434   stack_frame_id = get_stack_frame_id (frame);
11435   caller_frame_id = frame_unwind_caller_id (frame);
11436
11437   /* Keep within the current frame, or in frames called by the current
11438      one.  */
11439
11440   if (frame_id_p (caller_frame_id))
11441     {
11442       struct symtab_and_line sal2;
11443
11444       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11445       sal2.pc = frame_unwind_caller_pc (frame);
11446       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11447                                               sal2,
11448                                               caller_frame_id,
11449                                               bp_until);
11450       make_cleanup_delete_breakpoint (breakpoint2);
11451
11452       set_longjmp_breakpoint (tp, caller_frame_id);
11453       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11454     }
11455
11456   /* set_momentary_breakpoint could invalidate FRAME.  */
11457   frame = NULL;
11458
11459   if (anywhere)
11460     /* If the user told us to continue until a specified location,
11461        we don't specify a frame at which we need to stop.  */
11462     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11463                                            null_frame_id, bp_until);
11464   else
11465     /* Otherwise, specify the selected frame, because we want to stop
11466        only at the very same frame.  */
11467     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11468                                            stack_frame_id, bp_until);
11469   make_cleanup_delete_breakpoint (breakpoint);
11470
11471   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11472
11473   /* If we are running asynchronously, and proceed call above has
11474      actually managed to start the target, arrange for breakpoints to
11475      be deleted when the target stops.  Otherwise, we're already
11476      stopped and delete breakpoints via cleanup chain.  */
11477
11478   if (target_can_async_p () && is_running (inferior_ptid))
11479     {
11480       struct until_break_command_continuation_args *args;
11481       args = xmalloc (sizeof (*args));
11482
11483       args->breakpoint = breakpoint;
11484       args->breakpoint2 = breakpoint2;
11485       args->thread_num = thread;
11486
11487       discard_cleanups (old_chain);
11488       add_continuation (inferior_thread (),
11489                         until_break_command_continuation, args,
11490                         xfree);
11491     }
11492   else
11493     do_cleanups (old_chain);
11494 }
11495
11496 /* This function attempts to parse an optional "if <cond>" clause
11497    from the arg string.  If one is not found, it returns NULL.
11498
11499    Else, it returns a pointer to the condition string.  (It does not
11500    attempt to evaluate the string against a particular block.)  And,
11501    it updates arg to point to the first character following the parsed
11502    if clause in the arg string.  */
11503
11504 char *
11505 ep_parse_optional_if_clause (char **arg)
11506 {
11507   char *cond_string;
11508
11509   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11510     return NULL;
11511
11512   /* Skip the "if" keyword.  */
11513   (*arg) += 2;
11514
11515   /* Skip any extra leading whitespace, and record the start of the
11516      condition string.  */
11517   *arg = skip_spaces (*arg);
11518   cond_string = *arg;
11519
11520   /* Assume that the condition occupies the remainder of the arg
11521      string.  */
11522   (*arg) += strlen (cond_string);
11523
11524   return cond_string;
11525 }
11526
11527 /* Commands to deal with catching events, such as signals, exceptions,
11528    process start/exit, etc.  */
11529
11530 typedef enum
11531 {
11532   catch_fork_temporary, catch_vfork_temporary,
11533   catch_fork_permanent, catch_vfork_permanent
11534 }
11535 catch_fork_kind;
11536
11537 static void
11538 catch_fork_command_1 (char *arg, int from_tty, 
11539                       struct cmd_list_element *command)
11540 {
11541   struct gdbarch *gdbarch = get_current_arch ();
11542   char *cond_string = NULL;
11543   catch_fork_kind fork_kind;
11544   int tempflag;
11545
11546   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11547   tempflag = (fork_kind == catch_fork_temporary
11548               || fork_kind == catch_vfork_temporary);
11549
11550   if (!arg)
11551     arg = "";
11552   arg = skip_spaces (arg);
11553
11554   /* The allowed syntax is:
11555      catch [v]fork
11556      catch [v]fork if <cond>
11557
11558      First, check if there's an if clause.  */
11559   cond_string = ep_parse_optional_if_clause (&arg);
11560
11561   if ((*arg != '\0') && !isspace (*arg))
11562     error (_("Junk at end of arguments."));
11563
11564   /* If this target supports it, create a fork or vfork catchpoint
11565      and enable reporting of such events.  */
11566   switch (fork_kind)
11567     {
11568     case catch_fork_temporary:
11569     case catch_fork_permanent:
11570       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11571                                           &catch_fork_breakpoint_ops);
11572       break;
11573     case catch_vfork_temporary:
11574     case catch_vfork_permanent:
11575       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11576                                           &catch_vfork_breakpoint_ops);
11577       break;
11578     default:
11579       error (_("unsupported or unknown fork kind; cannot catch it"));
11580       break;
11581     }
11582 }
11583
11584 static void
11585 catch_exec_command_1 (char *arg, int from_tty, 
11586                       struct cmd_list_element *command)
11587 {
11588   struct exec_catchpoint *c;
11589   struct gdbarch *gdbarch = get_current_arch ();
11590   int tempflag;
11591   char *cond_string = NULL;
11592
11593   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11594
11595   if (!arg)
11596     arg = "";
11597   arg = skip_spaces (arg);
11598
11599   /* The allowed syntax is:
11600      catch exec
11601      catch exec if <cond>
11602
11603      First, check if there's an if clause.  */
11604   cond_string = ep_parse_optional_if_clause (&arg);
11605
11606   if ((*arg != '\0') && !isspace (*arg))
11607     error (_("Junk at end of arguments."));
11608
11609   c = XNEW (struct exec_catchpoint);
11610   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11611                    &catch_exec_breakpoint_ops);
11612   c->exec_pathname = NULL;
11613
11614   install_breakpoint (0, &c->base, 1);
11615 }
11616
11617 void
11618 init_ada_exception_breakpoint (struct breakpoint *b,
11619                                struct gdbarch *gdbarch,
11620                                struct symtab_and_line sal,
11621                                char *addr_string,
11622                                const struct breakpoint_ops *ops,
11623                                int tempflag,
11624                                int from_tty)
11625 {
11626   if (from_tty)
11627     {
11628       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11629       if (!loc_gdbarch)
11630         loc_gdbarch = gdbarch;
11631
11632       describe_other_breakpoints (loc_gdbarch,
11633                                   sal.pspace, sal.pc, sal.section, -1);
11634       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11635          version for exception catchpoints, because two catchpoints
11636          used for different exception names will use the same address.
11637          In this case, a "breakpoint ... also set at..." warning is
11638          unproductive.  Besides, the warning phrasing is also a bit
11639          inappropriate, we should use the word catchpoint, and tell
11640          the user what type of catchpoint it is.  The above is good
11641          enough for now, though.  */
11642     }
11643
11644   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11645
11646   b->enable_state = bp_enabled;
11647   b->disposition = tempflag ? disp_del : disp_donttouch;
11648   b->addr_string = addr_string;
11649   b->language = language_ada;
11650 }
11651
11652 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11653    filter list, or NULL if no filtering is required.  */
11654 static VEC(int) *
11655 catch_syscall_split_args (char *arg)
11656 {
11657   VEC(int) *result = NULL;
11658   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11659
11660   while (*arg != '\0')
11661     {
11662       int i, syscall_number;
11663       char *endptr;
11664       char cur_name[128];
11665       struct syscall s;
11666
11667       /* Skip whitespace.  */
11668       arg = skip_spaces (arg);
11669
11670       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11671         cur_name[i] = arg[i];
11672       cur_name[i] = '\0';
11673       arg += i;
11674
11675       /* Check if the user provided a syscall name or a number.  */
11676       syscall_number = (int) strtol (cur_name, &endptr, 0);
11677       if (*endptr == '\0')
11678         get_syscall_by_number (syscall_number, &s);
11679       else
11680         {
11681           /* We have a name.  Let's check if it's valid and convert it
11682              to a number.  */
11683           get_syscall_by_name (cur_name, &s);
11684
11685           if (s.number == UNKNOWN_SYSCALL)
11686             /* Here we have to issue an error instead of a warning,
11687                because GDB cannot do anything useful if there's no
11688                syscall number to be caught.  */
11689             error (_("Unknown syscall name '%s'."), cur_name);
11690         }
11691
11692       /* Ok, it's valid.  */
11693       VEC_safe_push (int, result, s.number);
11694     }
11695
11696   discard_cleanups (cleanup);
11697   return result;
11698 }
11699
11700 /* Implement the "catch syscall" command.  */
11701
11702 static void
11703 catch_syscall_command_1 (char *arg, int from_tty, 
11704                          struct cmd_list_element *command)
11705 {
11706   int tempflag;
11707   VEC(int) *filter;
11708   struct syscall s;
11709   struct gdbarch *gdbarch = get_current_arch ();
11710
11711   /* Checking if the feature if supported.  */
11712   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11713     error (_("The feature 'catch syscall' is not supported on \
11714 this architecture yet."));
11715
11716   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11717
11718   arg = skip_spaces (arg);
11719
11720   /* We need to do this first "dummy" translation in order
11721      to get the syscall XML file loaded or, most important,
11722      to display a warning to the user if there's no XML file
11723      for his/her architecture.  */
11724   get_syscall_by_number (0, &s);
11725
11726   /* The allowed syntax is:
11727      catch syscall
11728      catch syscall <name | number> [<name | number> ... <name | number>]
11729
11730      Let's check if there's a syscall name.  */
11731
11732   if (arg != NULL)
11733     filter = catch_syscall_split_args (arg);
11734   else
11735     filter = NULL;
11736
11737   create_syscall_event_catchpoint (tempflag, filter,
11738                                    &catch_syscall_breakpoint_ops);
11739 }
11740
11741 static void
11742 catch_command (char *arg, int from_tty)
11743 {
11744   error (_("Catch requires an event name."));
11745 }
11746 \f
11747
11748 static void
11749 tcatch_command (char *arg, int from_tty)
11750 {
11751   error (_("Catch requires an event name."));
11752 }
11753
11754 /* A qsort comparison function that sorts breakpoints in order.  */
11755
11756 static int
11757 compare_breakpoints (const void *a, const void *b)
11758 {
11759   const breakpoint_p *ba = a;
11760   uintptr_t ua = (uintptr_t) *ba;
11761   const breakpoint_p *bb = b;
11762   uintptr_t ub = (uintptr_t) *bb;
11763
11764   if ((*ba)->number < (*bb)->number)
11765     return -1;
11766   else if ((*ba)->number > (*bb)->number)
11767     return 1;
11768
11769   /* Now sort by address, in case we see, e..g, two breakpoints with
11770      the number 0.  */
11771   if (ua < ub)
11772     return -1;
11773   return ua > ub ? 1 : 0;
11774 }
11775
11776 /* Delete breakpoints by address or line.  */
11777
11778 static void
11779 clear_command (char *arg, int from_tty)
11780 {
11781   struct breakpoint *b, *prev;
11782   VEC(breakpoint_p) *found = 0;
11783   int ix;
11784   int default_match;
11785   struct symtabs_and_lines sals;
11786   struct symtab_and_line sal;
11787   int i;
11788   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11789
11790   if (arg)
11791     {
11792       sals = decode_line_with_current_source (arg,
11793                                               (DECODE_LINE_FUNFIRSTLINE
11794                                                | DECODE_LINE_LIST_MODE));
11795       make_cleanup (xfree, sals.sals);
11796       default_match = 0;
11797     }
11798   else
11799     {
11800       sals.sals = (struct symtab_and_line *)
11801         xmalloc (sizeof (struct symtab_and_line));
11802       make_cleanup (xfree, sals.sals);
11803       init_sal (&sal);          /* Initialize to zeroes.  */
11804
11805       /* Set sal's line, symtab, pc, and pspace to the values
11806          corresponding to the last call to print_frame_info.  If the
11807          codepoint is not valid, this will set all the fields to 0.  */
11808       get_last_displayed_sal (&sal);
11809       if (sal.symtab == 0)
11810         error (_("No source file specified."));
11811
11812       sals.sals[0] = sal;
11813       sals.nelts = 1;
11814
11815       default_match = 1;
11816     }
11817
11818   /* We don't call resolve_sal_pc here.  That's not as bad as it
11819      seems, because all existing breakpoints typically have both
11820      file/line and pc set.  So, if clear is given file/line, we can
11821      match this to existing breakpoint without obtaining pc at all.
11822
11823      We only support clearing given the address explicitly 
11824      present in breakpoint table.  Say, we've set breakpoint 
11825      at file:line.  There were several PC values for that file:line,
11826      due to optimization, all in one block.
11827
11828      We've picked one PC value.  If "clear" is issued with another
11829      PC corresponding to the same file:line, the breakpoint won't
11830      be cleared.  We probably can still clear the breakpoint, but 
11831      since the other PC value is never presented to user, user
11832      can only find it by guessing, and it does not seem important
11833      to support that.  */
11834
11835   /* For each line spec given, delete bps which correspond to it.  Do
11836      it in two passes, solely to preserve the current behavior that
11837      from_tty is forced true if we delete more than one
11838      breakpoint.  */
11839
11840   found = NULL;
11841   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11842   for (i = 0; i < sals.nelts; i++)
11843     {
11844       const char *sal_fullname;
11845
11846       /* If exact pc given, clear bpts at that pc.
11847          If line given (pc == 0), clear all bpts on specified line.
11848          If defaulting, clear all bpts on default line
11849          or at default pc.
11850
11851          defaulting    sal.pc != 0    tests to do
11852
11853          0              1             pc
11854          1              1             pc _and_ line
11855          0              0             line
11856          1              0             <can't happen> */
11857
11858       sal = sals.sals[i];
11859       sal_fullname = (sal.symtab == NULL
11860                       ? NULL : symtab_to_fullname (sal.symtab));
11861
11862       /* Find all matching breakpoints and add them to 'found'.  */
11863       ALL_BREAKPOINTS (b)
11864         {
11865           int match = 0;
11866           /* Are we going to delete b?  */
11867           if (b->type != bp_none && !is_watchpoint (b))
11868             {
11869               struct bp_location *loc = b->loc;
11870               for (; loc; loc = loc->next)
11871                 {
11872                   /* If the user specified file:line, don't allow a PC
11873                      match.  This matches historical gdb behavior.  */
11874                   int pc_match = (!sal.explicit_line
11875                                   && sal.pc
11876                                   && (loc->pspace == sal.pspace)
11877                                   && (loc->address == sal.pc)
11878                                   && (!section_is_overlay (loc->section)
11879                                       || loc->section == sal.section));
11880                   int line_match = 0;
11881
11882                   if ((default_match || sal.explicit_line)
11883                       && loc->symtab != NULL
11884                       && sal_fullname != NULL
11885                       && sal.pspace == loc->pspace
11886                       && loc->line_number == sal.line
11887                       && filename_cmp (symtab_to_fullname (loc->symtab),
11888                                        sal_fullname) == 0)
11889                     line_match = 1;
11890
11891                   if (pc_match || line_match)
11892                     {
11893                       match = 1;
11894                       break;
11895                     }
11896                 }
11897             }
11898
11899           if (match)
11900             VEC_safe_push(breakpoint_p, found, b);
11901         }
11902     }
11903
11904   /* Now go thru the 'found' chain and delete them.  */
11905   if (VEC_empty(breakpoint_p, found))
11906     {
11907       if (arg)
11908         error (_("No breakpoint at %s."), arg);
11909       else
11910         error (_("No breakpoint at this line."));
11911     }
11912
11913   /* Remove duplicates from the vec.  */
11914   qsort (VEC_address (breakpoint_p, found),
11915          VEC_length (breakpoint_p, found),
11916          sizeof (breakpoint_p),
11917          compare_breakpoints);
11918   prev = VEC_index (breakpoint_p, found, 0);
11919   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11920     {
11921       if (b == prev)
11922         {
11923           VEC_ordered_remove (breakpoint_p, found, ix);
11924           --ix;
11925         }
11926     }
11927
11928   if (VEC_length(breakpoint_p, found) > 1)
11929     from_tty = 1;       /* Always report if deleted more than one.  */
11930   if (from_tty)
11931     {
11932       if (VEC_length(breakpoint_p, found) == 1)
11933         printf_unfiltered (_("Deleted breakpoint "));
11934       else
11935         printf_unfiltered (_("Deleted breakpoints "));
11936     }
11937
11938   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11939     {
11940       if (from_tty)
11941         printf_unfiltered ("%d ", b->number);
11942       delete_breakpoint (b);
11943     }
11944   if (from_tty)
11945     putchar_unfiltered ('\n');
11946
11947   do_cleanups (cleanups);
11948 }
11949 \f
11950 /* Delete breakpoint in BS if they are `delete' breakpoints and
11951    all breakpoints that are marked for deletion, whether hit or not.
11952    This is called after any breakpoint is hit, or after errors.  */
11953
11954 void
11955 breakpoint_auto_delete (bpstat bs)
11956 {
11957   struct breakpoint *b, *b_tmp;
11958
11959   for (; bs; bs = bs->next)
11960     if (bs->breakpoint_at
11961         && bs->breakpoint_at->disposition == disp_del
11962         && bs->stop)
11963       delete_breakpoint (bs->breakpoint_at);
11964
11965   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11966   {
11967     if (b->disposition == disp_del_at_next_stop)
11968       delete_breakpoint (b);
11969   }
11970 }
11971
11972 /* A comparison function for bp_location AP and BP being interfaced to
11973    qsort.  Sort elements primarily by their ADDRESS (no matter what
11974    does breakpoint_address_is_meaningful say for its OWNER),
11975    secondarily by ordering first bp_permanent OWNERed elements and
11976    terciarily just ensuring the array is sorted stable way despite
11977    qsort being an unstable algorithm.  */
11978
11979 static int
11980 bp_location_compare (const void *ap, const void *bp)
11981 {
11982   struct bp_location *a = *(void **) ap;
11983   struct bp_location *b = *(void **) bp;
11984   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11985   int a_perm = a->owner->enable_state == bp_permanent;
11986   int b_perm = b->owner->enable_state == bp_permanent;
11987
11988   if (a->address != b->address)
11989     return (a->address > b->address) - (a->address < b->address);
11990
11991   /* Sort locations at the same address by their pspace number, keeping
11992      locations of the same inferior (in a multi-inferior environment)
11993      grouped.  */
11994
11995   if (a->pspace->num != b->pspace->num)
11996     return ((a->pspace->num > b->pspace->num)
11997             - (a->pspace->num < b->pspace->num));
11998
11999   /* Sort permanent breakpoints first.  */
12000   if (a_perm != b_perm)
12001     return (a_perm < b_perm) - (a_perm > b_perm);
12002
12003   /* Make the internal GDB representation stable across GDB runs
12004      where A and B memory inside GDB can differ.  Breakpoint locations of
12005      the same type at the same address can be sorted in arbitrary order.  */
12006
12007   if (a->owner->number != b->owner->number)
12008     return ((a->owner->number > b->owner->number)
12009             - (a->owner->number < b->owner->number));
12010
12011   return (a > b) - (a < b);
12012 }
12013
12014 /* Set bp_location_placed_address_before_address_max and
12015    bp_location_shadow_len_after_address_max according to the current
12016    content of the bp_location array.  */
12017
12018 static void
12019 bp_location_target_extensions_update (void)
12020 {
12021   struct bp_location *bl, **blp_tmp;
12022
12023   bp_location_placed_address_before_address_max = 0;
12024   bp_location_shadow_len_after_address_max = 0;
12025
12026   ALL_BP_LOCATIONS (bl, blp_tmp)
12027     {
12028       CORE_ADDR start, end, addr;
12029
12030       if (!bp_location_has_shadow (bl))
12031         continue;
12032
12033       start = bl->target_info.placed_address;
12034       end = start + bl->target_info.shadow_len;
12035
12036       gdb_assert (bl->address >= start);
12037       addr = bl->address - start;
12038       if (addr > bp_location_placed_address_before_address_max)
12039         bp_location_placed_address_before_address_max = addr;
12040
12041       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12042
12043       gdb_assert (bl->address < end);
12044       addr = end - bl->address;
12045       if (addr > bp_location_shadow_len_after_address_max)
12046         bp_location_shadow_len_after_address_max = addr;
12047     }
12048 }
12049
12050 /* Download tracepoint locations if they haven't been.  */
12051
12052 static void
12053 download_tracepoint_locations (void)
12054 {
12055   struct breakpoint *b;
12056   struct cleanup *old_chain;
12057
12058   if (!target_can_download_tracepoint ())
12059     return;
12060
12061   old_chain = save_current_space_and_thread ();
12062
12063   ALL_TRACEPOINTS (b)
12064     {
12065       struct bp_location *bl;
12066       struct tracepoint *t;
12067       int bp_location_downloaded = 0;
12068
12069       if ((b->type == bp_fast_tracepoint
12070            ? !may_insert_fast_tracepoints
12071            : !may_insert_tracepoints))
12072         continue;
12073
12074       for (bl = b->loc; bl; bl = bl->next)
12075         {
12076           /* In tracepoint, locations are _never_ duplicated, so
12077              should_be_inserted is equivalent to
12078              unduplicated_should_be_inserted.  */
12079           if (!should_be_inserted (bl) || bl->inserted)
12080             continue;
12081
12082           switch_to_program_space_and_thread (bl->pspace);
12083
12084           target_download_tracepoint (bl);
12085
12086           bl->inserted = 1;
12087           bp_location_downloaded = 1;
12088         }
12089       t = (struct tracepoint *) b;
12090       t->number_on_target = b->number;
12091       if (bp_location_downloaded)
12092         observer_notify_breakpoint_modified (b);
12093     }
12094
12095   do_cleanups (old_chain);
12096 }
12097
12098 /* Swap the insertion/duplication state between two locations.  */
12099
12100 static void
12101 swap_insertion (struct bp_location *left, struct bp_location *right)
12102 {
12103   const int left_inserted = left->inserted;
12104   const int left_duplicate = left->duplicate;
12105   const int left_needs_update = left->needs_update;
12106   const struct bp_target_info left_target_info = left->target_info;
12107
12108   /* Locations of tracepoints can never be duplicated.  */
12109   if (is_tracepoint (left->owner))
12110     gdb_assert (!left->duplicate);
12111   if (is_tracepoint (right->owner))
12112     gdb_assert (!right->duplicate);
12113
12114   left->inserted = right->inserted;
12115   left->duplicate = right->duplicate;
12116   left->needs_update = right->needs_update;
12117   left->target_info = right->target_info;
12118   right->inserted = left_inserted;
12119   right->duplicate = left_duplicate;
12120   right->needs_update = left_needs_update;
12121   right->target_info = left_target_info;
12122 }
12123
12124 /* Force the re-insertion of the locations at ADDRESS.  This is called
12125    once a new/deleted/modified duplicate location is found and we are evaluating
12126    conditions on the target's side.  Such conditions need to be updated on
12127    the target.  */
12128
12129 static void
12130 force_breakpoint_reinsertion (struct bp_location *bl)
12131 {
12132   struct bp_location **locp = NULL, **loc2p;
12133   struct bp_location *loc;
12134   CORE_ADDR address = 0;
12135   int pspace_num;
12136
12137   address = bl->address;
12138   pspace_num = bl->pspace->num;
12139
12140   /* This is only meaningful if the target is
12141      evaluating conditions and if the user has
12142      opted for condition evaluation on the target's
12143      side.  */
12144   if (gdb_evaluates_breakpoint_condition_p ()
12145       || !target_supports_evaluation_of_breakpoint_conditions ())
12146     return;
12147
12148   /* Flag all breakpoint locations with this address and
12149      the same program space as the location
12150      as "its condition has changed".  We need to
12151      update the conditions on the target's side.  */
12152   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12153     {
12154       loc = *loc2p;
12155
12156       if (!is_breakpoint (loc->owner)
12157           || pspace_num != loc->pspace->num)
12158         continue;
12159
12160       /* Flag the location appropriately.  We use a different state to
12161          let everyone know that we already updated the set of locations
12162          with addr bl->address and program space bl->pspace.  This is so
12163          we don't have to keep calling these functions just to mark locations
12164          that have already been marked.  */
12165       loc->condition_changed = condition_updated;
12166
12167       /* Free the agent expression bytecode as well.  We will compute
12168          it later on.  */
12169       if (loc->cond_bytecode)
12170         {
12171           free_agent_expr (loc->cond_bytecode);
12172           loc->cond_bytecode = NULL;
12173         }
12174     }
12175 }
12176
12177 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12178    into the inferior, only remove already-inserted locations that no
12179    longer should be inserted.  Functions that delete a breakpoint or
12180    breakpoints should pass false, so that deleting a breakpoint
12181    doesn't have the side effect of inserting the locations of other
12182    breakpoints that are marked not-inserted, but should_be_inserted
12183    returns true on them.
12184
12185    This behaviour is useful is situations close to tear-down -- e.g.,
12186    after an exec, while the target still has execution, but breakpoint
12187    shadows of the previous executable image should *NOT* be restored
12188    to the new image; or before detaching, where the target still has
12189    execution and wants to delete breakpoints from GDB's lists, and all
12190    breakpoints had already been removed from the inferior.  */
12191
12192 static void
12193 update_global_location_list (int should_insert)
12194 {
12195   struct breakpoint *b;
12196   struct bp_location **locp, *loc;
12197   struct cleanup *cleanups;
12198   /* Last breakpoint location address that was marked for update.  */
12199   CORE_ADDR last_addr = 0;
12200   /* Last breakpoint location program space that was marked for update.  */
12201   int last_pspace_num = -1;
12202
12203   /* Used in the duplicates detection below.  When iterating over all
12204      bp_locations, points to the first bp_location of a given address.
12205      Breakpoints and watchpoints of different types are never
12206      duplicates of each other.  Keep one pointer for each type of
12207      breakpoint/watchpoint, so we only need to loop over all locations
12208      once.  */
12209   struct bp_location *bp_loc_first;  /* breakpoint */
12210   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12211   struct bp_location *awp_loc_first; /* access watchpoint */
12212   struct bp_location *rwp_loc_first; /* read watchpoint */
12213
12214   /* Saved former bp_location array which we compare against the newly
12215      built bp_location from the current state of ALL_BREAKPOINTS.  */
12216   struct bp_location **old_location, **old_locp;
12217   unsigned old_location_count;
12218
12219   old_location = bp_location;
12220   old_location_count = bp_location_count;
12221   bp_location = NULL;
12222   bp_location_count = 0;
12223   cleanups = make_cleanup (xfree, old_location);
12224
12225   ALL_BREAKPOINTS (b)
12226     for (loc = b->loc; loc; loc = loc->next)
12227       bp_location_count++;
12228
12229   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12230   locp = bp_location;
12231   ALL_BREAKPOINTS (b)
12232     for (loc = b->loc; loc; loc = loc->next)
12233       *locp++ = loc;
12234   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12235          bp_location_compare);
12236
12237   bp_location_target_extensions_update ();
12238
12239   /* Identify bp_location instances that are no longer present in the
12240      new list, and therefore should be freed.  Note that it's not
12241      necessary that those locations should be removed from inferior --
12242      if there's another location at the same address (previously
12243      marked as duplicate), we don't need to remove/insert the
12244      location.
12245      
12246      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12247      and former bp_location array state respectively.  */
12248
12249   locp = bp_location;
12250   for (old_locp = old_location; old_locp < old_location + old_location_count;
12251        old_locp++)
12252     {
12253       struct bp_location *old_loc = *old_locp;
12254       struct bp_location **loc2p;
12255
12256       /* Tells if 'old_loc' is found among the new locations.  If
12257          not, we have to free it.  */
12258       int found_object = 0;
12259       /* Tells if the location should remain inserted in the target.  */
12260       int keep_in_target = 0;
12261       int removed = 0;
12262
12263       /* Skip LOCP entries which will definitely never be needed.
12264          Stop either at or being the one matching OLD_LOC.  */
12265       while (locp < bp_location + bp_location_count
12266              && (*locp)->address < old_loc->address)
12267         locp++;
12268
12269       for (loc2p = locp;
12270            (loc2p < bp_location + bp_location_count
12271             && (*loc2p)->address == old_loc->address);
12272            loc2p++)
12273         {
12274           /* Check if this is a new/duplicated location or a duplicated
12275              location that had its condition modified.  If so, we want to send
12276              its condition to the target if evaluation of conditions is taking
12277              place there.  */
12278           if ((*loc2p)->condition_changed == condition_modified
12279               && (last_addr != old_loc->address
12280                   || last_pspace_num != old_loc->pspace->num))
12281             {
12282               force_breakpoint_reinsertion (*loc2p);
12283               last_pspace_num = old_loc->pspace->num;
12284             }
12285
12286           if (*loc2p == old_loc)
12287             found_object = 1;
12288         }
12289
12290       /* We have already handled this address, update it so that we don't
12291          have to go through updates again.  */
12292       last_addr = old_loc->address;
12293
12294       /* Target-side condition evaluation: Handle deleted locations.  */
12295       if (!found_object)
12296         force_breakpoint_reinsertion (old_loc);
12297
12298       /* If this location is no longer present, and inserted, look if
12299          there's maybe a new location at the same address.  If so,
12300          mark that one inserted, and don't remove this one.  This is
12301          needed so that we don't have a time window where a breakpoint
12302          at certain location is not inserted.  */
12303
12304       if (old_loc->inserted)
12305         {
12306           /* If the location is inserted now, we might have to remove
12307              it.  */
12308
12309           if (found_object && should_be_inserted (old_loc))
12310             {
12311               /* The location is still present in the location list,
12312                  and still should be inserted.  Don't do anything.  */
12313               keep_in_target = 1;
12314             }
12315           else
12316             {
12317               /* This location still exists, but it won't be kept in the
12318                  target since it may have been disabled.  We proceed to
12319                  remove its target-side condition.  */
12320
12321               /* The location is either no longer present, or got
12322                  disabled.  See if there's another location at the
12323                  same address, in which case we don't need to remove
12324                  this one from the target.  */
12325
12326               /* OLD_LOC comes from existing struct breakpoint.  */
12327               if (breakpoint_address_is_meaningful (old_loc->owner))
12328                 {
12329                   for (loc2p = locp;
12330                        (loc2p < bp_location + bp_location_count
12331                         && (*loc2p)->address == old_loc->address);
12332                        loc2p++)
12333                     {
12334                       struct bp_location *loc2 = *loc2p;
12335
12336                       if (breakpoint_locations_match (loc2, old_loc))
12337                         {
12338                           /* Read watchpoint locations are switched to
12339                              access watchpoints, if the former are not
12340                              supported, but the latter are.  */
12341                           if (is_hardware_watchpoint (old_loc->owner))
12342                             {
12343                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12344                               loc2->watchpoint_type = old_loc->watchpoint_type;
12345                             }
12346
12347                           /* loc2 is a duplicated location. We need to check
12348                              if it should be inserted in case it will be
12349                              unduplicated.  */
12350                           if (loc2 != old_loc
12351                               && unduplicated_should_be_inserted (loc2))
12352                             {
12353                               swap_insertion (old_loc, loc2);
12354                               keep_in_target = 1;
12355                               break;
12356                             }
12357                         }
12358                     }
12359                 }
12360             }
12361
12362           if (!keep_in_target)
12363             {
12364               if (remove_breakpoint (old_loc, mark_uninserted))
12365                 {
12366                   /* This is just about all we can do.  We could keep
12367                      this location on the global list, and try to
12368                      remove it next time, but there's no particular
12369                      reason why we will succeed next time.
12370                      
12371                      Note that at this point, old_loc->owner is still
12372                      valid, as delete_breakpoint frees the breakpoint
12373                      only after calling us.  */
12374                   printf_filtered (_("warning: Error removing "
12375                                      "breakpoint %d\n"), 
12376                                    old_loc->owner->number);
12377                 }
12378               removed = 1;
12379             }
12380         }
12381
12382       if (!found_object)
12383         {
12384           if (removed && non_stop
12385               && breakpoint_address_is_meaningful (old_loc->owner)
12386               && !is_hardware_watchpoint (old_loc->owner))
12387             {
12388               /* This location was removed from the target.  In
12389                  non-stop mode, a race condition is possible where
12390                  we've removed a breakpoint, but stop events for that
12391                  breakpoint are already queued and will arrive later.
12392                  We apply an heuristic to be able to distinguish such
12393                  SIGTRAPs from other random SIGTRAPs: we keep this
12394                  breakpoint location for a bit, and will retire it
12395                  after we see some number of events.  The theory here
12396                  is that reporting of events should, "on the average",
12397                  be fair, so after a while we'll see events from all
12398                  threads that have anything of interest, and no longer
12399                  need to keep this breakpoint location around.  We
12400                  don't hold locations forever so to reduce chances of
12401                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12402                  SIGTRAP.
12403
12404                  The heuristic failing can be disastrous on
12405                  decr_pc_after_break targets.
12406
12407                  On decr_pc_after_break targets, like e.g., x86-linux,
12408                  if we fail to recognize a late breakpoint SIGTRAP,
12409                  because events_till_retirement has reached 0 too
12410                  soon, we'll fail to do the PC adjustment, and report
12411                  a random SIGTRAP to the user.  When the user resumes
12412                  the inferior, it will most likely immediately crash
12413                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12414                  corrupted, because of being resumed e.g., in the
12415                  middle of a multi-byte instruction, or skipped a
12416                  one-byte instruction.  This was actually seen happen
12417                  on native x86-linux, and should be less rare on
12418                  targets that do not support new thread events, like
12419                  remote, due to the heuristic depending on
12420                  thread_count.
12421
12422                  Mistaking a random SIGTRAP for a breakpoint trap
12423                  causes similar symptoms (PC adjustment applied when
12424                  it shouldn't), but then again, playing with SIGTRAPs
12425                  behind the debugger's back is asking for trouble.
12426
12427                  Since hardware watchpoint traps are always
12428                  distinguishable from other traps, so we don't need to
12429                  apply keep hardware watchpoint moribund locations
12430                  around.  We simply always ignore hardware watchpoint
12431                  traps we can no longer explain.  */
12432
12433               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12434               old_loc->owner = NULL;
12435
12436               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12437             }
12438           else
12439             {
12440               old_loc->owner = NULL;
12441               decref_bp_location (&old_loc);
12442             }
12443         }
12444     }
12445
12446   /* Rescan breakpoints at the same address and section, marking the
12447      first one as "first" and any others as "duplicates".  This is so
12448      that the bpt instruction is only inserted once.  If we have a
12449      permanent breakpoint at the same place as BPT, make that one the
12450      official one, and the rest as duplicates.  Permanent breakpoints
12451      are sorted first for the same address.
12452
12453      Do the same for hardware watchpoints, but also considering the
12454      watchpoint's type (regular/access/read) and length.  */
12455
12456   bp_loc_first = NULL;
12457   wp_loc_first = NULL;
12458   awp_loc_first = NULL;
12459   rwp_loc_first = NULL;
12460   ALL_BP_LOCATIONS (loc, locp)
12461     {
12462       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12463          non-NULL.  */
12464       struct bp_location **loc_first_p;
12465       b = loc->owner;
12466
12467       if (!unduplicated_should_be_inserted (loc)
12468           || !breakpoint_address_is_meaningful (b)
12469           /* Don't detect duplicate for tracepoint locations because they are
12470            never duplicated.  See the comments in field `duplicate' of
12471            `struct bp_location'.  */
12472           || is_tracepoint (b))
12473         {
12474           /* Clear the condition modification flag.  */
12475           loc->condition_changed = condition_unchanged;
12476           continue;
12477         }
12478
12479       /* Permanent breakpoint should always be inserted.  */
12480       if (b->enable_state == bp_permanent && ! loc->inserted)
12481         internal_error (__FILE__, __LINE__,
12482                         _("allegedly permanent breakpoint is not "
12483                         "actually inserted"));
12484
12485       if (b->type == bp_hardware_watchpoint)
12486         loc_first_p = &wp_loc_first;
12487       else if (b->type == bp_read_watchpoint)
12488         loc_first_p = &rwp_loc_first;
12489       else if (b->type == bp_access_watchpoint)
12490         loc_first_p = &awp_loc_first;
12491       else
12492         loc_first_p = &bp_loc_first;
12493
12494       if (*loc_first_p == NULL
12495           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12496           || !breakpoint_locations_match (loc, *loc_first_p))
12497         {
12498           *loc_first_p = loc;
12499           loc->duplicate = 0;
12500
12501           if (is_breakpoint (loc->owner) && loc->condition_changed)
12502             {
12503               loc->needs_update = 1;
12504               /* Clear the condition modification flag.  */
12505               loc->condition_changed = condition_unchanged;
12506             }
12507           continue;
12508         }
12509
12510
12511       /* This and the above ensure the invariant that the first location
12512          is not duplicated, and is the inserted one.
12513          All following are marked as duplicated, and are not inserted.  */
12514       if (loc->inserted)
12515         swap_insertion (loc, *loc_first_p);
12516       loc->duplicate = 1;
12517
12518       /* Clear the condition modification flag.  */
12519       loc->condition_changed = condition_unchanged;
12520
12521       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12522           && b->enable_state != bp_permanent)
12523         internal_error (__FILE__, __LINE__,
12524                         _("another breakpoint was inserted on top of "
12525                         "a permanent breakpoint"));
12526     }
12527
12528   if (breakpoints_always_inserted_mode ()
12529       && (have_live_inferiors ()
12530           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12531     {
12532       if (should_insert)
12533         insert_breakpoint_locations ();
12534       else
12535         {
12536           /* Though should_insert is false, we may need to update conditions
12537              on the target's side if it is evaluating such conditions.  We
12538              only update conditions for locations that are marked
12539              "needs_update".  */
12540           update_inserted_breakpoint_locations ();
12541         }
12542     }
12543
12544   if (should_insert)
12545     download_tracepoint_locations ();
12546
12547   do_cleanups (cleanups);
12548 }
12549
12550 void
12551 breakpoint_retire_moribund (void)
12552 {
12553   struct bp_location *loc;
12554   int ix;
12555
12556   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12557     if (--(loc->events_till_retirement) == 0)
12558       {
12559         decref_bp_location (&loc);
12560         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12561         --ix;
12562       }
12563 }
12564
12565 static void
12566 update_global_location_list_nothrow (int inserting)
12567 {
12568   volatile struct gdb_exception e;
12569
12570   TRY_CATCH (e, RETURN_MASK_ERROR)
12571     update_global_location_list (inserting);
12572 }
12573
12574 /* Clear BKP from a BPS.  */
12575
12576 static void
12577 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12578 {
12579   bpstat bs;
12580
12581   for (bs = bps; bs; bs = bs->next)
12582     if (bs->breakpoint_at == bpt)
12583       {
12584         bs->breakpoint_at = NULL;
12585         bs->old_val = NULL;
12586         /* bs->commands will be freed later.  */
12587       }
12588 }
12589
12590 /* Callback for iterate_over_threads.  */
12591 static int
12592 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12593 {
12594   struct breakpoint *bpt = data;
12595
12596   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12597   return 0;
12598 }
12599
12600 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12601    callbacks.  */
12602
12603 static void
12604 say_where (struct breakpoint *b)
12605 {
12606   struct value_print_options opts;
12607
12608   get_user_print_options (&opts);
12609
12610   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12611      single string.  */
12612   if (b->loc == NULL)
12613     {
12614       printf_filtered (_(" (%s) pending."), b->addr_string);
12615     }
12616   else
12617     {
12618       if (opts.addressprint || b->loc->symtab == NULL)
12619         {
12620           printf_filtered (" at ");
12621           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12622                           gdb_stdout);
12623         }
12624       if (b->loc->symtab != NULL)
12625         {
12626           /* If there is a single location, we can print the location
12627              more nicely.  */
12628           if (b->loc->next == NULL)
12629             printf_filtered (": file %s, line %d.",
12630                              symtab_to_filename_for_display (b->loc->symtab),
12631                              b->loc->line_number);
12632           else
12633             /* This is not ideal, but each location may have a
12634                different file name, and this at least reflects the
12635                real situation somewhat.  */
12636             printf_filtered (": %s.", b->addr_string);
12637         }
12638
12639       if (b->loc->next)
12640         {
12641           struct bp_location *loc = b->loc;
12642           int n = 0;
12643           for (; loc; loc = loc->next)
12644             ++n;
12645           printf_filtered (" (%d locations)", n);
12646         }
12647     }
12648 }
12649
12650 /* Default bp_location_ops methods.  */
12651
12652 static void
12653 bp_location_dtor (struct bp_location *self)
12654 {
12655   xfree (self->cond);
12656   if (self->cond_bytecode)
12657     free_agent_expr (self->cond_bytecode);
12658   xfree (self->function_name);
12659 }
12660
12661 static const struct bp_location_ops bp_location_ops =
12662 {
12663   bp_location_dtor
12664 };
12665
12666 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12667    inherit from.  */
12668
12669 static void
12670 base_breakpoint_dtor (struct breakpoint *self)
12671 {
12672   decref_counted_command_line (&self->commands);
12673   xfree (self->cond_string);
12674   xfree (self->extra_string);
12675   xfree (self->addr_string);
12676   xfree (self->filter);
12677   xfree (self->addr_string_range_end);
12678 }
12679
12680 static struct bp_location *
12681 base_breakpoint_allocate_location (struct breakpoint *self)
12682 {
12683   struct bp_location *loc;
12684
12685   loc = XNEW (struct bp_location);
12686   init_bp_location (loc, &bp_location_ops, self);
12687   return loc;
12688 }
12689
12690 static void
12691 base_breakpoint_re_set (struct breakpoint *b)
12692 {
12693   /* Nothing to re-set. */
12694 }
12695
12696 #define internal_error_pure_virtual_called() \
12697   gdb_assert_not_reached ("pure virtual function called")
12698
12699 static int
12700 base_breakpoint_insert_location (struct bp_location *bl)
12701 {
12702   internal_error_pure_virtual_called ();
12703 }
12704
12705 static int
12706 base_breakpoint_remove_location (struct bp_location *bl)
12707 {
12708   internal_error_pure_virtual_called ();
12709 }
12710
12711 static int
12712 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12713                                 struct address_space *aspace,
12714                                 CORE_ADDR bp_addr,
12715                                 const struct target_waitstatus *ws)
12716 {
12717   internal_error_pure_virtual_called ();
12718 }
12719
12720 static void
12721 base_breakpoint_check_status (bpstat bs)
12722 {
12723   /* Always stop.   */
12724 }
12725
12726 /* A "works_in_software_mode" breakpoint_ops method that just internal
12727    errors.  */
12728
12729 static int
12730 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12731 {
12732   internal_error_pure_virtual_called ();
12733 }
12734
12735 /* A "resources_needed" breakpoint_ops method that just internal
12736    errors.  */
12737
12738 static int
12739 base_breakpoint_resources_needed (const struct bp_location *bl)
12740 {
12741   internal_error_pure_virtual_called ();
12742 }
12743
12744 static enum print_stop_action
12745 base_breakpoint_print_it (bpstat bs)
12746 {
12747   internal_error_pure_virtual_called ();
12748 }
12749
12750 static void
12751 base_breakpoint_print_one_detail (const struct breakpoint *self,
12752                                   struct ui_out *uiout)
12753 {
12754   /* nothing */
12755 }
12756
12757 static void
12758 base_breakpoint_print_mention (struct breakpoint *b)
12759 {
12760   internal_error_pure_virtual_called ();
12761 }
12762
12763 static void
12764 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12765 {
12766   internal_error_pure_virtual_called ();
12767 }
12768
12769 static void
12770 base_breakpoint_create_sals_from_address (char **arg,
12771                                           struct linespec_result *canonical,
12772                                           enum bptype type_wanted,
12773                                           char *addr_start,
12774                                           char **copy_arg)
12775 {
12776   internal_error_pure_virtual_called ();
12777 }
12778
12779 static void
12780 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12781                                         struct linespec_result *c,
12782                                         char *cond_string,
12783                                         char *extra_string,
12784                                         enum bptype type_wanted,
12785                                         enum bpdisp disposition,
12786                                         int thread,
12787                                         int task, int ignore_count,
12788                                         const struct breakpoint_ops *o,
12789                                         int from_tty, int enabled,
12790                                         int internal, unsigned flags)
12791 {
12792   internal_error_pure_virtual_called ();
12793 }
12794
12795 static void
12796 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12797                                  struct symtabs_and_lines *sals)
12798 {
12799   internal_error_pure_virtual_called ();
12800 }
12801
12802 /* The default 'explains_signal' method.  */
12803
12804 static enum bpstat_signal_value
12805 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12806 {
12807   return BPSTAT_SIGNAL_HIDE;
12808 }
12809
12810 /* The default "after_condition_true" method.  */
12811
12812 static void
12813 base_breakpoint_after_condition_true (struct bpstats *bs)
12814 {
12815   /* Nothing to do.   */
12816 }
12817
12818 struct breakpoint_ops base_breakpoint_ops =
12819 {
12820   base_breakpoint_dtor,
12821   base_breakpoint_allocate_location,
12822   base_breakpoint_re_set,
12823   base_breakpoint_insert_location,
12824   base_breakpoint_remove_location,
12825   base_breakpoint_breakpoint_hit,
12826   base_breakpoint_check_status,
12827   base_breakpoint_resources_needed,
12828   base_breakpoint_works_in_software_mode,
12829   base_breakpoint_print_it,
12830   NULL,
12831   base_breakpoint_print_one_detail,
12832   base_breakpoint_print_mention,
12833   base_breakpoint_print_recreate,
12834   base_breakpoint_create_sals_from_address,
12835   base_breakpoint_create_breakpoints_sal,
12836   base_breakpoint_decode_linespec,
12837   base_breakpoint_explains_signal,
12838   base_breakpoint_after_condition_true,
12839 };
12840
12841 /* Default breakpoint_ops methods.  */
12842
12843 static void
12844 bkpt_re_set (struct breakpoint *b)
12845 {
12846   /* FIXME: is this still reachable?  */
12847   if (b->addr_string == NULL)
12848     {
12849       /* Anything without a string can't be re-set.  */
12850       delete_breakpoint (b);
12851       return;
12852     }
12853
12854   breakpoint_re_set_default (b);
12855 }
12856
12857 static int
12858 bkpt_insert_location (struct bp_location *bl)
12859 {
12860   if (bl->loc_type == bp_loc_hardware_breakpoint)
12861     return target_insert_hw_breakpoint (bl->gdbarch,
12862                                         &bl->target_info);
12863   else
12864     return target_insert_breakpoint (bl->gdbarch,
12865                                      &bl->target_info);
12866 }
12867
12868 static int
12869 bkpt_remove_location (struct bp_location *bl)
12870 {
12871   if (bl->loc_type == bp_loc_hardware_breakpoint)
12872     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12873   else
12874     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12875 }
12876
12877 static int
12878 bkpt_breakpoint_hit (const struct bp_location *bl,
12879                      struct address_space *aspace, CORE_ADDR bp_addr,
12880                      const struct target_waitstatus *ws)
12881 {
12882   if (ws->kind != TARGET_WAITKIND_STOPPED
12883       || ws->value.sig != GDB_SIGNAL_TRAP)
12884     return 0;
12885
12886   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12887                                  aspace, bp_addr))
12888     return 0;
12889
12890   if (overlay_debugging         /* unmapped overlay section */
12891       && section_is_overlay (bl->section)
12892       && !section_is_mapped (bl->section))
12893     return 0;
12894
12895   return 1;
12896 }
12897
12898 static int
12899 bkpt_resources_needed (const struct bp_location *bl)
12900 {
12901   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12902
12903   return 1;
12904 }
12905
12906 static enum print_stop_action
12907 bkpt_print_it (bpstat bs)
12908 {
12909   struct breakpoint *b;
12910   const struct bp_location *bl;
12911   int bp_temp;
12912   struct ui_out *uiout = current_uiout;
12913
12914   gdb_assert (bs->bp_location_at != NULL);
12915
12916   bl = bs->bp_location_at;
12917   b = bs->breakpoint_at;
12918
12919   bp_temp = b->disposition == disp_del;
12920   if (bl->address != bl->requested_address)
12921     breakpoint_adjustment_warning (bl->requested_address,
12922                                    bl->address,
12923                                    b->number, 1);
12924   annotate_breakpoint (b->number);
12925   if (bp_temp)
12926     ui_out_text (uiout, "\nTemporary breakpoint ");
12927   else
12928     ui_out_text (uiout, "\nBreakpoint ");
12929   if (ui_out_is_mi_like_p (uiout))
12930     {
12931       ui_out_field_string (uiout, "reason",
12932                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12933       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12934     }
12935   ui_out_field_int (uiout, "bkptno", b->number);
12936   ui_out_text (uiout, ", ");
12937
12938   return PRINT_SRC_AND_LOC;
12939 }
12940
12941 static void
12942 bkpt_print_mention (struct breakpoint *b)
12943 {
12944   if (ui_out_is_mi_like_p (current_uiout))
12945     return;
12946
12947   switch (b->type)
12948     {
12949     case bp_breakpoint:
12950     case bp_gnu_ifunc_resolver:
12951       if (b->disposition == disp_del)
12952         printf_filtered (_("Temporary breakpoint"));
12953       else
12954         printf_filtered (_("Breakpoint"));
12955       printf_filtered (_(" %d"), b->number);
12956       if (b->type == bp_gnu_ifunc_resolver)
12957         printf_filtered (_(" at gnu-indirect-function resolver"));
12958       break;
12959     case bp_hardware_breakpoint:
12960       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12961       break;
12962     case bp_dprintf:
12963       printf_filtered (_("Dprintf %d"), b->number);
12964       break;
12965     }
12966
12967   say_where (b);
12968 }
12969
12970 static void
12971 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12972 {
12973   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12974     fprintf_unfiltered (fp, "tbreak");
12975   else if (tp->type == bp_breakpoint)
12976     fprintf_unfiltered (fp, "break");
12977   else if (tp->type == bp_hardware_breakpoint
12978            && tp->disposition == disp_del)
12979     fprintf_unfiltered (fp, "thbreak");
12980   else if (tp->type == bp_hardware_breakpoint)
12981     fprintf_unfiltered (fp, "hbreak");
12982   else
12983     internal_error (__FILE__, __LINE__,
12984                     _("unhandled breakpoint type %d"), (int) tp->type);
12985
12986   fprintf_unfiltered (fp, " %s", tp->addr_string);
12987   print_recreate_thread (tp, fp);
12988 }
12989
12990 static void
12991 bkpt_create_sals_from_address (char **arg,
12992                                struct linespec_result *canonical,
12993                                enum bptype type_wanted,
12994                                char *addr_start, char **copy_arg)
12995 {
12996   create_sals_from_address_default (arg, canonical, type_wanted,
12997                                     addr_start, copy_arg);
12998 }
12999
13000 static void
13001 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13002                              struct linespec_result *canonical,
13003                              char *cond_string,
13004                              char *extra_string,
13005                              enum bptype type_wanted,
13006                              enum bpdisp disposition,
13007                              int thread,
13008                              int task, int ignore_count,
13009                              const struct breakpoint_ops *ops,
13010                              int from_tty, int enabled,
13011                              int internal, unsigned flags)
13012 {
13013   create_breakpoints_sal_default (gdbarch, canonical,
13014                                   cond_string, extra_string,
13015                                   type_wanted,
13016                                   disposition, thread, task,
13017                                   ignore_count, ops, from_tty,
13018                                   enabled, internal, flags);
13019 }
13020
13021 static void
13022 bkpt_decode_linespec (struct breakpoint *b, char **s,
13023                       struct symtabs_and_lines *sals)
13024 {
13025   decode_linespec_default (b, s, sals);
13026 }
13027
13028 /* Virtual table for internal breakpoints.  */
13029
13030 static void
13031 internal_bkpt_re_set (struct breakpoint *b)
13032 {
13033   switch (b->type)
13034     {
13035       /* Delete overlay event and longjmp master breakpoints; they
13036          will be reset later by breakpoint_re_set.  */
13037     case bp_overlay_event:
13038     case bp_longjmp_master:
13039     case bp_std_terminate_master:
13040     case bp_exception_master:
13041       delete_breakpoint (b);
13042       break;
13043
13044       /* This breakpoint is special, it's set up when the inferior
13045          starts and we really don't want to touch it.  */
13046     case bp_shlib_event:
13047
13048       /* Like bp_shlib_event, this breakpoint type is special.  Once
13049          it is set up, we do not want to touch it.  */
13050     case bp_thread_event:
13051       break;
13052     }
13053 }
13054
13055 static void
13056 internal_bkpt_check_status (bpstat bs)
13057 {
13058   if (bs->breakpoint_at->type == bp_shlib_event)
13059     {
13060       /* If requested, stop when the dynamic linker notifies GDB of
13061          events.  This allows the user to get control and place
13062          breakpoints in initializer routines for dynamically loaded
13063          objects (among other things).  */
13064       bs->stop = stop_on_solib_events;
13065       bs->print = stop_on_solib_events;
13066     }
13067   else
13068     bs->stop = 0;
13069 }
13070
13071 static enum print_stop_action
13072 internal_bkpt_print_it (bpstat bs)
13073 {
13074   struct breakpoint *b;
13075
13076   b = bs->breakpoint_at;
13077
13078   switch (b->type)
13079     {
13080     case bp_shlib_event:
13081       /* Did we stop because the user set the stop_on_solib_events
13082          variable?  (If so, we report this as a generic, "Stopped due
13083          to shlib event" message.) */
13084       print_solib_event (0);
13085       break;
13086
13087     case bp_thread_event:
13088       /* Not sure how we will get here.
13089          GDB should not stop for these breakpoints.  */
13090       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13091       break;
13092
13093     case bp_overlay_event:
13094       /* By analogy with the thread event, GDB should not stop for these.  */
13095       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13096       break;
13097
13098     case bp_longjmp_master:
13099       /* These should never be enabled.  */
13100       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13101       break;
13102
13103     case bp_std_terminate_master:
13104       /* These should never be enabled.  */
13105       printf_filtered (_("std::terminate Master Breakpoint: "
13106                          "gdb should not stop!\n"));
13107       break;
13108
13109     case bp_exception_master:
13110       /* These should never be enabled.  */
13111       printf_filtered (_("Exception Master Breakpoint: "
13112                          "gdb should not stop!\n"));
13113       break;
13114     }
13115
13116   return PRINT_NOTHING;
13117 }
13118
13119 static void
13120 internal_bkpt_print_mention (struct breakpoint *b)
13121 {
13122   /* Nothing to mention.  These breakpoints are internal.  */
13123 }
13124
13125 /* Virtual table for momentary breakpoints  */
13126
13127 static void
13128 momentary_bkpt_re_set (struct breakpoint *b)
13129 {
13130   /* Keep temporary breakpoints, which can be encountered when we step
13131      over a dlopen call and solib_add is resetting the breakpoints.
13132      Otherwise these should have been blown away via the cleanup chain
13133      or by breakpoint_init_inferior when we rerun the executable.  */
13134 }
13135
13136 static void
13137 momentary_bkpt_check_status (bpstat bs)
13138 {
13139   /* Nothing.  The point of these breakpoints is causing a stop.  */
13140 }
13141
13142 static enum print_stop_action
13143 momentary_bkpt_print_it (bpstat bs)
13144 {
13145   struct ui_out *uiout = current_uiout;
13146
13147   if (ui_out_is_mi_like_p (uiout))
13148     {
13149       struct breakpoint *b = bs->breakpoint_at;
13150
13151       switch (b->type)
13152         {
13153         case bp_finish:
13154           ui_out_field_string
13155             (uiout, "reason",
13156              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13157           break;
13158
13159         case bp_until:
13160           ui_out_field_string
13161             (uiout, "reason",
13162              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13163           break;
13164         }
13165     }
13166
13167   return PRINT_UNKNOWN;
13168 }
13169
13170 static void
13171 momentary_bkpt_print_mention (struct breakpoint *b)
13172 {
13173   /* Nothing to mention.  These breakpoints are internal.  */
13174 }
13175
13176 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13177
13178    It gets cleared already on the removal of the first one of such placed
13179    breakpoints.  This is OK as they get all removed altogether.  */
13180
13181 static void
13182 longjmp_bkpt_dtor (struct breakpoint *self)
13183 {
13184   struct thread_info *tp = find_thread_id (self->thread);
13185
13186   if (tp)
13187     tp->initiating_frame = null_frame_id;
13188
13189   momentary_breakpoint_ops.dtor (self);
13190 }
13191
13192 /* Specific methods for probe breakpoints.  */
13193
13194 static int
13195 bkpt_probe_insert_location (struct bp_location *bl)
13196 {
13197   int v = bkpt_insert_location (bl);
13198
13199   if (v == 0)
13200     {
13201       /* The insertion was successful, now let's set the probe's semaphore
13202          if needed.  */
13203       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
13204     }
13205
13206   return v;
13207 }
13208
13209 static int
13210 bkpt_probe_remove_location (struct bp_location *bl)
13211 {
13212   /* Let's clear the semaphore before removing the location.  */
13213   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
13214
13215   return bkpt_remove_location (bl);
13216 }
13217
13218 static void
13219 bkpt_probe_create_sals_from_address (char **arg,
13220                                      struct linespec_result *canonical,
13221                                      enum bptype type_wanted,
13222                                      char *addr_start, char **copy_arg)
13223 {
13224   struct linespec_sals lsal;
13225
13226   lsal.sals = parse_probes (arg, canonical);
13227
13228   *copy_arg = xstrdup (canonical->addr_string);
13229   lsal.canonical = xstrdup (*copy_arg);
13230
13231   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13232 }
13233
13234 static void
13235 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13236                             struct symtabs_and_lines *sals)
13237 {
13238   *sals = parse_probes (s, NULL);
13239   if (!sals->sals)
13240     error (_("probe not found"));
13241 }
13242
13243 /* The breakpoint_ops structure to be used in tracepoints.  */
13244
13245 static void
13246 tracepoint_re_set (struct breakpoint *b)
13247 {
13248   breakpoint_re_set_default (b);
13249 }
13250
13251 static int
13252 tracepoint_breakpoint_hit (const struct bp_location *bl,
13253                            struct address_space *aspace, CORE_ADDR bp_addr,
13254                            const struct target_waitstatus *ws)
13255 {
13256   /* By definition, the inferior does not report stops at
13257      tracepoints.  */
13258   return 0;
13259 }
13260
13261 static void
13262 tracepoint_print_one_detail (const struct breakpoint *self,
13263                              struct ui_out *uiout)
13264 {
13265   struct tracepoint *tp = (struct tracepoint *) self;
13266   if (tp->static_trace_marker_id)
13267     {
13268       gdb_assert (self->type == bp_static_tracepoint);
13269
13270       ui_out_text (uiout, "\tmarker id is ");
13271       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13272                            tp->static_trace_marker_id);
13273       ui_out_text (uiout, "\n");
13274     }
13275 }
13276
13277 static void
13278 tracepoint_print_mention (struct breakpoint *b)
13279 {
13280   if (ui_out_is_mi_like_p (current_uiout))
13281     return;
13282
13283   switch (b->type)
13284     {
13285     case bp_tracepoint:
13286       printf_filtered (_("Tracepoint"));
13287       printf_filtered (_(" %d"), b->number);
13288       break;
13289     case bp_fast_tracepoint:
13290       printf_filtered (_("Fast tracepoint"));
13291       printf_filtered (_(" %d"), b->number);
13292       break;
13293     case bp_static_tracepoint:
13294       printf_filtered (_("Static tracepoint"));
13295       printf_filtered (_(" %d"), b->number);
13296       break;
13297     default:
13298       internal_error (__FILE__, __LINE__,
13299                       _("unhandled tracepoint type %d"), (int) b->type);
13300     }
13301
13302   say_where (b);
13303 }
13304
13305 static void
13306 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13307 {
13308   struct tracepoint *tp = (struct tracepoint *) self;
13309
13310   if (self->type == bp_fast_tracepoint)
13311     fprintf_unfiltered (fp, "ftrace");
13312   if (self->type == bp_static_tracepoint)
13313     fprintf_unfiltered (fp, "strace");
13314   else if (self->type == bp_tracepoint)
13315     fprintf_unfiltered (fp, "trace");
13316   else
13317     internal_error (__FILE__, __LINE__,
13318                     _("unhandled tracepoint type %d"), (int) self->type);
13319
13320   fprintf_unfiltered (fp, " %s", self->addr_string);
13321   print_recreate_thread (self, fp);
13322
13323   if (tp->pass_count)
13324     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13325 }
13326
13327 static void
13328 tracepoint_create_sals_from_address (char **arg,
13329                                      struct linespec_result *canonical,
13330                                      enum bptype type_wanted,
13331                                      char *addr_start, char **copy_arg)
13332 {
13333   create_sals_from_address_default (arg, canonical, type_wanted,
13334                                     addr_start, copy_arg);
13335 }
13336
13337 static void
13338 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13339                                    struct linespec_result *canonical,
13340                                    char *cond_string,
13341                                    char *extra_string,
13342                                    enum bptype type_wanted,
13343                                    enum bpdisp disposition,
13344                                    int thread,
13345                                    int task, int ignore_count,
13346                                    const struct breakpoint_ops *ops,
13347                                    int from_tty, int enabled,
13348                                    int internal, unsigned flags)
13349 {
13350   create_breakpoints_sal_default (gdbarch, canonical,
13351                                   cond_string, extra_string,
13352                                   type_wanted,
13353                                   disposition, thread, task,
13354                                   ignore_count, ops, from_tty,
13355                                   enabled, internal, flags);
13356 }
13357
13358 static void
13359 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13360                             struct symtabs_and_lines *sals)
13361 {
13362   decode_linespec_default (b, s, sals);
13363 }
13364
13365 struct breakpoint_ops tracepoint_breakpoint_ops;
13366
13367 /* The breakpoint_ops structure to be use on tracepoints placed in a
13368    static probe.  */
13369
13370 static void
13371 tracepoint_probe_create_sals_from_address (char **arg,
13372                                            struct linespec_result *canonical,
13373                                            enum bptype type_wanted,
13374                                            char *addr_start, char **copy_arg)
13375 {
13376   /* We use the same method for breakpoint on probes.  */
13377   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13378                                        addr_start, copy_arg);
13379 }
13380
13381 static void
13382 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13383                                   struct symtabs_and_lines *sals)
13384 {
13385   /* We use the same method for breakpoint on probes.  */
13386   bkpt_probe_decode_linespec (b, s, sals);
13387 }
13388
13389 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13390
13391 /* Dprintf breakpoint_ops methods.  */
13392
13393 static void
13394 dprintf_re_set (struct breakpoint *b)
13395 {
13396   breakpoint_re_set_default (b);
13397
13398   /* This breakpoint could have been pending, and be resolved now, and
13399      if so, we should now have the extra string.  If we don't, the
13400      dprintf was malformed when created, but we couldn't tell because
13401      we can't extract the extra string until the location is
13402      resolved.  */
13403   if (b->loc != NULL && b->extra_string == NULL)
13404     error (_("Format string required"));
13405
13406   /* 1 - connect to target 1, that can run breakpoint commands.
13407      2 - create a dprintf, which resolves fine.
13408      3 - disconnect from target 1
13409      4 - connect to target 2, that can NOT run breakpoint commands.
13410
13411      After steps #3/#4, you'll want the dprintf command list to
13412      be updated, because target 1 and 2 may well return different
13413      answers for target_can_run_breakpoint_commands().
13414      Given absence of finer grained resetting, we get to do
13415      it all the time.  */
13416   if (b->extra_string != NULL)
13417     update_dprintf_command_list (b);
13418 }
13419
13420 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13421
13422 static void
13423 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13424 {
13425   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13426                       tp->extra_string);
13427   print_recreate_thread (tp, fp);
13428 }
13429
13430 /* Implement the "after_condition_true" breakpoint_ops method for
13431    dprintf.
13432
13433    dprintf's are implemented with regular commands in their command
13434    list, but we run the commands here instead of before presenting the
13435    stop to the user, as dprintf's don't actually cause a stop.  This
13436    also makes it so that the commands of multiple dprintfs at the same
13437    address are all handled.  */
13438
13439 static void
13440 dprintf_after_condition_true (struct bpstats *bs)
13441 {
13442   struct cleanup *old_chain;
13443   struct bpstats tmp_bs = { NULL };
13444   struct bpstats *tmp_bs_p = &tmp_bs;
13445
13446   /* dprintf's never cause a stop.  This wasn't set in the
13447      check_status hook instead because that would make the dprintf's
13448      condition not be evaluated.  */
13449   bs->stop = 0;
13450
13451   /* Run the command list here.  Take ownership of it instead of
13452      copying.  We never want these commands to run later in
13453      bpstat_do_actions, if a breakpoint that causes a stop happens to
13454      be set at same address as this dprintf, or even if running the
13455      commands here throws.  */
13456   tmp_bs.commands = bs->commands;
13457   bs->commands = NULL;
13458   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13459
13460   bpstat_do_actions_1 (&tmp_bs_p);
13461
13462   /* 'tmp_bs.commands' will usually be NULL by now, but
13463      bpstat_do_actions_1 may return early without processing the whole
13464      list.  */
13465   do_cleanups (old_chain);
13466 }
13467
13468 /* The breakpoint_ops structure to be used on static tracepoints with
13469    markers (`-m').  */
13470
13471 static void
13472 strace_marker_create_sals_from_address (char **arg,
13473                                         struct linespec_result *canonical,
13474                                         enum bptype type_wanted,
13475                                         char *addr_start, char **copy_arg)
13476 {
13477   struct linespec_sals lsal;
13478
13479   lsal.sals = decode_static_tracepoint_spec (arg);
13480
13481   *copy_arg = savestring (addr_start, *arg - addr_start);
13482
13483   canonical->addr_string = xstrdup (*copy_arg);
13484   lsal.canonical = xstrdup (*copy_arg);
13485   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13486 }
13487
13488 static void
13489 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13490                                       struct linespec_result *canonical,
13491                                       char *cond_string,
13492                                       char *extra_string,
13493                                       enum bptype type_wanted,
13494                                       enum bpdisp disposition,
13495                                       int thread,
13496                                       int task, int ignore_count,
13497                                       const struct breakpoint_ops *ops,
13498                                       int from_tty, int enabled,
13499                                       int internal, unsigned flags)
13500 {
13501   int i;
13502   struct linespec_sals *lsal = VEC_index (linespec_sals,
13503                                           canonical->sals, 0);
13504
13505   /* If the user is creating a static tracepoint by marker id
13506      (strace -m MARKER_ID), then store the sals index, so that
13507      breakpoint_re_set can try to match up which of the newly
13508      found markers corresponds to this one, and, don't try to
13509      expand multiple locations for each sal, given than SALS
13510      already should contain all sals for MARKER_ID.  */
13511
13512   for (i = 0; i < lsal->sals.nelts; ++i)
13513     {
13514       struct symtabs_and_lines expanded;
13515       struct tracepoint *tp;
13516       struct cleanup *old_chain;
13517       char *addr_string;
13518
13519       expanded.nelts = 1;
13520       expanded.sals = &lsal->sals.sals[i];
13521
13522       addr_string = xstrdup (canonical->addr_string);
13523       old_chain = make_cleanup (xfree, addr_string);
13524
13525       tp = XCNEW (struct tracepoint);
13526       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13527                            addr_string, NULL,
13528                            cond_string, extra_string,
13529                            type_wanted, disposition,
13530                            thread, task, ignore_count, ops,
13531                            from_tty, enabled, internal, flags,
13532                            canonical->special_display);
13533       /* Given that its possible to have multiple markers with
13534          the same string id, if the user is creating a static
13535          tracepoint by marker id ("strace -m MARKER_ID"), then
13536          store the sals index, so that breakpoint_re_set can
13537          try to match up which of the newly found markers
13538          corresponds to this one  */
13539       tp->static_trace_marker_id_idx = i;
13540
13541       install_breakpoint (internal, &tp->base, 0);
13542
13543       discard_cleanups (old_chain);
13544     }
13545 }
13546
13547 static void
13548 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13549                                struct symtabs_and_lines *sals)
13550 {
13551   struct tracepoint *tp = (struct tracepoint *) b;
13552
13553   *sals = decode_static_tracepoint_spec (s);
13554   if (sals->nelts > tp->static_trace_marker_id_idx)
13555     {
13556       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13557       sals->nelts = 1;
13558     }
13559   else
13560     error (_("marker %s not found"), tp->static_trace_marker_id);
13561 }
13562
13563 static struct breakpoint_ops strace_marker_breakpoint_ops;
13564
13565 static int
13566 strace_marker_p (struct breakpoint *b)
13567 {
13568   return b->ops == &strace_marker_breakpoint_ops;
13569 }
13570
13571 /* Delete a breakpoint and clean up all traces of it in the data
13572    structures.  */
13573
13574 void
13575 delete_breakpoint (struct breakpoint *bpt)
13576 {
13577   struct breakpoint *b;
13578
13579   gdb_assert (bpt != NULL);
13580
13581   /* Has this bp already been deleted?  This can happen because
13582      multiple lists can hold pointers to bp's.  bpstat lists are
13583      especial culprits.
13584
13585      One example of this happening is a watchpoint's scope bp.  When
13586      the scope bp triggers, we notice that the watchpoint is out of
13587      scope, and delete it.  We also delete its scope bp.  But the
13588      scope bp is marked "auto-deleting", and is already on a bpstat.
13589      That bpstat is then checked for auto-deleting bp's, which are
13590      deleted.
13591
13592      A real solution to this problem might involve reference counts in
13593      bp's, and/or giving them pointers back to their referencing
13594      bpstat's, and teaching delete_breakpoint to only free a bp's
13595      storage when no more references were extent.  A cheaper bandaid
13596      was chosen.  */
13597   if (bpt->type == bp_none)
13598     return;
13599
13600   /* At least avoid this stale reference until the reference counting
13601      of breakpoints gets resolved.  */
13602   if (bpt->related_breakpoint != bpt)
13603     {
13604       struct breakpoint *related;
13605       struct watchpoint *w;
13606
13607       if (bpt->type == bp_watchpoint_scope)
13608         w = (struct watchpoint *) bpt->related_breakpoint;
13609       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13610         w = (struct watchpoint *) bpt;
13611       else
13612         w = NULL;
13613       if (w != NULL)
13614         watchpoint_del_at_next_stop (w);
13615
13616       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13617       for (related = bpt; related->related_breakpoint != bpt;
13618            related = related->related_breakpoint);
13619       related->related_breakpoint = bpt->related_breakpoint;
13620       bpt->related_breakpoint = bpt;
13621     }
13622
13623   /* watch_command_1 creates a watchpoint but only sets its number if
13624      update_watchpoint succeeds in creating its bp_locations.  If there's
13625      a problem in that process, we'll be asked to delete the half-created
13626      watchpoint.  In that case, don't announce the deletion.  */
13627   if (bpt->number)
13628     observer_notify_breakpoint_deleted (bpt);
13629
13630   if (breakpoint_chain == bpt)
13631     breakpoint_chain = bpt->next;
13632
13633   ALL_BREAKPOINTS (b)
13634     if (b->next == bpt)
13635     {
13636       b->next = bpt->next;
13637       break;
13638     }
13639
13640   /* Be sure no bpstat's are pointing at the breakpoint after it's
13641      been freed.  */
13642   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13643      in all threads for now.  Note that we cannot just remove bpstats
13644      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13645      commands are associated with the bpstat; if we remove it here,
13646      then the later call to bpstat_do_actions (&stop_bpstat); in
13647      event-top.c won't do anything, and temporary breakpoints with
13648      commands won't work.  */
13649
13650   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13651
13652   /* Now that breakpoint is removed from breakpoint list, update the
13653      global location list.  This will remove locations that used to
13654      belong to this breakpoint.  Do this before freeing the breakpoint
13655      itself, since remove_breakpoint looks at location's owner.  It
13656      might be better design to have location completely
13657      self-contained, but it's not the case now.  */
13658   update_global_location_list (0);
13659
13660   bpt->ops->dtor (bpt);
13661   /* On the chance that someone will soon try again to delete this
13662      same bp, we mark it as deleted before freeing its storage.  */
13663   bpt->type = bp_none;
13664   xfree (bpt);
13665 }
13666
13667 static void
13668 do_delete_breakpoint_cleanup (void *b)
13669 {
13670   delete_breakpoint (b);
13671 }
13672
13673 struct cleanup *
13674 make_cleanup_delete_breakpoint (struct breakpoint *b)
13675 {
13676   return make_cleanup (do_delete_breakpoint_cleanup, b);
13677 }
13678
13679 /* Iterator function to call a user-provided callback function once
13680    for each of B and its related breakpoints.  */
13681
13682 static void
13683 iterate_over_related_breakpoints (struct breakpoint *b,
13684                                   void (*function) (struct breakpoint *,
13685                                                     void *),
13686                                   void *data)
13687 {
13688   struct breakpoint *related;
13689
13690   related = b;
13691   do
13692     {
13693       struct breakpoint *next;
13694
13695       /* FUNCTION may delete RELATED.  */
13696       next = related->related_breakpoint;
13697
13698       if (next == related)
13699         {
13700           /* RELATED is the last ring entry.  */
13701           function (related, data);
13702
13703           /* FUNCTION may have deleted it, so we'd never reach back to
13704              B.  There's nothing left to do anyway, so just break
13705              out.  */
13706           break;
13707         }
13708       else
13709         function (related, data);
13710
13711       related = next;
13712     }
13713   while (related != b);
13714 }
13715
13716 static void
13717 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13718 {
13719   delete_breakpoint (b);
13720 }
13721
13722 /* A callback for map_breakpoint_numbers that calls
13723    delete_breakpoint.  */
13724
13725 static void
13726 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13727 {
13728   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13729 }
13730
13731 void
13732 delete_command (char *arg, int from_tty)
13733 {
13734   struct breakpoint *b, *b_tmp;
13735
13736   dont_repeat ();
13737
13738   if (arg == 0)
13739     {
13740       int breaks_to_delete = 0;
13741
13742       /* Delete all breakpoints if no argument.  Do not delete
13743          internal breakpoints, these have to be deleted with an
13744          explicit breakpoint number argument.  */
13745       ALL_BREAKPOINTS (b)
13746         if (user_breakpoint_p (b))
13747           {
13748             breaks_to_delete = 1;
13749             break;
13750           }
13751
13752       /* Ask user only if there are some breakpoints to delete.  */
13753       if (!from_tty
13754           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13755         {
13756           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13757             if (user_breakpoint_p (b))
13758               delete_breakpoint (b);
13759         }
13760     }
13761   else
13762     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13763 }
13764
13765 static int
13766 all_locations_are_pending (struct bp_location *loc)
13767 {
13768   for (; loc; loc = loc->next)
13769     if (!loc->shlib_disabled
13770         && !loc->pspace->executing_startup)
13771       return 0;
13772   return 1;
13773 }
13774
13775 /* Subroutine of update_breakpoint_locations to simplify it.
13776    Return non-zero if multiple fns in list LOC have the same name.
13777    Null names are ignored.  */
13778
13779 static int
13780 ambiguous_names_p (struct bp_location *loc)
13781 {
13782   struct bp_location *l;
13783   htab_t htab = htab_create_alloc (13, htab_hash_string,
13784                                    (int (*) (const void *, 
13785                                              const void *)) streq,
13786                                    NULL, xcalloc, xfree);
13787
13788   for (l = loc; l != NULL; l = l->next)
13789     {
13790       const char **slot;
13791       const char *name = l->function_name;
13792
13793       /* Allow for some names to be NULL, ignore them.  */
13794       if (name == NULL)
13795         continue;
13796
13797       slot = (const char **) htab_find_slot (htab, (const void *) name,
13798                                              INSERT);
13799       /* NOTE: We can assume slot != NULL here because xcalloc never
13800          returns NULL.  */
13801       if (*slot != NULL)
13802         {
13803           htab_delete (htab);
13804           return 1;
13805         }
13806       *slot = name;
13807     }
13808
13809   htab_delete (htab);
13810   return 0;
13811 }
13812
13813 /* When symbols change, it probably means the sources changed as well,
13814    and it might mean the static tracepoint markers are no longer at
13815    the same address or line numbers they used to be at last we
13816    checked.  Losing your static tracepoints whenever you rebuild is
13817    undesirable.  This function tries to resync/rematch gdb static
13818    tracepoints with the markers on the target, for static tracepoints
13819    that have not been set by marker id.  Static tracepoint that have
13820    been set by marker id are reset by marker id in breakpoint_re_set.
13821    The heuristic is:
13822
13823    1) For a tracepoint set at a specific address, look for a marker at
13824    the old PC.  If one is found there, assume to be the same marker.
13825    If the name / string id of the marker found is different from the
13826    previous known name, assume that means the user renamed the marker
13827    in the sources, and output a warning.
13828
13829    2) For a tracepoint set at a given line number, look for a marker
13830    at the new address of the old line number.  If one is found there,
13831    assume to be the same marker.  If the name / string id of the
13832    marker found is different from the previous known name, assume that
13833    means the user renamed the marker in the sources, and output a
13834    warning.
13835
13836    3) If a marker is no longer found at the same address or line, it
13837    may mean the marker no longer exists.  But it may also just mean
13838    the code changed a bit.  Maybe the user added a few lines of code
13839    that made the marker move up or down (in line number terms).  Ask
13840    the target for info about the marker with the string id as we knew
13841    it.  If found, update line number and address in the matching
13842    static tracepoint.  This will get confused if there's more than one
13843    marker with the same ID (possible in UST, although unadvised
13844    precisely because it confuses tools).  */
13845
13846 static struct symtab_and_line
13847 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13848 {
13849   struct tracepoint *tp = (struct tracepoint *) b;
13850   struct static_tracepoint_marker marker;
13851   CORE_ADDR pc;
13852
13853   pc = sal.pc;
13854   if (sal.line)
13855     find_line_pc (sal.symtab, sal.line, &pc);
13856
13857   if (target_static_tracepoint_marker_at (pc, &marker))
13858     {
13859       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13860         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13861                  b->number,
13862                  tp->static_trace_marker_id, marker.str_id);
13863
13864       xfree (tp->static_trace_marker_id);
13865       tp->static_trace_marker_id = xstrdup (marker.str_id);
13866       release_static_tracepoint_marker (&marker);
13867
13868       return sal;
13869     }
13870
13871   /* Old marker wasn't found on target at lineno.  Try looking it up
13872      by string ID.  */
13873   if (!sal.explicit_pc
13874       && sal.line != 0
13875       && sal.symtab != NULL
13876       && tp->static_trace_marker_id != NULL)
13877     {
13878       VEC(static_tracepoint_marker_p) *markers;
13879
13880       markers
13881         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13882
13883       if (!VEC_empty(static_tracepoint_marker_p, markers))
13884         {
13885           struct symtab_and_line sal2;
13886           struct symbol *sym;
13887           struct static_tracepoint_marker *tpmarker;
13888           struct ui_out *uiout = current_uiout;
13889
13890           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13891
13892           xfree (tp->static_trace_marker_id);
13893           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13894
13895           warning (_("marker for static tracepoint %d (%s) not "
13896                      "found at previous line number"),
13897                    b->number, tp->static_trace_marker_id);
13898
13899           init_sal (&sal2);
13900
13901           sal2.pc = tpmarker->address;
13902
13903           sal2 = find_pc_line (tpmarker->address, 0);
13904           sym = find_pc_sect_function (tpmarker->address, NULL);
13905           ui_out_text (uiout, "Now in ");
13906           if (sym)
13907             {
13908               ui_out_field_string (uiout, "func",
13909                                    SYMBOL_PRINT_NAME (sym));
13910               ui_out_text (uiout, " at ");
13911             }
13912           ui_out_field_string (uiout, "file",
13913                                symtab_to_filename_for_display (sal2.symtab));
13914           ui_out_text (uiout, ":");
13915
13916           if (ui_out_is_mi_like_p (uiout))
13917             {
13918               const char *fullname = symtab_to_fullname (sal2.symtab);
13919
13920               ui_out_field_string (uiout, "fullname", fullname);
13921             }
13922
13923           ui_out_field_int (uiout, "line", sal2.line);
13924           ui_out_text (uiout, "\n");
13925
13926           b->loc->line_number = sal2.line;
13927           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13928
13929           xfree (b->addr_string);
13930           b->addr_string = xstrprintf ("%s:%d",
13931                                    symtab_to_filename_for_display (sal2.symtab),
13932                                        b->loc->line_number);
13933
13934           /* Might be nice to check if function changed, and warn if
13935              so.  */
13936
13937           release_static_tracepoint_marker (tpmarker);
13938         }
13939     }
13940   return sal;
13941 }
13942
13943 /* Returns 1 iff locations A and B are sufficiently same that
13944    we don't need to report breakpoint as changed.  */
13945
13946 static int
13947 locations_are_equal (struct bp_location *a, struct bp_location *b)
13948 {
13949   while (a && b)
13950     {
13951       if (a->address != b->address)
13952         return 0;
13953
13954       if (a->shlib_disabled != b->shlib_disabled)
13955         return 0;
13956
13957       if (a->enabled != b->enabled)
13958         return 0;
13959
13960       a = a->next;
13961       b = b->next;
13962     }
13963
13964   if ((a == NULL) != (b == NULL))
13965     return 0;
13966
13967   return 1;
13968 }
13969
13970 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13971    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13972    a ranged breakpoint.  */
13973
13974 void
13975 update_breakpoint_locations (struct breakpoint *b,
13976                              struct symtabs_and_lines sals,
13977                              struct symtabs_and_lines sals_end)
13978 {
13979   int i;
13980   struct bp_location *existing_locations = b->loc;
13981
13982   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13983     {
13984       /* Ranged breakpoints have only one start location and one end
13985          location.  */
13986       b->enable_state = bp_disabled;
13987       update_global_location_list (1);
13988       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13989                            "multiple locations found\n"),
13990                          b->number);
13991       return;
13992     }
13993
13994   /* If there's no new locations, and all existing locations are
13995      pending, don't do anything.  This optimizes the common case where
13996      all locations are in the same shared library, that was unloaded.
13997      We'd like to retain the location, so that when the library is
13998      loaded again, we don't loose the enabled/disabled status of the
13999      individual locations.  */
14000   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14001     return;
14002
14003   b->loc = NULL;
14004
14005   for (i = 0; i < sals.nelts; ++i)
14006     {
14007       struct bp_location *new_loc;
14008
14009       switch_to_program_space_and_thread (sals.sals[i].pspace);
14010
14011       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14012
14013       /* Reparse conditions, they might contain references to the
14014          old symtab.  */
14015       if (b->cond_string != NULL)
14016         {
14017           const char *s;
14018           volatile struct gdb_exception e;
14019
14020           s = b->cond_string;
14021           TRY_CATCH (e, RETURN_MASK_ERROR)
14022             {
14023               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14024                                            block_for_pc (sals.sals[i].pc), 
14025                                            0);
14026             }
14027           if (e.reason < 0)
14028             {
14029               warning (_("failed to reevaluate condition "
14030                          "for breakpoint %d: %s"), 
14031                        b->number, e.message);
14032               new_loc->enabled = 0;
14033             }
14034         }
14035
14036       if (sals_end.nelts)
14037         {
14038           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14039
14040           new_loc->length = end - sals.sals[0].pc + 1;
14041         }
14042     }
14043
14044   /* Update locations of permanent breakpoints.  */
14045   if (b->enable_state == bp_permanent)
14046     make_breakpoint_permanent (b);
14047
14048   /* If possible, carry over 'disable' status from existing
14049      breakpoints.  */
14050   {
14051     struct bp_location *e = existing_locations;
14052     /* If there are multiple breakpoints with the same function name,
14053        e.g. for inline functions, comparing function names won't work.
14054        Instead compare pc addresses; this is just a heuristic as things
14055        may have moved, but in practice it gives the correct answer
14056        often enough until a better solution is found.  */
14057     int have_ambiguous_names = ambiguous_names_p (b->loc);
14058
14059     for (; e; e = e->next)
14060       {
14061         if (!e->enabled && e->function_name)
14062           {
14063             struct bp_location *l = b->loc;
14064             if (have_ambiguous_names)
14065               {
14066                 for (; l; l = l->next)
14067                   if (breakpoint_locations_match (e, l))
14068                     {
14069                       l->enabled = 0;
14070                       break;
14071                     }
14072               }
14073             else
14074               {
14075                 for (; l; l = l->next)
14076                   if (l->function_name
14077                       && strcmp (e->function_name, l->function_name) == 0)
14078                     {
14079                       l->enabled = 0;
14080                       break;
14081                     }
14082               }
14083           }
14084       }
14085   }
14086
14087   if (!locations_are_equal (existing_locations, b->loc))
14088     observer_notify_breakpoint_modified (b);
14089
14090   update_global_location_list (1);
14091 }
14092
14093 /* Find the SaL locations corresponding to the given ADDR_STRING.
14094    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14095
14096 static struct symtabs_and_lines
14097 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14098 {
14099   char *s;
14100   struct symtabs_and_lines sals = {0};
14101   volatile struct gdb_exception e;
14102
14103   gdb_assert (b->ops != NULL);
14104   s = addr_string;
14105
14106   TRY_CATCH (e, RETURN_MASK_ERROR)
14107     {
14108       b->ops->decode_linespec (b, &s, &sals);
14109     }
14110   if (e.reason < 0)
14111     {
14112       int not_found_and_ok = 0;
14113       /* For pending breakpoints, it's expected that parsing will
14114          fail until the right shared library is loaded.  User has
14115          already told to create pending breakpoints and don't need
14116          extra messages.  If breakpoint is in bp_shlib_disabled
14117          state, then user already saw the message about that
14118          breakpoint being disabled, and don't want to see more
14119          errors.  */
14120       if (e.error == NOT_FOUND_ERROR
14121           && (b->condition_not_parsed 
14122               || (b->loc && b->loc->shlib_disabled)
14123               || (b->loc && b->loc->pspace->executing_startup)
14124               || b->enable_state == bp_disabled))
14125         not_found_and_ok = 1;
14126
14127       if (!not_found_and_ok)
14128         {
14129           /* We surely don't want to warn about the same breakpoint
14130              10 times.  One solution, implemented here, is disable
14131              the breakpoint on error.  Another solution would be to
14132              have separate 'warning emitted' flag.  Since this
14133              happens only when a binary has changed, I don't know
14134              which approach is better.  */
14135           b->enable_state = bp_disabled;
14136           throw_exception (e);
14137         }
14138     }
14139
14140   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14141     {
14142       int i;
14143
14144       for (i = 0; i < sals.nelts; ++i)
14145         resolve_sal_pc (&sals.sals[i]);
14146       if (b->condition_not_parsed && s && s[0])
14147         {
14148           char *cond_string, *extra_string;
14149           int thread, task;
14150
14151           find_condition_and_thread (s, sals.sals[0].pc,
14152                                      &cond_string, &thread, &task,
14153                                      &extra_string);
14154           if (cond_string)
14155             b->cond_string = cond_string;
14156           b->thread = thread;
14157           b->task = task;
14158           if (extra_string)
14159             b->extra_string = extra_string;
14160           b->condition_not_parsed = 0;
14161         }
14162
14163       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14164         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14165
14166       *found = 1;
14167     }
14168   else
14169     *found = 0;
14170
14171   return sals;
14172 }
14173
14174 /* The default re_set method, for typical hardware or software
14175    breakpoints.  Reevaluate the breakpoint and recreate its
14176    locations.  */
14177
14178 static void
14179 breakpoint_re_set_default (struct breakpoint *b)
14180 {
14181   int found;
14182   struct symtabs_and_lines sals, sals_end;
14183   struct symtabs_and_lines expanded = {0};
14184   struct symtabs_and_lines expanded_end = {0};
14185
14186   sals = addr_string_to_sals (b, b->addr_string, &found);
14187   if (found)
14188     {
14189       make_cleanup (xfree, sals.sals);
14190       expanded = sals;
14191     }
14192
14193   if (b->addr_string_range_end)
14194     {
14195       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14196       if (found)
14197         {
14198           make_cleanup (xfree, sals_end.sals);
14199           expanded_end = sals_end;
14200         }
14201     }
14202
14203   update_breakpoint_locations (b, expanded, expanded_end);
14204 }
14205
14206 /* Default method for creating SALs from an address string.  It basically
14207    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14208
14209 static void
14210 create_sals_from_address_default (char **arg,
14211                                   struct linespec_result *canonical,
14212                                   enum bptype type_wanted,
14213                                   char *addr_start, char **copy_arg)
14214 {
14215   parse_breakpoint_sals (arg, canonical);
14216 }
14217
14218 /* Call create_breakpoints_sal for the given arguments.  This is the default
14219    function for the `create_breakpoints_sal' method of
14220    breakpoint_ops.  */
14221
14222 static void
14223 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14224                                 struct linespec_result *canonical,
14225                                 char *cond_string,
14226                                 char *extra_string,
14227                                 enum bptype type_wanted,
14228                                 enum bpdisp disposition,
14229                                 int thread,
14230                                 int task, int ignore_count,
14231                                 const struct breakpoint_ops *ops,
14232                                 int from_tty, int enabled,
14233                                 int internal, unsigned flags)
14234 {
14235   create_breakpoints_sal (gdbarch, canonical, cond_string,
14236                           extra_string,
14237                           type_wanted, disposition,
14238                           thread, task, ignore_count, ops, from_tty,
14239                           enabled, internal, flags);
14240 }
14241
14242 /* Decode the line represented by S by calling decode_line_full.  This is the
14243    default function for the `decode_linespec' method of breakpoint_ops.  */
14244
14245 static void
14246 decode_linespec_default (struct breakpoint *b, char **s,
14247                          struct symtabs_and_lines *sals)
14248 {
14249   struct linespec_result canonical;
14250
14251   init_linespec_result (&canonical);
14252   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14253                     (struct symtab *) NULL, 0,
14254                     &canonical, multiple_symbols_all,
14255                     b->filter);
14256
14257   /* We should get 0 or 1 resulting SALs.  */
14258   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14259
14260   if (VEC_length (linespec_sals, canonical.sals) > 0)
14261     {
14262       struct linespec_sals *lsal;
14263
14264       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14265       *sals = lsal->sals;
14266       /* Arrange it so the destructor does not free the
14267          contents.  */
14268       lsal->sals.sals = NULL;
14269     }
14270
14271   destroy_linespec_result (&canonical);
14272 }
14273
14274 /* Prepare the global context for a re-set of breakpoint B.  */
14275
14276 static struct cleanup *
14277 prepare_re_set_context (struct breakpoint *b)
14278 {
14279   struct cleanup *cleanups;
14280
14281   input_radix = b->input_radix;
14282   cleanups = save_current_space_and_thread ();
14283   if (b->pspace != NULL)
14284     switch_to_program_space_and_thread (b->pspace);
14285   set_language (b->language);
14286
14287   return cleanups;
14288 }
14289
14290 /* Reset a breakpoint given it's struct breakpoint * BINT.
14291    The value we return ends up being the return value from catch_errors.
14292    Unused in this case.  */
14293
14294 static int
14295 breakpoint_re_set_one (void *bint)
14296 {
14297   /* Get past catch_errs.  */
14298   struct breakpoint *b = (struct breakpoint *) bint;
14299   struct cleanup *cleanups;
14300
14301   cleanups = prepare_re_set_context (b);
14302   b->ops->re_set (b);
14303   do_cleanups (cleanups);
14304   return 0;
14305 }
14306
14307 /* Re-set all breakpoints after symbols have been re-loaded.  */
14308 void
14309 breakpoint_re_set (void)
14310 {
14311   struct breakpoint *b, *b_tmp;
14312   enum language save_language;
14313   int save_input_radix;
14314   struct cleanup *old_chain;
14315
14316   save_language = current_language->la_language;
14317   save_input_radix = input_radix;
14318   old_chain = save_current_program_space ();
14319
14320   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14321   {
14322     /* Format possible error msg.  */
14323     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14324                                 b->number);
14325     struct cleanup *cleanups = make_cleanup (xfree, message);
14326     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14327     do_cleanups (cleanups);
14328   }
14329   set_language (save_language);
14330   input_radix = save_input_radix;
14331
14332   jit_breakpoint_re_set ();
14333
14334   do_cleanups (old_chain);
14335
14336   create_overlay_event_breakpoint ();
14337   create_longjmp_master_breakpoint ();
14338   create_std_terminate_master_breakpoint ();
14339   create_exception_master_breakpoint ();
14340 }
14341 \f
14342 /* Reset the thread number of this breakpoint:
14343
14344    - If the breakpoint is for all threads, leave it as-is.
14345    - Else, reset it to the current thread for inferior_ptid.  */
14346 void
14347 breakpoint_re_set_thread (struct breakpoint *b)
14348 {
14349   if (b->thread != -1)
14350     {
14351       if (in_thread_list (inferior_ptid))
14352         b->thread = pid_to_thread_id (inferior_ptid);
14353
14354       /* We're being called after following a fork.  The new fork is
14355          selected as current, and unless this was a vfork will have a
14356          different program space from the original thread.  Reset that
14357          as well.  */
14358       b->loc->pspace = current_program_space;
14359     }
14360 }
14361
14362 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14363    If from_tty is nonzero, it prints a message to that effect,
14364    which ends with a period (no newline).  */
14365
14366 void
14367 set_ignore_count (int bptnum, int count, int from_tty)
14368 {
14369   struct breakpoint *b;
14370
14371   if (count < 0)
14372     count = 0;
14373
14374   ALL_BREAKPOINTS (b)
14375     if (b->number == bptnum)
14376     {
14377       if (is_tracepoint (b))
14378         {
14379           if (from_tty && count != 0)
14380             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14381                              bptnum);
14382           return;
14383         }
14384       
14385       b->ignore_count = count;
14386       if (from_tty)
14387         {
14388           if (count == 0)
14389             printf_filtered (_("Will stop next time "
14390                                "breakpoint %d is reached."),
14391                              bptnum);
14392           else if (count == 1)
14393             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14394                              bptnum);
14395           else
14396             printf_filtered (_("Will ignore next %d "
14397                                "crossings of breakpoint %d."),
14398                              count, bptnum);
14399         }
14400       observer_notify_breakpoint_modified (b);
14401       return;
14402     }
14403
14404   error (_("No breakpoint number %d."), bptnum);
14405 }
14406
14407 /* Command to set ignore-count of breakpoint N to COUNT.  */
14408
14409 static void
14410 ignore_command (char *args, int from_tty)
14411 {
14412   char *p = args;
14413   int num;
14414
14415   if (p == 0)
14416     error_no_arg (_("a breakpoint number"));
14417
14418   num = get_number (&p);
14419   if (num == 0)
14420     error (_("bad breakpoint number: '%s'"), args);
14421   if (*p == 0)
14422     error (_("Second argument (specified ignore-count) is missing."));
14423
14424   set_ignore_count (num,
14425                     longest_to_int (value_as_long (parse_and_eval (p))),
14426                     from_tty);
14427   if (from_tty)
14428     printf_filtered ("\n");
14429 }
14430 \f
14431 /* Call FUNCTION on each of the breakpoints
14432    whose numbers are given in ARGS.  */
14433
14434 static void
14435 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14436                                                       void *),
14437                         void *data)
14438 {
14439   int num;
14440   struct breakpoint *b, *tmp;
14441   int match;
14442   struct get_number_or_range_state state;
14443
14444   if (args == 0)
14445     error_no_arg (_("one or more breakpoint numbers"));
14446
14447   init_number_or_range (&state, args);
14448
14449   while (!state.finished)
14450     {
14451       char *p = state.string;
14452
14453       match = 0;
14454
14455       num = get_number_or_range (&state);
14456       if (num == 0)
14457         {
14458           warning (_("bad breakpoint number at or near '%s'"), p);
14459         }
14460       else
14461         {
14462           ALL_BREAKPOINTS_SAFE (b, tmp)
14463             if (b->number == num)
14464               {
14465                 match = 1;
14466                 function (b, data);
14467                 break;
14468               }
14469           if (match == 0)
14470             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14471         }
14472     }
14473 }
14474
14475 static struct bp_location *
14476 find_location_by_number (char *number)
14477 {
14478   char *dot = strchr (number, '.');
14479   char *p1;
14480   int bp_num;
14481   int loc_num;
14482   struct breakpoint *b;
14483   struct bp_location *loc;  
14484
14485   *dot = '\0';
14486
14487   p1 = number;
14488   bp_num = get_number (&p1);
14489   if (bp_num == 0)
14490     error (_("Bad breakpoint number '%s'"), number);
14491
14492   ALL_BREAKPOINTS (b)
14493     if (b->number == bp_num)
14494       {
14495         break;
14496       }
14497
14498   if (!b || b->number != bp_num)
14499     error (_("Bad breakpoint number '%s'"), number);
14500   
14501   p1 = dot+1;
14502   loc_num = get_number (&p1);
14503   if (loc_num == 0)
14504     error (_("Bad breakpoint location number '%s'"), number);
14505
14506   --loc_num;
14507   loc = b->loc;
14508   for (;loc_num && loc; --loc_num, loc = loc->next)
14509     ;
14510   if (!loc)
14511     error (_("Bad breakpoint location number '%s'"), dot+1);
14512     
14513   return loc;  
14514 }
14515
14516
14517 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14518    If from_tty is nonzero, it prints a message to that effect,
14519    which ends with a period (no newline).  */
14520
14521 void
14522 disable_breakpoint (struct breakpoint *bpt)
14523 {
14524   /* Never disable a watchpoint scope breakpoint; we want to
14525      hit them when we leave scope so we can delete both the
14526      watchpoint and its scope breakpoint at that time.  */
14527   if (bpt->type == bp_watchpoint_scope)
14528     return;
14529
14530   /* You can't disable permanent breakpoints.  */
14531   if (bpt->enable_state == bp_permanent)
14532     return;
14533
14534   bpt->enable_state = bp_disabled;
14535
14536   /* Mark breakpoint locations modified.  */
14537   mark_breakpoint_modified (bpt);
14538
14539   if (target_supports_enable_disable_tracepoint ()
14540       && current_trace_status ()->running && is_tracepoint (bpt))
14541     {
14542       struct bp_location *location;
14543      
14544       for (location = bpt->loc; location; location = location->next)
14545         target_disable_tracepoint (location);
14546     }
14547
14548   update_global_location_list (0);
14549
14550   observer_notify_breakpoint_modified (bpt);
14551 }
14552
14553 /* A callback for iterate_over_related_breakpoints.  */
14554
14555 static void
14556 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14557 {
14558   disable_breakpoint (b);
14559 }
14560
14561 /* A callback for map_breakpoint_numbers that calls
14562    disable_breakpoint.  */
14563
14564 static void
14565 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14566 {
14567   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14568 }
14569
14570 static void
14571 disable_command (char *args, int from_tty)
14572 {
14573   if (args == 0)
14574     {
14575       struct breakpoint *bpt;
14576
14577       ALL_BREAKPOINTS (bpt)
14578         if (user_breakpoint_p (bpt))
14579           disable_breakpoint (bpt);
14580     }
14581   else
14582     {
14583       char *num = extract_arg (&args);
14584
14585       while (num)
14586         {
14587           if (strchr (num, '.'))
14588             {
14589               struct bp_location *loc = find_location_by_number (num);
14590
14591               if (loc)
14592                 {
14593                   if (loc->enabled)
14594                     {
14595                       loc->enabled = 0;
14596                       mark_breakpoint_location_modified (loc);
14597                     }
14598                   if (target_supports_enable_disable_tracepoint ()
14599                       && current_trace_status ()->running && loc->owner
14600                       && is_tracepoint (loc->owner))
14601                     target_disable_tracepoint (loc);
14602                 }
14603               update_global_location_list (0);
14604             }
14605           else
14606             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14607           num = extract_arg (&args);
14608         }
14609     }
14610 }
14611
14612 static void
14613 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14614                         int count)
14615 {
14616   int target_resources_ok;
14617
14618   if (bpt->type == bp_hardware_breakpoint)
14619     {
14620       int i;
14621       i = hw_breakpoint_used_count ();
14622       target_resources_ok = 
14623         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14624                                             i + 1, 0);
14625       if (target_resources_ok == 0)
14626         error (_("No hardware breakpoint support in the target."));
14627       else if (target_resources_ok < 0)
14628         error (_("Hardware breakpoints used exceeds limit."));
14629     }
14630
14631   if (is_watchpoint (bpt))
14632     {
14633       /* Initialize it just to avoid a GCC false warning.  */
14634       enum enable_state orig_enable_state = 0;
14635       volatile struct gdb_exception e;
14636
14637       TRY_CATCH (e, RETURN_MASK_ALL)
14638         {
14639           struct watchpoint *w = (struct watchpoint *) bpt;
14640
14641           orig_enable_state = bpt->enable_state;
14642           bpt->enable_state = bp_enabled;
14643           update_watchpoint (w, 1 /* reparse */);
14644         }
14645       if (e.reason < 0)
14646         {
14647           bpt->enable_state = orig_enable_state;
14648           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14649                              bpt->number);
14650           return;
14651         }
14652     }
14653
14654   if (bpt->enable_state != bp_permanent)
14655     bpt->enable_state = bp_enabled;
14656
14657   bpt->enable_state = bp_enabled;
14658
14659   /* Mark breakpoint locations modified.  */
14660   mark_breakpoint_modified (bpt);
14661
14662   if (target_supports_enable_disable_tracepoint ()
14663       && current_trace_status ()->running && is_tracepoint (bpt))
14664     {
14665       struct bp_location *location;
14666
14667       for (location = bpt->loc; location; location = location->next)
14668         target_enable_tracepoint (location);
14669     }
14670
14671   bpt->disposition = disposition;
14672   bpt->enable_count = count;
14673   update_global_location_list (1);
14674
14675   observer_notify_breakpoint_modified (bpt);
14676 }
14677
14678
14679 void
14680 enable_breakpoint (struct breakpoint *bpt)
14681 {
14682   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14683 }
14684
14685 static void
14686 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14687 {
14688   enable_breakpoint (bpt);
14689 }
14690
14691 /* A callback for map_breakpoint_numbers that calls
14692    enable_breakpoint.  */
14693
14694 static void
14695 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14696 {
14697   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14698 }
14699
14700 /* The enable command enables the specified breakpoints (or all defined
14701    breakpoints) so they once again become (or continue to be) effective
14702    in stopping the inferior.  */
14703
14704 static void
14705 enable_command (char *args, int from_tty)
14706 {
14707   if (args == 0)
14708     {
14709       struct breakpoint *bpt;
14710
14711       ALL_BREAKPOINTS (bpt)
14712         if (user_breakpoint_p (bpt))
14713           enable_breakpoint (bpt);
14714     }
14715   else
14716     {
14717       char *num = extract_arg (&args);
14718
14719       while (num)
14720         {
14721           if (strchr (num, '.'))
14722             {
14723               struct bp_location *loc = find_location_by_number (num);
14724
14725               if (loc)
14726                 {
14727                   if (!loc->enabled)
14728                     {
14729                       loc->enabled = 1;
14730                       mark_breakpoint_location_modified (loc);
14731                     }
14732                   if (target_supports_enable_disable_tracepoint ()
14733                       && current_trace_status ()->running && loc->owner
14734                       && is_tracepoint (loc->owner))
14735                     target_enable_tracepoint (loc);
14736                 }
14737               update_global_location_list (1);
14738             }
14739           else
14740             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14741           num = extract_arg (&args);
14742         }
14743     }
14744 }
14745
14746 /* This struct packages up disposition data for application to multiple
14747    breakpoints.  */
14748
14749 struct disp_data
14750 {
14751   enum bpdisp disp;
14752   int count;
14753 };
14754
14755 static void
14756 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14757 {
14758   struct disp_data disp_data = *(struct disp_data *) arg;
14759
14760   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14761 }
14762
14763 static void
14764 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14765 {
14766   struct disp_data disp = { disp_disable, 1 };
14767
14768   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14769 }
14770
14771 static void
14772 enable_once_command (char *args, int from_tty)
14773 {
14774   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14775 }
14776
14777 static void
14778 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14779 {
14780   struct disp_data disp = { disp_disable, *(int *) countptr };
14781
14782   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14783 }
14784
14785 static void
14786 enable_count_command (char *args, int from_tty)
14787 {
14788   int count = get_number (&args);
14789
14790   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14791 }
14792
14793 static void
14794 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14795 {
14796   struct disp_data disp = { disp_del, 1 };
14797
14798   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14799 }
14800
14801 static void
14802 enable_delete_command (char *args, int from_tty)
14803 {
14804   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14805 }
14806 \f
14807 static void
14808 set_breakpoint_cmd (char *args, int from_tty)
14809 {
14810 }
14811
14812 static void
14813 show_breakpoint_cmd (char *args, int from_tty)
14814 {
14815 }
14816
14817 /* Invalidate last known value of any hardware watchpoint if
14818    the memory which that value represents has been written to by
14819    GDB itself.  */
14820
14821 static void
14822 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14823                                       CORE_ADDR addr, ssize_t len,
14824                                       const bfd_byte *data)
14825 {
14826   struct breakpoint *bp;
14827
14828   ALL_BREAKPOINTS (bp)
14829     if (bp->enable_state == bp_enabled
14830         && bp->type == bp_hardware_watchpoint)
14831       {
14832         struct watchpoint *wp = (struct watchpoint *) bp;
14833
14834         if (wp->val_valid && wp->val)
14835           {
14836             struct bp_location *loc;
14837
14838             for (loc = bp->loc; loc != NULL; loc = loc->next)
14839               if (loc->loc_type == bp_loc_hardware_watchpoint
14840                   && loc->address + loc->length > addr
14841                   && addr + len > loc->address)
14842                 {
14843                   value_free (wp->val);
14844                   wp->val = NULL;
14845                   wp->val_valid = 0;
14846                 }
14847           }
14848       }
14849 }
14850
14851 /* Create and insert a raw software breakpoint at PC.  Return an
14852    identifier, which should be used to remove the breakpoint later.
14853    In general, places which call this should be using something on the
14854    breakpoint chain instead; this function should be eliminated
14855    someday.  */
14856
14857 void *
14858 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14859                                   struct address_space *aspace, CORE_ADDR pc)
14860 {
14861   struct bp_target_info *bp_tgt;
14862
14863   bp_tgt = XZALLOC (struct bp_target_info);
14864
14865   bp_tgt->placed_address_space = aspace;
14866   bp_tgt->placed_address = pc;
14867
14868   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14869     {
14870       /* Could not insert the breakpoint.  */
14871       xfree (bp_tgt);
14872       return NULL;
14873     }
14874
14875   return bp_tgt;
14876 }
14877
14878 /* Remove a breakpoint BP inserted by
14879    deprecated_insert_raw_breakpoint.  */
14880
14881 int
14882 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14883 {
14884   struct bp_target_info *bp_tgt = bp;
14885   int ret;
14886
14887   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14888   xfree (bp_tgt);
14889
14890   return ret;
14891 }
14892
14893 /* One (or perhaps two) breakpoints used for software single
14894    stepping.  */
14895
14896 static void *single_step_breakpoints[2];
14897 static struct gdbarch *single_step_gdbarch[2];
14898
14899 /* Create and insert a breakpoint for software single step.  */
14900
14901 void
14902 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14903                                struct address_space *aspace, 
14904                                CORE_ADDR next_pc)
14905 {
14906   void **bpt_p;
14907
14908   if (single_step_breakpoints[0] == NULL)
14909     {
14910       bpt_p = &single_step_breakpoints[0];
14911       single_step_gdbarch[0] = gdbarch;
14912     }
14913   else
14914     {
14915       gdb_assert (single_step_breakpoints[1] == NULL);
14916       bpt_p = &single_step_breakpoints[1];
14917       single_step_gdbarch[1] = gdbarch;
14918     }
14919
14920   /* NOTE drow/2006-04-11: A future improvement to this function would
14921      be to only create the breakpoints once, and actually put them on
14922      the breakpoint chain.  That would let us use set_raw_breakpoint.
14923      We could adjust the addresses each time they were needed.  Doing
14924      this requires corresponding changes elsewhere where single step
14925      breakpoints are handled, however.  So, for now, we use this.  */
14926
14927   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14928   if (*bpt_p == NULL)
14929     error (_("Could not insert single-step breakpoint at %s"),
14930              paddress (gdbarch, next_pc));
14931 }
14932
14933 /* Check if the breakpoints used for software single stepping
14934    were inserted or not.  */
14935
14936 int
14937 single_step_breakpoints_inserted (void)
14938 {
14939   return (single_step_breakpoints[0] != NULL
14940           || single_step_breakpoints[1] != NULL);
14941 }
14942
14943 /* Remove and delete any breakpoints used for software single step.  */
14944
14945 void
14946 remove_single_step_breakpoints (void)
14947 {
14948   gdb_assert (single_step_breakpoints[0] != NULL);
14949
14950   /* See insert_single_step_breakpoint for more about this deprecated
14951      call.  */
14952   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14953                                     single_step_breakpoints[0]);
14954   single_step_gdbarch[0] = NULL;
14955   single_step_breakpoints[0] = NULL;
14956
14957   if (single_step_breakpoints[1] != NULL)
14958     {
14959       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14960                                         single_step_breakpoints[1]);
14961       single_step_gdbarch[1] = NULL;
14962       single_step_breakpoints[1] = NULL;
14963     }
14964 }
14965
14966 /* Delete software single step breakpoints without removing them from
14967    the inferior.  This is intended to be used if the inferior's address
14968    space where they were inserted is already gone, e.g. after exit or
14969    exec.  */
14970
14971 void
14972 cancel_single_step_breakpoints (void)
14973 {
14974   int i;
14975
14976   for (i = 0; i < 2; i++)
14977     if (single_step_breakpoints[i])
14978       {
14979         xfree (single_step_breakpoints[i]);
14980         single_step_breakpoints[i] = NULL;
14981         single_step_gdbarch[i] = NULL;
14982       }
14983 }
14984
14985 /* Detach software single-step breakpoints from INFERIOR_PTID without
14986    removing them.  */
14987
14988 static void
14989 detach_single_step_breakpoints (void)
14990 {
14991   int i;
14992
14993   for (i = 0; i < 2; i++)
14994     if (single_step_breakpoints[i])
14995       target_remove_breakpoint (single_step_gdbarch[i],
14996                                 single_step_breakpoints[i]);
14997 }
14998
14999 /* Check whether a software single-step breakpoint is inserted at
15000    PC.  */
15001
15002 static int
15003 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15004                                         CORE_ADDR pc)
15005 {
15006   int i;
15007
15008   for (i = 0; i < 2; i++)
15009     {
15010       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15011       if (bp_tgt
15012           && breakpoint_address_match (bp_tgt->placed_address_space,
15013                                        bp_tgt->placed_address,
15014                                        aspace, pc))
15015         return 1;
15016     }
15017
15018   return 0;
15019 }
15020
15021 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15022    non-zero otherwise.  */
15023 static int
15024 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15025 {
15026   if (syscall_catchpoint_p (bp)
15027       && bp->enable_state != bp_disabled
15028       && bp->enable_state != bp_call_disabled)
15029     return 1;
15030   else
15031     return 0;
15032 }
15033
15034 int
15035 catch_syscall_enabled (void)
15036 {
15037   struct catch_syscall_inferior_data *inf_data
15038     = get_catch_syscall_inferior_data (current_inferior ());
15039
15040   return inf_data->total_syscalls_count != 0;
15041 }
15042
15043 int
15044 catching_syscall_number (int syscall_number)
15045 {
15046   struct breakpoint *bp;
15047
15048   ALL_BREAKPOINTS (bp)
15049     if (is_syscall_catchpoint_enabled (bp))
15050       {
15051         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15052
15053         if (c->syscalls_to_be_caught)
15054           {
15055             int i, iter;
15056             for (i = 0;
15057                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15058                  i++)
15059               if (syscall_number == iter)
15060                 return 1;
15061           }
15062         else
15063           return 1;
15064       }
15065
15066   return 0;
15067 }
15068
15069 /* Complete syscall names.  Used by "catch syscall".  */
15070 static VEC (char_ptr) *
15071 catch_syscall_completer (struct cmd_list_element *cmd,
15072                          const char *text, const char *word)
15073 {
15074   const char **list = get_syscall_names ();
15075   VEC (char_ptr) *retlist
15076     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15077
15078   xfree (list);
15079   return retlist;
15080 }
15081
15082 /* Tracepoint-specific operations.  */
15083
15084 /* Set tracepoint count to NUM.  */
15085 static void
15086 set_tracepoint_count (int num)
15087 {
15088   tracepoint_count = num;
15089   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15090 }
15091
15092 static void
15093 trace_command (char *arg, int from_tty)
15094 {
15095   struct breakpoint_ops *ops;
15096   const char *arg_cp = arg;
15097
15098   if (arg && probe_linespec_to_ops (&arg_cp))
15099     ops = &tracepoint_probe_breakpoint_ops;
15100   else
15101     ops = &tracepoint_breakpoint_ops;
15102
15103   create_breakpoint (get_current_arch (),
15104                      arg,
15105                      NULL, 0, NULL, 1 /* parse arg */,
15106                      0 /* tempflag */,
15107                      bp_tracepoint /* type_wanted */,
15108                      0 /* Ignore count */,
15109                      pending_break_support,
15110                      ops,
15111                      from_tty,
15112                      1 /* enabled */,
15113                      0 /* internal */, 0);
15114 }
15115
15116 static void
15117 ftrace_command (char *arg, int from_tty)
15118 {
15119   create_breakpoint (get_current_arch (),
15120                      arg,
15121                      NULL, 0, NULL, 1 /* parse arg */,
15122                      0 /* tempflag */,
15123                      bp_fast_tracepoint /* type_wanted */,
15124                      0 /* Ignore count */,
15125                      pending_break_support,
15126                      &tracepoint_breakpoint_ops,
15127                      from_tty,
15128                      1 /* enabled */,
15129                      0 /* internal */, 0);
15130 }
15131
15132 /* strace command implementation.  Creates a static tracepoint.  */
15133
15134 static void
15135 strace_command (char *arg, int from_tty)
15136 {
15137   struct breakpoint_ops *ops;
15138
15139   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15140      or with a normal static tracepoint.  */
15141   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15142     ops = &strace_marker_breakpoint_ops;
15143   else
15144     ops = &tracepoint_breakpoint_ops;
15145
15146   create_breakpoint (get_current_arch (),
15147                      arg,
15148                      NULL, 0, NULL, 1 /* parse arg */,
15149                      0 /* tempflag */,
15150                      bp_static_tracepoint /* type_wanted */,
15151                      0 /* Ignore count */,
15152                      pending_break_support,
15153                      ops,
15154                      from_tty,
15155                      1 /* enabled */,
15156                      0 /* internal */, 0);
15157 }
15158
15159 /* Set up a fake reader function that gets command lines from a linked
15160    list that was acquired during tracepoint uploading.  */
15161
15162 static struct uploaded_tp *this_utp;
15163 static int next_cmd;
15164
15165 static char *
15166 read_uploaded_action (void)
15167 {
15168   char *rslt;
15169
15170   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15171
15172   next_cmd++;
15173
15174   return rslt;
15175 }
15176
15177 /* Given information about a tracepoint as recorded on a target (which
15178    can be either a live system or a trace file), attempt to create an
15179    equivalent GDB tracepoint.  This is not a reliable process, since
15180    the target does not necessarily have all the information used when
15181    the tracepoint was originally defined.  */
15182   
15183 struct tracepoint *
15184 create_tracepoint_from_upload (struct uploaded_tp *utp)
15185 {
15186   char *addr_str, small_buf[100];
15187   struct tracepoint *tp;
15188
15189   if (utp->at_string)
15190     addr_str = utp->at_string;
15191   else
15192     {
15193       /* In the absence of a source location, fall back to raw
15194          address.  Since there is no way to confirm that the address
15195          means the same thing as when the trace was started, warn the
15196          user.  */
15197       warning (_("Uploaded tracepoint %d has no "
15198                  "source location, using raw address"),
15199                utp->number);
15200       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15201       addr_str = small_buf;
15202     }
15203
15204   /* There's not much we can do with a sequence of bytecodes.  */
15205   if (utp->cond && !utp->cond_string)
15206     warning (_("Uploaded tracepoint %d condition "
15207                "has no source form, ignoring it"),
15208              utp->number);
15209
15210   if (!create_breakpoint (get_current_arch (),
15211                           addr_str,
15212                           utp->cond_string, -1, NULL,
15213                           0 /* parse cond/thread */,
15214                           0 /* tempflag */,
15215                           utp->type /* type_wanted */,
15216                           0 /* Ignore count */,
15217                           pending_break_support,
15218                           &tracepoint_breakpoint_ops,
15219                           0 /* from_tty */,
15220                           utp->enabled /* enabled */,
15221                           0 /* internal */,
15222                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15223     return NULL;
15224
15225   /* Get the tracepoint we just created.  */
15226   tp = get_tracepoint (tracepoint_count);
15227   gdb_assert (tp != NULL);
15228
15229   if (utp->pass > 0)
15230     {
15231       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15232                  tp->base.number);
15233
15234       trace_pass_command (small_buf, 0);
15235     }
15236
15237   /* If we have uploaded versions of the original commands, set up a
15238      special-purpose "reader" function and call the usual command line
15239      reader, then pass the result to the breakpoint command-setting
15240      function.  */
15241   if (!VEC_empty (char_ptr, utp->cmd_strings))
15242     {
15243       struct command_line *cmd_list;
15244
15245       this_utp = utp;
15246       next_cmd = 0;
15247
15248       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15249
15250       breakpoint_set_commands (&tp->base, cmd_list);
15251     }
15252   else if (!VEC_empty (char_ptr, utp->actions)
15253            || !VEC_empty (char_ptr, utp->step_actions))
15254     warning (_("Uploaded tracepoint %d actions "
15255                "have no source form, ignoring them"),
15256              utp->number);
15257
15258   /* Copy any status information that might be available.  */
15259   tp->base.hit_count = utp->hit_count;
15260   tp->traceframe_usage = utp->traceframe_usage;
15261
15262   return tp;
15263 }
15264   
15265 /* Print information on tracepoint number TPNUM_EXP, or all if
15266    omitted.  */
15267
15268 static void
15269 tracepoints_info (char *args, int from_tty)
15270 {
15271   struct ui_out *uiout = current_uiout;
15272   int num_printed;
15273
15274   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15275
15276   if (num_printed == 0)
15277     {
15278       if (args == NULL || *args == '\0')
15279         ui_out_message (uiout, 0, "No tracepoints.\n");
15280       else
15281         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15282     }
15283
15284   default_collect_info ();
15285 }
15286
15287 /* The 'enable trace' command enables tracepoints.
15288    Not supported by all targets.  */
15289 static void
15290 enable_trace_command (char *args, int from_tty)
15291 {
15292   enable_command (args, from_tty);
15293 }
15294
15295 /* The 'disable trace' command disables tracepoints.
15296    Not supported by all targets.  */
15297 static void
15298 disable_trace_command (char *args, int from_tty)
15299 {
15300   disable_command (args, from_tty);
15301 }
15302
15303 /* Remove a tracepoint (or all if no argument).  */
15304 static void
15305 delete_trace_command (char *arg, int from_tty)
15306 {
15307   struct breakpoint *b, *b_tmp;
15308
15309   dont_repeat ();
15310
15311   if (arg == 0)
15312     {
15313       int breaks_to_delete = 0;
15314
15315       /* Delete all breakpoints if no argument.
15316          Do not delete internal or call-dummy breakpoints, these
15317          have to be deleted with an explicit breakpoint number 
15318          argument.  */
15319       ALL_TRACEPOINTS (b)
15320         if (is_tracepoint (b) && user_breakpoint_p (b))
15321           {
15322             breaks_to_delete = 1;
15323             break;
15324           }
15325
15326       /* Ask user only if there are some breakpoints to delete.  */
15327       if (!from_tty
15328           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15329         {
15330           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15331             if (is_tracepoint (b) && user_breakpoint_p (b))
15332               delete_breakpoint (b);
15333         }
15334     }
15335   else
15336     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15337 }
15338
15339 /* Helper function for trace_pass_command.  */
15340
15341 static void
15342 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15343 {
15344   tp->pass_count = count;
15345   observer_notify_breakpoint_modified (&tp->base);
15346   if (from_tty)
15347     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15348                      tp->base.number, count);
15349 }
15350
15351 /* Set passcount for tracepoint.
15352
15353    First command argument is passcount, second is tracepoint number.
15354    If tracepoint number omitted, apply to most recently defined.
15355    Also accepts special argument "all".  */
15356
15357 static void
15358 trace_pass_command (char *args, int from_tty)
15359 {
15360   struct tracepoint *t1;
15361   unsigned int count;
15362
15363   if (args == 0 || *args == 0)
15364     error (_("passcount command requires an "
15365              "argument (count + optional TP num)"));
15366
15367   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15368
15369   args = skip_spaces (args);
15370   if (*args && strncasecmp (args, "all", 3) == 0)
15371     {
15372       struct breakpoint *b;
15373
15374       args += 3;                        /* Skip special argument "all".  */
15375       if (*args)
15376         error (_("Junk at end of arguments."));
15377
15378       ALL_TRACEPOINTS (b)
15379       {
15380         t1 = (struct tracepoint *) b;
15381         trace_pass_set_count (t1, count, from_tty);
15382       }
15383     }
15384   else if (*args == '\0')
15385     {
15386       t1 = get_tracepoint_by_number (&args, NULL, 1);
15387       if (t1)
15388         trace_pass_set_count (t1, count, from_tty);
15389     }
15390   else
15391     {
15392       struct get_number_or_range_state state;
15393
15394       init_number_or_range (&state, args);
15395       while (!state.finished)
15396         {
15397           t1 = get_tracepoint_by_number (&args, &state, 1);
15398           if (t1)
15399             trace_pass_set_count (t1, count, from_tty);
15400         }
15401     }
15402 }
15403
15404 struct tracepoint *
15405 get_tracepoint (int num)
15406 {
15407   struct breakpoint *t;
15408
15409   ALL_TRACEPOINTS (t)
15410     if (t->number == num)
15411       return (struct tracepoint *) t;
15412
15413   return NULL;
15414 }
15415
15416 /* Find the tracepoint with the given target-side number (which may be
15417    different from the tracepoint number after disconnecting and
15418    reconnecting).  */
15419
15420 struct tracepoint *
15421 get_tracepoint_by_number_on_target (int num)
15422 {
15423   struct breakpoint *b;
15424
15425   ALL_TRACEPOINTS (b)
15426     {
15427       struct tracepoint *t = (struct tracepoint *) b;
15428
15429       if (t->number_on_target == num)
15430         return t;
15431     }
15432
15433   return NULL;
15434 }
15435
15436 /* Utility: parse a tracepoint number and look it up in the list.
15437    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15438    If OPTIONAL_P is true, then if the argument is missing, the most
15439    recent tracepoint (tracepoint_count) is returned.  */
15440 struct tracepoint *
15441 get_tracepoint_by_number (char **arg,
15442                           struct get_number_or_range_state *state,
15443                           int optional_p)
15444 {
15445   struct breakpoint *t;
15446   int tpnum;
15447   char *instring = arg == NULL ? NULL : *arg;
15448
15449   if (state)
15450     {
15451       gdb_assert (!state->finished);
15452       tpnum = get_number_or_range (state);
15453     }
15454   else if (arg == NULL || *arg == NULL || ! **arg)
15455     {
15456       if (optional_p)
15457         tpnum = tracepoint_count;
15458       else
15459         error_no_arg (_("tracepoint number"));
15460     }
15461   else
15462     tpnum = get_number (arg);
15463
15464   if (tpnum <= 0)
15465     {
15466       if (instring && *instring)
15467         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15468                          instring);
15469       else
15470         printf_filtered (_("Tracepoint argument missing "
15471                            "and no previous tracepoint\n"));
15472       return NULL;
15473     }
15474
15475   ALL_TRACEPOINTS (t)
15476     if (t->number == tpnum)
15477     {
15478       return (struct tracepoint *) t;
15479     }
15480
15481   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15482   return NULL;
15483 }
15484
15485 void
15486 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15487 {
15488   if (b->thread != -1)
15489     fprintf_unfiltered (fp, " thread %d", b->thread);
15490
15491   if (b->task != 0)
15492     fprintf_unfiltered (fp, " task %d", b->task);
15493
15494   fprintf_unfiltered (fp, "\n");
15495 }
15496
15497 /* Save information on user settable breakpoints (watchpoints, etc) to
15498    a new script file named FILENAME.  If FILTER is non-NULL, call it
15499    on each breakpoint and only include the ones for which it returns
15500    non-zero.  */
15501
15502 static void
15503 save_breakpoints (char *filename, int from_tty,
15504                   int (*filter) (const struct breakpoint *))
15505 {
15506   struct breakpoint *tp;
15507   int any = 0;
15508   struct cleanup *cleanup;
15509   struct ui_file *fp;
15510   int extra_trace_bits = 0;
15511
15512   if (filename == 0 || *filename == 0)
15513     error (_("Argument required (file name in which to save)"));
15514
15515   /* See if we have anything to save.  */
15516   ALL_BREAKPOINTS (tp)
15517   {
15518     /* Skip internal and momentary breakpoints.  */
15519     if (!user_breakpoint_p (tp))
15520       continue;
15521
15522     /* If we have a filter, only save the breakpoints it accepts.  */
15523     if (filter && !filter (tp))
15524       continue;
15525
15526     any = 1;
15527
15528     if (is_tracepoint (tp))
15529       {
15530         extra_trace_bits = 1;
15531
15532         /* We can stop searching.  */
15533         break;
15534       }
15535   }
15536
15537   if (!any)
15538     {
15539       warning (_("Nothing to save."));
15540       return;
15541     }
15542
15543   filename = tilde_expand (filename);
15544   cleanup = make_cleanup (xfree, filename);
15545   fp = gdb_fopen (filename, "w");
15546   if (!fp)
15547     error (_("Unable to open file '%s' for saving (%s)"),
15548            filename, safe_strerror (errno));
15549   make_cleanup_ui_file_delete (fp);
15550
15551   if (extra_trace_bits)
15552     save_trace_state_variables (fp);
15553
15554   ALL_BREAKPOINTS (tp)
15555   {
15556     /* Skip internal and momentary breakpoints.  */
15557     if (!user_breakpoint_p (tp))
15558       continue;
15559
15560     /* If we have a filter, only save the breakpoints it accepts.  */
15561     if (filter && !filter (tp))
15562       continue;
15563
15564     tp->ops->print_recreate (tp, fp);
15565
15566     /* Note, we can't rely on tp->number for anything, as we can't
15567        assume the recreated breakpoint numbers will match.  Use $bpnum
15568        instead.  */
15569
15570     if (tp->cond_string)
15571       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15572
15573     if (tp->ignore_count)
15574       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15575
15576     if (tp->type != bp_dprintf && tp->commands)
15577       {
15578         volatile struct gdb_exception ex;       
15579
15580         fprintf_unfiltered (fp, "  commands\n");
15581         
15582         ui_out_redirect (current_uiout, fp);
15583         TRY_CATCH (ex, RETURN_MASK_ALL)
15584           {
15585             print_command_lines (current_uiout, tp->commands->commands, 2);
15586           }
15587         ui_out_redirect (current_uiout, NULL);
15588
15589         if (ex.reason < 0)
15590           throw_exception (ex);
15591
15592         fprintf_unfiltered (fp, "  end\n");
15593       }
15594
15595     if (tp->enable_state == bp_disabled)
15596       fprintf_unfiltered (fp, "disable\n");
15597
15598     /* If this is a multi-location breakpoint, check if the locations
15599        should be individually disabled.  Watchpoint locations are
15600        special, and not user visible.  */
15601     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15602       {
15603         struct bp_location *loc;
15604         int n = 1;
15605
15606         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15607           if (!loc->enabled)
15608             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15609       }
15610   }
15611
15612   if (extra_trace_bits && *default_collect)
15613     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15614
15615   if (from_tty)
15616     printf_filtered (_("Saved to file '%s'.\n"), filename);
15617   do_cleanups (cleanup);
15618 }
15619
15620 /* The `save breakpoints' command.  */
15621
15622 static void
15623 save_breakpoints_command (char *args, int from_tty)
15624 {
15625   save_breakpoints (args, from_tty, NULL);
15626 }
15627
15628 /* The `save tracepoints' command.  */
15629
15630 static void
15631 save_tracepoints_command (char *args, int from_tty)
15632 {
15633   save_breakpoints (args, from_tty, is_tracepoint);
15634 }
15635
15636 /* Create a vector of all tracepoints.  */
15637
15638 VEC(breakpoint_p) *
15639 all_tracepoints (void)
15640 {
15641   VEC(breakpoint_p) *tp_vec = 0;
15642   struct breakpoint *tp;
15643
15644   ALL_TRACEPOINTS (tp)
15645   {
15646     VEC_safe_push (breakpoint_p, tp_vec, tp);
15647   }
15648
15649   return tp_vec;
15650 }
15651
15652 \f
15653 /* This help string is used for the break, hbreak, tbreak and thbreak
15654    commands.  It is defined as a macro to prevent duplication.
15655    COMMAND should be a string constant containing the name of the
15656    command.  */
15657 #define BREAK_ARGS_HELP(command) \
15658 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15659 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15660 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15661 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15662 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15663 If a line number is specified, break at start of code for that line.\n\
15664 If a function is specified, break at start of code for that function.\n\
15665 If an address is specified, break at that exact address.\n\
15666 With no LOCATION, uses current execution address of the selected\n\
15667 stack frame.  This is useful for breaking on return to a stack frame.\n\
15668 \n\
15669 THREADNUM is the number from \"info threads\".\n\
15670 CONDITION is a boolean expression.\n\
15671 \n\
15672 Multiple breakpoints at one place are permitted, and useful if their\n\
15673 conditions are different.\n\
15674 \n\
15675 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15676
15677 /* List of subcommands for "catch".  */
15678 static struct cmd_list_element *catch_cmdlist;
15679
15680 /* List of subcommands for "tcatch".  */
15681 static struct cmd_list_element *tcatch_cmdlist;
15682
15683 void
15684 add_catch_command (char *name, char *docstring,
15685                    void (*sfunc) (char *args, int from_tty,
15686                                   struct cmd_list_element *command),
15687                    completer_ftype *completer,
15688                    void *user_data_catch,
15689                    void *user_data_tcatch)
15690 {
15691   struct cmd_list_element *command;
15692
15693   command = add_cmd (name, class_breakpoint, NULL, docstring,
15694                      &catch_cmdlist);
15695   set_cmd_sfunc (command, sfunc);
15696   set_cmd_context (command, user_data_catch);
15697   set_cmd_completer (command, completer);
15698
15699   command = add_cmd (name, class_breakpoint, NULL, docstring,
15700                      &tcatch_cmdlist);
15701   set_cmd_sfunc (command, sfunc);
15702   set_cmd_context (command, user_data_tcatch);
15703   set_cmd_completer (command, completer);
15704 }
15705
15706 static void
15707 clear_syscall_counts (struct inferior *inf)
15708 {
15709   struct catch_syscall_inferior_data *inf_data
15710     = get_catch_syscall_inferior_data (inf);
15711
15712   inf_data->total_syscalls_count = 0;
15713   inf_data->any_syscall_count = 0;
15714   VEC_free (int, inf_data->syscalls_counts);
15715 }
15716
15717 static void
15718 save_command (char *arg, int from_tty)
15719 {
15720   printf_unfiltered (_("\"save\" must be followed by "
15721                        "the name of a save subcommand.\n"));
15722   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15723 }
15724
15725 struct breakpoint *
15726 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15727                           void *data)
15728 {
15729   struct breakpoint *b, *b_tmp;
15730
15731   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15732     {
15733       if ((*callback) (b, data))
15734         return b;
15735     }
15736
15737   return NULL;
15738 }
15739
15740 /* Zero if any of the breakpoint's locations could be a location where
15741    functions have been inlined, nonzero otherwise.  */
15742
15743 static int
15744 is_non_inline_function (struct breakpoint *b)
15745 {
15746   /* The shared library event breakpoint is set on the address of a
15747      non-inline function.  */
15748   if (b->type == bp_shlib_event)
15749     return 1;
15750
15751   return 0;
15752 }
15753
15754 /* Nonzero if the specified PC cannot be a location where functions
15755    have been inlined.  */
15756
15757 int
15758 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15759                            const struct target_waitstatus *ws)
15760 {
15761   struct breakpoint *b;
15762   struct bp_location *bl;
15763
15764   ALL_BREAKPOINTS (b)
15765     {
15766       if (!is_non_inline_function (b))
15767         continue;
15768
15769       for (bl = b->loc; bl != NULL; bl = bl->next)
15770         {
15771           if (!bl->shlib_disabled
15772               && bpstat_check_location (bl, aspace, pc, ws))
15773             return 1;
15774         }
15775     }
15776
15777   return 0;
15778 }
15779
15780 /* Remove any references to OBJFILE which is going to be freed.  */
15781
15782 void
15783 breakpoint_free_objfile (struct objfile *objfile)
15784 {
15785   struct bp_location **locp, *loc;
15786
15787   ALL_BP_LOCATIONS (loc, locp)
15788     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
15789       loc->symtab = NULL;
15790 }
15791
15792 void
15793 initialize_breakpoint_ops (void)
15794 {
15795   static int initialized = 0;
15796
15797   struct breakpoint_ops *ops;
15798
15799   if (initialized)
15800     return;
15801   initialized = 1;
15802
15803   /* The breakpoint_ops structure to be inherit by all kinds of
15804      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15805      internal and momentary breakpoints, etc.).  */
15806   ops = &bkpt_base_breakpoint_ops;
15807   *ops = base_breakpoint_ops;
15808   ops->re_set = bkpt_re_set;
15809   ops->insert_location = bkpt_insert_location;
15810   ops->remove_location = bkpt_remove_location;
15811   ops->breakpoint_hit = bkpt_breakpoint_hit;
15812   ops->create_sals_from_address = bkpt_create_sals_from_address;
15813   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15814   ops->decode_linespec = bkpt_decode_linespec;
15815
15816   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15817   ops = &bkpt_breakpoint_ops;
15818   *ops = bkpt_base_breakpoint_ops;
15819   ops->re_set = bkpt_re_set;
15820   ops->resources_needed = bkpt_resources_needed;
15821   ops->print_it = bkpt_print_it;
15822   ops->print_mention = bkpt_print_mention;
15823   ops->print_recreate = bkpt_print_recreate;
15824
15825   /* Ranged breakpoints.  */
15826   ops = &ranged_breakpoint_ops;
15827   *ops = bkpt_breakpoint_ops;
15828   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15829   ops->resources_needed = resources_needed_ranged_breakpoint;
15830   ops->print_it = print_it_ranged_breakpoint;
15831   ops->print_one = print_one_ranged_breakpoint;
15832   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15833   ops->print_mention = print_mention_ranged_breakpoint;
15834   ops->print_recreate = print_recreate_ranged_breakpoint;
15835
15836   /* Internal breakpoints.  */
15837   ops = &internal_breakpoint_ops;
15838   *ops = bkpt_base_breakpoint_ops;
15839   ops->re_set = internal_bkpt_re_set;
15840   ops->check_status = internal_bkpt_check_status;
15841   ops->print_it = internal_bkpt_print_it;
15842   ops->print_mention = internal_bkpt_print_mention;
15843
15844   /* Momentary breakpoints.  */
15845   ops = &momentary_breakpoint_ops;
15846   *ops = bkpt_base_breakpoint_ops;
15847   ops->re_set = momentary_bkpt_re_set;
15848   ops->check_status = momentary_bkpt_check_status;
15849   ops->print_it = momentary_bkpt_print_it;
15850   ops->print_mention = momentary_bkpt_print_mention;
15851
15852   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15853   ops = &longjmp_breakpoint_ops;
15854   *ops = momentary_breakpoint_ops;
15855   ops->dtor = longjmp_bkpt_dtor;
15856
15857   /* Probe breakpoints.  */
15858   ops = &bkpt_probe_breakpoint_ops;
15859   *ops = bkpt_breakpoint_ops;
15860   ops->insert_location = bkpt_probe_insert_location;
15861   ops->remove_location = bkpt_probe_remove_location;
15862   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15863   ops->decode_linespec = bkpt_probe_decode_linespec;
15864
15865   /* Watchpoints.  */
15866   ops = &watchpoint_breakpoint_ops;
15867   *ops = base_breakpoint_ops;
15868   ops->dtor = dtor_watchpoint;
15869   ops->re_set = re_set_watchpoint;
15870   ops->insert_location = insert_watchpoint;
15871   ops->remove_location = remove_watchpoint;
15872   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15873   ops->check_status = check_status_watchpoint;
15874   ops->resources_needed = resources_needed_watchpoint;
15875   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15876   ops->print_it = print_it_watchpoint;
15877   ops->print_mention = print_mention_watchpoint;
15878   ops->print_recreate = print_recreate_watchpoint;
15879   ops->explains_signal = explains_signal_watchpoint;
15880
15881   /* Masked watchpoints.  */
15882   ops = &masked_watchpoint_breakpoint_ops;
15883   *ops = watchpoint_breakpoint_ops;
15884   ops->insert_location = insert_masked_watchpoint;
15885   ops->remove_location = remove_masked_watchpoint;
15886   ops->resources_needed = resources_needed_masked_watchpoint;
15887   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15888   ops->print_it = print_it_masked_watchpoint;
15889   ops->print_one_detail = print_one_detail_masked_watchpoint;
15890   ops->print_mention = print_mention_masked_watchpoint;
15891   ops->print_recreate = print_recreate_masked_watchpoint;
15892
15893   /* Tracepoints.  */
15894   ops = &tracepoint_breakpoint_ops;
15895   *ops = base_breakpoint_ops;
15896   ops->re_set = tracepoint_re_set;
15897   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15898   ops->print_one_detail = tracepoint_print_one_detail;
15899   ops->print_mention = tracepoint_print_mention;
15900   ops->print_recreate = tracepoint_print_recreate;
15901   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15902   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15903   ops->decode_linespec = tracepoint_decode_linespec;
15904
15905   /* Probe tracepoints.  */
15906   ops = &tracepoint_probe_breakpoint_ops;
15907   *ops = tracepoint_breakpoint_ops;
15908   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15909   ops->decode_linespec = tracepoint_probe_decode_linespec;
15910
15911   /* Static tracepoints with marker (`-m').  */
15912   ops = &strace_marker_breakpoint_ops;
15913   *ops = tracepoint_breakpoint_ops;
15914   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15915   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15916   ops->decode_linespec = strace_marker_decode_linespec;
15917
15918   /* Fork catchpoints.  */
15919   ops = &catch_fork_breakpoint_ops;
15920   *ops = base_breakpoint_ops;
15921   ops->insert_location = insert_catch_fork;
15922   ops->remove_location = remove_catch_fork;
15923   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15924   ops->print_it = print_it_catch_fork;
15925   ops->print_one = print_one_catch_fork;
15926   ops->print_mention = print_mention_catch_fork;
15927   ops->print_recreate = print_recreate_catch_fork;
15928
15929   /* Vfork catchpoints.  */
15930   ops = &catch_vfork_breakpoint_ops;
15931   *ops = base_breakpoint_ops;
15932   ops->insert_location = insert_catch_vfork;
15933   ops->remove_location = remove_catch_vfork;
15934   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15935   ops->print_it = print_it_catch_vfork;
15936   ops->print_one = print_one_catch_vfork;
15937   ops->print_mention = print_mention_catch_vfork;
15938   ops->print_recreate = print_recreate_catch_vfork;
15939
15940   /* Exec catchpoints.  */
15941   ops = &catch_exec_breakpoint_ops;
15942   *ops = base_breakpoint_ops;
15943   ops->dtor = dtor_catch_exec;
15944   ops->insert_location = insert_catch_exec;
15945   ops->remove_location = remove_catch_exec;
15946   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15947   ops->print_it = print_it_catch_exec;
15948   ops->print_one = print_one_catch_exec;
15949   ops->print_mention = print_mention_catch_exec;
15950   ops->print_recreate = print_recreate_catch_exec;
15951
15952   /* Syscall catchpoints.  */
15953   ops = &catch_syscall_breakpoint_ops;
15954   *ops = base_breakpoint_ops;
15955   ops->dtor = dtor_catch_syscall;
15956   ops->insert_location = insert_catch_syscall;
15957   ops->remove_location = remove_catch_syscall;
15958   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15959   ops->print_it = print_it_catch_syscall;
15960   ops->print_one = print_one_catch_syscall;
15961   ops->print_mention = print_mention_catch_syscall;
15962   ops->print_recreate = print_recreate_catch_syscall;
15963
15964   /* Solib-related catchpoints.  */
15965   ops = &catch_solib_breakpoint_ops;
15966   *ops = base_breakpoint_ops;
15967   ops->dtor = dtor_catch_solib;
15968   ops->insert_location = insert_catch_solib;
15969   ops->remove_location = remove_catch_solib;
15970   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15971   ops->check_status = check_status_catch_solib;
15972   ops->print_it = print_it_catch_solib;
15973   ops->print_one = print_one_catch_solib;
15974   ops->print_mention = print_mention_catch_solib;
15975   ops->print_recreate = print_recreate_catch_solib;
15976
15977   ops = &dprintf_breakpoint_ops;
15978   *ops = bkpt_base_breakpoint_ops;
15979   ops->re_set = dprintf_re_set;
15980   ops->resources_needed = bkpt_resources_needed;
15981   ops->print_it = bkpt_print_it;
15982   ops->print_mention = bkpt_print_mention;
15983   ops->print_recreate = dprintf_print_recreate;
15984   ops->after_condition_true = dprintf_after_condition_true;
15985 }
15986
15987 /* Chain containing all defined "enable breakpoint" subcommands.  */
15988
15989 static struct cmd_list_element *enablebreaklist = NULL;
15990
15991 void
15992 _initialize_breakpoint (void)
15993 {
15994   struct cmd_list_element *c;
15995
15996   initialize_breakpoint_ops ();
15997
15998   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15999   observer_attach_inferior_exit (clear_syscall_counts);
16000   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16001
16002   breakpoint_objfile_key
16003     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16004
16005   catch_syscall_inferior_data
16006     = register_inferior_data_with_cleanup (NULL,
16007                                            catch_syscall_inferior_data_cleanup);
16008
16009   breakpoint_chain = 0;
16010   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16011      before a breakpoint is set.  */
16012   breakpoint_count = 0;
16013
16014   tracepoint_count = 0;
16015
16016   add_com ("ignore", class_breakpoint, ignore_command, _("\
16017 Set ignore-count of breakpoint number N to COUNT.\n\
16018 Usage is `ignore N COUNT'."));
16019   if (xdb_commands)
16020     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16021
16022   add_com ("commands", class_breakpoint, commands_command, _("\
16023 Set commands to be executed when a breakpoint is hit.\n\
16024 Give breakpoint number as argument after \"commands\".\n\
16025 With no argument, the targeted breakpoint is the last one set.\n\
16026 The commands themselves follow starting on the next line.\n\
16027 Type a line containing \"end\" to indicate the end of them.\n\
16028 Give \"silent\" as the first line to make the breakpoint silent;\n\
16029 then no output is printed when it is hit, except what the commands print."));
16030
16031   c = add_com ("condition", class_breakpoint, condition_command, _("\
16032 Specify breakpoint number N to break only if COND is true.\n\
16033 Usage is `condition N COND', where N is an integer and COND is an\n\
16034 expression to be evaluated whenever breakpoint N is reached."));
16035   set_cmd_completer (c, condition_completer);
16036
16037   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16038 Set a temporary breakpoint.\n\
16039 Like \"break\" except the breakpoint is only temporary,\n\
16040 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16041 by using \"enable delete\" on the breakpoint number.\n\
16042 \n"
16043 BREAK_ARGS_HELP ("tbreak")));
16044   set_cmd_completer (c, location_completer);
16045
16046   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16047 Set a hardware assisted breakpoint.\n\
16048 Like \"break\" except the breakpoint requires hardware support,\n\
16049 some target hardware may not have this support.\n\
16050 \n"
16051 BREAK_ARGS_HELP ("hbreak")));
16052   set_cmd_completer (c, location_completer);
16053
16054   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16055 Set a temporary hardware assisted breakpoint.\n\
16056 Like \"hbreak\" except the breakpoint is only temporary,\n\
16057 so it will be deleted when hit.\n\
16058 \n"
16059 BREAK_ARGS_HELP ("thbreak")));
16060   set_cmd_completer (c, location_completer);
16061
16062   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16063 Enable some breakpoints.\n\
16064 Give breakpoint numbers (separated by spaces) as arguments.\n\
16065 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16066 This is used to cancel the effect of the \"disable\" command.\n\
16067 With a subcommand you can enable temporarily."),
16068                   &enablelist, "enable ", 1, &cmdlist);
16069   if (xdb_commands)
16070     add_com ("ab", class_breakpoint, enable_command, _("\
16071 Enable some breakpoints.\n\
16072 Give breakpoint numbers (separated by spaces) as arguments.\n\
16073 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16074 This is used to cancel the effect of the \"disable\" command.\n\
16075 With a subcommand you can enable temporarily."));
16076
16077   add_com_alias ("en", "enable", class_breakpoint, 1);
16078
16079   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16080 Enable some breakpoints.\n\
16081 Give breakpoint numbers (separated by spaces) as arguments.\n\
16082 This is used to cancel the effect of the \"disable\" command.\n\
16083 May be abbreviated to simply \"enable\".\n"),
16084                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16085
16086   add_cmd ("once", no_class, enable_once_command, _("\
16087 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16088 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16089            &enablebreaklist);
16090
16091   add_cmd ("delete", no_class, enable_delete_command, _("\
16092 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16093 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16094            &enablebreaklist);
16095
16096   add_cmd ("count", no_class, enable_count_command, _("\
16097 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16098 If a breakpoint is hit while enabled in this fashion,\n\
16099 the count is decremented; when it reaches zero, the breakpoint is 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            &enablelist);
16106
16107   add_cmd ("once", no_class, enable_once_command, _("\
16108 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16109 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16110            &enablelist);
16111
16112   add_cmd ("count", no_class, enable_count_command, _("\
16113 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16114 If a breakpoint is hit while enabled in this fashion,\n\
16115 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16116            &enablelist);
16117
16118   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16119 Disable some breakpoints.\n\
16120 Arguments are breakpoint numbers with spaces in between.\n\
16121 To disable all breakpoints, give no argument.\n\
16122 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16123                   &disablelist, "disable ", 1, &cmdlist);
16124   add_com_alias ("dis", "disable", class_breakpoint, 1);
16125   add_com_alias ("disa", "disable", class_breakpoint, 1);
16126   if (xdb_commands)
16127     add_com ("sb", class_breakpoint, disable_command, _("\
16128 Disable some breakpoints.\n\
16129 Arguments are breakpoint numbers with spaces in between.\n\
16130 To disable all breakpoints, give no argument.\n\
16131 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16132
16133   add_cmd ("breakpoints", class_alias, disable_command, _("\
16134 Disable some breakpoints.\n\
16135 Arguments are breakpoint numbers with spaces in between.\n\
16136 To disable all breakpoints, give no argument.\n\
16137 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16138 This command may be abbreviated \"disable\"."),
16139            &disablelist);
16140
16141   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16142 Delete some breakpoints or auto-display expressions.\n\
16143 Arguments are breakpoint numbers with spaces in between.\n\
16144 To delete all breakpoints, give no argument.\n\
16145 \n\
16146 Also a prefix command for deletion of other GDB objects.\n\
16147 The \"unset\" command is also an alias for \"delete\"."),
16148                   &deletelist, "delete ", 1, &cmdlist);
16149   add_com_alias ("d", "delete", class_breakpoint, 1);
16150   add_com_alias ("del", "delete", class_breakpoint, 1);
16151   if (xdb_commands)
16152     add_com ("db", class_breakpoint, delete_command, _("\
16153 Delete some breakpoints.\n\
16154 Arguments are breakpoint numbers with spaces in between.\n\
16155 To delete all breakpoints, give no argument.\n"));
16156
16157   add_cmd ("breakpoints", class_alias, delete_command, _("\
16158 Delete some breakpoints or auto-display expressions.\n\
16159 Arguments are breakpoint numbers with spaces in between.\n\
16160 To delete all breakpoints, give no argument.\n\
16161 This command may be abbreviated \"delete\"."),
16162            &deletelist);
16163
16164   add_com ("clear", class_breakpoint, clear_command, _("\
16165 Clear breakpoint at specified line or function.\n\
16166 Argument may be line number, function name, or \"*\" and an address.\n\
16167 If line number is specified, all breakpoints in that line are cleared.\n\
16168 If function is specified, breakpoints at beginning of function are cleared.\n\
16169 If an address is specified, breakpoints at that address are cleared.\n\
16170 \n\
16171 With no argument, clears all breakpoints in the line that the selected frame\n\
16172 is executing in.\n\
16173 \n\
16174 See also the \"delete\" command which clears breakpoints by number."));
16175   add_com_alias ("cl", "clear", class_breakpoint, 1);
16176
16177   c = add_com ("break", class_breakpoint, break_command, _("\
16178 Set breakpoint at specified line or function.\n"
16179 BREAK_ARGS_HELP ("break")));
16180   set_cmd_completer (c, location_completer);
16181
16182   add_com_alias ("b", "break", class_run, 1);
16183   add_com_alias ("br", "break", class_run, 1);
16184   add_com_alias ("bre", "break", class_run, 1);
16185   add_com_alias ("brea", "break", class_run, 1);
16186
16187   if (xdb_commands)
16188    add_com_alias ("ba", "break", class_breakpoint, 1);
16189
16190   if (dbx_commands)
16191     {
16192       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16193 Break in function/address or break at a line in the current file."),
16194                              &stoplist, "stop ", 1, &cmdlist);
16195       add_cmd ("in", class_breakpoint, stopin_command,
16196                _("Break in function or address."), &stoplist);
16197       add_cmd ("at", class_breakpoint, stopat_command,
16198                _("Break at a line in the current file."), &stoplist);
16199       add_com ("status", class_info, breakpoints_info, _("\
16200 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16201 The \"Type\" column indicates one of:\n\
16202 \tbreakpoint     - normal breakpoint\n\
16203 \twatchpoint     - watchpoint\n\
16204 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16205 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16206 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16207 address and file/line number respectively.\n\
16208 \n\
16209 Convenience variable \"$_\" and default examine address for \"x\"\n\
16210 are set to the address of the last breakpoint listed unless the command\n\
16211 is prefixed with \"server \".\n\n\
16212 Convenience variable \"$bpnum\" contains the number of the last\n\
16213 breakpoint set."));
16214     }
16215
16216   add_info ("breakpoints", breakpoints_info, _("\
16217 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16218 The \"Type\" column indicates one of:\n\
16219 \tbreakpoint     - normal breakpoint\n\
16220 \twatchpoint     - watchpoint\n\
16221 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16222 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16223 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16224 address and file/line number respectively.\n\
16225 \n\
16226 Convenience variable \"$_\" and default examine address for \"x\"\n\
16227 are set to the address of the last breakpoint listed unless the command\n\
16228 is prefixed with \"server \".\n\n\
16229 Convenience variable \"$bpnum\" contains the number of the last\n\
16230 breakpoint set."));
16231
16232   add_info_alias ("b", "breakpoints", 1);
16233
16234   if (xdb_commands)
16235     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16236 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16237 The \"Type\" column indicates one of:\n\
16238 \tbreakpoint     - normal breakpoint\n\
16239 \twatchpoint     - watchpoint\n\
16240 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16241 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16242 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16243 address and file/line number respectively.\n\
16244 \n\
16245 Convenience variable \"$_\" and default examine address for \"x\"\n\
16246 are set to the address of the last breakpoint listed unless the command\n\
16247 is prefixed with \"server \".\n\n\
16248 Convenience variable \"$bpnum\" contains the number of the last\n\
16249 breakpoint set."));
16250
16251   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16252 Status of all breakpoints, or breakpoint number NUMBER.\n\
16253 The \"Type\" column indicates one of:\n\
16254 \tbreakpoint     - normal breakpoint\n\
16255 \twatchpoint     - watchpoint\n\
16256 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16257 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16258 \tuntil          - internal breakpoint used by the \"until\" command\n\
16259 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16260 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16261 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16262 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16263 address and file/line number respectively.\n\
16264 \n\
16265 Convenience variable \"$_\" and default examine address for \"x\"\n\
16266 are set to the address of the last breakpoint listed unless the command\n\
16267 is prefixed with \"server \".\n\n\
16268 Convenience variable \"$bpnum\" contains the number of the last\n\
16269 breakpoint set."),
16270            &maintenanceinfolist);
16271
16272   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16273 Set catchpoints to catch events."),
16274                   &catch_cmdlist, "catch ",
16275                   0/*allow-unknown*/, &cmdlist);
16276
16277   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16278 Set temporary catchpoints to catch events."),
16279                   &tcatch_cmdlist, "tcatch ",
16280                   0/*allow-unknown*/, &cmdlist);
16281
16282   add_catch_command ("fork", _("Catch calls to fork."),
16283                      catch_fork_command_1,
16284                      NULL,
16285                      (void *) (uintptr_t) catch_fork_permanent,
16286                      (void *) (uintptr_t) catch_fork_temporary);
16287   add_catch_command ("vfork", _("Catch calls to vfork."),
16288                      catch_fork_command_1,
16289                      NULL,
16290                      (void *) (uintptr_t) catch_vfork_permanent,
16291                      (void *) (uintptr_t) catch_vfork_temporary);
16292   add_catch_command ("exec", _("Catch calls to exec."),
16293                      catch_exec_command_1,
16294                      NULL,
16295                      CATCH_PERMANENT,
16296                      CATCH_TEMPORARY);
16297   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16298 Usage: catch load [REGEX]\n\
16299 If REGEX is given, only stop for libraries matching the regular expression."),
16300                      catch_load_command_1,
16301                      NULL,
16302                      CATCH_PERMANENT,
16303                      CATCH_TEMPORARY);
16304   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16305 Usage: catch unload [REGEX]\n\
16306 If REGEX is given, only stop for libraries matching the regular expression."),
16307                      catch_unload_command_1,
16308                      NULL,
16309                      CATCH_PERMANENT,
16310                      CATCH_TEMPORARY);
16311   add_catch_command ("syscall", _("\
16312 Catch system calls by their names and/or numbers.\n\
16313 Arguments say which system calls to catch.  If no arguments\n\
16314 are given, every system call will be caught.\n\
16315 Arguments, if given, should be one or more system call names\n\
16316 (if your system supports that), or system call numbers."),
16317                      catch_syscall_command_1,
16318                      catch_syscall_completer,
16319                      CATCH_PERMANENT,
16320                      CATCH_TEMPORARY);
16321
16322   c = add_com ("watch", class_breakpoint, watch_command, _("\
16323 Set a watchpoint for an expression.\n\
16324 Usage: watch [-l|-location] EXPRESSION\n\
16325 A watchpoint stops execution of your program whenever the value of\n\
16326 an expression changes.\n\
16327 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16328 the memory to which it refers."));
16329   set_cmd_completer (c, expression_completer);
16330
16331   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16332 Set a read watchpoint for an expression.\n\
16333 Usage: rwatch [-l|-location] EXPRESSION\n\
16334 A watchpoint stops execution of your program whenever the value of\n\
16335 an expression is read.\n\
16336 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16337 the memory to which it refers."));
16338   set_cmd_completer (c, expression_completer);
16339
16340   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16341 Set a watchpoint for an expression.\n\
16342 Usage: awatch [-l|-location] EXPRESSION\n\
16343 A watchpoint stops execution of your program whenever the value of\n\
16344 an expression is either read or written.\n\
16345 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16346 the memory to which it refers."));
16347   set_cmd_completer (c, expression_completer);
16348
16349   add_info ("watchpoints", watchpoints_info, _("\
16350 Status of specified watchpoints (all watchpoints if no argument)."));
16351
16352   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16353      respond to changes - contrary to the description.  */
16354   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16355                             &can_use_hw_watchpoints, _("\
16356 Set debugger's willingness to use watchpoint hardware."), _("\
16357 Show debugger's willingness to use watchpoint hardware."), _("\
16358 If zero, gdb will not use hardware for new watchpoints, even if\n\
16359 such is available.  (However, any hardware watchpoints that were\n\
16360 created before setting this to nonzero, will continue to use watchpoint\n\
16361 hardware.)"),
16362                             NULL,
16363                             show_can_use_hw_watchpoints,
16364                             &setlist, &showlist);
16365
16366   can_use_hw_watchpoints = 1;
16367
16368   /* Tracepoint manipulation commands.  */
16369
16370   c = add_com ("trace", class_breakpoint, trace_command, _("\
16371 Set a tracepoint at specified line or function.\n\
16372 \n"
16373 BREAK_ARGS_HELP ("trace") "\n\
16374 Do \"help tracepoints\" for info on other tracepoint commands."));
16375   set_cmd_completer (c, location_completer);
16376
16377   add_com_alias ("tp", "trace", class_alias, 0);
16378   add_com_alias ("tr", "trace", class_alias, 1);
16379   add_com_alias ("tra", "trace", class_alias, 1);
16380   add_com_alias ("trac", "trace", class_alias, 1);
16381
16382   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16383 Set a fast tracepoint at specified line or function.\n\
16384 \n"
16385 BREAK_ARGS_HELP ("ftrace") "\n\
16386 Do \"help tracepoints\" for info on other tracepoint commands."));
16387   set_cmd_completer (c, location_completer);
16388
16389   c = add_com ("strace", class_breakpoint, strace_command, _("\
16390 Set a static tracepoint at specified line, function or marker.\n\
16391 \n\
16392 strace [LOCATION] [if CONDITION]\n\
16393 LOCATION may be a line number, function name, \"*\" and an address,\n\
16394 or -m MARKER_ID.\n\
16395 If a line number is specified, probe the marker at start of code\n\
16396 for that line.  If a function is specified, probe the marker at start\n\
16397 of code for that function.  If an address is specified, probe the marker\n\
16398 at that exact address.  If a marker id is specified, probe the marker\n\
16399 with that name.  With no LOCATION, uses current execution address of\n\
16400 the selected stack frame.\n\
16401 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16402 This collects arbitrary user data passed in the probe point call to the\n\
16403 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16404 by printing the $_sdata variable like any other convenience variable.\n\
16405 \n\
16406 CONDITION is a boolean expression.\n\
16407 \n\
16408 Multiple tracepoints at one place are permitted, and useful if their\n\
16409 conditions are different.\n\
16410 \n\
16411 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16412 Do \"help tracepoints\" for info on other tracepoint commands."));
16413   set_cmd_completer (c, location_completer);
16414
16415   add_info ("tracepoints", tracepoints_info, _("\
16416 Status of specified tracepoints (all tracepoints if no argument).\n\
16417 Convenience variable \"$tpnum\" contains the number of the\n\
16418 last tracepoint set."));
16419
16420   add_info_alias ("tp", "tracepoints", 1);
16421
16422   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16423 Delete specified tracepoints.\n\
16424 Arguments are tracepoint numbers, separated by spaces.\n\
16425 No argument means delete all tracepoints."),
16426            &deletelist);
16427   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16428
16429   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16430 Disable specified tracepoints.\n\
16431 Arguments are tracepoint numbers, separated by spaces.\n\
16432 No argument means disable all tracepoints."),
16433            &disablelist);
16434   deprecate_cmd (c, "disable");
16435
16436   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16437 Enable specified tracepoints.\n\
16438 Arguments are tracepoint numbers, separated by spaces.\n\
16439 No argument means enable all tracepoints."),
16440            &enablelist);
16441   deprecate_cmd (c, "enable");
16442
16443   add_com ("passcount", class_trace, trace_pass_command, _("\
16444 Set the passcount for a tracepoint.\n\
16445 The trace will end when the tracepoint has been passed 'count' times.\n\
16446 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16447 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16448
16449   add_prefix_cmd ("save", class_breakpoint, save_command,
16450                   _("Save breakpoint definitions as a script."),
16451                   &save_cmdlist, "save ",
16452                   0/*allow-unknown*/, &cmdlist);
16453
16454   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16455 Save current breakpoint definitions as a script.\n\
16456 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16457 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16458 session to restore them."),
16459                &save_cmdlist);
16460   set_cmd_completer (c, filename_completer);
16461
16462   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16463 Save current tracepoint definitions as a script.\n\
16464 Use the 'source' command in another debug session to restore them."),
16465                &save_cmdlist);
16466   set_cmd_completer (c, filename_completer);
16467
16468   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16469   deprecate_cmd (c, "save tracepoints");
16470
16471   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16472 Breakpoint specific settings\n\
16473 Configure various breakpoint-specific variables such as\n\
16474 pending breakpoint behavior"),
16475                   &breakpoint_set_cmdlist, "set breakpoint ",
16476                   0/*allow-unknown*/, &setlist);
16477   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16478 Breakpoint specific settings\n\
16479 Configure various breakpoint-specific variables such as\n\
16480 pending breakpoint behavior"),
16481                   &breakpoint_show_cmdlist, "show breakpoint ",
16482                   0/*allow-unknown*/, &showlist);
16483
16484   add_setshow_auto_boolean_cmd ("pending", no_class,
16485                                 &pending_break_support, _("\
16486 Set debugger's behavior regarding pending breakpoints."), _("\
16487 Show debugger's behavior regarding pending breakpoints."), _("\
16488 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16489 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16490 an error.  If auto, an unrecognized breakpoint location results in a\n\
16491 user-query to see if a pending breakpoint should be created."),
16492                                 NULL,
16493                                 show_pending_break_support,
16494                                 &breakpoint_set_cmdlist,
16495                                 &breakpoint_show_cmdlist);
16496
16497   pending_break_support = AUTO_BOOLEAN_AUTO;
16498
16499   add_setshow_boolean_cmd ("auto-hw", no_class,
16500                            &automatic_hardware_breakpoints, _("\
16501 Set automatic usage of hardware breakpoints."), _("\
16502 Show automatic usage of hardware breakpoints."), _("\
16503 If set, the debugger will automatically use hardware breakpoints for\n\
16504 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16505 a warning will be emitted for such breakpoints."),
16506                            NULL,
16507                            show_automatic_hardware_breakpoints,
16508                            &breakpoint_set_cmdlist,
16509                            &breakpoint_show_cmdlist);
16510
16511   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16512                                 &always_inserted_mode, _("\
16513 Set mode for inserting breakpoints."), _("\
16514 Show mode for inserting breakpoints."), _("\
16515 When this mode is off, breakpoints are inserted in inferior when it is\n\
16516 resumed, and removed when execution stops.  When this mode is on,\n\
16517 breakpoints are inserted immediately and removed only when the user\n\
16518 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16519 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16520 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16521 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16522 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16523                                 NULL,
16524                                 &show_always_inserted_mode,
16525                                 &breakpoint_set_cmdlist,
16526                                 &breakpoint_show_cmdlist);
16527
16528   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16529                         condition_evaluation_enums,
16530                         &condition_evaluation_mode_1, _("\
16531 Set mode of breakpoint condition evaluation."), _("\
16532 Show mode of breakpoint condition evaluation."), _("\
16533 When this is set to \"host\", breakpoint conditions will be\n\
16534 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16535 breakpoint conditions will be downloaded to the target (if the target\n\
16536 supports such feature) and conditions will be evaluated on the target's side.\n\
16537 If this is set to \"auto\" (default), this will be automatically set to\n\
16538 \"target\" if it supports condition evaluation, otherwise it will\n\
16539 be set to \"gdb\""),
16540                            &set_condition_evaluation_mode,
16541                            &show_condition_evaluation_mode,
16542                            &breakpoint_set_cmdlist,
16543                            &breakpoint_show_cmdlist);
16544
16545   add_com ("break-range", class_breakpoint, break_range_command, _("\
16546 Set a breakpoint for an address range.\n\
16547 break-range START-LOCATION, END-LOCATION\n\
16548 where START-LOCATION and END-LOCATION can be one of the following:\n\
16549   LINENUM, for that line in the current file,\n\
16550   FILE:LINENUM, for that line in that file,\n\
16551   +OFFSET, for that number of lines after the current line\n\
16552            or the start of the range\n\
16553   FUNCTION, for the first line in that function,\n\
16554   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16555   *ADDRESS, for the instruction at that address.\n\
16556 \n\
16557 The breakpoint will stop execution of the inferior whenever it executes\n\
16558 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16559 range (including START-LOCATION and END-LOCATION)."));
16560
16561   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16562 Set a dynamic printf at specified line or function.\n\
16563 dprintf location,format string,arg1,arg2,...\n\
16564 location may be a line number, function name, or \"*\" and an address.\n\
16565 If a line number is specified, break at start of code for that line.\n\
16566 If a function is specified, break at start of code for that function."));
16567   set_cmd_completer (c, location_completer);
16568
16569   add_setshow_enum_cmd ("dprintf-style", class_support,
16570                         dprintf_style_enums, &dprintf_style, _("\
16571 Set the style of usage for dynamic printf."), _("\
16572 Show the style of usage for dynamic printf."), _("\
16573 This setting chooses how GDB will do a dynamic printf.\n\
16574 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16575 console, as with the \"printf\" command.\n\
16576 If the value is \"call\", the print is done by calling a function in your\n\
16577 program; by default printf(), but you can choose a different function or\n\
16578 output stream by setting dprintf-function and dprintf-channel."),
16579                         update_dprintf_commands, NULL,
16580                         &setlist, &showlist);
16581
16582   dprintf_function = xstrdup ("printf");
16583   add_setshow_string_cmd ("dprintf-function", class_support,
16584                           &dprintf_function, _("\
16585 Set the function to use for dynamic printf"), _("\
16586 Show the function to use for dynamic printf"), NULL,
16587                           update_dprintf_commands, NULL,
16588                           &setlist, &showlist);
16589
16590   dprintf_channel = xstrdup ("");
16591   add_setshow_string_cmd ("dprintf-channel", class_support,
16592                           &dprintf_channel, _("\
16593 Set the channel to use for dynamic printf"), _("\
16594 Show the channel to use for dynamic printf"), NULL,
16595                           update_dprintf_commands, NULL,
16596                           &setlist, &showlist);
16597
16598   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16599                            &disconnected_dprintf, _("\
16600 Set whether dprintf continues after GDB disconnects."), _("\
16601 Show whether dprintf continues after GDB disconnects."), _("\
16602 Use this to let dprintf commands continue to hit and produce output\n\
16603 even if GDB disconnects or detaches from the target."),
16604                            NULL,
16605                            NULL,
16606                            &setlist, &showlist);
16607
16608   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16609 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16610 (target agent only) This is useful for formatted output in user-defined commands."));
16611
16612   automatic_hardware_breakpoints = 1;
16613
16614   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16615   observer_attach_thread_exit (remove_threaded_breakpoints);
16616 }