Fix regressions caused by thread-specific breakpoint deletion.
[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                   fprintf_unfiltered (tmp_error_stream, 
2574                                       "Cannot insert breakpoint %d.\n", 
2575                                       bl->owner->number);
2576                   fprintf_filtered (tmp_error_stream, 
2577                                     "Error accessing memory address ");
2578                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2579                                   tmp_error_stream);
2580                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2581                                     safe_strerror (val));
2582                 }
2583
2584             }
2585         }
2586       else
2587         bl->inserted = 1;
2588
2589       return val;
2590     }
2591
2592   else if (bl->loc_type == bp_loc_hardware_watchpoint
2593            /* NOTE drow/2003-09-08: This state only exists for removing
2594               watchpoints.  It's not clear that it's necessary...  */
2595            && bl->owner->disposition != disp_del_at_next_stop)
2596     {
2597       gdb_assert (bl->owner->ops != NULL
2598                   && bl->owner->ops->insert_location != NULL);
2599
2600       val = bl->owner->ops->insert_location (bl);
2601
2602       /* If trying to set a read-watchpoint, and it turns out it's not
2603          supported, try emulating one with an access watchpoint.  */
2604       if (val == 1 && bl->watchpoint_type == hw_read)
2605         {
2606           struct bp_location *loc, **loc_temp;
2607
2608           /* But don't try to insert it, if there's already another
2609              hw_access location that would be considered a duplicate
2610              of this one.  */
2611           ALL_BP_LOCATIONS (loc, loc_temp)
2612             if (loc != bl
2613                 && loc->watchpoint_type == hw_access
2614                 && watchpoint_locations_match (bl, loc))
2615               {
2616                 bl->duplicate = 1;
2617                 bl->inserted = 1;
2618                 bl->target_info = loc->target_info;
2619                 bl->watchpoint_type = hw_access;
2620                 val = 0;
2621                 break;
2622               }
2623
2624           if (val == 1)
2625             {
2626               bl->watchpoint_type = hw_access;
2627               val = bl->owner->ops->insert_location (bl);
2628
2629               if (val)
2630                 /* Back to the original value.  */
2631                 bl->watchpoint_type = hw_read;
2632             }
2633         }
2634
2635       bl->inserted = (val == 0);
2636     }
2637
2638   else if (bl->owner->type == bp_catchpoint)
2639     {
2640       gdb_assert (bl->owner->ops != NULL
2641                   && bl->owner->ops->insert_location != NULL);
2642
2643       val = bl->owner->ops->insert_location (bl);
2644       if (val)
2645         {
2646           bl->owner->enable_state = bp_disabled;
2647
2648           if (val == 1)
2649             warning (_("\
2650 Error inserting catchpoint %d: Your system does not support this type\n\
2651 of catchpoint."), bl->owner->number);
2652           else
2653             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2654         }
2655
2656       bl->inserted = (val == 0);
2657
2658       /* We've already printed an error message if there was a problem
2659          inserting this catchpoint, and we've disabled the catchpoint,
2660          so just return success.  */
2661       return 0;
2662     }
2663
2664   return 0;
2665 }
2666
2667 /* This function is called when program space PSPACE is about to be
2668    deleted.  It takes care of updating breakpoints to not reference
2669    PSPACE anymore.  */
2670
2671 void
2672 breakpoint_program_space_exit (struct program_space *pspace)
2673 {
2674   struct breakpoint *b, *b_temp;
2675   struct bp_location *loc, **loc_temp;
2676
2677   /* Remove any breakpoint that was set through this program space.  */
2678   ALL_BREAKPOINTS_SAFE (b, b_temp)
2679     {
2680       if (b->pspace == pspace)
2681         delete_breakpoint (b);
2682     }
2683
2684   /* Breakpoints set through other program spaces could have locations
2685      bound to PSPACE as well.  Remove those.  */
2686   ALL_BP_LOCATIONS (loc, loc_temp)
2687     {
2688       struct bp_location *tmp;
2689
2690       if (loc->pspace == pspace)
2691         {
2692           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2693           if (loc->owner->loc == loc)
2694             loc->owner->loc = loc->next;
2695           else
2696             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2697               if (tmp->next == loc)
2698                 {
2699                   tmp->next = loc->next;
2700                   break;
2701                 }
2702         }
2703     }
2704
2705   /* Now update the global location list to permanently delete the
2706      removed locations above.  */
2707   update_global_location_list (0);
2708 }
2709
2710 /* Make sure all breakpoints are inserted in inferior.
2711    Throws exception on any error.
2712    A breakpoint that is already inserted won't be inserted
2713    again, so calling this function twice is safe.  */
2714 void
2715 insert_breakpoints (void)
2716 {
2717   struct breakpoint *bpt;
2718
2719   ALL_BREAKPOINTS (bpt)
2720     if (is_hardware_watchpoint (bpt))
2721       {
2722         struct watchpoint *w = (struct watchpoint *) bpt;
2723
2724         update_watchpoint (w, 0 /* don't reparse.  */);
2725       }
2726
2727   update_global_location_list (1);
2728
2729   /* update_global_location_list does not insert breakpoints when
2730      always_inserted_mode is not enabled.  Explicitly insert them
2731      now.  */
2732   if (!breakpoints_always_inserted_mode ())
2733     insert_breakpoint_locations ();
2734 }
2735
2736 /* Invoke CALLBACK for each of bp_location.  */
2737
2738 void
2739 iterate_over_bp_locations (walk_bp_location_callback callback)
2740 {
2741   struct bp_location *loc, **loc_tmp;
2742
2743   ALL_BP_LOCATIONS (loc, loc_tmp)
2744     {
2745       callback (loc, NULL);
2746     }
2747 }
2748
2749 /* This is used when we need to synch breakpoint conditions between GDB and the
2750    target.  It is the case with deleting and disabling of breakpoints when using
2751    always-inserted mode.  */
2752
2753 static void
2754 update_inserted_breakpoint_locations (void)
2755 {
2756   struct bp_location *bl, **blp_tmp;
2757   int error_flag = 0;
2758   int val = 0;
2759   int disabled_breaks = 0;
2760   int hw_breakpoint_error = 0;
2761   int hw_bp_details_reported = 0;
2762
2763   struct ui_file *tmp_error_stream = mem_fileopen ();
2764   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2765
2766   /* Explicitly mark the warning -- this will only be printed if
2767      there was an error.  */
2768   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2769
2770   save_current_space_and_thread ();
2771
2772   ALL_BP_LOCATIONS (bl, blp_tmp)
2773     {
2774       /* We only want to update software breakpoints and hardware
2775          breakpoints.  */
2776       if (!is_breakpoint (bl->owner))
2777         continue;
2778
2779       /* We only want to update locations that are already inserted
2780          and need updating.  This is to avoid unwanted insertion during
2781          deletion of breakpoints.  */
2782       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2783         continue;
2784
2785       switch_to_program_space_and_thread (bl->pspace);
2786
2787       /* For targets that support global breakpoints, there's no need
2788          to select an inferior to insert breakpoint to.  In fact, even
2789          if we aren't attached to any process yet, we should still
2790          insert breakpoints.  */
2791       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2792           && ptid_equal (inferior_ptid, null_ptid))
2793         continue;
2794
2795       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2796                                     &hw_breakpoint_error, &hw_bp_details_reported);
2797       if (val)
2798         error_flag = val;
2799     }
2800
2801   if (error_flag)
2802     {
2803       target_terminal_ours_for_output ();
2804       error_stream (tmp_error_stream);
2805     }
2806
2807   do_cleanups (cleanups);
2808 }
2809
2810 /* Used when starting or continuing the program.  */
2811
2812 static void
2813 insert_breakpoint_locations (void)
2814 {
2815   struct breakpoint *bpt;
2816   struct bp_location *bl, **blp_tmp;
2817   int error_flag = 0;
2818   int val = 0;
2819   int disabled_breaks = 0;
2820   int hw_breakpoint_error = 0;
2821   int hw_bp_error_explained_already = 0;
2822
2823   struct ui_file *tmp_error_stream = mem_fileopen ();
2824   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2825   
2826   /* Explicitly mark the warning -- this will only be printed if
2827      there was an error.  */
2828   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2829
2830   save_current_space_and_thread ();
2831
2832   ALL_BP_LOCATIONS (bl, blp_tmp)
2833     {
2834       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2835         continue;
2836
2837       /* There is no point inserting thread-specific breakpoints if
2838          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2839          has BL->OWNER always non-NULL.  */
2840       if (bl->owner->thread != -1
2841           && !valid_thread_id (bl->owner->thread))
2842         continue;
2843
2844       switch_to_program_space_and_thread (bl->pspace);
2845
2846       /* For targets that support global breakpoints, there's no need
2847          to select an inferior to insert breakpoint to.  In fact, even
2848          if we aren't attached to any process yet, we should still
2849          insert breakpoints.  */
2850       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2851           && ptid_equal (inferior_ptid, null_ptid))
2852         continue;
2853
2854       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2855                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2856       if (val)
2857         error_flag = val;
2858     }
2859
2860   /* If we failed to insert all locations of a watchpoint, remove
2861      them, as half-inserted watchpoint is of limited use.  */
2862   ALL_BREAKPOINTS (bpt)  
2863     {
2864       int some_failed = 0;
2865       struct bp_location *loc;
2866
2867       if (!is_hardware_watchpoint (bpt))
2868         continue;
2869
2870       if (!breakpoint_enabled (bpt))
2871         continue;
2872
2873       if (bpt->disposition == disp_del_at_next_stop)
2874         continue;
2875       
2876       for (loc = bpt->loc; loc; loc = loc->next)
2877         if (!loc->inserted && should_be_inserted (loc))
2878           {
2879             some_failed = 1;
2880             break;
2881           }
2882       if (some_failed)
2883         {
2884           for (loc = bpt->loc; loc; loc = loc->next)
2885             if (loc->inserted)
2886               remove_breakpoint (loc, mark_uninserted);
2887
2888           hw_breakpoint_error = 1;
2889           fprintf_unfiltered (tmp_error_stream,
2890                               "Could not insert hardware watchpoint %d.\n", 
2891                               bpt->number);
2892           error_flag = -1;
2893         }
2894     }
2895
2896   if (error_flag)
2897     {
2898       /* If a hardware breakpoint or watchpoint was inserted, add a
2899          message about possibly exhausted resources.  */
2900       if (hw_breakpoint_error && !hw_bp_error_explained_already)
2901         {
2902           fprintf_unfiltered (tmp_error_stream, 
2903                               "Could not insert hardware breakpoints:\n\
2904 You may have requested too many hardware breakpoints/watchpoints.\n");
2905         }
2906       target_terminal_ours_for_output ();
2907       error_stream (tmp_error_stream);
2908     }
2909
2910   do_cleanups (cleanups);
2911 }
2912
2913 /* Used when the program stops.
2914    Returns zero if successful, or non-zero if there was a problem
2915    removing a breakpoint location.  */
2916
2917 int
2918 remove_breakpoints (void)
2919 {
2920   struct bp_location *bl, **blp_tmp;
2921   int val = 0;
2922
2923   ALL_BP_LOCATIONS (bl, blp_tmp)
2924   {
2925     if (bl->inserted && !is_tracepoint (bl->owner))
2926       val |= remove_breakpoint (bl, mark_uninserted);
2927   }
2928   return val;
2929 }
2930
2931 /* When a thread exits, remove breakpoints that are related to
2932    that thread.  */
2933
2934 static void
2935 remove_threaded_breakpoints (struct thread_info *tp, int silent)
2936 {
2937   struct breakpoint *b, *b_tmp;
2938
2939   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2940     {
2941       if (b->thread == tp->num && user_breakpoint_p (b))
2942         {
2943           b->disposition = disp_del_at_next_stop;
2944
2945           printf_filtered (_("\
2946 Thread-specific breakpoint %d deleted - thread %d is gone.\n"),
2947                           b->number, tp->num);
2948
2949           /* Hide it from the user.  */
2950           b->number = 0;
2951        }
2952     }
2953 }
2954
2955 /* Remove breakpoints of process PID.  */
2956
2957 int
2958 remove_breakpoints_pid (int pid)
2959 {
2960   struct bp_location *bl, **blp_tmp;
2961   int val;
2962   struct inferior *inf = find_inferior_pid (pid);
2963
2964   ALL_BP_LOCATIONS (bl, blp_tmp)
2965   {
2966     if (bl->pspace != inf->pspace)
2967       continue;
2968
2969     if (bl->owner->type == bp_dprintf)
2970       continue;
2971
2972     if (bl->inserted)
2973       {
2974         val = remove_breakpoint (bl, mark_uninserted);
2975         if (val != 0)
2976           return val;
2977       }
2978   }
2979   return 0;
2980 }
2981
2982 int
2983 reattach_breakpoints (int pid)
2984 {
2985   struct cleanup *old_chain;
2986   struct bp_location *bl, **blp_tmp;
2987   int val;
2988   struct ui_file *tmp_error_stream;
2989   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
2990   struct inferior *inf;
2991   struct thread_info *tp;
2992
2993   tp = any_live_thread_of_process (pid);
2994   if (tp == NULL)
2995     return 1;
2996
2997   inf = find_inferior_pid (pid);
2998   old_chain = save_inferior_ptid ();
2999
3000   inferior_ptid = tp->ptid;
3001
3002   tmp_error_stream = mem_fileopen ();
3003   make_cleanup_ui_file_delete (tmp_error_stream);
3004
3005   ALL_BP_LOCATIONS (bl, blp_tmp)
3006   {
3007     if (bl->pspace != inf->pspace)
3008       continue;
3009
3010     if (bl->inserted)
3011       {
3012         bl->inserted = 0;
3013         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3014         if (val != 0)
3015           {
3016             do_cleanups (old_chain);
3017             return val;
3018           }
3019       }
3020   }
3021   do_cleanups (old_chain);
3022   return 0;
3023 }
3024
3025 static int internal_breakpoint_number = -1;
3026
3027 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3028    If INTERNAL is non-zero, the breakpoint number will be populated
3029    from internal_breakpoint_number and that variable decremented.
3030    Otherwise the breakpoint number will be populated from
3031    breakpoint_count and that value incremented.  Internal breakpoints
3032    do not set the internal var bpnum.  */
3033 static void
3034 set_breakpoint_number (int internal, struct breakpoint *b)
3035 {
3036   if (internal)
3037     b->number = internal_breakpoint_number--;
3038   else
3039     {
3040       set_breakpoint_count (breakpoint_count + 1);
3041       b->number = breakpoint_count;
3042     }
3043 }
3044
3045 static struct breakpoint *
3046 create_internal_breakpoint (struct gdbarch *gdbarch,
3047                             CORE_ADDR address, enum bptype type,
3048                             const struct breakpoint_ops *ops)
3049 {
3050   struct symtab_and_line sal;
3051   struct breakpoint *b;
3052
3053   init_sal (&sal);              /* Initialize to zeroes.  */
3054
3055   sal.pc = address;
3056   sal.section = find_pc_overlay (sal.pc);
3057   sal.pspace = current_program_space;
3058
3059   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3060   b->number = internal_breakpoint_number--;
3061   b->disposition = disp_donttouch;
3062
3063   return b;
3064 }
3065
3066 static const char *const longjmp_names[] =
3067   {
3068     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3069   };
3070 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3071
3072 /* Per-objfile data private to breakpoint.c.  */
3073 struct breakpoint_objfile_data
3074 {
3075   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3076   struct minimal_symbol *overlay_msym;
3077
3078   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3079   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
3080
3081   /* True if we have looked for longjmp probes.  */
3082   int longjmp_searched;
3083
3084   /* SystemTap probe points for longjmp (if any).  */
3085   VEC (probe_p) *longjmp_probes;
3086
3087   /* Minimal symbol for "std::terminate()" (if any).  */
3088   struct minimal_symbol *terminate_msym;
3089
3090   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3091   struct minimal_symbol *exception_msym;
3092
3093   /* True if we have looked for exception probes.  */
3094   int exception_searched;
3095
3096   /* SystemTap probe points for unwinding (if any).  */
3097   VEC (probe_p) *exception_probes;
3098 };
3099
3100 static const struct objfile_data *breakpoint_objfile_key;
3101
3102 /* Minimal symbol not found sentinel.  */
3103 static struct minimal_symbol msym_not_found;
3104
3105 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3106
3107 static int
3108 msym_not_found_p (const struct minimal_symbol *msym)
3109 {
3110   return msym == &msym_not_found;
3111 }
3112
3113 /* Return per-objfile data needed by breakpoint.c.
3114    Allocate the data if necessary.  */
3115
3116 static struct breakpoint_objfile_data *
3117 get_breakpoint_objfile_data (struct objfile *objfile)
3118 {
3119   struct breakpoint_objfile_data *bp_objfile_data;
3120
3121   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3122   if (bp_objfile_data == NULL)
3123     {
3124       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3125                                        sizeof (*bp_objfile_data));
3126
3127       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3128       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3129     }
3130   return bp_objfile_data;
3131 }
3132
3133 static void
3134 free_breakpoint_probes (struct objfile *obj, void *data)
3135 {
3136   struct breakpoint_objfile_data *bp_objfile_data = data;
3137
3138   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3139   VEC_free (probe_p, bp_objfile_data->exception_probes);
3140 }
3141
3142 static void
3143 create_overlay_event_breakpoint (void)
3144 {
3145   struct objfile *objfile;
3146   const char *const func_name = "_ovly_debug_event";
3147
3148   ALL_OBJFILES (objfile)
3149     {
3150       struct breakpoint *b;
3151       struct breakpoint_objfile_data *bp_objfile_data;
3152       CORE_ADDR addr;
3153
3154       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3155
3156       if (msym_not_found_p (bp_objfile_data->overlay_msym))
3157         continue;
3158
3159       if (bp_objfile_data->overlay_msym == NULL)
3160         {
3161           struct minimal_symbol *m;
3162
3163           m = lookup_minimal_symbol_text (func_name, objfile);
3164           if (m == NULL)
3165             {
3166               /* Avoid future lookups in this objfile.  */
3167               bp_objfile_data->overlay_msym = &msym_not_found;
3168               continue;
3169             }
3170           bp_objfile_data->overlay_msym = m;
3171         }
3172
3173       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3174       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3175                                       bp_overlay_event,
3176                                       &internal_breakpoint_ops);
3177       b->addr_string = xstrdup (func_name);
3178
3179       if (overlay_debugging == ovly_auto)
3180         {
3181           b->enable_state = bp_enabled;
3182           overlay_events_enabled = 1;
3183         }
3184       else
3185        {
3186          b->enable_state = bp_disabled;
3187          overlay_events_enabled = 0;
3188        }
3189     }
3190   update_global_location_list (1);
3191 }
3192
3193 static void
3194 create_longjmp_master_breakpoint (void)
3195 {
3196   struct program_space *pspace;
3197   struct cleanup *old_chain;
3198
3199   old_chain = save_current_program_space ();
3200
3201   ALL_PSPACES (pspace)
3202   {
3203     struct objfile *objfile;
3204
3205     set_current_program_space (pspace);
3206
3207     ALL_OBJFILES (objfile)
3208     {
3209       int i;
3210       struct gdbarch *gdbarch;
3211       struct breakpoint_objfile_data *bp_objfile_data;
3212
3213       gdbarch = get_objfile_arch (objfile);
3214       if (!gdbarch_get_longjmp_target_p (gdbarch))
3215         continue;
3216
3217       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3218
3219       if (!bp_objfile_data->longjmp_searched)
3220         {
3221           VEC (probe_p) *ret;
3222
3223           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3224           if (ret != NULL)
3225             {
3226               /* We are only interested in checking one element.  */
3227               struct probe *p = VEC_index (probe_p, ret, 0);
3228
3229               if (!can_evaluate_probe_arguments (p))
3230                 {
3231                   /* We cannot use the probe interface here, because it does
3232                      not know how to evaluate arguments.  */
3233                   VEC_free (probe_p, ret);
3234                   ret = NULL;
3235                 }
3236             }
3237           bp_objfile_data->longjmp_probes = ret;
3238           bp_objfile_data->longjmp_searched = 1;
3239         }
3240
3241       if (bp_objfile_data->longjmp_probes != NULL)
3242         {
3243           int i;
3244           struct probe *probe;
3245           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3246
3247           for (i = 0;
3248                VEC_iterate (probe_p,
3249                             bp_objfile_data->longjmp_probes,
3250                             i, probe);
3251                ++i)
3252             {
3253               struct breakpoint *b;
3254
3255               b = create_internal_breakpoint (gdbarch, probe->address,
3256                                               bp_longjmp_master,
3257                                               &internal_breakpoint_ops);
3258               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3259               b->enable_state = bp_disabled;
3260             }
3261
3262           continue;
3263         }
3264
3265       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3266         {
3267           struct breakpoint *b;
3268           const char *func_name;
3269           CORE_ADDR addr;
3270
3271           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
3272             continue;
3273
3274           func_name = longjmp_names[i];
3275           if (bp_objfile_data->longjmp_msym[i] == NULL)
3276             {
3277               struct minimal_symbol *m;
3278
3279               m = lookup_minimal_symbol_text (func_name, objfile);
3280               if (m == NULL)
3281                 {
3282                   /* Prevent future lookups in this objfile.  */
3283                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
3284                   continue;
3285                 }
3286               bp_objfile_data->longjmp_msym[i] = m;
3287             }
3288
3289           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3290           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3291                                           &internal_breakpoint_ops);
3292           b->addr_string = xstrdup (func_name);
3293           b->enable_state = bp_disabled;
3294         }
3295     }
3296   }
3297   update_global_location_list (1);
3298
3299   do_cleanups (old_chain);
3300 }
3301
3302 /* Create a master std::terminate breakpoint.  */
3303 static void
3304 create_std_terminate_master_breakpoint (void)
3305 {
3306   struct program_space *pspace;
3307   struct cleanup *old_chain;
3308   const char *const func_name = "std::terminate()";
3309
3310   old_chain = save_current_program_space ();
3311
3312   ALL_PSPACES (pspace)
3313   {
3314     struct objfile *objfile;
3315     CORE_ADDR addr;
3316
3317     set_current_program_space (pspace);
3318
3319     ALL_OBJFILES (objfile)
3320     {
3321       struct breakpoint *b;
3322       struct breakpoint_objfile_data *bp_objfile_data;
3323
3324       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3325
3326       if (msym_not_found_p (bp_objfile_data->terminate_msym))
3327         continue;
3328
3329       if (bp_objfile_data->terminate_msym == NULL)
3330         {
3331           struct minimal_symbol *m;
3332
3333           m = lookup_minimal_symbol (func_name, NULL, objfile);
3334           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
3335                             && MSYMBOL_TYPE (m) != mst_file_text))
3336             {
3337               /* Prevent future lookups in this objfile.  */
3338               bp_objfile_data->terminate_msym = &msym_not_found;
3339               continue;
3340             }
3341           bp_objfile_data->terminate_msym = m;
3342         }
3343
3344       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3345       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3346                                       bp_std_terminate_master,
3347                                       &internal_breakpoint_ops);
3348       b->addr_string = xstrdup (func_name);
3349       b->enable_state = bp_disabled;
3350     }
3351   }
3352
3353   update_global_location_list (1);
3354
3355   do_cleanups (old_chain);
3356 }
3357
3358 /* Install a master breakpoint on the unwinder's debug hook.  */
3359
3360 static void
3361 create_exception_master_breakpoint (void)
3362 {
3363   struct objfile *objfile;
3364   const char *const func_name = "_Unwind_DebugHook";
3365
3366   ALL_OBJFILES (objfile)
3367     {
3368       struct breakpoint *b;
3369       struct gdbarch *gdbarch;
3370       struct breakpoint_objfile_data *bp_objfile_data;
3371       CORE_ADDR addr;
3372
3373       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3374
3375       /* We prefer the SystemTap probe point if it exists.  */
3376       if (!bp_objfile_data->exception_searched)
3377         {
3378           VEC (probe_p) *ret;
3379
3380           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3381
3382           if (ret != NULL)
3383             {
3384               /* We are only interested in checking one element.  */
3385               struct probe *p = VEC_index (probe_p, ret, 0);
3386
3387               if (!can_evaluate_probe_arguments (p))
3388                 {
3389                   /* We cannot use the probe interface here, because it does
3390                      not know how to evaluate arguments.  */
3391                   VEC_free (probe_p, ret);
3392                   ret = NULL;
3393                 }
3394             }
3395           bp_objfile_data->exception_probes = ret;
3396           bp_objfile_data->exception_searched = 1;
3397         }
3398
3399       if (bp_objfile_data->exception_probes != NULL)
3400         {
3401           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3402           int i;
3403           struct probe *probe;
3404
3405           for (i = 0;
3406                VEC_iterate (probe_p,
3407                             bp_objfile_data->exception_probes,
3408                             i, probe);
3409                ++i)
3410             {
3411               struct breakpoint *b;
3412
3413               b = create_internal_breakpoint (gdbarch, probe->address,
3414                                               bp_exception_master,
3415                                               &internal_breakpoint_ops);
3416               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3417               b->enable_state = bp_disabled;
3418             }
3419
3420           continue;
3421         }
3422
3423       /* Otherwise, try the hook function.  */
3424
3425       if (msym_not_found_p (bp_objfile_data->exception_msym))
3426         continue;
3427
3428       gdbarch = get_objfile_arch (objfile);
3429
3430       if (bp_objfile_data->exception_msym == NULL)
3431         {
3432           struct minimal_symbol *debug_hook;
3433
3434           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3435           if (debug_hook == NULL)
3436             {
3437               bp_objfile_data->exception_msym = &msym_not_found;
3438               continue;
3439             }
3440
3441           bp_objfile_data->exception_msym = debug_hook;
3442         }
3443
3444       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3445       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3446                                                  &current_target);
3447       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3448                                       &internal_breakpoint_ops);
3449       b->addr_string = xstrdup (func_name);
3450       b->enable_state = bp_disabled;
3451     }
3452
3453   update_global_location_list (1);
3454 }
3455
3456 void
3457 update_breakpoints_after_exec (void)
3458 {
3459   struct breakpoint *b, *b_tmp;
3460   struct bp_location *bploc, **bplocp_tmp;
3461
3462   /* We're about to delete breakpoints from GDB's lists.  If the
3463      INSERTED flag is true, GDB will try to lift the breakpoints by
3464      writing the breakpoints' "shadow contents" back into memory.  The
3465      "shadow contents" are NOT valid after an exec, so GDB should not
3466      do that.  Instead, the target is responsible from marking
3467      breakpoints out as soon as it detects an exec.  We don't do that
3468      here instead, because there may be other attempts to delete
3469      breakpoints after detecting an exec and before reaching here.  */
3470   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3471     if (bploc->pspace == current_program_space)
3472       gdb_assert (!bploc->inserted);
3473
3474   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3475   {
3476     if (b->pspace != current_program_space)
3477       continue;
3478
3479     /* Solib breakpoints must be explicitly reset after an exec().  */
3480     if (b->type == bp_shlib_event)
3481       {
3482         delete_breakpoint (b);
3483         continue;
3484       }
3485
3486     /* JIT breakpoints must be explicitly reset after an exec().  */
3487     if (b->type == bp_jit_event)
3488       {
3489         delete_breakpoint (b);
3490         continue;
3491       }
3492
3493     /* Thread event breakpoints must be set anew after an exec(),
3494        as must overlay event and longjmp master breakpoints.  */
3495     if (b->type == bp_thread_event || b->type == bp_overlay_event
3496         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3497         || b->type == bp_exception_master)
3498       {
3499         delete_breakpoint (b);
3500         continue;
3501       }
3502
3503     /* Step-resume breakpoints are meaningless after an exec().  */
3504     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3505       {
3506         delete_breakpoint (b);
3507         continue;
3508       }
3509
3510     /* Longjmp and longjmp-resume breakpoints are also meaningless
3511        after an exec.  */
3512     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3513         || b->type == bp_longjmp_call_dummy
3514         || b->type == bp_exception || b->type == bp_exception_resume)
3515       {
3516         delete_breakpoint (b);
3517         continue;
3518       }
3519
3520     if (b->type == bp_catchpoint)
3521       {
3522         /* For now, none of the bp_catchpoint breakpoints need to
3523            do anything at this point.  In the future, if some of
3524            the catchpoints need to something, we will need to add
3525            a new method, and call this method from here.  */
3526         continue;
3527       }
3528
3529     /* bp_finish is a special case.  The only way we ought to be able
3530        to see one of these when an exec() has happened, is if the user
3531        caught a vfork, and then said "finish".  Ordinarily a finish just
3532        carries them to the call-site of the current callee, by setting
3533        a temporary bp there and resuming.  But in this case, the finish
3534        will carry them entirely through the vfork & exec.
3535
3536        We don't want to allow a bp_finish to remain inserted now.  But
3537        we can't safely delete it, 'cause finish_command has a handle to
3538        the bp on a bpstat, and will later want to delete it.  There's a
3539        chance (and I've seen it happen) that if we delete the bp_finish
3540        here, that its storage will get reused by the time finish_command
3541        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3542        We really must allow finish_command to delete a bp_finish.
3543
3544        In the absence of a general solution for the "how do we know
3545        it's safe to delete something others may have handles to?"
3546        problem, what we'll do here is just uninsert the bp_finish, and
3547        let finish_command delete it.
3548
3549        (We know the bp_finish is "doomed" in the sense that it's
3550        momentary, and will be deleted as soon as finish_command sees
3551        the inferior stopped.  So it doesn't matter that the bp's
3552        address is probably bogus in the new a.out, unlike e.g., the
3553        solib breakpoints.)  */
3554
3555     if (b->type == bp_finish)
3556       {
3557         continue;
3558       }
3559
3560     /* Without a symbolic address, we have little hope of the
3561        pre-exec() address meaning the same thing in the post-exec()
3562        a.out.  */
3563     if (b->addr_string == NULL)
3564       {
3565         delete_breakpoint (b);
3566         continue;
3567       }
3568   }
3569   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3570   create_overlay_event_breakpoint ();
3571   create_longjmp_master_breakpoint ();
3572   create_std_terminate_master_breakpoint ();
3573   create_exception_master_breakpoint ();
3574 }
3575
3576 int
3577 detach_breakpoints (ptid_t ptid)
3578 {
3579   struct bp_location *bl, **blp_tmp;
3580   int val = 0;
3581   struct cleanup *old_chain = save_inferior_ptid ();
3582   struct inferior *inf = current_inferior ();
3583
3584   if (PIDGET (ptid) == PIDGET (inferior_ptid))
3585     error (_("Cannot detach breakpoints of inferior_ptid"));
3586
3587   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3588   inferior_ptid = ptid;
3589   ALL_BP_LOCATIONS (bl, blp_tmp)
3590   {
3591     if (bl->pspace != inf->pspace)
3592       continue;
3593
3594     /* This function must physically remove breakpoints locations
3595        from the specified ptid, without modifying the breakpoint
3596        package's state.  Locations of type bp_loc_other are only
3597        maintained at GDB side.  So, there is no need to remove
3598        these bp_loc_other locations.  Moreover, removing these
3599        would modify the breakpoint package's state.  */
3600     if (bl->loc_type == bp_loc_other)
3601       continue;
3602
3603     if (bl->inserted)
3604       val |= remove_breakpoint_1 (bl, mark_inserted);
3605   }
3606
3607   /* Detach single-step breakpoints as well.  */
3608   detach_single_step_breakpoints ();
3609
3610   do_cleanups (old_chain);
3611   return val;
3612 }
3613
3614 /* Remove the breakpoint location BL from the current address space.
3615    Note that this is used to detach breakpoints from a child fork.
3616    When we get here, the child isn't in the inferior list, and neither
3617    do we have objects to represent its address space --- we should
3618    *not* look at bl->pspace->aspace here.  */
3619
3620 static int
3621 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3622 {
3623   int val;
3624
3625   /* BL is never in moribund_locations by our callers.  */
3626   gdb_assert (bl->owner != NULL);
3627
3628   if (bl->owner->enable_state == bp_permanent)
3629     /* Permanent breakpoints cannot be inserted or removed.  */
3630     return 0;
3631
3632   /* The type of none suggests that owner is actually deleted.
3633      This should not ever happen.  */
3634   gdb_assert (bl->owner->type != bp_none);
3635
3636   if (bl->loc_type == bp_loc_software_breakpoint
3637       || bl->loc_type == bp_loc_hardware_breakpoint)
3638     {
3639       /* "Normal" instruction breakpoint: either the standard
3640          trap-instruction bp (bp_breakpoint), or a
3641          bp_hardware_breakpoint.  */
3642
3643       /* First check to see if we have to handle an overlay.  */
3644       if (overlay_debugging == ovly_off
3645           || bl->section == NULL
3646           || !(section_is_overlay (bl->section)))
3647         {
3648           /* No overlay handling: just remove the breakpoint.  */
3649           val = bl->owner->ops->remove_location (bl);
3650         }
3651       else
3652         {
3653           /* This breakpoint is in an overlay section.
3654              Did we set a breakpoint at the LMA?  */
3655           if (!overlay_events_enabled)
3656               {
3657                 /* Yes -- overlay event support is not active, so we
3658                    should have set a breakpoint at the LMA.  Remove it.  
3659                 */
3660                 /* Ignore any failures: if the LMA is in ROM, we will
3661                    have already warned when we failed to insert it.  */
3662                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3663                   target_remove_hw_breakpoint (bl->gdbarch,
3664                                                &bl->overlay_target_info);
3665                 else
3666                   target_remove_breakpoint (bl->gdbarch,
3667                                             &bl->overlay_target_info);
3668               }
3669           /* Did we set a breakpoint at the VMA? 
3670              If so, we will have marked the breakpoint 'inserted'.  */
3671           if (bl->inserted)
3672             {
3673               /* Yes -- remove it.  Previously we did not bother to
3674                  remove the breakpoint if the section had been
3675                  unmapped, but let's not rely on that being safe.  We
3676                  don't know what the overlay manager might do.  */
3677
3678               /* However, we should remove *software* breakpoints only
3679                  if the section is still mapped, or else we overwrite
3680                  wrong code with the saved shadow contents.  */
3681               if (bl->loc_type == bp_loc_hardware_breakpoint
3682                   || section_is_mapped (bl->section))
3683                 val = bl->owner->ops->remove_location (bl);
3684               else
3685                 val = 0;
3686             }
3687           else
3688             {
3689               /* No -- not inserted, so no need to remove.  No error.  */
3690               val = 0;
3691             }
3692         }
3693
3694       /* In some cases, we might not be able to remove a breakpoint
3695          in a shared library that has already been removed, but we
3696          have not yet processed the shlib unload event.  */
3697       if (val && solib_name_from_address (bl->pspace, bl->address))
3698         val = 0;
3699
3700       if (val)
3701         return val;
3702       bl->inserted = (is == mark_inserted);
3703     }
3704   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3705     {
3706       gdb_assert (bl->owner->ops != NULL
3707                   && bl->owner->ops->remove_location != NULL);
3708
3709       bl->inserted = (is == mark_inserted);
3710       bl->owner->ops->remove_location (bl);
3711
3712       /* Failure to remove any of the hardware watchpoints comes here.  */
3713       if ((is == mark_uninserted) && (bl->inserted))
3714         warning (_("Could not remove hardware watchpoint %d."),
3715                  bl->owner->number);
3716     }
3717   else if (bl->owner->type == bp_catchpoint
3718            && breakpoint_enabled (bl->owner)
3719            && !bl->duplicate)
3720     {
3721       gdb_assert (bl->owner->ops != NULL
3722                   && bl->owner->ops->remove_location != NULL);
3723
3724       val = bl->owner->ops->remove_location (bl);
3725       if (val)
3726         return val;
3727
3728       bl->inserted = (is == mark_inserted);
3729     }
3730
3731   return 0;
3732 }
3733
3734 static int
3735 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3736 {
3737   int ret;
3738   struct cleanup *old_chain;
3739
3740   /* BL is never in moribund_locations by our callers.  */
3741   gdb_assert (bl->owner != NULL);
3742
3743   if (bl->owner->enable_state == bp_permanent)
3744     /* Permanent breakpoints cannot be inserted or removed.  */
3745     return 0;
3746
3747   /* The type of none suggests that owner is actually deleted.
3748      This should not ever happen.  */
3749   gdb_assert (bl->owner->type != bp_none);
3750
3751   old_chain = save_current_space_and_thread ();
3752
3753   switch_to_program_space_and_thread (bl->pspace);
3754
3755   ret = remove_breakpoint_1 (bl, is);
3756
3757   do_cleanups (old_chain);
3758   return ret;
3759 }
3760
3761 /* Clear the "inserted" flag in all breakpoints.  */
3762
3763 void
3764 mark_breakpoints_out (void)
3765 {
3766   struct bp_location *bl, **blp_tmp;
3767
3768   ALL_BP_LOCATIONS (bl, blp_tmp)
3769     if (bl->pspace == current_program_space)
3770       bl->inserted = 0;
3771 }
3772
3773 /* Clear the "inserted" flag in all breakpoints and delete any
3774    breakpoints which should go away between runs of the program.
3775
3776    Plus other such housekeeping that has to be done for breakpoints
3777    between runs.
3778
3779    Note: this function gets called at the end of a run (by
3780    generic_mourn_inferior) and when a run begins (by
3781    init_wait_for_inferior).  */
3782
3783
3784
3785 void
3786 breakpoint_init_inferior (enum inf_context context)
3787 {
3788   struct breakpoint *b, *b_tmp;
3789   struct bp_location *bl, **blp_tmp;
3790   int ix;
3791   struct program_space *pspace = current_program_space;
3792
3793   /* If breakpoint locations are shared across processes, then there's
3794      nothing to do.  */
3795   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3796     return;
3797
3798   ALL_BP_LOCATIONS (bl, blp_tmp)
3799   {
3800     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3801     if (bl->pspace == pspace
3802         && bl->owner->enable_state != bp_permanent)
3803       bl->inserted = 0;
3804   }
3805
3806   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3807   {
3808     if (b->loc && b->loc->pspace != pspace)
3809       continue;
3810
3811     switch (b->type)
3812       {
3813       case bp_call_dummy:
3814       case bp_longjmp_call_dummy:
3815
3816         /* If the call dummy breakpoint is at the entry point it will
3817            cause problems when the inferior is rerun, so we better get
3818            rid of it.  */
3819
3820       case bp_watchpoint_scope:
3821
3822         /* Also get rid of scope breakpoints.  */
3823
3824       case bp_shlib_event:
3825
3826         /* Also remove solib event breakpoints.  Their addresses may
3827            have changed since the last time we ran the program.
3828            Actually we may now be debugging against different target;
3829            and so the solib backend that installed this breakpoint may
3830            not be used in by the target.  E.g.,
3831
3832            (gdb) file prog-linux
3833            (gdb) run               # native linux target
3834            ...
3835            (gdb) kill
3836            (gdb) file prog-win.exe
3837            (gdb) tar rem :9999     # remote Windows gdbserver.
3838         */
3839
3840       case bp_step_resume:
3841
3842         /* Also remove step-resume breakpoints.  */
3843
3844         delete_breakpoint (b);
3845         break;
3846
3847       case bp_watchpoint:
3848       case bp_hardware_watchpoint:
3849       case bp_read_watchpoint:
3850       case bp_access_watchpoint:
3851         {
3852           struct watchpoint *w = (struct watchpoint *) b;
3853
3854           /* Likewise for watchpoints on local expressions.  */
3855           if (w->exp_valid_block != NULL)
3856             delete_breakpoint (b);
3857           else if (context == inf_starting)
3858             {
3859               /* Reset val field to force reread of starting value in
3860                  insert_breakpoints.  */
3861               if (w->val)
3862                 value_free (w->val);
3863               w->val = NULL;
3864               w->val_valid = 0;
3865           }
3866         }
3867         break;
3868       default:
3869         break;
3870       }
3871   }
3872
3873   /* Get rid of the moribund locations.  */
3874   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3875     decref_bp_location (&bl);
3876   VEC_free (bp_location_p, moribund_locations);
3877 }
3878
3879 /* These functions concern about actual breakpoints inserted in the
3880    target --- to e.g. check if we need to do decr_pc adjustment or if
3881    we need to hop over the bkpt --- so we check for address space
3882    match, not program space.  */
3883
3884 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3885    exists at PC.  It returns ordinary_breakpoint_here if it's an
3886    ordinary breakpoint, or permanent_breakpoint_here if it's a
3887    permanent breakpoint.
3888    - When continuing from a location with an ordinary breakpoint, we
3889      actually single step once before calling insert_breakpoints.
3890    - When continuing from a location with a permanent breakpoint, we
3891      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3892      the target, to advance the PC past the breakpoint.  */
3893
3894 enum breakpoint_here
3895 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3896 {
3897   struct bp_location *bl, **blp_tmp;
3898   int any_breakpoint_here = 0;
3899
3900   ALL_BP_LOCATIONS (bl, blp_tmp)
3901     {
3902       if (bl->loc_type != bp_loc_software_breakpoint
3903           && bl->loc_type != bp_loc_hardware_breakpoint)
3904         continue;
3905
3906       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3907       if ((breakpoint_enabled (bl->owner)
3908            || bl->owner->enable_state == bp_permanent)
3909           && breakpoint_location_address_match (bl, aspace, pc))
3910         {
3911           if (overlay_debugging 
3912               && section_is_overlay (bl->section)
3913               && !section_is_mapped (bl->section))
3914             continue;           /* unmapped overlay -- can't be a match */
3915           else if (bl->owner->enable_state == bp_permanent)
3916             return permanent_breakpoint_here;
3917           else
3918             any_breakpoint_here = 1;
3919         }
3920     }
3921
3922   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3923 }
3924
3925 /* Return true if there's a moribund breakpoint at PC.  */
3926
3927 int
3928 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3929 {
3930   struct bp_location *loc;
3931   int ix;
3932
3933   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3934     if (breakpoint_location_address_match (loc, aspace, pc))
3935       return 1;
3936
3937   return 0;
3938 }
3939
3940 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3941    inserted using regular breakpoint_chain / bp_location array
3942    mechanism.  This does not check for single-step breakpoints, which
3943    are inserted and removed using direct target manipulation.  */
3944
3945 int
3946 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3947                                     CORE_ADDR pc)
3948 {
3949   struct bp_location *bl, **blp_tmp;
3950
3951   ALL_BP_LOCATIONS (bl, blp_tmp)
3952     {
3953       if (bl->loc_type != bp_loc_software_breakpoint
3954           && bl->loc_type != bp_loc_hardware_breakpoint)
3955         continue;
3956
3957       if (bl->inserted
3958           && breakpoint_location_address_match (bl, aspace, pc))
3959         {
3960           if (overlay_debugging 
3961               && section_is_overlay (bl->section)
3962               && !section_is_mapped (bl->section))
3963             continue;           /* unmapped overlay -- can't be a match */
3964           else
3965             return 1;
3966         }
3967     }
3968   return 0;
3969 }
3970
3971 /* Returns non-zero iff there's either regular breakpoint
3972    or a single step breakpoint inserted at PC.  */
3973
3974 int
3975 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3976 {
3977   if (regular_breakpoint_inserted_here_p (aspace, pc))
3978     return 1;
3979
3980   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3981     return 1;
3982
3983   return 0;
3984 }
3985
3986 /* This function returns non-zero iff there is a software breakpoint
3987    inserted at PC.  */
3988
3989 int
3990 software_breakpoint_inserted_here_p (struct address_space *aspace,
3991                                      CORE_ADDR pc)
3992 {
3993   struct bp_location *bl, **blp_tmp;
3994
3995   ALL_BP_LOCATIONS (bl, blp_tmp)
3996     {
3997       if (bl->loc_type != bp_loc_software_breakpoint)
3998         continue;
3999
4000       if (bl->inserted
4001           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4002                                        aspace, pc))
4003         {
4004           if (overlay_debugging 
4005               && section_is_overlay (bl->section)
4006               && !section_is_mapped (bl->section))
4007             continue;           /* unmapped overlay -- can't be a match */
4008           else
4009             return 1;
4010         }
4011     }
4012
4013   /* Also check for software single-step breakpoints.  */
4014   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4015     return 1;
4016
4017   return 0;
4018 }
4019
4020 int
4021 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4022                                        CORE_ADDR addr, ULONGEST len)
4023 {
4024   struct breakpoint *bpt;
4025
4026   ALL_BREAKPOINTS (bpt)
4027     {
4028       struct bp_location *loc;
4029
4030       if (bpt->type != bp_hardware_watchpoint
4031           && bpt->type != bp_access_watchpoint)
4032         continue;
4033
4034       if (!breakpoint_enabled (bpt))
4035         continue;
4036
4037       for (loc = bpt->loc; loc; loc = loc->next)
4038         if (loc->pspace->aspace == aspace && loc->inserted)
4039           {
4040             CORE_ADDR l, h;
4041
4042             /* Check for intersection.  */
4043             l = max (loc->address, addr);
4044             h = min (loc->address + loc->length, addr + len);
4045             if (l < h)
4046               return 1;
4047           }
4048     }
4049   return 0;
4050 }
4051
4052 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4053    PC is valid for process/thread PTID.  */
4054
4055 int
4056 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4057                          ptid_t ptid)
4058 {
4059   struct bp_location *bl, **blp_tmp;
4060   /* The thread and task IDs associated to PTID, computed lazily.  */
4061   int thread = -1;
4062   int task = 0;
4063   
4064   ALL_BP_LOCATIONS (bl, blp_tmp)
4065     {
4066       if (bl->loc_type != bp_loc_software_breakpoint
4067           && bl->loc_type != bp_loc_hardware_breakpoint)
4068         continue;
4069
4070       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4071       if (!breakpoint_enabled (bl->owner)
4072           && bl->owner->enable_state != bp_permanent)
4073         continue;
4074
4075       if (!breakpoint_location_address_match (bl, aspace, pc))
4076         continue;
4077
4078       if (bl->owner->thread != -1)
4079         {
4080           /* This is a thread-specific breakpoint.  Check that ptid
4081              matches that thread.  If thread hasn't been computed yet,
4082              it is now time to do so.  */
4083           if (thread == -1)
4084             thread = pid_to_thread_id (ptid);
4085           if (bl->owner->thread != thread)
4086             continue;
4087         }
4088
4089       if (bl->owner->task != 0)
4090         {
4091           /* This is a task-specific breakpoint.  Check that ptid
4092              matches that task.  If task hasn't been computed yet,
4093              it is now time to do so.  */
4094           if (task == 0)
4095             task = ada_get_task_number (ptid);
4096           if (bl->owner->task != task)
4097             continue;
4098         }
4099
4100       if (overlay_debugging 
4101           && section_is_overlay (bl->section)
4102           && !section_is_mapped (bl->section))
4103         continue;           /* unmapped overlay -- can't be a match */
4104
4105       return 1;
4106     }
4107
4108   return 0;
4109 }
4110 \f
4111
4112 /* bpstat stuff.  External routines' interfaces are documented
4113    in breakpoint.h.  */
4114
4115 int
4116 is_catchpoint (struct breakpoint *ep)
4117 {
4118   return (ep->type == bp_catchpoint);
4119 }
4120
4121 /* Frees any storage that is part of a bpstat.  Does not walk the
4122    'next' chain.  */
4123
4124 static void
4125 bpstat_free (bpstat bs)
4126 {
4127   if (bs->old_val != NULL)
4128     value_free (bs->old_val);
4129   decref_counted_command_line (&bs->commands);
4130   decref_bp_location (&bs->bp_location_at);
4131   xfree (bs);
4132 }
4133
4134 /* Clear a bpstat so that it says we are not at any breakpoint.
4135    Also free any storage that is part of a bpstat.  */
4136
4137 void
4138 bpstat_clear (bpstat *bsp)
4139 {
4140   bpstat p;
4141   bpstat q;
4142
4143   if (bsp == 0)
4144     return;
4145   p = *bsp;
4146   while (p != NULL)
4147     {
4148       q = p->next;
4149       bpstat_free (p);
4150       p = q;
4151     }
4152   *bsp = NULL;
4153 }
4154
4155 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4156    is part of the bpstat is copied as well.  */
4157
4158 bpstat
4159 bpstat_copy (bpstat bs)
4160 {
4161   bpstat p = NULL;
4162   bpstat tmp;
4163   bpstat retval = NULL;
4164
4165   if (bs == NULL)
4166     return bs;
4167
4168   for (; bs != NULL; bs = bs->next)
4169     {
4170       tmp = (bpstat) xmalloc (sizeof (*tmp));
4171       memcpy (tmp, bs, sizeof (*tmp));
4172       incref_counted_command_line (tmp->commands);
4173       incref_bp_location (tmp->bp_location_at);
4174       if (bs->old_val != NULL)
4175         {
4176           tmp->old_val = value_copy (bs->old_val);
4177           release_value (tmp->old_val);
4178         }
4179
4180       if (p == NULL)
4181         /* This is the first thing in the chain.  */
4182         retval = tmp;
4183       else
4184         p->next = tmp;
4185       p = tmp;
4186     }
4187   p->next = NULL;
4188   return retval;
4189 }
4190
4191 /* Find the bpstat associated with this breakpoint.  */
4192
4193 bpstat
4194 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4195 {
4196   if (bsp == NULL)
4197     return NULL;
4198
4199   for (; bsp != NULL; bsp = bsp->next)
4200     {
4201       if (bsp->breakpoint_at == breakpoint)
4202         return bsp;
4203     }
4204   return NULL;
4205 }
4206
4207 /* See breakpoint.h.  */
4208
4209 enum bpstat_signal_value
4210 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4211 {
4212   enum bpstat_signal_value result = BPSTAT_SIGNAL_NO;
4213
4214   for (; bsp != NULL; bsp = bsp->next)
4215     {
4216       /* Ensure that, if we ever entered this loop, then we at least
4217          return BPSTAT_SIGNAL_HIDE.  */
4218       enum bpstat_signal_value newval;
4219
4220       if (bsp->breakpoint_at == NULL)
4221         {
4222           /* A moribund location can never explain a signal other than
4223              GDB_SIGNAL_TRAP.  */
4224           if (sig == GDB_SIGNAL_TRAP)
4225             newval = BPSTAT_SIGNAL_HIDE;
4226           else
4227             newval = BPSTAT_SIGNAL_NO;
4228         }
4229       else
4230         newval = bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4231                                                            sig);
4232
4233       if (newval > result)
4234         result = newval;
4235     }
4236
4237   return result;
4238 }
4239
4240 /* Put in *NUM the breakpoint number of the first breakpoint we are
4241    stopped at.  *BSP upon return is a bpstat which points to the
4242    remaining breakpoints stopped at (but which is not guaranteed to be
4243    good for anything but further calls to bpstat_num).
4244
4245    Return 0 if passed a bpstat which does not indicate any breakpoints.
4246    Return -1 if stopped at a breakpoint that has been deleted since
4247    we set it.
4248    Return 1 otherwise.  */
4249
4250 int
4251 bpstat_num (bpstat *bsp, int *num)
4252 {
4253   struct breakpoint *b;
4254
4255   if ((*bsp) == NULL)
4256     return 0;                   /* No more breakpoint values */
4257
4258   /* We assume we'll never have several bpstats that correspond to a
4259      single breakpoint -- otherwise, this function might return the
4260      same number more than once and this will look ugly.  */
4261   b = (*bsp)->breakpoint_at;
4262   *bsp = (*bsp)->next;
4263   if (b == NULL)
4264     return -1;                  /* breakpoint that's been deleted since */
4265
4266   *num = b->number;             /* We have its number */
4267   return 1;
4268 }
4269
4270 /* See breakpoint.h.  */
4271
4272 void
4273 bpstat_clear_actions (void)
4274 {
4275   struct thread_info *tp;
4276   bpstat bs;
4277
4278   if (ptid_equal (inferior_ptid, null_ptid))
4279     return;
4280
4281   tp = find_thread_ptid (inferior_ptid);
4282   if (tp == NULL)
4283     return;
4284
4285   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4286     {
4287       decref_counted_command_line (&bs->commands);
4288
4289       if (bs->old_val != NULL)
4290         {
4291           value_free (bs->old_val);
4292           bs->old_val = NULL;
4293         }
4294     }
4295 }
4296
4297 /* Called when a command is about to proceed the inferior.  */
4298
4299 static void
4300 breakpoint_about_to_proceed (void)
4301 {
4302   if (!ptid_equal (inferior_ptid, null_ptid))
4303     {
4304       struct thread_info *tp = inferior_thread ();
4305
4306       /* Allow inferior function calls in breakpoint commands to not
4307          interrupt the command list.  When the call finishes
4308          successfully, the inferior will be standing at the same
4309          breakpoint as if nothing happened.  */
4310       if (tp->control.in_infcall)
4311         return;
4312     }
4313
4314   breakpoint_proceeded = 1;
4315 }
4316
4317 /* Stub for cleaning up our state if we error-out of a breakpoint
4318    command.  */
4319 static void
4320 cleanup_executing_breakpoints (void *ignore)
4321 {
4322   executing_breakpoint_commands = 0;
4323 }
4324
4325 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4326    or its equivalent.  */
4327
4328 static int
4329 command_line_is_silent (struct command_line *cmd)
4330 {
4331   return cmd && (strcmp ("silent", cmd->line) == 0
4332                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4333 }
4334
4335 /* Execute all the commands associated with all the breakpoints at
4336    this location.  Any of these commands could cause the process to
4337    proceed beyond this point, etc.  We look out for such changes by
4338    checking the global "breakpoint_proceeded" after each command.
4339
4340    Returns true if a breakpoint command resumed the inferior.  In that
4341    case, it is the caller's responsibility to recall it again with the
4342    bpstat of the current thread.  */
4343
4344 static int
4345 bpstat_do_actions_1 (bpstat *bsp)
4346 {
4347   bpstat bs;
4348   struct cleanup *old_chain;
4349   int again = 0;
4350
4351   /* Avoid endless recursion if a `source' command is contained
4352      in bs->commands.  */
4353   if (executing_breakpoint_commands)
4354     return 0;
4355
4356   executing_breakpoint_commands = 1;
4357   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4358
4359   prevent_dont_repeat ();
4360
4361   /* This pointer will iterate over the list of bpstat's.  */
4362   bs = *bsp;
4363
4364   breakpoint_proceeded = 0;
4365   for (; bs != NULL; bs = bs->next)
4366     {
4367       struct counted_command_line *ccmd;
4368       struct command_line *cmd;
4369       struct cleanup *this_cmd_tree_chain;
4370
4371       /* Take ownership of the BSP's command tree, if it has one.
4372
4373          The command tree could legitimately contain commands like
4374          'step' and 'next', which call clear_proceed_status, which
4375          frees stop_bpstat's command tree.  To make sure this doesn't
4376          free the tree we're executing out from under us, we need to
4377          take ownership of the tree ourselves.  Since a given bpstat's
4378          commands are only executed once, we don't need to copy it; we
4379          can clear the pointer in the bpstat, and make sure we free
4380          the tree when we're done.  */
4381       ccmd = bs->commands;
4382       bs->commands = NULL;
4383       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4384       cmd = ccmd ? ccmd->commands : NULL;
4385       if (command_line_is_silent (cmd))
4386         {
4387           /* The action has been already done by bpstat_stop_status.  */
4388           cmd = cmd->next;
4389         }
4390
4391       while (cmd != NULL)
4392         {
4393           execute_control_command (cmd);
4394
4395           if (breakpoint_proceeded)
4396             break;
4397           else
4398             cmd = cmd->next;
4399         }
4400
4401       /* We can free this command tree now.  */
4402       do_cleanups (this_cmd_tree_chain);
4403
4404       if (breakpoint_proceeded)
4405         {
4406           if (target_can_async_p ())
4407             /* If we are in async mode, then the target might be still
4408                running, not stopped at any breakpoint, so nothing for
4409                us to do here -- just return to the event loop.  */
4410             ;
4411           else
4412             /* In sync mode, when execute_control_command returns
4413                we're already standing on the next breakpoint.
4414                Breakpoint commands for that stop were not run, since
4415                execute_command does not run breakpoint commands --
4416                only command_line_handler does, but that one is not
4417                involved in execution of breakpoint commands.  So, we
4418                can now execute breakpoint commands.  It should be
4419                noted that making execute_command do bpstat actions is
4420                not an option -- in this case we'll have recursive
4421                invocation of bpstat for each breakpoint with a
4422                command, and can easily blow up GDB stack.  Instead, we
4423                return true, which will trigger the caller to recall us
4424                with the new stop_bpstat.  */
4425             again = 1;
4426           break;
4427         }
4428     }
4429   do_cleanups (old_chain);
4430   return again;
4431 }
4432
4433 void
4434 bpstat_do_actions (void)
4435 {
4436   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4437
4438   /* Do any commands attached to breakpoint we are stopped at.  */
4439   while (!ptid_equal (inferior_ptid, null_ptid)
4440          && target_has_execution
4441          && !is_exited (inferior_ptid)
4442          && !is_executing (inferior_ptid))
4443     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4444        and only return when it is stopped at the next breakpoint, we
4445        keep doing breakpoint actions until it returns false to
4446        indicate the inferior was not resumed.  */
4447     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4448       break;
4449
4450   discard_cleanups (cleanup_if_error);
4451 }
4452
4453 /* Print out the (old or new) value associated with a watchpoint.  */
4454
4455 static void
4456 watchpoint_value_print (struct value *val, struct ui_file *stream)
4457 {
4458   if (val == NULL)
4459     fprintf_unfiltered (stream, _("<unreadable>"));
4460   else
4461     {
4462       struct value_print_options opts;
4463       get_user_print_options (&opts);
4464       value_print (val, stream, &opts);
4465     }
4466 }
4467
4468 /* Generic routine for printing messages indicating why we
4469    stopped.  The behavior of this function depends on the value
4470    'print_it' in the bpstat structure.  Under some circumstances we
4471    may decide not to print anything here and delegate the task to
4472    normal_stop().  */
4473
4474 static enum print_stop_action
4475 print_bp_stop_message (bpstat bs)
4476 {
4477   switch (bs->print_it)
4478     {
4479     case print_it_noop:
4480       /* Nothing should be printed for this bpstat entry.  */
4481       return PRINT_UNKNOWN;
4482       break;
4483
4484     case print_it_done:
4485       /* We still want to print the frame, but we already printed the
4486          relevant messages.  */
4487       return PRINT_SRC_AND_LOC;
4488       break;
4489
4490     case print_it_normal:
4491       {
4492         struct breakpoint *b = bs->breakpoint_at;
4493
4494         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4495            which has since been deleted.  */
4496         if (b == NULL)
4497           return PRINT_UNKNOWN;
4498
4499         /* Normal case.  Call the breakpoint's print_it method.  */
4500         return b->ops->print_it (bs);
4501       }
4502       break;
4503
4504     default:
4505       internal_error (__FILE__, __LINE__,
4506                       _("print_bp_stop_message: unrecognized enum value"));
4507       break;
4508     }
4509 }
4510
4511 /* A helper function that prints a shared library stopped event.  */
4512
4513 static void
4514 print_solib_event (int is_catchpoint)
4515 {
4516   int any_deleted
4517     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4518   int any_added
4519     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4520
4521   if (!is_catchpoint)
4522     {
4523       if (any_added || any_deleted)
4524         ui_out_text (current_uiout,
4525                      _("Stopped due to shared library event:\n"));
4526       else
4527         ui_out_text (current_uiout,
4528                      _("Stopped due to shared library event (no "
4529                        "libraries added or removed)\n"));
4530     }
4531
4532   if (ui_out_is_mi_like_p (current_uiout))
4533     ui_out_field_string (current_uiout, "reason",
4534                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4535
4536   if (any_deleted)
4537     {
4538       struct cleanup *cleanup;
4539       char *name;
4540       int ix;
4541
4542       ui_out_text (current_uiout, _("  Inferior unloaded "));
4543       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4544                                                     "removed");
4545       for (ix = 0;
4546            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4547                         ix, name);
4548            ++ix)
4549         {
4550           if (ix > 0)
4551             ui_out_text (current_uiout, "    ");
4552           ui_out_field_string (current_uiout, "library", name);
4553           ui_out_text (current_uiout, "\n");
4554         }
4555
4556       do_cleanups (cleanup);
4557     }
4558
4559   if (any_added)
4560     {
4561       struct so_list *iter;
4562       int ix;
4563       struct cleanup *cleanup;
4564
4565       ui_out_text (current_uiout, _("  Inferior loaded "));
4566       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4567                                                     "added");
4568       for (ix = 0;
4569            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4570                         ix, iter);
4571            ++ix)
4572         {
4573           if (ix > 0)
4574             ui_out_text (current_uiout, "    ");
4575           ui_out_field_string (current_uiout, "library", iter->so_name);
4576           ui_out_text (current_uiout, "\n");
4577         }
4578
4579       do_cleanups (cleanup);
4580     }
4581 }
4582
4583 /* Print a message indicating what happened.  This is called from
4584    normal_stop().  The input to this routine is the head of the bpstat
4585    list - a list of the eventpoints that caused this stop.  KIND is
4586    the target_waitkind for the stopping event.  This
4587    routine calls the generic print routine for printing a message
4588    about reasons for stopping.  This will print (for example) the
4589    "Breakpoint n," part of the output.  The return value of this
4590    routine is one of:
4591
4592    PRINT_UNKNOWN: Means we printed nothing.
4593    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4594    code to print the location.  An example is 
4595    "Breakpoint 1, " which should be followed by
4596    the location.
4597    PRINT_SRC_ONLY: Means we printed something, but there is no need
4598    to also print the location part of the message.
4599    An example is the catch/throw messages, which
4600    don't require a location appended to the end.
4601    PRINT_NOTHING: We have done some printing and we don't need any 
4602    further info to be printed.  */
4603
4604 enum print_stop_action
4605 bpstat_print (bpstat bs, int kind)
4606 {
4607   int val;
4608
4609   /* Maybe another breakpoint in the chain caused us to stop.
4610      (Currently all watchpoints go on the bpstat whether hit or not.
4611      That probably could (should) be changed, provided care is taken
4612      with respect to bpstat_explains_signal).  */
4613   for (; bs; bs = bs->next)
4614     {
4615       val = print_bp_stop_message (bs);
4616       if (val == PRINT_SRC_ONLY 
4617           || val == PRINT_SRC_AND_LOC 
4618           || val == PRINT_NOTHING)
4619         return val;
4620     }
4621
4622   /* If we had hit a shared library event breakpoint,
4623      print_bp_stop_message would print out this message.  If we hit an
4624      OS-level shared library event, do the same thing.  */
4625   if (kind == TARGET_WAITKIND_LOADED)
4626     {
4627       print_solib_event (0);
4628       return PRINT_NOTHING;
4629     }
4630
4631   /* We reached the end of the chain, or we got a null BS to start
4632      with and nothing was printed.  */
4633   return PRINT_UNKNOWN;
4634 }
4635
4636 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4637    used inside a catch_errors to evaluate the breakpoint condition.
4638    The argument is a "struct expression *" that has been cast to a
4639    "char *" to make it pass through catch_errors.  */
4640
4641 static int
4642 breakpoint_cond_eval (void *exp)
4643 {
4644   struct value *mark = value_mark ();
4645   int i = !value_true (evaluate_expression ((struct expression *) exp));
4646
4647   value_free_to_mark (mark);
4648   return i;
4649 }
4650
4651 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4652
4653 static bpstat
4654 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4655 {
4656   bpstat bs;
4657
4658   bs = (bpstat) xmalloc (sizeof (*bs));
4659   bs->next = NULL;
4660   **bs_link_pointer = bs;
4661   *bs_link_pointer = &bs->next;
4662   bs->breakpoint_at = bl->owner;
4663   bs->bp_location_at = bl;
4664   incref_bp_location (bl);
4665   /* If the condition is false, etc., don't do the commands.  */
4666   bs->commands = NULL;
4667   bs->old_val = NULL;
4668   bs->print_it = print_it_normal;
4669   return bs;
4670 }
4671 \f
4672 /* The target has stopped with waitstatus WS.  Check if any hardware
4673    watchpoints have triggered, according to the target.  */
4674
4675 int
4676 watchpoints_triggered (struct target_waitstatus *ws)
4677 {
4678   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4679   CORE_ADDR addr;
4680   struct breakpoint *b;
4681
4682   if (!stopped_by_watchpoint)
4683     {
4684       /* We were not stopped by a watchpoint.  Mark all watchpoints
4685          as not triggered.  */
4686       ALL_BREAKPOINTS (b)
4687         if (is_hardware_watchpoint (b))
4688           {
4689             struct watchpoint *w = (struct watchpoint *) b;
4690
4691             w->watchpoint_triggered = watch_triggered_no;
4692           }
4693
4694       return 0;
4695     }
4696
4697   if (!target_stopped_data_address (&current_target, &addr))
4698     {
4699       /* We were stopped by a watchpoint, but we don't know where.
4700          Mark all watchpoints as unknown.  */
4701       ALL_BREAKPOINTS (b)
4702         if (is_hardware_watchpoint (b))
4703           {
4704             struct watchpoint *w = (struct watchpoint *) b;
4705
4706             w->watchpoint_triggered = watch_triggered_unknown;
4707           }
4708
4709       return stopped_by_watchpoint;
4710     }
4711
4712   /* The target could report the data address.  Mark watchpoints
4713      affected by this data address as triggered, and all others as not
4714      triggered.  */
4715
4716   ALL_BREAKPOINTS (b)
4717     if (is_hardware_watchpoint (b))
4718       {
4719         struct watchpoint *w = (struct watchpoint *) b;
4720         struct bp_location *loc;
4721
4722         w->watchpoint_triggered = watch_triggered_no;
4723         for (loc = b->loc; loc; loc = loc->next)
4724           {
4725             if (is_masked_watchpoint (b))
4726               {
4727                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4728                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4729
4730                 if (newaddr == start)
4731                   {
4732                     w->watchpoint_triggered = watch_triggered_yes;
4733                     break;
4734                   }
4735               }
4736             /* Exact match not required.  Within range is sufficient.  */
4737             else if (target_watchpoint_addr_within_range (&current_target,
4738                                                          addr, loc->address,
4739                                                          loc->length))
4740               {
4741                 w->watchpoint_triggered = watch_triggered_yes;
4742                 break;
4743               }
4744           }
4745       }
4746
4747   return 1;
4748 }
4749
4750 /* Possible return values for watchpoint_check (this can't be an enum
4751    because of check_errors).  */
4752 /* The watchpoint has been deleted.  */
4753 #define WP_DELETED 1
4754 /* The value has changed.  */
4755 #define WP_VALUE_CHANGED 2
4756 /* The value has not changed.  */
4757 #define WP_VALUE_NOT_CHANGED 3
4758 /* Ignore this watchpoint, no matter if the value changed or not.  */
4759 #define WP_IGNORE 4
4760
4761 #define BP_TEMPFLAG 1
4762 #define BP_HARDWAREFLAG 2
4763
4764 /* Evaluate watchpoint condition expression and check if its value
4765    changed.
4766
4767    P should be a pointer to struct bpstat, but is defined as a void *
4768    in order for this function to be usable with catch_errors.  */
4769
4770 static int
4771 watchpoint_check (void *p)
4772 {
4773   bpstat bs = (bpstat) p;
4774   struct watchpoint *b;
4775   struct frame_info *fr;
4776   int within_current_scope;
4777
4778   /* BS is built from an existing struct breakpoint.  */
4779   gdb_assert (bs->breakpoint_at != NULL);
4780   b = (struct watchpoint *) bs->breakpoint_at;
4781
4782   /* If this is a local watchpoint, we only want to check if the
4783      watchpoint frame is in scope if the current thread is the thread
4784      that was used to create the watchpoint.  */
4785   if (!watchpoint_in_thread_scope (b))
4786     return WP_IGNORE;
4787
4788   if (b->exp_valid_block == NULL)
4789     within_current_scope = 1;
4790   else
4791     {
4792       struct frame_info *frame = get_current_frame ();
4793       struct gdbarch *frame_arch = get_frame_arch (frame);
4794       CORE_ADDR frame_pc = get_frame_pc (frame);
4795
4796       /* in_function_epilogue_p() returns a non-zero value if we're
4797          still in the function but the stack frame has already been
4798          invalidated.  Since we can't rely on the values of local
4799          variables after the stack has been destroyed, we are treating
4800          the watchpoint in that state as `not changed' without further
4801          checking.  Don't mark watchpoints as changed if the current
4802          frame is in an epilogue - even if they are in some other
4803          frame, our view of the stack is likely to be wrong and
4804          frame_find_by_id could error out.  */
4805       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4806         return WP_IGNORE;
4807
4808       fr = frame_find_by_id (b->watchpoint_frame);
4809       within_current_scope = (fr != NULL);
4810
4811       /* If we've gotten confused in the unwinder, we might have
4812          returned a frame that can't describe this variable.  */
4813       if (within_current_scope)
4814         {
4815           struct symbol *function;
4816
4817           function = get_frame_function (fr);
4818           if (function == NULL
4819               || !contained_in (b->exp_valid_block,
4820                                 SYMBOL_BLOCK_VALUE (function)))
4821             within_current_scope = 0;
4822         }
4823
4824       if (within_current_scope)
4825         /* If we end up stopping, the current frame will get selected
4826            in normal_stop.  So this call to select_frame won't affect
4827            the user.  */
4828         select_frame (fr);
4829     }
4830
4831   if (within_current_scope)
4832     {
4833       /* We use value_{,free_to_}mark because it could be a *long*
4834          time before we return to the command level and call
4835          free_all_values.  We can't call free_all_values because we
4836          might be in the middle of evaluating a function call.  */
4837
4838       int pc = 0;
4839       struct value *mark;
4840       struct value *new_val;
4841
4842       if (is_masked_watchpoint (&b->base))
4843         /* Since we don't know the exact trigger address (from
4844            stopped_data_address), just tell the user we've triggered
4845            a mask watchpoint.  */
4846         return WP_VALUE_CHANGED;
4847
4848       mark = value_mark ();
4849       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
4850
4851       /* We use value_equal_contents instead of value_equal because
4852          the latter coerces an array to a pointer, thus comparing just
4853          the address of the array instead of its contents.  This is
4854          not what we want.  */
4855       if ((b->val != NULL) != (new_val != NULL)
4856           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4857         {
4858           if (new_val != NULL)
4859             {
4860               release_value (new_val);
4861               value_free_to_mark (mark);
4862             }
4863           bs->old_val = b->val;
4864           b->val = new_val;
4865           b->val_valid = 1;
4866           return WP_VALUE_CHANGED;
4867         }
4868       else
4869         {
4870           /* Nothing changed.  */
4871           value_free_to_mark (mark);
4872           return WP_VALUE_NOT_CHANGED;
4873         }
4874     }
4875   else
4876     {
4877       struct ui_out *uiout = current_uiout;
4878
4879       /* This seems like the only logical thing to do because
4880          if we temporarily ignored the watchpoint, then when
4881          we reenter the block in which it is valid it contains
4882          garbage (in the case of a function, it may have two
4883          garbage values, one before and one after the prologue).
4884          So we can't even detect the first assignment to it and
4885          watch after that (since the garbage may or may not equal
4886          the first value assigned).  */
4887       /* We print all the stop information in
4888          breakpoint_ops->print_it, but in this case, by the time we
4889          call breakpoint_ops->print_it this bp will be deleted
4890          already.  So we have no choice but print the information
4891          here.  */
4892       if (ui_out_is_mi_like_p (uiout))
4893         ui_out_field_string
4894           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4895       ui_out_text (uiout, "\nWatchpoint ");
4896       ui_out_field_int (uiout, "wpnum", b->base.number);
4897       ui_out_text (uiout,
4898                    " deleted because the program has left the block in\n\
4899 which its expression is valid.\n");     
4900
4901       /* Make sure the watchpoint's commands aren't executed.  */
4902       decref_counted_command_line (&b->base.commands);
4903       watchpoint_del_at_next_stop (b);
4904
4905       return WP_DELETED;
4906     }
4907 }
4908
4909 /* Return true if it looks like target has stopped due to hitting
4910    breakpoint location BL.  This function does not check if we should
4911    stop, only if BL explains the stop.  */
4912
4913 static int
4914 bpstat_check_location (const struct bp_location *bl,
4915                        struct address_space *aspace, CORE_ADDR bp_addr,
4916                        const struct target_waitstatus *ws)
4917 {
4918   struct breakpoint *b = bl->owner;
4919
4920   /* BL is from an existing breakpoint.  */
4921   gdb_assert (b != NULL);
4922
4923   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4924 }
4925
4926 /* Determine if the watched values have actually changed, and we
4927    should stop.  If not, set BS->stop to 0.  */
4928
4929 static void
4930 bpstat_check_watchpoint (bpstat bs)
4931 {
4932   const struct bp_location *bl;
4933   struct watchpoint *b;
4934
4935   /* BS is built for existing struct breakpoint.  */
4936   bl = bs->bp_location_at;
4937   gdb_assert (bl != NULL);
4938   b = (struct watchpoint *) bs->breakpoint_at;
4939   gdb_assert (b != NULL);
4940
4941     {
4942       int must_check_value = 0;
4943       
4944       if (b->base.type == bp_watchpoint)
4945         /* For a software watchpoint, we must always check the
4946            watched value.  */
4947         must_check_value = 1;
4948       else if (b->watchpoint_triggered == watch_triggered_yes)
4949         /* We have a hardware watchpoint (read, write, or access)
4950            and the target earlier reported an address watched by
4951            this watchpoint.  */
4952         must_check_value = 1;
4953       else if (b->watchpoint_triggered == watch_triggered_unknown
4954                && b->base.type == bp_hardware_watchpoint)
4955         /* We were stopped by a hardware watchpoint, but the target could
4956            not report the data address.  We must check the watchpoint's
4957            value.  Access and read watchpoints are out of luck; without
4958            a data address, we can't figure it out.  */
4959         must_check_value = 1;
4960
4961       if (must_check_value)
4962         {
4963           char *message
4964             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4965                           b->base.number);
4966           struct cleanup *cleanups = make_cleanup (xfree, message);
4967           int e = catch_errors (watchpoint_check, bs, message,
4968                                 RETURN_MASK_ALL);
4969           do_cleanups (cleanups);
4970           switch (e)
4971             {
4972             case WP_DELETED:
4973               /* We've already printed what needs to be printed.  */
4974               bs->print_it = print_it_done;
4975               /* Stop.  */
4976               break;
4977             case WP_IGNORE:
4978               bs->print_it = print_it_noop;
4979               bs->stop = 0;
4980               break;
4981             case WP_VALUE_CHANGED:
4982               if (b->base.type == bp_read_watchpoint)
4983                 {
4984                   /* There are two cases to consider here:
4985
4986                      1. We're watching the triggered memory for reads.
4987                      In that case, trust the target, and always report
4988                      the watchpoint hit to the user.  Even though
4989                      reads don't cause value changes, the value may
4990                      have changed since the last time it was read, and
4991                      since we're not trapping writes, we will not see
4992                      those, and as such we should ignore our notion of
4993                      old value.
4994
4995                      2. We're watching the triggered memory for both
4996                      reads and writes.  There are two ways this may
4997                      happen:
4998
4999                      2.1. This is a target that can't break on data
5000                      reads only, but can break on accesses (reads or
5001                      writes), such as e.g., x86.  We detect this case
5002                      at the time we try to insert read watchpoints.
5003
5004                      2.2. Otherwise, the target supports read
5005                      watchpoints, but, the user set an access or write
5006                      watchpoint watching the same memory as this read
5007                      watchpoint.
5008
5009                      If we're watching memory writes as well as reads,
5010                      ignore watchpoint hits when we find that the
5011                      value hasn't changed, as reads don't cause
5012                      changes.  This still gives false positives when
5013                      the program writes the same value to memory as
5014                      what there was already in memory (we will confuse
5015                      it for a read), but it's much better than
5016                      nothing.  */
5017
5018                   int other_write_watchpoint = 0;
5019
5020                   if (bl->watchpoint_type == hw_read)
5021                     {
5022                       struct breakpoint *other_b;
5023
5024                       ALL_BREAKPOINTS (other_b)
5025                         if (other_b->type == bp_hardware_watchpoint
5026                             || other_b->type == bp_access_watchpoint)
5027                           {
5028                             struct watchpoint *other_w =
5029                               (struct watchpoint *) other_b;
5030
5031                             if (other_w->watchpoint_triggered
5032                                 == watch_triggered_yes)
5033                               {
5034                                 other_write_watchpoint = 1;
5035                                 break;
5036                               }
5037                           }
5038                     }
5039
5040                   if (other_write_watchpoint
5041                       || bl->watchpoint_type == hw_access)
5042                     {
5043                       /* We're watching the same memory for writes,
5044                          and the value changed since the last time we
5045                          updated it, so this trap must be for a write.
5046                          Ignore it.  */
5047                       bs->print_it = print_it_noop;
5048                       bs->stop = 0;
5049                     }
5050                 }
5051               break;
5052             case WP_VALUE_NOT_CHANGED:
5053               if (b->base.type == bp_hardware_watchpoint
5054                   || b->base.type == bp_watchpoint)
5055                 {
5056                   /* Don't stop: write watchpoints shouldn't fire if
5057                      the value hasn't changed.  */
5058                   bs->print_it = print_it_noop;
5059                   bs->stop = 0;
5060                 }
5061               /* Stop.  */
5062               break;
5063             default:
5064               /* Can't happen.  */
5065             case 0:
5066               /* Error from catch_errors.  */
5067               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5068               watchpoint_del_at_next_stop (b);
5069               /* We've already printed what needs to be printed.  */
5070               bs->print_it = print_it_done;
5071               break;
5072             }
5073         }
5074       else      /* must_check_value == 0 */
5075         {
5076           /* This is a case where some watchpoint(s) triggered, but
5077              not at the address of this watchpoint, or else no
5078              watchpoint triggered after all.  So don't print
5079              anything for this watchpoint.  */
5080           bs->print_it = print_it_noop;
5081           bs->stop = 0;
5082         }
5083     }
5084 }
5085
5086
5087 /* Check conditions (condition proper, frame, thread and ignore count)
5088    of breakpoint referred to by BS.  If we should not stop for this
5089    breakpoint, set BS->stop to 0.  */
5090
5091 static void
5092 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5093 {
5094   int thread_id = pid_to_thread_id (ptid);
5095   const struct bp_location *bl;
5096   struct breakpoint *b;
5097
5098   /* BS is built for existing struct breakpoint.  */
5099   bl = bs->bp_location_at;
5100   gdb_assert (bl != NULL);
5101   b = bs->breakpoint_at;
5102   gdb_assert (b != NULL);
5103
5104   /* Even if the target evaluated the condition on its end and notified GDB, we
5105      need to do so again since GDB does not know if we stopped due to a
5106      breakpoint or a single step breakpoint.  */
5107
5108   if (frame_id_p (b->frame_id)
5109       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5110     bs->stop = 0;
5111   else if (bs->stop)
5112     {
5113       int value_is_zero = 0;
5114       struct expression *cond;
5115
5116       /* Evaluate Python breakpoints that have a "stop"
5117          method implemented.  */
5118       if (b->py_bp_object)
5119         bs->stop = gdbpy_should_stop (b->py_bp_object);
5120
5121       if (is_watchpoint (b))
5122         {
5123           struct watchpoint *w = (struct watchpoint *) b;
5124
5125           cond = w->cond_exp;
5126         }
5127       else
5128         cond = bl->cond;
5129
5130       if (cond && b->disposition != disp_del_at_next_stop)
5131         {
5132           int within_current_scope = 1;
5133           struct watchpoint * w;
5134
5135           /* We use value_mark and value_free_to_mark because it could
5136              be a long time before we return to the command level and
5137              call free_all_values.  We can't call free_all_values
5138              because we might be in the middle of evaluating a
5139              function call.  */
5140           struct value *mark = value_mark ();
5141
5142           if (is_watchpoint (b))
5143             w = (struct watchpoint *) b;
5144           else
5145             w = NULL;
5146
5147           /* Need to select the frame, with all that implies so that
5148              the conditions will have the right context.  Because we
5149              use the frame, we will not see an inlined function's
5150              variables when we arrive at a breakpoint at the start
5151              of the inlined function; the current frame will be the
5152              call site.  */
5153           if (w == NULL || w->cond_exp_valid_block == NULL)
5154             select_frame (get_current_frame ());
5155           else
5156             {
5157               struct frame_info *frame;
5158
5159               /* For local watchpoint expressions, which particular
5160                  instance of a local is being watched matters, so we
5161                  keep track of the frame to evaluate the expression
5162                  in.  To evaluate the condition however, it doesn't
5163                  really matter which instantiation of the function
5164                  where the condition makes sense triggers the
5165                  watchpoint.  This allows an expression like "watch
5166                  global if q > 10" set in `func', catch writes to
5167                  global on all threads that call `func', or catch
5168                  writes on all recursive calls of `func' by a single
5169                  thread.  We simply always evaluate the condition in
5170                  the innermost frame that's executing where it makes
5171                  sense to evaluate the condition.  It seems
5172                  intuitive.  */
5173               frame = block_innermost_frame (w->cond_exp_valid_block);
5174               if (frame != NULL)
5175                 select_frame (frame);
5176               else
5177                 within_current_scope = 0;
5178             }
5179           if (within_current_scope)
5180             value_is_zero
5181               = catch_errors (breakpoint_cond_eval, cond,
5182                               "Error in testing breakpoint condition:\n",
5183                               RETURN_MASK_ALL);
5184           else
5185             {
5186               warning (_("Watchpoint condition cannot be tested "
5187                          "in the current scope"));
5188               /* If we failed to set the right context for this
5189                  watchpoint, unconditionally report it.  */
5190               value_is_zero = 0;
5191             }
5192           /* FIXME-someday, should give breakpoint #.  */
5193           value_free_to_mark (mark);
5194         }
5195
5196       if (cond && value_is_zero)
5197         {
5198           bs->stop = 0;
5199         }
5200       else if (b->thread != -1 && b->thread != thread_id)
5201         {
5202           bs->stop = 0;
5203         }
5204       else if (b->ignore_count > 0)
5205         {
5206           b->ignore_count--;
5207           bs->stop = 0;
5208           /* Increase the hit count even though we don't stop.  */
5209           ++(b->hit_count);
5210           observer_notify_breakpoint_modified (b);
5211         }       
5212     }
5213 }
5214
5215
5216 /* Get a bpstat associated with having just stopped at address
5217    BP_ADDR in thread PTID.
5218
5219    Determine whether we stopped at a breakpoint, etc, or whether we
5220    don't understand this stop.  Result is a chain of bpstat's such
5221    that:
5222
5223    if we don't understand the stop, the result is a null pointer.
5224
5225    if we understand why we stopped, the result is not null.
5226
5227    Each element of the chain refers to a particular breakpoint or
5228    watchpoint at which we have stopped.  (We may have stopped for
5229    several reasons concurrently.)
5230
5231    Each element of the chain has valid next, breakpoint_at,
5232    commands, FIXME??? fields.  */
5233
5234 bpstat
5235 bpstat_stop_status (struct address_space *aspace,
5236                     CORE_ADDR bp_addr, ptid_t ptid,
5237                     const struct target_waitstatus *ws)
5238 {
5239   struct breakpoint *b = NULL;
5240   struct bp_location *bl;
5241   struct bp_location *loc;
5242   /* First item of allocated bpstat's.  */
5243   bpstat bs_head = NULL, *bs_link = &bs_head;
5244   /* Pointer to the last thing in the chain currently.  */
5245   bpstat bs;
5246   int ix;
5247   int need_remove_insert;
5248   int removed_any;
5249
5250   /* First, build the bpstat chain with locations that explain a
5251      target stop, while being careful to not set the target running,
5252      as that may invalidate locations (in particular watchpoint
5253      locations are recreated).  Resuming will happen here with
5254      breakpoint conditions or watchpoint expressions that include
5255      inferior function calls.  */
5256
5257   ALL_BREAKPOINTS (b)
5258     {
5259       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5260         continue;
5261
5262       for (bl = b->loc; bl != NULL; bl = bl->next)
5263         {
5264           /* For hardware watchpoints, we look only at the first
5265              location.  The watchpoint_check function will work on the
5266              entire expression, not the individual locations.  For
5267              read watchpoints, the watchpoints_triggered function has
5268              checked all locations already.  */
5269           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5270             break;
5271
5272           if (!bl->enabled || bl->shlib_disabled)
5273             continue;
5274
5275           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5276             continue;
5277
5278           /* Come here if it's a watchpoint, or if the break address
5279              matches.  */
5280
5281           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5282                                                    explain stop.  */
5283
5284           /* Assume we stop.  Should we find a watchpoint that is not
5285              actually triggered, or if the condition of the breakpoint
5286              evaluates as false, we'll reset 'stop' to 0.  */
5287           bs->stop = 1;
5288           bs->print = 1;
5289
5290           /* If this is a scope breakpoint, mark the associated
5291              watchpoint as triggered so that we will handle the
5292              out-of-scope event.  We'll get to the watchpoint next
5293              iteration.  */
5294           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5295             {
5296               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5297
5298               w->watchpoint_triggered = watch_triggered_yes;
5299             }
5300         }
5301     }
5302
5303   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5304     {
5305       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5306         {
5307           bs = bpstat_alloc (loc, &bs_link);
5308           /* For hits of moribund locations, we should just proceed.  */
5309           bs->stop = 0;
5310           bs->print = 0;
5311           bs->print_it = print_it_noop;
5312         }
5313     }
5314
5315   /* A bit of special processing for shlib breakpoints.  We need to
5316      process solib loading here, so that the lists of loaded and
5317      unloaded libraries are correct before we handle "catch load" and
5318      "catch unload".  */
5319   for (bs = bs_head; bs != NULL; bs = bs->next)
5320     {
5321       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5322         {
5323           handle_solib_event ();
5324           break;
5325         }
5326     }
5327
5328   /* Now go through the locations that caused the target to stop, and
5329      check whether we're interested in reporting this stop to higher
5330      layers, or whether we should resume the target transparently.  */
5331
5332   removed_any = 0;
5333
5334   for (bs = bs_head; bs != NULL; bs = bs->next)
5335     {
5336       if (!bs->stop)
5337         continue;
5338
5339       b = bs->breakpoint_at;
5340       b->ops->check_status (bs);
5341       if (bs->stop)
5342         {
5343           bpstat_check_breakpoint_conditions (bs, ptid);
5344
5345           if (bs->stop)
5346             {
5347               ++(b->hit_count);
5348               observer_notify_breakpoint_modified (b);
5349
5350               /* We will stop here.  */
5351               if (b->disposition == disp_disable)
5352                 {
5353                   --(b->enable_count);
5354                   if (b->enable_count <= 0
5355                       && b->enable_state != bp_permanent)
5356                     b->enable_state = bp_disabled;
5357                   removed_any = 1;
5358                 }
5359               if (b->silent)
5360                 bs->print = 0;
5361               bs->commands = b->commands;
5362               incref_counted_command_line (bs->commands);
5363               if (command_line_is_silent (bs->commands
5364                                           ? bs->commands->commands : NULL))
5365                 bs->print = 0;
5366
5367               b->ops->after_condition_true (bs);
5368             }
5369
5370         }
5371
5372       /* Print nothing for this entry if we don't stop or don't
5373          print.  */
5374       if (!bs->stop || !bs->print)
5375         bs->print_it = print_it_noop;
5376     }
5377
5378   /* If we aren't stopping, the value of some hardware watchpoint may
5379      not have changed, but the intermediate memory locations we are
5380      watching may have.  Don't bother if we're stopping; this will get
5381      done later.  */
5382   need_remove_insert = 0;
5383   if (! bpstat_causes_stop (bs_head))
5384     for (bs = bs_head; bs != NULL; bs = bs->next)
5385       if (!bs->stop
5386           && bs->breakpoint_at
5387           && is_hardware_watchpoint (bs->breakpoint_at))
5388         {
5389           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5390
5391           update_watchpoint (w, 0 /* don't reparse.  */);
5392           need_remove_insert = 1;
5393         }
5394
5395   if (need_remove_insert)
5396     update_global_location_list (1);
5397   else if (removed_any)
5398     update_global_location_list (0);
5399
5400   return bs_head;
5401 }
5402
5403 static void
5404 handle_jit_event (void)
5405 {
5406   struct frame_info *frame;
5407   struct gdbarch *gdbarch;
5408
5409   /* Switch terminal for any messages produced by
5410      breakpoint_re_set.  */
5411   target_terminal_ours_for_output ();
5412
5413   frame = get_current_frame ();
5414   gdbarch = get_frame_arch (frame);
5415
5416   jit_event_handler (gdbarch);
5417
5418   target_terminal_inferior ();
5419 }
5420
5421 /* Prepare WHAT final decision for infrun.  */
5422
5423 /* Decide what infrun needs to do with this bpstat.  */
5424
5425 struct bpstat_what
5426 bpstat_what (bpstat bs_head)
5427 {
5428   struct bpstat_what retval;
5429   int jit_event = 0;
5430   bpstat bs;
5431
5432   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5433   retval.call_dummy = STOP_NONE;
5434   retval.is_longjmp = 0;
5435
5436   for (bs = bs_head; bs != NULL; bs = bs->next)
5437     {
5438       /* Extract this BS's action.  After processing each BS, we check
5439          if its action overrides all we've seem so far.  */
5440       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5441       enum bptype bptype;
5442
5443       if (bs->breakpoint_at == NULL)
5444         {
5445           /* I suspect this can happen if it was a momentary
5446              breakpoint which has since been deleted.  */
5447           bptype = bp_none;
5448         }
5449       else
5450         bptype = bs->breakpoint_at->type;
5451
5452       switch (bptype)
5453         {
5454         case bp_none:
5455           break;
5456         case bp_breakpoint:
5457         case bp_hardware_breakpoint:
5458         case bp_until:
5459         case bp_finish:
5460         case bp_shlib_event:
5461           if (bs->stop)
5462             {
5463               if (bs->print)
5464                 this_action = BPSTAT_WHAT_STOP_NOISY;
5465               else
5466                 this_action = BPSTAT_WHAT_STOP_SILENT;
5467             }
5468           else
5469             this_action = BPSTAT_WHAT_SINGLE;
5470           break;
5471         case bp_watchpoint:
5472         case bp_hardware_watchpoint:
5473         case bp_read_watchpoint:
5474         case bp_access_watchpoint:
5475           if (bs->stop)
5476             {
5477               if (bs->print)
5478                 this_action = BPSTAT_WHAT_STOP_NOISY;
5479               else
5480                 this_action = BPSTAT_WHAT_STOP_SILENT;
5481             }
5482           else
5483             {
5484               /* There was a watchpoint, but we're not stopping.
5485                  This requires no further action.  */
5486             }
5487           break;
5488         case bp_longjmp:
5489         case bp_longjmp_call_dummy:
5490         case bp_exception:
5491           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5492           retval.is_longjmp = bptype != bp_exception;
5493           break;
5494         case bp_longjmp_resume:
5495         case bp_exception_resume:
5496           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5497           retval.is_longjmp = bptype == bp_longjmp_resume;
5498           break;
5499         case bp_step_resume:
5500           if (bs->stop)
5501             this_action = BPSTAT_WHAT_STEP_RESUME;
5502           else
5503             {
5504               /* It is for the wrong frame.  */
5505               this_action = BPSTAT_WHAT_SINGLE;
5506             }
5507           break;
5508         case bp_hp_step_resume:
5509           if (bs->stop)
5510             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5511           else
5512             {
5513               /* It is for the wrong frame.  */
5514               this_action = BPSTAT_WHAT_SINGLE;
5515             }
5516           break;
5517         case bp_watchpoint_scope:
5518         case bp_thread_event:
5519         case bp_overlay_event:
5520         case bp_longjmp_master:
5521         case bp_std_terminate_master:
5522         case bp_exception_master:
5523           this_action = BPSTAT_WHAT_SINGLE;
5524           break;
5525         case bp_catchpoint:
5526           if (bs->stop)
5527             {
5528               if (bs->print)
5529                 this_action = BPSTAT_WHAT_STOP_NOISY;
5530               else
5531                 this_action = BPSTAT_WHAT_STOP_SILENT;
5532             }
5533           else
5534             {
5535               /* There was a catchpoint, but we're not stopping.
5536                  This requires no further action.  */
5537             }
5538           break;
5539         case bp_jit_event:
5540           jit_event = 1;
5541           this_action = BPSTAT_WHAT_SINGLE;
5542           break;
5543         case bp_call_dummy:
5544           /* Make sure the action is stop (silent or noisy),
5545              so infrun.c pops the dummy frame.  */
5546           retval.call_dummy = STOP_STACK_DUMMY;
5547           this_action = BPSTAT_WHAT_STOP_SILENT;
5548           break;
5549         case bp_std_terminate:
5550           /* Make sure the action is stop (silent or noisy),
5551              so infrun.c pops the dummy frame.  */
5552           retval.call_dummy = STOP_STD_TERMINATE;
5553           this_action = BPSTAT_WHAT_STOP_SILENT;
5554           break;
5555         case bp_tracepoint:
5556         case bp_fast_tracepoint:
5557         case bp_static_tracepoint:
5558           /* Tracepoint hits should not be reported back to GDB, and
5559              if one got through somehow, it should have been filtered
5560              out already.  */
5561           internal_error (__FILE__, __LINE__,
5562                           _("bpstat_what: tracepoint encountered"));
5563           break;
5564         case bp_gnu_ifunc_resolver:
5565           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5566           this_action = BPSTAT_WHAT_SINGLE;
5567           break;
5568         case bp_gnu_ifunc_resolver_return:
5569           /* The breakpoint will be removed, execution will restart from the
5570              PC of the former breakpoint.  */
5571           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5572           break;
5573
5574         case bp_dprintf:
5575           if (bs->stop)
5576             this_action = BPSTAT_WHAT_STOP_SILENT;
5577           else
5578             this_action = BPSTAT_WHAT_SINGLE;
5579           break;
5580
5581         default:
5582           internal_error (__FILE__, __LINE__,
5583                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5584         }
5585
5586       retval.main_action = max (retval.main_action, this_action);
5587     }
5588
5589   /* These operations may affect the bs->breakpoint_at state so they are
5590      delayed after MAIN_ACTION is decided above.  */
5591
5592   if (jit_event)
5593     {
5594       if (debug_infrun)
5595         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5596
5597       handle_jit_event ();
5598     }
5599
5600   for (bs = bs_head; bs != NULL; bs = bs->next)
5601     {
5602       struct breakpoint *b = bs->breakpoint_at;
5603
5604       if (b == NULL)
5605         continue;
5606       switch (b->type)
5607         {
5608         case bp_gnu_ifunc_resolver:
5609           gnu_ifunc_resolver_stop (b);
5610           break;
5611         case bp_gnu_ifunc_resolver_return:
5612           gnu_ifunc_resolver_return_stop (b);
5613           break;
5614         }
5615     }
5616
5617   return retval;
5618 }
5619
5620 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5621    without hardware support).  This isn't related to a specific bpstat,
5622    just to things like whether watchpoints are set.  */
5623
5624 int
5625 bpstat_should_step (void)
5626 {
5627   struct breakpoint *b;
5628
5629   ALL_BREAKPOINTS (b)
5630     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5631       return 1;
5632   return 0;
5633 }
5634
5635 int
5636 bpstat_causes_stop (bpstat bs)
5637 {
5638   for (; bs != NULL; bs = bs->next)
5639     if (bs->stop)
5640       return 1;
5641
5642   return 0;
5643 }
5644
5645 \f
5646
5647 /* Compute a string of spaces suitable to indent the next line
5648    so it starts at the position corresponding to the table column
5649    named COL_NAME in the currently active table of UIOUT.  */
5650
5651 static char *
5652 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5653 {
5654   static char wrap_indent[80];
5655   int i, total_width, width, align;
5656   char *text;
5657
5658   total_width = 0;
5659   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5660     {
5661       if (strcmp (text, col_name) == 0)
5662         {
5663           gdb_assert (total_width < sizeof wrap_indent);
5664           memset (wrap_indent, ' ', total_width);
5665           wrap_indent[total_width] = 0;
5666
5667           return wrap_indent;
5668         }
5669
5670       total_width += width + 1;
5671     }
5672
5673   return NULL;
5674 }
5675
5676 /* Determine if the locations of this breakpoint will have their conditions
5677    evaluated by the target, host or a mix of both.  Returns the following:
5678
5679     "host": Host evals condition.
5680     "host or target": Host or Target evals condition.
5681     "target": Target evals condition.
5682 */
5683
5684 static const char *
5685 bp_condition_evaluator (struct breakpoint *b)
5686 {
5687   struct bp_location *bl;
5688   char host_evals = 0;
5689   char target_evals = 0;
5690
5691   if (!b)
5692     return NULL;
5693
5694   if (!is_breakpoint (b))
5695     return NULL;
5696
5697   if (gdb_evaluates_breakpoint_condition_p ()
5698       || !target_supports_evaluation_of_breakpoint_conditions ())
5699     return condition_evaluation_host;
5700
5701   for (bl = b->loc; bl; bl = bl->next)
5702     {
5703       if (bl->cond_bytecode)
5704         target_evals++;
5705       else
5706         host_evals++;
5707     }
5708
5709   if (host_evals && target_evals)
5710     return condition_evaluation_both;
5711   else if (target_evals)
5712     return condition_evaluation_target;
5713   else
5714     return condition_evaluation_host;
5715 }
5716
5717 /* Determine the breakpoint location's condition evaluator.  This is
5718    similar to bp_condition_evaluator, but for locations.  */
5719
5720 static const char *
5721 bp_location_condition_evaluator (struct bp_location *bl)
5722 {
5723   if (bl && !is_breakpoint (bl->owner))
5724     return NULL;
5725
5726   if (gdb_evaluates_breakpoint_condition_p ()
5727       || !target_supports_evaluation_of_breakpoint_conditions ())
5728     return condition_evaluation_host;
5729
5730   if (bl && bl->cond_bytecode)
5731     return condition_evaluation_target;
5732   else
5733     return condition_evaluation_host;
5734 }
5735
5736 /* Print the LOC location out of the list of B->LOC locations.  */
5737
5738 static void
5739 print_breakpoint_location (struct breakpoint *b,
5740                            struct bp_location *loc)
5741 {
5742   struct ui_out *uiout = current_uiout;
5743   struct cleanup *old_chain = save_current_program_space ();
5744
5745   if (loc != NULL && loc->shlib_disabled)
5746     loc = NULL;
5747
5748   if (loc != NULL)
5749     set_current_program_space (loc->pspace);
5750
5751   if (b->display_canonical)
5752     ui_out_field_string (uiout, "what", b->addr_string);
5753   else if (loc && loc->symtab)
5754     {
5755       struct symbol *sym 
5756         = find_pc_sect_function (loc->address, loc->section);
5757       if (sym)
5758         {
5759           ui_out_text (uiout, "in ");
5760           ui_out_field_string (uiout, "func",
5761                                SYMBOL_PRINT_NAME (sym));
5762           ui_out_text (uiout, " ");
5763           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5764           ui_out_text (uiout, "at ");
5765         }
5766       ui_out_field_string (uiout, "file",
5767                            symtab_to_filename_for_display (loc->symtab));
5768       ui_out_text (uiout, ":");
5769
5770       if (ui_out_is_mi_like_p (uiout))
5771         ui_out_field_string (uiout, "fullname",
5772                              symtab_to_fullname (loc->symtab));
5773       
5774       ui_out_field_int (uiout, "line", loc->line_number);
5775     }
5776   else if (loc)
5777     {
5778       struct ui_file *stb = mem_fileopen ();
5779       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5780
5781       print_address_symbolic (loc->gdbarch, loc->address, stb,
5782                               demangle, "");
5783       ui_out_field_stream (uiout, "at", stb);
5784
5785       do_cleanups (stb_chain);
5786     }
5787   else
5788     ui_out_field_string (uiout, "pending", b->addr_string);
5789
5790   if (loc && is_breakpoint (b)
5791       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5792       && bp_condition_evaluator (b) == condition_evaluation_both)
5793     {
5794       ui_out_text (uiout, " (");
5795       ui_out_field_string (uiout, "evaluated-by",
5796                            bp_location_condition_evaluator (loc));
5797       ui_out_text (uiout, ")");
5798     }
5799
5800   do_cleanups (old_chain);
5801 }
5802
5803 static const char *
5804 bptype_string (enum bptype type)
5805 {
5806   struct ep_type_description
5807     {
5808       enum bptype type;
5809       char *description;
5810     };
5811   static struct ep_type_description bptypes[] =
5812   {
5813     {bp_none, "?deleted?"},
5814     {bp_breakpoint, "breakpoint"},
5815     {bp_hardware_breakpoint, "hw breakpoint"},
5816     {bp_until, "until"},
5817     {bp_finish, "finish"},
5818     {bp_watchpoint, "watchpoint"},
5819     {bp_hardware_watchpoint, "hw watchpoint"},
5820     {bp_read_watchpoint, "read watchpoint"},
5821     {bp_access_watchpoint, "acc watchpoint"},
5822     {bp_longjmp, "longjmp"},
5823     {bp_longjmp_resume, "longjmp resume"},
5824     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5825     {bp_exception, "exception"},
5826     {bp_exception_resume, "exception resume"},
5827     {bp_step_resume, "step resume"},
5828     {bp_hp_step_resume, "high-priority step resume"},
5829     {bp_watchpoint_scope, "watchpoint scope"},
5830     {bp_call_dummy, "call dummy"},
5831     {bp_std_terminate, "std::terminate"},
5832     {bp_shlib_event, "shlib events"},
5833     {bp_thread_event, "thread events"},
5834     {bp_overlay_event, "overlay events"},
5835     {bp_longjmp_master, "longjmp master"},
5836     {bp_std_terminate_master, "std::terminate master"},
5837     {bp_exception_master, "exception master"},
5838     {bp_catchpoint, "catchpoint"},
5839     {bp_tracepoint, "tracepoint"},
5840     {bp_fast_tracepoint, "fast tracepoint"},
5841     {bp_static_tracepoint, "static tracepoint"},
5842     {bp_dprintf, "dprintf"},
5843     {bp_jit_event, "jit events"},
5844     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5845     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5846   };
5847
5848   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5849       || ((int) type != bptypes[(int) type].type))
5850     internal_error (__FILE__, __LINE__,
5851                     _("bptypes table does not describe type #%d."),
5852                     (int) type);
5853
5854   return bptypes[(int) type].description;
5855 }
5856
5857 /* For MI, output a field named 'thread-groups' with a list as the value.
5858    For CLI, prefix the list with the string 'inf'. */
5859
5860 static void
5861 output_thread_groups (struct ui_out *uiout,
5862                       const char *field_name,
5863                       VEC(int) *inf_num,
5864                       int mi_only)
5865 {
5866   struct cleanup *back_to;
5867   int is_mi = ui_out_is_mi_like_p (uiout);
5868   int inf;
5869   int i;
5870
5871   /* For backward compatibility, don't display inferiors in CLI unless
5872      there are several.  Always display them for MI. */
5873   if (!is_mi && mi_only)
5874     return;
5875
5876   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
5877
5878   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
5879     {
5880       if (is_mi)
5881         {
5882           char mi_group[10];
5883
5884           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
5885           ui_out_field_string (uiout, NULL, mi_group);
5886         }
5887       else
5888         {
5889           if (i == 0)
5890             ui_out_text (uiout, " inf ");
5891           else
5892             ui_out_text (uiout, ", ");
5893         
5894           ui_out_text (uiout, plongest (inf));
5895         }
5896     }
5897
5898   do_cleanups (back_to);
5899 }
5900
5901 /* Print B to gdb_stdout.  */
5902
5903 static void
5904 print_one_breakpoint_location (struct breakpoint *b,
5905                                struct bp_location *loc,
5906                                int loc_number,
5907                                struct bp_location **last_loc,
5908                                int allflag)
5909 {
5910   struct command_line *l;
5911   static char bpenables[] = "nynny";
5912
5913   struct ui_out *uiout = current_uiout;
5914   int header_of_multiple = 0;
5915   int part_of_multiple = (loc != NULL);
5916   struct value_print_options opts;
5917
5918   get_user_print_options (&opts);
5919
5920   gdb_assert (!loc || loc_number != 0);
5921   /* See comment in print_one_breakpoint concerning treatment of
5922      breakpoints with single disabled location.  */
5923   if (loc == NULL 
5924       && (b->loc != NULL 
5925           && (b->loc->next != NULL || !b->loc->enabled)))
5926     header_of_multiple = 1;
5927   if (loc == NULL)
5928     loc = b->loc;
5929
5930   annotate_record ();
5931
5932   /* 1 */
5933   annotate_field (0);
5934   if (part_of_multiple)
5935     {
5936       char *formatted;
5937       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5938       ui_out_field_string (uiout, "number", formatted);
5939       xfree (formatted);
5940     }
5941   else
5942     {
5943       ui_out_field_int (uiout, "number", b->number);
5944     }
5945
5946   /* 2 */
5947   annotate_field (1);
5948   if (part_of_multiple)
5949     ui_out_field_skip (uiout, "type");
5950   else
5951     ui_out_field_string (uiout, "type", bptype_string (b->type));
5952
5953   /* 3 */
5954   annotate_field (2);
5955   if (part_of_multiple)
5956     ui_out_field_skip (uiout, "disp");
5957   else
5958     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5959
5960
5961   /* 4 */
5962   annotate_field (3);
5963   if (part_of_multiple)
5964     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5965   else
5966     ui_out_field_fmt (uiout, "enabled", "%c", 
5967                       bpenables[(int) b->enable_state]);
5968   ui_out_spaces (uiout, 2);
5969
5970   
5971   /* 5 and 6 */
5972   if (b->ops != NULL && b->ops->print_one != NULL)
5973     {
5974       /* Although the print_one can possibly print all locations,
5975          calling it here is not likely to get any nice result.  So,
5976          make sure there's just one location.  */
5977       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5978       b->ops->print_one (b, last_loc);
5979     }
5980   else
5981     switch (b->type)
5982       {
5983       case bp_none:
5984         internal_error (__FILE__, __LINE__,
5985                         _("print_one_breakpoint: bp_none encountered\n"));
5986         break;
5987
5988       case bp_watchpoint:
5989       case bp_hardware_watchpoint:
5990       case bp_read_watchpoint:
5991       case bp_access_watchpoint:
5992         {
5993           struct watchpoint *w = (struct watchpoint *) b;
5994
5995           /* Field 4, the address, is omitted (which makes the columns
5996              not line up too nicely with the headers, but the effect
5997              is relatively readable).  */
5998           if (opts.addressprint)
5999             ui_out_field_skip (uiout, "addr");
6000           annotate_field (5);
6001           ui_out_field_string (uiout, "what", w->exp_string);
6002         }
6003         break;
6004
6005       case bp_breakpoint:
6006       case bp_hardware_breakpoint:
6007       case bp_until:
6008       case bp_finish:
6009       case bp_longjmp:
6010       case bp_longjmp_resume:
6011       case bp_longjmp_call_dummy:
6012       case bp_exception:
6013       case bp_exception_resume:
6014       case bp_step_resume:
6015       case bp_hp_step_resume:
6016       case bp_watchpoint_scope:
6017       case bp_call_dummy:
6018       case bp_std_terminate:
6019       case bp_shlib_event:
6020       case bp_thread_event:
6021       case bp_overlay_event:
6022       case bp_longjmp_master:
6023       case bp_std_terminate_master:
6024       case bp_exception_master:
6025       case bp_tracepoint:
6026       case bp_fast_tracepoint:
6027       case bp_static_tracepoint:
6028       case bp_dprintf:
6029       case bp_jit_event:
6030       case bp_gnu_ifunc_resolver:
6031       case bp_gnu_ifunc_resolver_return:
6032         if (opts.addressprint)
6033           {
6034             annotate_field (4);
6035             if (header_of_multiple)
6036               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6037             else if (b->loc == NULL || loc->shlib_disabled)
6038               ui_out_field_string (uiout, "addr", "<PENDING>");
6039             else
6040               ui_out_field_core_addr (uiout, "addr",
6041                                       loc->gdbarch, loc->address);
6042           }
6043         annotate_field (5);
6044         if (!header_of_multiple)
6045           print_breakpoint_location (b, loc);
6046         if (b->loc)
6047           *last_loc = b->loc;
6048         break;
6049       }
6050
6051
6052   if (loc != NULL && !header_of_multiple)
6053     {
6054       struct inferior *inf;
6055       VEC(int) *inf_num = NULL;
6056       int mi_only = 1;
6057
6058       ALL_INFERIORS (inf)
6059         {
6060           if (inf->pspace == loc->pspace)
6061             VEC_safe_push (int, inf_num, inf->num);
6062         }
6063
6064         /* For backward compatibility, don't display inferiors in CLI unless
6065            there are several.  Always display for MI. */
6066         if (allflag
6067             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6068                 && (number_of_program_spaces () > 1
6069                     || number_of_inferiors () > 1)
6070                 /* LOC is for existing B, it cannot be in
6071                    moribund_locations and thus having NULL OWNER.  */
6072                 && loc->owner->type != bp_catchpoint))
6073         mi_only = 0;
6074       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6075       VEC_free (int, inf_num);
6076     }
6077
6078   if (!part_of_multiple)
6079     {
6080       if (b->thread != -1)
6081         {
6082           /* FIXME: This seems to be redundant and lost here; see the
6083              "stop only in" line a little further down.  */
6084           ui_out_text (uiout, " thread ");
6085           ui_out_field_int (uiout, "thread", b->thread);
6086         }
6087       else if (b->task != 0)
6088         {
6089           ui_out_text (uiout, " task ");
6090           ui_out_field_int (uiout, "task", b->task);
6091         }
6092     }
6093
6094   ui_out_text (uiout, "\n");
6095
6096   if (!part_of_multiple)
6097     b->ops->print_one_detail (b, uiout);
6098
6099   if (part_of_multiple && frame_id_p (b->frame_id))
6100     {
6101       annotate_field (6);
6102       ui_out_text (uiout, "\tstop only in stack frame at ");
6103       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6104          the frame ID.  */
6105       ui_out_field_core_addr (uiout, "frame",
6106                               b->gdbarch, b->frame_id.stack_addr);
6107       ui_out_text (uiout, "\n");
6108     }
6109   
6110   if (!part_of_multiple && b->cond_string)
6111     {
6112       annotate_field (7);
6113       if (is_tracepoint (b))
6114         ui_out_text (uiout, "\ttrace only if ");
6115       else
6116         ui_out_text (uiout, "\tstop only if ");
6117       ui_out_field_string (uiout, "cond", b->cond_string);
6118
6119       /* Print whether the target is doing the breakpoint's condition
6120          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6121       if (is_breakpoint (b)
6122           && breakpoint_condition_evaluation_mode ()
6123           == condition_evaluation_target)
6124         {
6125           ui_out_text (uiout, " (");
6126           ui_out_field_string (uiout, "evaluated-by",
6127                                bp_condition_evaluator (b));
6128           ui_out_text (uiout, " evals)");
6129         }
6130       ui_out_text (uiout, "\n");
6131     }
6132
6133   if (!part_of_multiple && b->thread != -1)
6134     {
6135       /* FIXME should make an annotation for this.  */
6136       ui_out_text (uiout, "\tstop only in thread ");
6137       ui_out_field_int (uiout, "thread", b->thread);
6138       ui_out_text (uiout, "\n");
6139     }
6140   
6141   if (!part_of_multiple)
6142     {
6143       if (b->hit_count)
6144         {
6145           /* FIXME should make an annotation for this.  */
6146           if (is_catchpoint (b))
6147             ui_out_text (uiout, "\tcatchpoint");
6148           else if (is_tracepoint (b))
6149             ui_out_text (uiout, "\ttracepoint");
6150           else
6151             ui_out_text (uiout, "\tbreakpoint");
6152           ui_out_text (uiout, " already hit ");
6153           ui_out_field_int (uiout, "times", b->hit_count);
6154           if (b->hit_count == 1)
6155             ui_out_text (uiout, " time\n");
6156           else
6157             ui_out_text (uiout, " times\n");
6158         }
6159       else
6160         {
6161           /* Output the count also if it is zero, but only if this is mi.  */
6162           if (ui_out_is_mi_like_p (uiout))
6163             ui_out_field_int (uiout, "times", b->hit_count);
6164         }
6165     }
6166
6167   if (!part_of_multiple && b->ignore_count)
6168     {
6169       annotate_field (8);
6170       ui_out_text (uiout, "\tignore next ");
6171       ui_out_field_int (uiout, "ignore", b->ignore_count);
6172       ui_out_text (uiout, " hits\n");
6173     }
6174
6175   /* Note that an enable count of 1 corresponds to "enable once"
6176      behavior, which is reported by the combination of enablement and
6177      disposition, so we don't need to mention it here.  */
6178   if (!part_of_multiple && b->enable_count > 1)
6179     {
6180       annotate_field (8);
6181       ui_out_text (uiout, "\tdisable after ");
6182       /* Tweak the wording to clarify that ignore and enable counts
6183          are distinct, and have additive effect.  */
6184       if (b->ignore_count)
6185         ui_out_text (uiout, "additional ");
6186       else
6187         ui_out_text (uiout, "next ");
6188       ui_out_field_int (uiout, "enable", b->enable_count);
6189       ui_out_text (uiout, " hits\n");
6190     }
6191
6192   if (!part_of_multiple && is_tracepoint (b))
6193     {
6194       struct tracepoint *tp = (struct tracepoint *) b;
6195
6196       if (tp->traceframe_usage)
6197         {
6198           ui_out_text (uiout, "\ttrace buffer usage ");
6199           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6200           ui_out_text (uiout, " bytes\n");
6201         }
6202     }
6203
6204   l = b->commands ? b->commands->commands : NULL;
6205   if (!part_of_multiple && l)
6206     {
6207       struct cleanup *script_chain;
6208
6209       annotate_field (9);
6210       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6211       print_command_lines (uiout, l, 4);
6212       do_cleanups (script_chain);
6213     }
6214
6215   if (is_tracepoint (b))
6216     {
6217       struct tracepoint *t = (struct tracepoint *) b;
6218
6219       if (!part_of_multiple && t->pass_count)
6220         {
6221           annotate_field (10);
6222           ui_out_text (uiout, "\tpass count ");
6223           ui_out_field_int (uiout, "pass", t->pass_count);
6224           ui_out_text (uiout, " \n");
6225         }
6226
6227       /* Don't display it when tracepoint or tracepoint location is
6228          pending.   */
6229       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6230         {
6231           annotate_field (11);
6232
6233           if (ui_out_is_mi_like_p (uiout))
6234             ui_out_field_string (uiout, "installed",
6235                                  loc->inserted ? "y" : "n");
6236           else
6237             {
6238               if (loc->inserted)
6239                 ui_out_text (uiout, "\t");
6240               else
6241                 ui_out_text (uiout, "\tnot ");
6242               ui_out_text (uiout, "installed on target\n");
6243             }
6244         }
6245     }
6246
6247   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6248     {
6249       if (is_watchpoint (b))
6250         {
6251           struct watchpoint *w = (struct watchpoint *) b;
6252
6253           ui_out_field_string (uiout, "original-location", w->exp_string);
6254         }
6255       else if (b->addr_string)
6256         ui_out_field_string (uiout, "original-location", b->addr_string);
6257     }
6258 }
6259
6260 static void
6261 print_one_breakpoint (struct breakpoint *b,
6262                       struct bp_location **last_loc, 
6263                       int allflag)
6264 {
6265   struct cleanup *bkpt_chain;
6266   struct ui_out *uiout = current_uiout;
6267
6268   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6269
6270   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6271   do_cleanups (bkpt_chain);
6272
6273   /* If this breakpoint has custom print function,
6274      it's already printed.  Otherwise, print individual
6275      locations, if any.  */
6276   if (b->ops == NULL || b->ops->print_one == NULL)
6277     {
6278       /* If breakpoint has a single location that is disabled, we
6279          print it as if it had several locations, since otherwise it's
6280          hard to represent "breakpoint enabled, location disabled"
6281          situation.
6282
6283          Note that while hardware watchpoints have several locations
6284          internally, that's not a property exposed to user.  */
6285       if (b->loc 
6286           && !is_hardware_watchpoint (b)
6287           && (b->loc->next || !b->loc->enabled))
6288         {
6289           struct bp_location *loc;
6290           int n = 1;
6291
6292           for (loc = b->loc; loc; loc = loc->next, ++n)
6293             {
6294               struct cleanup *inner2 =
6295                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6296               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6297               do_cleanups (inner2);
6298             }
6299         }
6300     }
6301 }
6302
6303 static int
6304 breakpoint_address_bits (struct breakpoint *b)
6305 {
6306   int print_address_bits = 0;
6307   struct bp_location *loc;
6308
6309   for (loc = b->loc; loc; loc = loc->next)
6310     {
6311       int addr_bit;
6312
6313       /* Software watchpoints that aren't watching memory don't have
6314          an address to print.  */
6315       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6316         continue;
6317
6318       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6319       if (addr_bit > print_address_bits)
6320         print_address_bits = addr_bit;
6321     }
6322
6323   return print_address_bits;
6324 }
6325
6326 struct captured_breakpoint_query_args
6327   {
6328     int bnum;
6329   };
6330
6331 static int
6332 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6333 {
6334   struct captured_breakpoint_query_args *args = data;
6335   struct breakpoint *b;
6336   struct bp_location *dummy_loc = NULL;
6337
6338   ALL_BREAKPOINTS (b)
6339     {
6340       if (args->bnum == b->number)
6341         {
6342           print_one_breakpoint (b, &dummy_loc, 0);
6343           return GDB_RC_OK;
6344         }
6345     }
6346   return GDB_RC_NONE;
6347 }
6348
6349 enum gdb_rc
6350 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6351                       char **error_message)
6352 {
6353   struct captured_breakpoint_query_args args;
6354
6355   args.bnum = bnum;
6356   /* For the moment we don't trust print_one_breakpoint() to not throw
6357      an error.  */
6358   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6359                                  error_message, RETURN_MASK_ALL) < 0)
6360     return GDB_RC_FAIL;
6361   else
6362     return GDB_RC_OK;
6363 }
6364
6365 /* Return true if this breakpoint was set by the user, false if it is
6366    internal or momentary.  */
6367
6368 int
6369 user_breakpoint_p (struct breakpoint *b)
6370 {
6371   return b->number > 0;
6372 }
6373
6374 /* Print information on user settable breakpoint (watchpoint, etc)
6375    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6376    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6377    FILTER is non-NULL, call it on each breakpoint and only include the
6378    ones for which it returns non-zero.  Return the total number of
6379    breakpoints listed.  */
6380
6381 static int
6382 breakpoint_1 (char *args, int allflag, 
6383               int (*filter) (const struct breakpoint *))
6384 {
6385   struct breakpoint *b;
6386   struct bp_location *last_loc = NULL;
6387   int nr_printable_breakpoints;
6388   struct cleanup *bkpttbl_chain;
6389   struct value_print_options opts;
6390   int print_address_bits = 0;
6391   int print_type_col_width = 14;
6392   struct ui_out *uiout = current_uiout;
6393
6394   get_user_print_options (&opts);
6395
6396   /* Compute the number of rows in the table, as well as the size
6397      required for address fields.  */
6398   nr_printable_breakpoints = 0;
6399   ALL_BREAKPOINTS (b)
6400     {
6401       /* If we have a filter, only list the breakpoints it accepts.  */
6402       if (filter && !filter (b))
6403         continue;
6404
6405       /* If we have an "args" string, it is a list of breakpoints to 
6406          accept.  Skip the others.  */
6407       if (args != NULL && *args != '\0')
6408         {
6409           if (allflag && parse_and_eval_long (args) != b->number)
6410             continue;
6411           if (!allflag && !number_is_in_list (args, b->number))
6412             continue;
6413         }
6414
6415       if (allflag || user_breakpoint_p (b))
6416         {
6417           int addr_bit, type_len;
6418
6419           addr_bit = breakpoint_address_bits (b);
6420           if (addr_bit > print_address_bits)
6421             print_address_bits = addr_bit;
6422
6423           type_len = strlen (bptype_string (b->type));
6424           if (type_len > print_type_col_width)
6425             print_type_col_width = type_len;
6426
6427           nr_printable_breakpoints++;
6428         }
6429     }
6430
6431   if (opts.addressprint)
6432     bkpttbl_chain 
6433       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6434                                              nr_printable_breakpoints,
6435                                              "BreakpointTable");
6436   else
6437     bkpttbl_chain 
6438       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6439                                              nr_printable_breakpoints,
6440                                              "BreakpointTable");
6441
6442   if (nr_printable_breakpoints > 0)
6443     annotate_breakpoints_headers ();
6444   if (nr_printable_breakpoints > 0)
6445     annotate_field (0);
6446   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6447   if (nr_printable_breakpoints > 0)
6448     annotate_field (1);
6449   ui_out_table_header (uiout, print_type_col_width, ui_left,
6450                        "type", "Type");                         /* 2 */
6451   if (nr_printable_breakpoints > 0)
6452     annotate_field (2);
6453   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6454   if (nr_printable_breakpoints > 0)
6455     annotate_field (3);
6456   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6457   if (opts.addressprint)
6458     {
6459       if (nr_printable_breakpoints > 0)
6460         annotate_field (4);
6461       if (print_address_bits <= 32)
6462         ui_out_table_header (uiout, 10, ui_left, 
6463                              "addr", "Address");                /* 5 */
6464       else
6465         ui_out_table_header (uiout, 18, ui_left, 
6466                              "addr", "Address");                /* 5 */
6467     }
6468   if (nr_printable_breakpoints > 0)
6469     annotate_field (5);
6470   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6471   ui_out_table_body (uiout);
6472   if (nr_printable_breakpoints > 0)
6473     annotate_breakpoints_table ();
6474
6475   ALL_BREAKPOINTS (b)
6476     {
6477       QUIT;
6478       /* If we have a filter, only list the breakpoints it accepts.  */
6479       if (filter && !filter (b))
6480         continue;
6481
6482       /* If we have an "args" string, it is a list of breakpoints to 
6483          accept.  Skip the others.  */
6484
6485       if (args != NULL && *args != '\0')
6486         {
6487           if (allflag)  /* maintenance info breakpoint */
6488             {
6489               if (parse_and_eval_long (args) != b->number)
6490                 continue;
6491             }
6492           else          /* all others */
6493             {
6494               if (!number_is_in_list (args, b->number))
6495                 continue;
6496             }
6497         }
6498       /* We only print out user settable breakpoints unless the
6499          allflag is set.  */
6500       if (allflag || user_breakpoint_p (b))
6501         print_one_breakpoint (b, &last_loc, allflag);
6502     }
6503
6504   do_cleanups (bkpttbl_chain);
6505
6506   if (nr_printable_breakpoints == 0)
6507     {
6508       /* If there's a filter, let the caller decide how to report
6509          empty list.  */
6510       if (!filter)
6511         {
6512           if (args == NULL || *args == '\0')
6513             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6514           else
6515             ui_out_message (uiout, 0, 
6516                             "No breakpoint or watchpoint matching '%s'.\n",
6517                             args);
6518         }
6519     }
6520   else
6521     {
6522       if (last_loc && !server_command)
6523         set_next_address (last_loc->gdbarch, last_loc->address);
6524     }
6525
6526   /* FIXME?  Should this be moved up so that it is only called when
6527      there have been breakpoints? */
6528   annotate_breakpoints_table_end ();
6529
6530   return nr_printable_breakpoints;
6531 }
6532
6533 /* Display the value of default-collect in a way that is generally
6534    compatible with the breakpoint list.  */
6535
6536 static void
6537 default_collect_info (void)
6538 {
6539   struct ui_out *uiout = current_uiout;
6540
6541   /* If it has no value (which is frequently the case), say nothing; a
6542      message like "No default-collect." gets in user's face when it's
6543      not wanted.  */
6544   if (!*default_collect)
6545     return;
6546
6547   /* The following phrase lines up nicely with per-tracepoint collect
6548      actions.  */
6549   ui_out_text (uiout, "default collect ");
6550   ui_out_field_string (uiout, "default-collect", default_collect);
6551   ui_out_text (uiout, " \n");
6552 }
6553   
6554 static void
6555 breakpoints_info (char *args, int from_tty)
6556 {
6557   breakpoint_1 (args, 0, NULL);
6558
6559   default_collect_info ();
6560 }
6561
6562 static void
6563 watchpoints_info (char *args, int from_tty)
6564 {
6565   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6566   struct ui_out *uiout = current_uiout;
6567
6568   if (num_printed == 0)
6569     {
6570       if (args == NULL || *args == '\0')
6571         ui_out_message (uiout, 0, "No watchpoints.\n");
6572       else
6573         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6574     }
6575 }
6576
6577 static void
6578 maintenance_info_breakpoints (char *args, int from_tty)
6579 {
6580   breakpoint_1 (args, 1, NULL);
6581
6582   default_collect_info ();
6583 }
6584
6585 static int
6586 breakpoint_has_pc (struct breakpoint *b,
6587                    struct program_space *pspace,
6588                    CORE_ADDR pc, struct obj_section *section)
6589 {
6590   struct bp_location *bl = b->loc;
6591
6592   for (; bl; bl = bl->next)
6593     {
6594       if (bl->pspace == pspace
6595           && bl->address == pc
6596           && (!overlay_debugging || bl->section == section))
6597         return 1;         
6598     }
6599   return 0;
6600 }
6601
6602 /* Print a message describing any user-breakpoints set at PC.  This
6603    concerns with logical breakpoints, so we match program spaces, not
6604    address spaces.  */
6605
6606 static void
6607 describe_other_breakpoints (struct gdbarch *gdbarch,
6608                             struct program_space *pspace, CORE_ADDR pc,
6609                             struct obj_section *section, int thread)
6610 {
6611   int others = 0;
6612   struct breakpoint *b;
6613
6614   ALL_BREAKPOINTS (b)
6615     others += (user_breakpoint_p (b)
6616                && breakpoint_has_pc (b, pspace, pc, section));
6617   if (others > 0)
6618     {
6619       if (others == 1)
6620         printf_filtered (_("Note: breakpoint "));
6621       else /* if (others == ???) */
6622         printf_filtered (_("Note: breakpoints "));
6623       ALL_BREAKPOINTS (b)
6624         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6625           {
6626             others--;
6627             printf_filtered ("%d", b->number);
6628             if (b->thread == -1 && thread != -1)
6629               printf_filtered (" (all threads)");
6630             else if (b->thread != -1)
6631               printf_filtered (" (thread %d)", b->thread);
6632             printf_filtered ("%s%s ",
6633                              ((b->enable_state == bp_disabled
6634                                || b->enable_state == bp_call_disabled)
6635                               ? " (disabled)"
6636                               : b->enable_state == bp_permanent 
6637                               ? " (permanent)"
6638                               : ""),
6639                              (others > 1) ? "," 
6640                              : ((others == 1) ? " and" : ""));
6641           }
6642       printf_filtered (_("also set at pc "));
6643       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6644       printf_filtered (".\n");
6645     }
6646 }
6647 \f
6648
6649 /* Return true iff it is meaningful to use the address member of
6650    BPT.  For some breakpoint types, the address member is irrelevant
6651    and it makes no sense to attempt to compare it to other addresses
6652    (or use it for any other purpose either).
6653
6654    More specifically, each of the following breakpoint types will
6655    always have a zero valued address and we don't want to mark
6656    breakpoints of any of these types to be a duplicate of an actual
6657    breakpoint at address zero:
6658
6659       bp_watchpoint
6660       bp_catchpoint
6661
6662 */
6663
6664 static int
6665 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6666 {
6667   enum bptype type = bpt->type;
6668
6669   return (type != bp_watchpoint && type != bp_catchpoint);
6670 }
6671
6672 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6673    true if LOC1 and LOC2 represent the same watchpoint location.  */
6674
6675 static int
6676 watchpoint_locations_match (struct bp_location *loc1, 
6677                             struct bp_location *loc2)
6678 {
6679   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6680   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6681
6682   /* Both of them must exist.  */
6683   gdb_assert (w1 != NULL);
6684   gdb_assert (w2 != NULL);
6685
6686   /* If the target can evaluate the condition expression in hardware,
6687      then we we need to insert both watchpoints even if they are at
6688      the same place.  Otherwise the watchpoint will only trigger when
6689      the condition of whichever watchpoint was inserted evaluates to
6690      true, not giving a chance for GDB to check the condition of the
6691      other watchpoint.  */
6692   if ((w1->cond_exp
6693        && target_can_accel_watchpoint_condition (loc1->address, 
6694                                                  loc1->length,
6695                                                  loc1->watchpoint_type,
6696                                                  w1->cond_exp))
6697       || (w2->cond_exp
6698           && target_can_accel_watchpoint_condition (loc2->address, 
6699                                                     loc2->length,
6700                                                     loc2->watchpoint_type,
6701                                                     w2->cond_exp)))
6702     return 0;
6703
6704   /* Note that this checks the owner's type, not the location's.  In
6705      case the target does not support read watchpoints, but does
6706      support access watchpoints, we'll have bp_read_watchpoint
6707      watchpoints with hw_access locations.  Those should be considered
6708      duplicates of hw_read locations.  The hw_read locations will
6709      become hw_access locations later.  */
6710   return (loc1->owner->type == loc2->owner->type
6711           && loc1->pspace->aspace == loc2->pspace->aspace
6712           && loc1->address == loc2->address
6713           && loc1->length == loc2->length);
6714 }
6715
6716 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6717    same breakpoint location.  In most targets, this can only be true
6718    if ASPACE1 matches ASPACE2.  On targets that have global
6719    breakpoints, the address space doesn't really matter.  */
6720
6721 static int
6722 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6723                           struct address_space *aspace2, CORE_ADDR addr2)
6724 {
6725   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6726            || aspace1 == aspace2)
6727           && addr1 == addr2);
6728 }
6729
6730 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6731    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6732    matches ASPACE2.  On targets that have global breakpoints, the address
6733    space doesn't really matter.  */
6734
6735 static int
6736 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6737                                 int len1, struct address_space *aspace2,
6738                                 CORE_ADDR addr2)
6739 {
6740   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6741            || aspace1 == aspace2)
6742           && addr2 >= addr1 && addr2 < addr1 + len1);
6743 }
6744
6745 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6746    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6747    matches the breakpoint's address space.  On targets that have global
6748    breakpoints, the address space doesn't really matter.  */
6749
6750 static int
6751 breakpoint_location_address_match (struct bp_location *bl,
6752                                    struct address_space *aspace,
6753                                    CORE_ADDR addr)
6754 {
6755   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6756                                     aspace, addr)
6757           || (bl->length
6758               && breakpoint_address_match_range (bl->pspace->aspace,
6759                                                  bl->address, bl->length,
6760                                                  aspace, addr)));
6761 }
6762
6763 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6764    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6765    true, otherwise returns false.  */
6766
6767 static int
6768 tracepoint_locations_match (struct bp_location *loc1,
6769                             struct bp_location *loc2)
6770 {
6771   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6772     /* Since tracepoint locations are never duplicated with others', tracepoint
6773        locations at the same address of different tracepoints are regarded as
6774        different locations.  */
6775     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6776   else
6777     return 0;
6778 }
6779
6780 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6781    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6782    represent the same location.  */
6783
6784 static int
6785 breakpoint_locations_match (struct bp_location *loc1, 
6786                             struct bp_location *loc2)
6787 {
6788   int hw_point1, hw_point2;
6789
6790   /* Both of them must not be in moribund_locations.  */
6791   gdb_assert (loc1->owner != NULL);
6792   gdb_assert (loc2->owner != NULL);
6793
6794   hw_point1 = is_hardware_watchpoint (loc1->owner);
6795   hw_point2 = is_hardware_watchpoint (loc2->owner);
6796
6797   if (hw_point1 != hw_point2)
6798     return 0;
6799   else if (hw_point1)
6800     return watchpoint_locations_match (loc1, loc2);
6801   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6802     return tracepoint_locations_match (loc1, loc2);
6803   else
6804     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6805     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6806                                      loc2->pspace->aspace, loc2->address)
6807             && loc1->length == loc2->length);
6808 }
6809
6810 static void
6811 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6812                                int bnum, int have_bnum)
6813 {
6814   /* The longest string possibly returned by hex_string_custom
6815      is 50 chars.  These must be at least that big for safety.  */
6816   char astr1[64];
6817   char astr2[64];
6818
6819   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6820   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6821   if (have_bnum)
6822     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6823              bnum, astr1, astr2);
6824   else
6825     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6826 }
6827
6828 /* Adjust a breakpoint's address to account for architectural
6829    constraints on breakpoint placement.  Return the adjusted address.
6830    Note: Very few targets require this kind of adjustment.  For most
6831    targets, this function is simply the identity function.  */
6832
6833 static CORE_ADDR
6834 adjust_breakpoint_address (struct gdbarch *gdbarch,
6835                            CORE_ADDR bpaddr, enum bptype bptype)
6836 {
6837   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6838     {
6839       /* Very few targets need any kind of breakpoint adjustment.  */
6840       return bpaddr;
6841     }
6842   else if (bptype == bp_watchpoint
6843            || bptype == bp_hardware_watchpoint
6844            || bptype == bp_read_watchpoint
6845            || bptype == bp_access_watchpoint
6846            || bptype == bp_catchpoint)
6847     {
6848       /* Watchpoints and the various bp_catch_* eventpoints should not
6849          have their addresses modified.  */
6850       return bpaddr;
6851     }
6852   else
6853     {
6854       CORE_ADDR adjusted_bpaddr;
6855
6856       /* Some targets have architectural constraints on the placement
6857          of breakpoint instructions.  Obtain the adjusted address.  */
6858       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6859
6860       /* An adjusted breakpoint address can significantly alter
6861          a user's expectations.  Print a warning if an adjustment
6862          is required.  */
6863       if (adjusted_bpaddr != bpaddr)
6864         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6865
6866       return adjusted_bpaddr;
6867     }
6868 }
6869
6870 void
6871 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6872                   struct breakpoint *owner)
6873 {
6874   memset (loc, 0, sizeof (*loc));
6875
6876   gdb_assert (ops != NULL);
6877
6878   loc->ops = ops;
6879   loc->owner = owner;
6880   loc->cond = NULL;
6881   loc->cond_bytecode = NULL;
6882   loc->shlib_disabled = 0;
6883   loc->enabled = 1;
6884
6885   switch (owner->type)
6886     {
6887     case bp_breakpoint:
6888     case bp_until:
6889     case bp_finish:
6890     case bp_longjmp:
6891     case bp_longjmp_resume:
6892     case bp_longjmp_call_dummy:
6893     case bp_exception:
6894     case bp_exception_resume:
6895     case bp_step_resume:
6896     case bp_hp_step_resume:
6897     case bp_watchpoint_scope:
6898     case bp_call_dummy:
6899     case bp_std_terminate:
6900     case bp_shlib_event:
6901     case bp_thread_event:
6902     case bp_overlay_event:
6903     case bp_jit_event:
6904     case bp_longjmp_master:
6905     case bp_std_terminate_master:
6906     case bp_exception_master:
6907     case bp_gnu_ifunc_resolver:
6908     case bp_gnu_ifunc_resolver_return:
6909     case bp_dprintf:
6910       loc->loc_type = bp_loc_software_breakpoint;
6911       mark_breakpoint_location_modified (loc);
6912       break;
6913     case bp_hardware_breakpoint:
6914       loc->loc_type = bp_loc_hardware_breakpoint;
6915       mark_breakpoint_location_modified (loc);
6916       break;
6917     case bp_hardware_watchpoint:
6918     case bp_read_watchpoint:
6919     case bp_access_watchpoint:
6920       loc->loc_type = bp_loc_hardware_watchpoint;
6921       break;
6922     case bp_watchpoint:
6923     case bp_catchpoint:
6924     case bp_tracepoint:
6925     case bp_fast_tracepoint:
6926     case bp_static_tracepoint:
6927       loc->loc_type = bp_loc_other;
6928       break;
6929     default:
6930       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6931     }
6932
6933   loc->refc = 1;
6934 }
6935
6936 /* Allocate a struct bp_location.  */
6937
6938 static struct bp_location *
6939 allocate_bp_location (struct breakpoint *bpt)
6940 {
6941   return bpt->ops->allocate_location (bpt);
6942 }
6943
6944 static void
6945 free_bp_location (struct bp_location *loc)
6946 {
6947   loc->ops->dtor (loc);
6948   xfree (loc);
6949 }
6950
6951 /* Increment reference count.  */
6952
6953 static void
6954 incref_bp_location (struct bp_location *bl)
6955 {
6956   ++bl->refc;
6957 }
6958
6959 /* Decrement reference count.  If the reference count reaches 0,
6960    destroy the bp_location.  Sets *BLP to NULL.  */
6961
6962 static void
6963 decref_bp_location (struct bp_location **blp)
6964 {
6965   gdb_assert ((*blp)->refc > 0);
6966
6967   if (--(*blp)->refc == 0)
6968     free_bp_location (*blp);
6969   *blp = NULL;
6970 }
6971
6972 /* Add breakpoint B at the end of the global breakpoint chain.  */
6973
6974 static void
6975 add_to_breakpoint_chain (struct breakpoint *b)
6976 {
6977   struct breakpoint *b1;
6978
6979   /* Add this breakpoint to the end of the chain so that a list of
6980      breakpoints will come out in order of increasing numbers.  */
6981
6982   b1 = breakpoint_chain;
6983   if (b1 == 0)
6984     breakpoint_chain = b;
6985   else
6986     {
6987       while (b1->next)
6988         b1 = b1->next;
6989       b1->next = b;
6990     }
6991 }
6992
6993 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6994
6995 static void
6996 init_raw_breakpoint_without_location (struct breakpoint *b,
6997                                       struct gdbarch *gdbarch,
6998                                       enum bptype bptype,
6999                                       const struct breakpoint_ops *ops)
7000 {
7001   memset (b, 0, sizeof (*b));
7002
7003   gdb_assert (ops != NULL);
7004
7005   b->ops = ops;
7006   b->type = bptype;
7007   b->gdbarch = gdbarch;
7008   b->language = current_language->la_language;
7009   b->input_radix = input_radix;
7010   b->thread = -1;
7011   b->enable_state = bp_enabled;
7012   b->next = 0;
7013   b->silent = 0;
7014   b->ignore_count = 0;
7015   b->commands = NULL;
7016   b->frame_id = null_frame_id;
7017   b->condition_not_parsed = 0;
7018   b->py_bp_object = NULL;
7019   b->related_breakpoint = b;
7020 }
7021
7022 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7023    that has type BPTYPE and has no locations as yet.  */
7024
7025 static struct breakpoint *
7026 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7027                                      enum bptype bptype,
7028                                      const struct breakpoint_ops *ops)
7029 {
7030   struct breakpoint *b = XNEW (struct breakpoint);
7031
7032   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7033   add_to_breakpoint_chain (b);
7034   return b;
7035 }
7036
7037 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7038    resolutions should be made as the user specified the location explicitly
7039    enough.  */
7040
7041 static void
7042 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7043 {
7044   gdb_assert (loc->owner != NULL);
7045
7046   if (loc->owner->type == bp_breakpoint
7047       || loc->owner->type == bp_hardware_breakpoint
7048       || is_tracepoint (loc->owner))
7049     {
7050       int is_gnu_ifunc;
7051       const char *function_name;
7052       CORE_ADDR func_addr;
7053
7054       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7055                                           &func_addr, NULL, &is_gnu_ifunc);
7056
7057       if (is_gnu_ifunc && !explicit_loc)
7058         {
7059           struct breakpoint *b = loc->owner;
7060
7061           gdb_assert (loc->pspace == current_program_space);
7062           if (gnu_ifunc_resolve_name (function_name,
7063                                       &loc->requested_address))
7064             {
7065               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7066               loc->address = adjust_breakpoint_address (loc->gdbarch,
7067                                                         loc->requested_address,
7068                                                         b->type);
7069             }
7070           else if (b->type == bp_breakpoint && b->loc == loc
7071                    && loc->next == NULL && b->related_breakpoint == b)
7072             {
7073               /* Create only the whole new breakpoint of this type but do not
7074                  mess more complicated breakpoints with multiple locations.  */
7075               b->type = bp_gnu_ifunc_resolver;
7076               /* Remember the resolver's address for use by the return
7077                  breakpoint.  */
7078               loc->related_address = func_addr;
7079             }
7080         }
7081
7082       if (function_name)
7083         loc->function_name = xstrdup (function_name);
7084     }
7085 }
7086
7087 /* Attempt to determine architecture of location identified by SAL.  */
7088 struct gdbarch *
7089 get_sal_arch (struct symtab_and_line sal)
7090 {
7091   if (sal.section)
7092     return get_objfile_arch (sal.section->objfile);
7093   if (sal.symtab)
7094     return get_objfile_arch (sal.symtab->objfile);
7095
7096   return NULL;
7097 }
7098
7099 /* Low level routine for partially initializing a breakpoint of type
7100    BPTYPE.  The newly created breakpoint's address, section, source
7101    file name, and line number are provided by SAL.
7102
7103    It is expected that the caller will complete the initialization of
7104    the newly created breakpoint struct as well as output any status
7105    information regarding the creation of a new breakpoint.  */
7106
7107 static void
7108 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7109                      struct symtab_and_line sal, enum bptype bptype,
7110                      const struct breakpoint_ops *ops)
7111 {
7112   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7113
7114   add_location_to_breakpoint (b, &sal);
7115
7116   if (bptype != bp_catchpoint)
7117     gdb_assert (sal.pspace != NULL);
7118
7119   /* Store the program space that was used to set the breakpoint,
7120      except for ordinary breakpoints, which are independent of the
7121      program space.  */
7122   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7123     b->pspace = sal.pspace;
7124 }
7125
7126 /* set_raw_breakpoint is a low level routine for allocating and
7127    partially initializing a breakpoint of type BPTYPE.  The newly
7128    created breakpoint's address, section, source file name, and line
7129    number are provided by SAL.  The newly created and partially
7130    initialized breakpoint is added to the breakpoint chain and
7131    is also returned as the value of this function.
7132
7133    It is expected that the caller will complete the initialization of
7134    the newly created breakpoint struct as well as output any status
7135    information regarding the creation of a new breakpoint.  In
7136    particular, set_raw_breakpoint does NOT set the breakpoint
7137    number!  Care should be taken to not allow an error to occur
7138    prior to completing the initialization of the breakpoint.  If this
7139    should happen, a bogus breakpoint will be left on the chain.  */
7140
7141 struct breakpoint *
7142 set_raw_breakpoint (struct gdbarch *gdbarch,
7143                     struct symtab_and_line sal, enum bptype bptype,
7144                     const struct breakpoint_ops *ops)
7145 {
7146   struct breakpoint *b = XNEW (struct breakpoint);
7147
7148   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7149   add_to_breakpoint_chain (b);
7150   return b;
7151 }
7152
7153
7154 /* Note that the breakpoint object B describes a permanent breakpoint
7155    instruction, hard-wired into the inferior's code.  */
7156 void
7157 make_breakpoint_permanent (struct breakpoint *b)
7158 {
7159   struct bp_location *bl;
7160
7161   b->enable_state = bp_permanent;
7162
7163   /* By definition, permanent breakpoints are already present in the
7164      code.  Mark all locations as inserted.  For now,
7165      make_breakpoint_permanent is called in just one place, so it's
7166      hard to say if it's reasonable to have permanent breakpoint with
7167      multiple locations or not, but it's easy to implement.  */
7168   for (bl = b->loc; bl; bl = bl->next)
7169     bl->inserted = 1;
7170 }
7171
7172 /* Call this routine when stepping and nexting to enable a breakpoint
7173    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7174    initiated the operation.  */
7175
7176 void
7177 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7178 {
7179   struct breakpoint *b, *b_tmp;
7180   int thread = tp->num;
7181
7182   /* To avoid having to rescan all objfile symbols at every step,
7183      we maintain a list of continually-inserted but always disabled
7184      longjmp "master" breakpoints.  Here, we simply create momentary
7185      clones of those and enable them for the requested thread.  */
7186   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7187     if (b->pspace == current_program_space
7188         && (b->type == bp_longjmp_master
7189             || b->type == bp_exception_master))
7190       {
7191         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7192         struct breakpoint *clone;
7193
7194         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7195            after their removal.  */
7196         clone = momentary_breakpoint_from_master (b, type,
7197                                                   &longjmp_breakpoint_ops);
7198         clone->thread = thread;
7199       }
7200
7201   tp->initiating_frame = frame;
7202 }
7203
7204 /* Delete all longjmp breakpoints from THREAD.  */
7205 void
7206 delete_longjmp_breakpoint (int thread)
7207 {
7208   struct breakpoint *b, *b_tmp;
7209
7210   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7211     if (b->type == bp_longjmp || b->type == bp_exception)
7212       {
7213         if (b->thread == thread)
7214           delete_breakpoint (b);
7215       }
7216 }
7217
7218 void
7219 delete_longjmp_breakpoint_at_next_stop (int thread)
7220 {
7221   struct breakpoint *b, *b_tmp;
7222
7223   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7224     if (b->type == bp_longjmp || b->type == bp_exception)
7225       {
7226         if (b->thread == thread)
7227           b->disposition = disp_del_at_next_stop;
7228       }
7229 }
7230
7231 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7232    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7233    pointer to any of them.  Return NULL if this system cannot place longjmp
7234    breakpoints.  */
7235
7236 struct breakpoint *
7237 set_longjmp_breakpoint_for_call_dummy (void)
7238 {
7239   struct breakpoint *b, *retval = NULL;
7240
7241   ALL_BREAKPOINTS (b)
7242     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7243       {
7244         struct breakpoint *new_b;
7245
7246         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7247                                                   &momentary_breakpoint_ops);
7248         new_b->thread = pid_to_thread_id (inferior_ptid);
7249
7250         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7251
7252         gdb_assert (new_b->related_breakpoint == new_b);
7253         if (retval == NULL)
7254           retval = new_b;
7255         new_b->related_breakpoint = retval;
7256         while (retval->related_breakpoint != new_b->related_breakpoint)
7257           retval = retval->related_breakpoint;
7258         retval->related_breakpoint = new_b;
7259       }
7260
7261   return retval;
7262 }
7263
7264 /* Verify all existing dummy frames and their associated breakpoints for
7265    THREAD.  Remove those which can no longer be found in the current frame
7266    stack.
7267
7268    You should call this function only at places where it is safe to currently
7269    unwind the whole stack.  Failed stack unwind would discard live dummy
7270    frames.  */
7271
7272 void
7273 check_longjmp_breakpoint_for_call_dummy (int thread)
7274 {
7275   struct breakpoint *b, *b_tmp;
7276
7277   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7278     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7279       {
7280         struct breakpoint *dummy_b = b->related_breakpoint;
7281
7282         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7283           dummy_b = dummy_b->related_breakpoint;
7284         if (dummy_b->type != bp_call_dummy
7285             || frame_find_by_id (dummy_b->frame_id) != NULL)
7286           continue;
7287         
7288         dummy_frame_discard (dummy_b->frame_id);
7289
7290         while (b->related_breakpoint != b)
7291           {
7292             if (b_tmp == b->related_breakpoint)
7293               b_tmp = b->related_breakpoint->next;
7294             delete_breakpoint (b->related_breakpoint);
7295           }
7296         delete_breakpoint (b);
7297       }
7298 }
7299
7300 void
7301 enable_overlay_breakpoints (void)
7302 {
7303   struct breakpoint *b;
7304
7305   ALL_BREAKPOINTS (b)
7306     if (b->type == bp_overlay_event)
7307     {
7308       b->enable_state = bp_enabled;
7309       update_global_location_list (1);
7310       overlay_events_enabled = 1;
7311     }
7312 }
7313
7314 void
7315 disable_overlay_breakpoints (void)
7316 {
7317   struct breakpoint *b;
7318
7319   ALL_BREAKPOINTS (b)
7320     if (b->type == bp_overlay_event)
7321     {
7322       b->enable_state = bp_disabled;
7323       update_global_location_list (0);
7324       overlay_events_enabled = 0;
7325     }
7326 }
7327
7328 /* Set an active std::terminate breakpoint for each std::terminate
7329    master breakpoint.  */
7330 void
7331 set_std_terminate_breakpoint (void)
7332 {
7333   struct breakpoint *b, *b_tmp;
7334
7335   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7336     if (b->pspace == current_program_space
7337         && b->type == bp_std_terminate_master)
7338       {
7339         momentary_breakpoint_from_master (b, bp_std_terminate,
7340                                           &momentary_breakpoint_ops);
7341       }
7342 }
7343
7344 /* Delete all the std::terminate breakpoints.  */
7345 void
7346 delete_std_terminate_breakpoint (void)
7347 {
7348   struct breakpoint *b, *b_tmp;
7349
7350   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7351     if (b->type == bp_std_terminate)
7352       delete_breakpoint (b);
7353 }
7354
7355 struct breakpoint *
7356 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7357 {
7358   struct breakpoint *b;
7359
7360   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7361                                   &internal_breakpoint_ops);
7362
7363   b->enable_state = bp_enabled;
7364   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7365   b->addr_string
7366     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7367
7368   update_global_location_list_nothrow (1);
7369
7370   return b;
7371 }
7372
7373 void
7374 remove_thread_event_breakpoints (void)
7375 {
7376   struct breakpoint *b, *b_tmp;
7377
7378   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7379     if (b->type == bp_thread_event
7380         && b->loc->pspace == current_program_space)
7381       delete_breakpoint (b);
7382 }
7383
7384 struct lang_and_radix
7385   {
7386     enum language lang;
7387     int radix;
7388   };
7389
7390 /* Create a breakpoint for JIT code registration and unregistration.  */
7391
7392 struct breakpoint *
7393 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7394 {
7395   struct breakpoint *b;
7396
7397   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7398                                   &internal_breakpoint_ops);
7399   update_global_location_list_nothrow (1);
7400   return b;
7401 }
7402
7403 /* Remove JIT code registration and unregistration breakpoint(s).  */
7404
7405 void
7406 remove_jit_event_breakpoints (void)
7407 {
7408   struct breakpoint *b, *b_tmp;
7409
7410   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7411     if (b->type == bp_jit_event
7412         && b->loc->pspace == current_program_space)
7413       delete_breakpoint (b);
7414 }
7415
7416 void
7417 remove_solib_event_breakpoints (void)
7418 {
7419   struct breakpoint *b, *b_tmp;
7420
7421   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7422     if (b->type == bp_shlib_event
7423         && b->loc->pspace == current_program_space)
7424       delete_breakpoint (b);
7425 }
7426
7427 struct breakpoint *
7428 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7429 {
7430   struct breakpoint *b;
7431
7432   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7433                                   &internal_breakpoint_ops);
7434   update_global_location_list_nothrow (1);
7435   return b;
7436 }
7437
7438 /* Disable any breakpoints that are on code in shared libraries.  Only
7439    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7440
7441 void
7442 disable_breakpoints_in_shlibs (void)
7443 {
7444   struct bp_location *loc, **locp_tmp;
7445
7446   ALL_BP_LOCATIONS (loc, locp_tmp)
7447   {
7448     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7449     struct breakpoint *b = loc->owner;
7450
7451     /* We apply the check to all breakpoints, including disabled for
7452        those with loc->duplicate set.  This is so that when breakpoint
7453        becomes enabled, or the duplicate is removed, gdb will try to
7454        insert all breakpoints.  If we don't set shlib_disabled here,
7455        we'll try to insert those breakpoints and fail.  */
7456     if (((b->type == bp_breakpoint)
7457          || (b->type == bp_jit_event)
7458          || (b->type == bp_hardware_breakpoint)
7459          || (is_tracepoint (b)))
7460         && loc->pspace == current_program_space
7461         && !loc->shlib_disabled
7462         && solib_name_from_address (loc->pspace, loc->address)
7463         )
7464       {
7465         loc->shlib_disabled = 1;
7466       }
7467   }
7468 }
7469
7470 /* Disable any breakpoints and tracepoints that are in an unloaded shared
7471    library.  Only apply to enabled breakpoints, disabled ones can just stay
7472    disabled.  */
7473
7474 static void
7475 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7476 {
7477   struct bp_location *loc, **locp_tmp;
7478   int disabled_shlib_breaks = 0;
7479
7480   /* SunOS a.out shared libraries are always mapped, so do not
7481      disable breakpoints; they will only be reported as unloaded
7482      through clear_solib when GDB discards its shared library
7483      list.  See clear_solib for more information.  */
7484   if (exec_bfd != NULL
7485       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7486     return;
7487
7488   ALL_BP_LOCATIONS (loc, locp_tmp)
7489   {
7490     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7491     struct breakpoint *b = loc->owner;
7492
7493     if (solib->pspace == loc->pspace
7494         && !loc->shlib_disabled
7495         && (((b->type == bp_breakpoint
7496               || b->type == bp_jit_event
7497               || b->type == bp_hardware_breakpoint)
7498              && (loc->loc_type == bp_loc_hardware_breakpoint
7499                  || loc->loc_type == bp_loc_software_breakpoint))
7500             || is_tracepoint (b))
7501         && solib_contains_address_p (solib, loc->address))
7502       {
7503         loc->shlib_disabled = 1;
7504         /* At this point, we cannot rely on remove_breakpoint
7505            succeeding so we must mark the breakpoint as not inserted
7506            to prevent future errors occurring in remove_breakpoints.  */
7507         loc->inserted = 0;
7508
7509         /* This may cause duplicate notifications for the same breakpoint.  */
7510         observer_notify_breakpoint_modified (b);
7511
7512         if (!disabled_shlib_breaks)
7513           {
7514             target_terminal_ours_for_output ();
7515             warning (_("Temporarily disabling breakpoints "
7516                        "for unloaded shared library \"%s\""),
7517                      solib->so_name);
7518           }
7519         disabled_shlib_breaks = 1;
7520       }
7521   }
7522 }
7523
7524 /* FORK & VFORK catchpoints.  */
7525
7526 /* An instance of this type is used to represent a fork or vfork
7527    catchpoint.  It includes a "struct breakpoint" as a kind of base
7528    class; users downcast to "struct breakpoint *" when needed.  A
7529    breakpoint is really of this type iff its ops pointer points to
7530    CATCH_FORK_BREAKPOINT_OPS.  */
7531
7532 struct fork_catchpoint
7533 {
7534   /* The base class.  */
7535   struct breakpoint base;
7536
7537   /* Process id of a child process whose forking triggered this
7538      catchpoint.  This field is only valid immediately after this
7539      catchpoint has triggered.  */
7540   ptid_t forked_inferior_pid;
7541 };
7542
7543 /* Implement the "insert" breakpoint_ops method for fork
7544    catchpoints.  */
7545
7546 static int
7547 insert_catch_fork (struct bp_location *bl)
7548 {
7549   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
7550 }
7551
7552 /* Implement the "remove" breakpoint_ops method for fork
7553    catchpoints.  */
7554
7555 static int
7556 remove_catch_fork (struct bp_location *bl)
7557 {
7558   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
7559 }
7560
7561 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7562    catchpoints.  */
7563
7564 static int
7565 breakpoint_hit_catch_fork (const struct bp_location *bl,
7566                            struct address_space *aspace, CORE_ADDR bp_addr,
7567                            const struct target_waitstatus *ws)
7568 {
7569   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7570
7571   if (ws->kind != TARGET_WAITKIND_FORKED)
7572     return 0;
7573
7574   c->forked_inferior_pid = ws->value.related_pid;
7575   return 1;
7576 }
7577
7578 /* Implement the "print_it" breakpoint_ops method for fork
7579    catchpoints.  */
7580
7581 static enum print_stop_action
7582 print_it_catch_fork (bpstat bs)
7583 {
7584   struct ui_out *uiout = current_uiout;
7585   struct breakpoint *b = bs->breakpoint_at;
7586   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7587
7588   annotate_catchpoint (b->number);
7589   if (b->disposition == disp_del)
7590     ui_out_text (uiout, "\nTemporary catchpoint ");
7591   else
7592     ui_out_text (uiout, "\nCatchpoint ");
7593   if (ui_out_is_mi_like_p (uiout))
7594     {
7595       ui_out_field_string (uiout, "reason",
7596                            async_reason_lookup (EXEC_ASYNC_FORK));
7597       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7598     }
7599   ui_out_field_int (uiout, "bkptno", b->number);
7600   ui_out_text (uiout, " (forked process ");
7601   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7602   ui_out_text (uiout, "), ");
7603   return PRINT_SRC_AND_LOC;
7604 }
7605
7606 /* Implement the "print_one" breakpoint_ops method for fork
7607    catchpoints.  */
7608
7609 static void
7610 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7611 {
7612   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7613   struct value_print_options opts;
7614   struct ui_out *uiout = current_uiout;
7615
7616   get_user_print_options (&opts);
7617
7618   /* Field 4, the address, is omitted (which makes the columns not
7619      line up too nicely with the headers, but the effect is relatively
7620      readable).  */
7621   if (opts.addressprint)
7622     ui_out_field_skip (uiout, "addr");
7623   annotate_field (5);
7624   ui_out_text (uiout, "fork");
7625   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7626     {
7627       ui_out_text (uiout, ", process ");
7628       ui_out_field_int (uiout, "what",
7629                         ptid_get_pid (c->forked_inferior_pid));
7630       ui_out_spaces (uiout, 1);
7631     }
7632
7633   if (ui_out_is_mi_like_p (uiout))
7634     ui_out_field_string (uiout, "catch-type", "fork");
7635 }
7636
7637 /* Implement the "print_mention" breakpoint_ops method for fork
7638    catchpoints.  */
7639
7640 static void
7641 print_mention_catch_fork (struct breakpoint *b)
7642 {
7643   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7644 }
7645
7646 /* Implement the "print_recreate" breakpoint_ops method for fork
7647    catchpoints.  */
7648
7649 static void
7650 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7651 {
7652   fprintf_unfiltered (fp, "catch fork");
7653   print_recreate_thread (b, fp);
7654 }
7655
7656 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7657
7658 static struct breakpoint_ops catch_fork_breakpoint_ops;
7659
7660 /* Implement the "insert" breakpoint_ops method for vfork
7661    catchpoints.  */
7662
7663 static int
7664 insert_catch_vfork (struct bp_location *bl)
7665 {
7666   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7667 }
7668
7669 /* Implement the "remove" breakpoint_ops method for vfork
7670    catchpoints.  */
7671
7672 static int
7673 remove_catch_vfork (struct bp_location *bl)
7674 {
7675   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7676 }
7677
7678 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7679    catchpoints.  */
7680
7681 static int
7682 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7683                             struct address_space *aspace, CORE_ADDR bp_addr,
7684                             const struct target_waitstatus *ws)
7685 {
7686   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7687
7688   if (ws->kind != TARGET_WAITKIND_VFORKED)
7689     return 0;
7690
7691   c->forked_inferior_pid = ws->value.related_pid;
7692   return 1;
7693 }
7694
7695 /* Implement the "print_it" breakpoint_ops method for vfork
7696    catchpoints.  */
7697
7698 static enum print_stop_action
7699 print_it_catch_vfork (bpstat bs)
7700 {
7701   struct ui_out *uiout = current_uiout;
7702   struct breakpoint *b = bs->breakpoint_at;
7703   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7704
7705   annotate_catchpoint (b->number);
7706   if (b->disposition == disp_del)
7707     ui_out_text (uiout, "\nTemporary catchpoint ");
7708   else
7709     ui_out_text (uiout, "\nCatchpoint ");
7710   if (ui_out_is_mi_like_p (uiout))
7711     {
7712       ui_out_field_string (uiout, "reason",
7713                            async_reason_lookup (EXEC_ASYNC_VFORK));
7714       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7715     }
7716   ui_out_field_int (uiout, "bkptno", b->number);
7717   ui_out_text (uiout, " (vforked process ");
7718   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7719   ui_out_text (uiout, "), ");
7720   return PRINT_SRC_AND_LOC;
7721 }
7722
7723 /* Implement the "print_one" breakpoint_ops method for vfork
7724    catchpoints.  */
7725
7726 static void
7727 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7728 {
7729   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7730   struct value_print_options opts;
7731   struct ui_out *uiout = current_uiout;
7732
7733   get_user_print_options (&opts);
7734   /* Field 4, the address, is omitted (which makes the columns not
7735      line up too nicely with the headers, but the effect is relatively
7736      readable).  */
7737   if (opts.addressprint)
7738     ui_out_field_skip (uiout, "addr");
7739   annotate_field (5);
7740   ui_out_text (uiout, "vfork");
7741   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7742     {
7743       ui_out_text (uiout, ", process ");
7744       ui_out_field_int (uiout, "what",
7745                         ptid_get_pid (c->forked_inferior_pid));
7746       ui_out_spaces (uiout, 1);
7747     }
7748
7749   if (ui_out_is_mi_like_p (uiout))
7750     ui_out_field_string (uiout, "catch-type", "vfork");
7751 }
7752
7753 /* Implement the "print_mention" breakpoint_ops method for vfork
7754    catchpoints.  */
7755
7756 static void
7757 print_mention_catch_vfork (struct breakpoint *b)
7758 {
7759   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7760 }
7761
7762 /* Implement the "print_recreate" breakpoint_ops method for vfork
7763    catchpoints.  */
7764
7765 static void
7766 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7767 {
7768   fprintf_unfiltered (fp, "catch vfork");
7769   print_recreate_thread (b, fp);
7770 }
7771
7772 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7773
7774 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7775
7776 /* An instance of this type is used to represent an solib catchpoint.
7777    It includes a "struct breakpoint" as a kind of base class; users
7778    downcast to "struct breakpoint *" when needed.  A breakpoint is
7779    really of this type iff its ops pointer points to
7780    CATCH_SOLIB_BREAKPOINT_OPS.  */
7781
7782 struct solib_catchpoint
7783 {
7784   /* The base class.  */
7785   struct breakpoint base;
7786
7787   /* True for "catch load", false for "catch unload".  */
7788   unsigned char is_load;
7789
7790   /* Regular expression to match, if any.  COMPILED is only valid when
7791      REGEX is non-NULL.  */
7792   char *regex;
7793   regex_t compiled;
7794 };
7795
7796 static void
7797 dtor_catch_solib (struct breakpoint *b)
7798 {
7799   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7800
7801   if (self->regex)
7802     regfree (&self->compiled);
7803   xfree (self->regex);
7804
7805   base_breakpoint_ops.dtor (b);
7806 }
7807
7808 static int
7809 insert_catch_solib (struct bp_location *ignore)
7810 {
7811   return 0;
7812 }
7813
7814 static int
7815 remove_catch_solib (struct bp_location *ignore)
7816 {
7817   return 0;
7818 }
7819
7820 static int
7821 breakpoint_hit_catch_solib (const struct bp_location *bl,
7822                             struct address_space *aspace,
7823                             CORE_ADDR bp_addr,
7824                             const struct target_waitstatus *ws)
7825 {
7826   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7827   struct breakpoint *other;
7828
7829   if (ws->kind == TARGET_WAITKIND_LOADED)
7830     return 1;
7831
7832   ALL_BREAKPOINTS (other)
7833   {
7834     struct bp_location *other_bl;
7835
7836     if (other == bl->owner)
7837       continue;
7838
7839     if (other->type != bp_shlib_event)
7840       continue;
7841
7842     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7843       continue;
7844
7845     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7846       {
7847         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7848           return 1;
7849       }
7850   }
7851
7852   return 0;
7853 }
7854
7855 static void
7856 check_status_catch_solib (struct bpstats *bs)
7857 {
7858   struct solib_catchpoint *self
7859     = (struct solib_catchpoint *) bs->breakpoint_at;
7860   int ix;
7861
7862   if (self->is_load)
7863     {
7864       struct so_list *iter;
7865
7866       for (ix = 0;
7867            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7868                         ix, iter);
7869            ++ix)
7870         {
7871           if (!self->regex
7872               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7873             return;
7874         }
7875     }
7876   else
7877     {
7878       char *iter;
7879
7880       for (ix = 0;
7881            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7882                         ix, iter);
7883            ++ix)
7884         {
7885           if (!self->regex
7886               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7887             return;
7888         }
7889     }
7890
7891   bs->stop = 0;
7892   bs->print_it = print_it_noop;
7893 }
7894
7895 static enum print_stop_action
7896 print_it_catch_solib (bpstat bs)
7897 {
7898   struct breakpoint *b = bs->breakpoint_at;
7899   struct ui_out *uiout = current_uiout;
7900
7901   annotate_catchpoint (b->number);
7902   if (b->disposition == disp_del)
7903     ui_out_text (uiout, "\nTemporary catchpoint ");
7904   else
7905     ui_out_text (uiout, "\nCatchpoint ");
7906   ui_out_field_int (uiout, "bkptno", b->number);
7907   ui_out_text (uiout, "\n");
7908   if (ui_out_is_mi_like_p (uiout))
7909     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7910   print_solib_event (1);
7911   return PRINT_SRC_AND_LOC;
7912 }
7913
7914 static void
7915 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7916 {
7917   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7918   struct value_print_options opts;
7919   struct ui_out *uiout = current_uiout;
7920   char *msg;
7921
7922   get_user_print_options (&opts);
7923   /* Field 4, the address, is omitted (which makes the columns not
7924      line up too nicely with the headers, but the effect is relatively
7925      readable).  */
7926   if (opts.addressprint)
7927     {
7928       annotate_field (4);
7929       ui_out_field_skip (uiout, "addr");
7930     }
7931
7932   annotate_field (5);
7933   if (self->is_load)
7934     {
7935       if (self->regex)
7936         msg = xstrprintf (_("load of library matching %s"), self->regex);
7937       else
7938         msg = xstrdup (_("load of library"));
7939     }
7940   else
7941     {
7942       if (self->regex)
7943         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7944       else
7945         msg = xstrdup (_("unload of library"));
7946     }
7947   ui_out_field_string (uiout, "what", msg);
7948   xfree (msg);
7949
7950   if (ui_out_is_mi_like_p (uiout))
7951     ui_out_field_string (uiout, "catch-type",
7952                          self->is_load ? "load" : "unload");
7953 }
7954
7955 static void
7956 print_mention_catch_solib (struct breakpoint *b)
7957 {
7958   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7959
7960   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7961                    self->is_load ? "load" : "unload");
7962 }
7963
7964 static void
7965 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7966 {
7967   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7968
7969   fprintf_unfiltered (fp, "%s %s",
7970                       b->disposition == disp_del ? "tcatch" : "catch",
7971                       self->is_load ? "load" : "unload");
7972   if (self->regex)
7973     fprintf_unfiltered (fp, " %s", self->regex);
7974   fprintf_unfiltered (fp, "\n");
7975 }
7976
7977 static struct breakpoint_ops catch_solib_breakpoint_ops;
7978
7979 /* Shared helper function (MI and CLI) for creating and installing
7980    a shared object event catchpoint.  If IS_LOAD is non-zero then
7981    the events to be caught are load events, otherwise they are
7982    unload events.  If IS_TEMP is non-zero the catchpoint is a
7983    temporary one.  If ENABLED is non-zero the catchpoint is
7984    created in an enabled state.  */
7985
7986 void
7987 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
7988 {
7989   struct solib_catchpoint *c;
7990   struct gdbarch *gdbarch = get_current_arch ();
7991   struct cleanup *cleanup;
7992
7993   if (!arg)
7994     arg = "";
7995   arg = skip_spaces (arg);
7996
7997   c = XCNEW (struct solib_catchpoint);
7998   cleanup = make_cleanup (xfree, c);
7999
8000   if (*arg != '\0')
8001     {
8002       int errcode;
8003
8004       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8005       if (errcode != 0)
8006         {
8007           char *err = get_regcomp_error (errcode, &c->compiled);
8008
8009           make_cleanup (xfree, err);
8010           error (_("Invalid regexp (%s): %s"), err, arg);
8011         }
8012       c->regex = xstrdup (arg);
8013     }
8014
8015   c->is_load = is_load;
8016   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8017                    &catch_solib_breakpoint_ops);
8018
8019   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8020
8021   discard_cleanups (cleanup);
8022   install_breakpoint (0, &c->base, 1);
8023 }
8024
8025 /* A helper function that does all the work for "catch load" and
8026    "catch unload".  */
8027
8028 static void
8029 catch_load_or_unload (char *arg, int from_tty, int is_load,
8030                       struct cmd_list_element *command)
8031 {
8032   int tempflag;
8033   const int enabled = 1;
8034
8035   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8036
8037   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8038 }
8039
8040 static void
8041 catch_load_command_1 (char *arg, int from_tty,
8042                       struct cmd_list_element *command)
8043 {
8044   catch_load_or_unload (arg, from_tty, 1, command);
8045 }
8046
8047 static void
8048 catch_unload_command_1 (char *arg, int from_tty,
8049                         struct cmd_list_element *command)
8050 {
8051   catch_load_or_unload (arg, from_tty, 0, command);
8052 }
8053
8054 /* An instance of this type is used to represent a syscall catchpoint.
8055    It includes a "struct breakpoint" as a kind of base class; users
8056    downcast to "struct breakpoint *" when needed.  A breakpoint is
8057    really of this type iff its ops pointer points to
8058    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8059
8060 struct syscall_catchpoint
8061 {
8062   /* The base class.  */
8063   struct breakpoint base;
8064
8065   /* Syscall numbers used for the 'catch syscall' feature.  If no
8066      syscall has been specified for filtering, its value is NULL.
8067      Otherwise, it holds a list of all syscalls to be caught.  The
8068      list elements are allocated with xmalloc.  */
8069   VEC(int) *syscalls_to_be_caught;
8070 };
8071
8072 /* Implement the "dtor" breakpoint_ops method for syscall
8073    catchpoints.  */
8074
8075 static void
8076 dtor_catch_syscall (struct breakpoint *b)
8077 {
8078   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8079
8080   VEC_free (int, c->syscalls_to_be_caught);
8081
8082   base_breakpoint_ops.dtor (b);
8083 }
8084
8085 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8086
8087 struct catch_syscall_inferior_data
8088 {
8089   /* We keep a count of the number of times the user has requested a
8090      particular syscall to be tracked, and pass this information to the
8091      target.  This lets capable targets implement filtering directly.  */
8092
8093   /* Number of times that "any" syscall is requested.  */
8094   int any_syscall_count;
8095
8096   /* Count of each system call.  */
8097   VEC(int) *syscalls_counts;
8098
8099   /* This counts all syscall catch requests, so we can readily determine
8100      if any catching is necessary.  */
8101   int total_syscalls_count;
8102 };
8103
8104 static struct catch_syscall_inferior_data*
8105 get_catch_syscall_inferior_data (struct inferior *inf)
8106 {
8107   struct catch_syscall_inferior_data *inf_data;
8108
8109   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8110   if (inf_data == NULL)
8111     {
8112       inf_data = XZALLOC (struct catch_syscall_inferior_data);
8113       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8114     }
8115
8116   return inf_data;
8117 }
8118
8119 static void
8120 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8121 {
8122   xfree (arg);
8123 }
8124
8125
8126 /* Implement the "insert" breakpoint_ops method for syscall
8127    catchpoints.  */
8128
8129 static int
8130 insert_catch_syscall (struct bp_location *bl)
8131 {
8132   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8133   struct inferior *inf = current_inferior ();
8134   struct catch_syscall_inferior_data *inf_data
8135     = get_catch_syscall_inferior_data (inf);
8136
8137   ++inf_data->total_syscalls_count;
8138   if (!c->syscalls_to_be_caught)
8139     ++inf_data->any_syscall_count;
8140   else
8141     {
8142       int i, iter;
8143
8144       for (i = 0;
8145            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8146            i++)
8147         {
8148           int elem;
8149
8150           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8151             {
8152               int old_size = VEC_length (int, inf_data->syscalls_counts);
8153               uintptr_t vec_addr_offset
8154                 = old_size * ((uintptr_t) sizeof (int));
8155               uintptr_t vec_addr;
8156               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8157               vec_addr = ((uintptr_t) VEC_address (int,
8158                                                   inf_data->syscalls_counts)
8159                           + vec_addr_offset);
8160               memset ((void *) vec_addr, 0,
8161                       (iter + 1 - old_size) * sizeof (int));
8162             }
8163           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8164           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8165         }
8166     }
8167
8168   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
8169                                         inf_data->total_syscalls_count != 0,
8170                                         inf_data->any_syscall_count,
8171                                         VEC_length (int,
8172                                                     inf_data->syscalls_counts),
8173                                         VEC_address (int,
8174                                                      inf_data->syscalls_counts));
8175 }
8176
8177 /* Implement the "remove" breakpoint_ops method for syscall
8178    catchpoints.  */
8179
8180 static int
8181 remove_catch_syscall (struct bp_location *bl)
8182 {
8183   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8184   struct inferior *inf = current_inferior ();
8185   struct catch_syscall_inferior_data *inf_data
8186     = get_catch_syscall_inferior_data (inf);
8187
8188   --inf_data->total_syscalls_count;
8189   if (!c->syscalls_to_be_caught)
8190     --inf_data->any_syscall_count;
8191   else
8192     {
8193       int i, iter;
8194
8195       for (i = 0;
8196            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8197            i++)
8198         {
8199           int elem;
8200           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8201             /* Shouldn't happen.  */
8202             continue;
8203           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8204           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8205         }
8206     }
8207
8208   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
8209                                         inf_data->total_syscalls_count != 0,
8210                                         inf_data->any_syscall_count,
8211                                         VEC_length (int,
8212                                                     inf_data->syscalls_counts),
8213                                         VEC_address (int,
8214                                                      inf_data->syscalls_counts));
8215 }
8216
8217 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8218    catchpoints.  */
8219
8220 static int
8221 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8222                               struct address_space *aspace, CORE_ADDR bp_addr,
8223                               const struct target_waitstatus *ws)
8224 {
8225   /* We must check if we are catching specific syscalls in this
8226      breakpoint.  If we are, then we must guarantee that the called
8227      syscall is the same syscall we are catching.  */
8228   int syscall_number = 0;
8229   const struct syscall_catchpoint *c
8230     = (const struct syscall_catchpoint *) bl->owner;
8231
8232   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8233       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8234     return 0;
8235
8236   syscall_number = ws->value.syscall_number;
8237
8238   /* Now, checking if the syscall is the same.  */
8239   if (c->syscalls_to_be_caught)
8240     {
8241       int i, iter;
8242
8243       for (i = 0;
8244            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8245            i++)
8246         if (syscall_number == iter)
8247           break;
8248       /* Not the same.  */
8249       if (!iter)
8250         return 0;
8251     }
8252
8253   return 1;
8254 }
8255
8256 /* Implement the "print_it" breakpoint_ops method for syscall
8257    catchpoints.  */
8258
8259 static enum print_stop_action
8260 print_it_catch_syscall (bpstat bs)
8261 {
8262   struct ui_out *uiout = current_uiout;
8263   struct breakpoint *b = bs->breakpoint_at;
8264   /* These are needed because we want to know in which state a
8265      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8266      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8267      must print "called syscall" or "returned from syscall".  */
8268   ptid_t ptid;
8269   struct target_waitstatus last;
8270   struct syscall s;
8271
8272   get_last_target_status (&ptid, &last);
8273
8274   get_syscall_by_number (last.value.syscall_number, &s);
8275
8276   annotate_catchpoint (b->number);
8277
8278   if (b->disposition == disp_del)
8279     ui_out_text (uiout, "\nTemporary catchpoint ");
8280   else
8281     ui_out_text (uiout, "\nCatchpoint ");
8282   if (ui_out_is_mi_like_p (uiout))
8283     {
8284       ui_out_field_string (uiout, "reason",
8285                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8286                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8287                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8288       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8289     }
8290   ui_out_field_int (uiout, "bkptno", b->number);
8291
8292   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8293     ui_out_text (uiout, " (call to syscall ");
8294   else
8295     ui_out_text (uiout, " (returned from syscall ");
8296
8297   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8298     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8299   if (s.name != NULL)
8300     ui_out_field_string (uiout, "syscall-name", s.name);
8301
8302   ui_out_text (uiout, "), ");
8303
8304   return PRINT_SRC_AND_LOC;
8305 }
8306
8307 /* Implement the "print_one" breakpoint_ops method for syscall
8308    catchpoints.  */
8309
8310 static void
8311 print_one_catch_syscall (struct breakpoint *b,
8312                          struct bp_location **last_loc)
8313 {
8314   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8315   struct value_print_options opts;
8316   struct ui_out *uiout = current_uiout;
8317
8318   get_user_print_options (&opts);
8319   /* Field 4, the address, is omitted (which makes the columns not
8320      line up too nicely with the headers, but the effect is relatively
8321      readable).  */
8322   if (opts.addressprint)
8323     ui_out_field_skip (uiout, "addr");
8324   annotate_field (5);
8325
8326   if (c->syscalls_to_be_caught
8327       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8328     ui_out_text (uiout, "syscalls \"");
8329   else
8330     ui_out_text (uiout, "syscall \"");
8331
8332   if (c->syscalls_to_be_caught)
8333     {
8334       int i, iter;
8335       char *text = xstrprintf ("%s", "");
8336
8337       for (i = 0;
8338            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8339            i++)
8340         {
8341           char *x = text;
8342           struct syscall s;
8343           get_syscall_by_number (iter, &s);
8344
8345           if (s.name != NULL)
8346             text = xstrprintf ("%s%s, ", text, s.name);
8347           else
8348             text = xstrprintf ("%s%d, ", text, iter);
8349
8350           /* We have to xfree the last 'text' (now stored at 'x')
8351              because xstrprintf dynamically allocates new space for it
8352              on every call.  */
8353           xfree (x);
8354         }
8355       /* Remove the last comma.  */
8356       text[strlen (text) - 2] = '\0';
8357       ui_out_field_string (uiout, "what", text);
8358     }
8359   else
8360     ui_out_field_string (uiout, "what", "<any syscall>");
8361   ui_out_text (uiout, "\" ");
8362
8363   if (ui_out_is_mi_like_p (uiout))
8364     ui_out_field_string (uiout, "catch-type", "syscall");
8365 }
8366
8367 /* Implement the "print_mention" breakpoint_ops method for syscall
8368    catchpoints.  */
8369
8370 static void
8371 print_mention_catch_syscall (struct breakpoint *b)
8372 {
8373   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8374
8375   if (c->syscalls_to_be_caught)
8376     {
8377       int i, iter;
8378
8379       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8380         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8381       else
8382         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8383
8384       for (i = 0;
8385            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8386            i++)
8387         {
8388           struct syscall s;
8389           get_syscall_by_number (iter, &s);
8390
8391           if (s.name)
8392             printf_filtered (" '%s' [%d]", s.name, s.number);
8393           else
8394             printf_filtered (" %d", s.number);
8395         }
8396       printf_filtered (")");
8397     }
8398   else
8399     printf_filtered (_("Catchpoint %d (any syscall)"),
8400                      b->number);
8401 }
8402
8403 /* Implement the "print_recreate" breakpoint_ops method for syscall
8404    catchpoints.  */
8405
8406 static void
8407 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8408 {
8409   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8410
8411   fprintf_unfiltered (fp, "catch syscall");
8412
8413   if (c->syscalls_to_be_caught)
8414     {
8415       int i, iter;
8416
8417       for (i = 0;
8418            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8419            i++)
8420         {
8421           struct syscall s;
8422
8423           get_syscall_by_number (iter, &s);
8424           if (s.name)
8425             fprintf_unfiltered (fp, " %s", s.name);
8426           else
8427             fprintf_unfiltered (fp, " %d", s.number);
8428         }
8429     }
8430   print_recreate_thread (b, fp);
8431 }
8432
8433 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8434
8435 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8436
8437 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8438
8439 static int
8440 syscall_catchpoint_p (struct breakpoint *b)
8441 {
8442   return (b->ops == &catch_syscall_breakpoint_ops);
8443 }
8444
8445 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8446    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8447    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8448    the breakpoint_ops structure associated to the catchpoint.  */
8449
8450 void
8451 init_catchpoint (struct breakpoint *b,
8452                  struct gdbarch *gdbarch, int tempflag,
8453                  char *cond_string,
8454                  const struct breakpoint_ops *ops)
8455 {
8456   struct symtab_and_line sal;
8457
8458   init_sal (&sal);
8459   sal.pspace = current_program_space;
8460
8461   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8462
8463   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8464   b->disposition = tempflag ? disp_del : disp_donttouch;
8465 }
8466
8467 void
8468 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8469 {
8470   add_to_breakpoint_chain (b);
8471   set_breakpoint_number (internal, b);
8472   if (is_tracepoint (b))
8473     set_tracepoint_count (breakpoint_count);
8474   if (!internal)
8475     mention (b);
8476   observer_notify_breakpoint_created (b);
8477
8478   if (update_gll)
8479     update_global_location_list (1);
8480 }
8481
8482 static void
8483 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8484                                     int tempflag, char *cond_string,
8485                                     const struct breakpoint_ops *ops)
8486 {
8487   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8488
8489   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8490
8491   c->forked_inferior_pid = null_ptid;
8492
8493   install_breakpoint (0, &c->base, 1);
8494 }
8495
8496 /* Exec catchpoints.  */
8497
8498 /* An instance of this type is used to represent an exec catchpoint.
8499    It includes a "struct breakpoint" as a kind of base class; users
8500    downcast to "struct breakpoint *" when needed.  A breakpoint is
8501    really of this type iff its ops pointer points to
8502    CATCH_EXEC_BREAKPOINT_OPS.  */
8503
8504 struct exec_catchpoint
8505 {
8506   /* The base class.  */
8507   struct breakpoint base;
8508
8509   /* Filename of a program whose exec triggered this catchpoint.
8510      This field is only valid immediately after this catchpoint has
8511      triggered.  */
8512   char *exec_pathname;
8513 };
8514
8515 /* Implement the "dtor" breakpoint_ops method for exec
8516    catchpoints.  */
8517
8518 static void
8519 dtor_catch_exec (struct breakpoint *b)
8520 {
8521   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8522
8523   xfree (c->exec_pathname);
8524
8525   base_breakpoint_ops.dtor (b);
8526 }
8527
8528 static int
8529 insert_catch_exec (struct bp_location *bl)
8530 {
8531   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
8532 }
8533
8534 static int
8535 remove_catch_exec (struct bp_location *bl)
8536 {
8537   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
8538 }
8539
8540 static int
8541 breakpoint_hit_catch_exec (const struct bp_location *bl,
8542                            struct address_space *aspace, CORE_ADDR bp_addr,
8543                            const struct target_waitstatus *ws)
8544 {
8545   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8546
8547   if (ws->kind != TARGET_WAITKIND_EXECD)
8548     return 0;
8549
8550   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8551   return 1;
8552 }
8553
8554 static enum print_stop_action
8555 print_it_catch_exec (bpstat bs)
8556 {
8557   struct ui_out *uiout = current_uiout;
8558   struct breakpoint *b = bs->breakpoint_at;
8559   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8560
8561   annotate_catchpoint (b->number);
8562   if (b->disposition == disp_del)
8563     ui_out_text (uiout, "\nTemporary catchpoint ");
8564   else
8565     ui_out_text (uiout, "\nCatchpoint ");
8566   if (ui_out_is_mi_like_p (uiout))
8567     {
8568       ui_out_field_string (uiout, "reason",
8569                            async_reason_lookup (EXEC_ASYNC_EXEC));
8570       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8571     }
8572   ui_out_field_int (uiout, "bkptno", b->number);
8573   ui_out_text (uiout, " (exec'd ");
8574   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8575   ui_out_text (uiout, "), ");
8576
8577   return PRINT_SRC_AND_LOC;
8578 }
8579
8580 static void
8581 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8582 {
8583   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8584   struct value_print_options opts;
8585   struct ui_out *uiout = current_uiout;
8586
8587   get_user_print_options (&opts);
8588
8589   /* Field 4, the address, is omitted (which makes the columns
8590      not line up too nicely with the headers, but the effect
8591      is relatively readable).  */
8592   if (opts.addressprint)
8593     ui_out_field_skip (uiout, "addr");
8594   annotate_field (5);
8595   ui_out_text (uiout, "exec");
8596   if (c->exec_pathname != NULL)
8597     {
8598       ui_out_text (uiout, ", program \"");
8599       ui_out_field_string (uiout, "what", c->exec_pathname);
8600       ui_out_text (uiout, "\" ");
8601     }
8602
8603   if (ui_out_is_mi_like_p (uiout))
8604     ui_out_field_string (uiout, "catch-type", "exec");
8605 }
8606
8607 static void
8608 print_mention_catch_exec (struct breakpoint *b)
8609 {
8610   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8611 }
8612
8613 /* Implement the "print_recreate" breakpoint_ops method for exec
8614    catchpoints.  */
8615
8616 static void
8617 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8618 {
8619   fprintf_unfiltered (fp, "catch exec");
8620   print_recreate_thread (b, fp);
8621 }
8622
8623 static struct breakpoint_ops catch_exec_breakpoint_ops;
8624
8625 static void
8626 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8627                                  const struct breakpoint_ops *ops)
8628 {
8629   struct syscall_catchpoint *c;
8630   struct gdbarch *gdbarch = get_current_arch ();
8631
8632   c = XNEW (struct syscall_catchpoint);
8633   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8634   c->syscalls_to_be_caught = filter;
8635
8636   install_breakpoint (0, &c->base, 1);
8637 }
8638
8639 static int
8640 hw_breakpoint_used_count (void)
8641 {
8642   int i = 0;
8643   struct breakpoint *b;
8644   struct bp_location *bl;
8645
8646   ALL_BREAKPOINTS (b)
8647   {
8648     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8649       for (bl = b->loc; bl; bl = bl->next)
8650         {
8651           /* Special types of hardware breakpoints may use more than
8652              one register.  */
8653           i += b->ops->resources_needed (bl);
8654         }
8655   }
8656
8657   return i;
8658 }
8659
8660 /* Returns the resources B would use if it were a hardware
8661    watchpoint.  */
8662
8663 static int
8664 hw_watchpoint_use_count (struct breakpoint *b)
8665 {
8666   int i = 0;
8667   struct bp_location *bl;
8668
8669   if (!breakpoint_enabled (b))
8670     return 0;
8671
8672   for (bl = b->loc; bl; bl = bl->next)
8673     {
8674       /* Special types of hardware watchpoints may use more than
8675          one register.  */
8676       i += b->ops->resources_needed (bl);
8677     }
8678
8679   return i;
8680 }
8681
8682 /* Returns the sum the used resources of all hardware watchpoints of
8683    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8684    the sum of the used resources of all hardware watchpoints of other
8685    types _not_ TYPE.  */
8686
8687 static int
8688 hw_watchpoint_used_count_others (struct breakpoint *except,
8689                                  enum bptype type, int *other_type_used)
8690 {
8691   int i = 0;
8692   struct breakpoint *b;
8693
8694   *other_type_used = 0;
8695   ALL_BREAKPOINTS (b)
8696     {
8697       if (b == except)
8698         continue;
8699       if (!breakpoint_enabled (b))
8700         continue;
8701
8702       if (b->type == type)
8703         i += hw_watchpoint_use_count (b);
8704       else if (is_hardware_watchpoint (b))
8705         *other_type_used = 1;
8706     }
8707
8708   return i;
8709 }
8710
8711 void
8712 disable_watchpoints_before_interactive_call_start (void)
8713 {
8714   struct breakpoint *b;
8715
8716   ALL_BREAKPOINTS (b)
8717   {
8718     if (is_watchpoint (b) && breakpoint_enabled (b))
8719       {
8720         b->enable_state = bp_call_disabled;
8721         update_global_location_list (0);
8722       }
8723   }
8724 }
8725
8726 void
8727 enable_watchpoints_after_interactive_call_stop (void)
8728 {
8729   struct breakpoint *b;
8730
8731   ALL_BREAKPOINTS (b)
8732   {
8733     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8734       {
8735         b->enable_state = bp_enabled;
8736         update_global_location_list (1);
8737       }
8738   }
8739 }
8740
8741 void
8742 disable_breakpoints_before_startup (void)
8743 {
8744   current_program_space->executing_startup = 1;
8745   update_global_location_list (0);
8746 }
8747
8748 void
8749 enable_breakpoints_after_startup (void)
8750 {
8751   current_program_space->executing_startup = 0;
8752   breakpoint_re_set ();
8753 }
8754
8755
8756 /* Set a breakpoint that will evaporate an end of command
8757    at address specified by SAL.
8758    Restrict it to frame FRAME if FRAME is nonzero.  */
8759
8760 struct breakpoint *
8761 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8762                           struct frame_id frame_id, enum bptype type)
8763 {
8764   struct breakpoint *b;
8765
8766   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8767      tail-called one.  */
8768   gdb_assert (!frame_id_artificial_p (frame_id));
8769
8770   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8771   b->enable_state = bp_enabled;
8772   b->disposition = disp_donttouch;
8773   b->frame_id = frame_id;
8774
8775   /* If we're debugging a multi-threaded program, then we want
8776      momentary breakpoints to be active in only a single thread of
8777      control.  */
8778   if (in_thread_list (inferior_ptid))
8779     b->thread = pid_to_thread_id (inferior_ptid);
8780
8781   update_global_location_list_nothrow (1);
8782
8783   return b;
8784 }
8785
8786 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8787    The new breakpoint will have type TYPE, and use OPS as it
8788    breakpoint_ops.  */
8789
8790 static struct breakpoint *
8791 momentary_breakpoint_from_master (struct breakpoint *orig,
8792                                   enum bptype type,
8793                                   const struct breakpoint_ops *ops)
8794 {
8795   struct breakpoint *copy;
8796
8797   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8798   copy->loc = allocate_bp_location (copy);
8799   set_breakpoint_location_function (copy->loc, 1);
8800
8801   copy->loc->gdbarch = orig->loc->gdbarch;
8802   copy->loc->requested_address = orig->loc->requested_address;
8803   copy->loc->address = orig->loc->address;
8804   copy->loc->section = orig->loc->section;
8805   copy->loc->pspace = orig->loc->pspace;
8806   copy->loc->probe = orig->loc->probe;
8807   copy->loc->line_number = orig->loc->line_number;
8808   copy->loc->symtab = orig->loc->symtab;
8809   copy->frame_id = orig->frame_id;
8810   copy->thread = orig->thread;
8811   copy->pspace = orig->pspace;
8812
8813   copy->enable_state = bp_enabled;
8814   copy->disposition = disp_donttouch;
8815   copy->number = internal_breakpoint_number--;
8816
8817   update_global_location_list_nothrow (0);
8818   return copy;
8819 }
8820
8821 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8822    ORIG is NULL.  */
8823
8824 struct breakpoint *
8825 clone_momentary_breakpoint (struct breakpoint *orig)
8826 {
8827   /* If there's nothing to clone, then return nothing.  */
8828   if (orig == NULL)
8829     return NULL;
8830
8831   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8832 }
8833
8834 struct breakpoint *
8835 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8836                                 enum bptype type)
8837 {
8838   struct symtab_and_line sal;
8839
8840   sal = find_pc_line (pc, 0);
8841   sal.pc = pc;
8842   sal.section = find_pc_overlay (pc);
8843   sal.explicit_pc = 1;
8844
8845   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8846 }
8847 \f
8848
8849 /* Tell the user we have just set a breakpoint B.  */
8850
8851 static void
8852 mention (struct breakpoint *b)
8853 {
8854   b->ops->print_mention (b);
8855   if (ui_out_is_mi_like_p (current_uiout))
8856     return;
8857   printf_filtered ("\n");
8858 }
8859 \f
8860
8861 static struct bp_location *
8862 add_location_to_breakpoint (struct breakpoint *b,
8863                             const struct symtab_and_line *sal)
8864 {
8865   struct bp_location *loc, **tmp;
8866   CORE_ADDR adjusted_address;
8867   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8868
8869   if (loc_gdbarch == NULL)
8870     loc_gdbarch = b->gdbarch;
8871
8872   /* Adjust the breakpoint's address prior to allocating a location.
8873      Once we call allocate_bp_location(), that mostly uninitialized
8874      location will be placed on the location chain.  Adjustment of the
8875      breakpoint may cause target_read_memory() to be called and we do
8876      not want its scan of the location chain to find a breakpoint and
8877      location that's only been partially initialized.  */
8878   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8879                                                 sal->pc, b->type);
8880
8881   /* Sort the locations by their ADDRESS.  */
8882   loc = allocate_bp_location (b);
8883   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8884        tmp = &((*tmp)->next))
8885     ;
8886   loc->next = *tmp;
8887   *tmp = loc;
8888
8889   loc->requested_address = sal->pc;
8890   loc->address = adjusted_address;
8891   loc->pspace = sal->pspace;
8892   loc->probe = sal->probe;
8893   gdb_assert (loc->pspace != NULL);
8894   loc->section = sal->section;
8895   loc->gdbarch = loc_gdbarch;
8896   loc->line_number = sal->line;
8897   loc->symtab = sal->symtab;
8898
8899   set_breakpoint_location_function (loc,
8900                                     sal->explicit_pc || sal->explicit_line);
8901   return loc;
8902 }
8903 \f
8904
8905 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8906    return 0 otherwise.  */
8907
8908 static int
8909 bp_loc_is_permanent (struct bp_location *loc)
8910 {
8911   int len;
8912   CORE_ADDR addr;
8913   const gdb_byte *bpoint;
8914   gdb_byte *target_mem;
8915   struct cleanup *cleanup;
8916   int retval = 0;
8917
8918   gdb_assert (loc != NULL);
8919
8920   addr = loc->address;
8921   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8922
8923   /* Software breakpoints unsupported?  */
8924   if (bpoint == NULL)
8925     return 0;
8926
8927   target_mem = alloca (len);
8928
8929   /* Enable the automatic memory restoration from breakpoints while
8930      we read the memory.  Otherwise we could say about our temporary
8931      breakpoints they are permanent.  */
8932   cleanup = save_current_space_and_thread ();
8933
8934   switch_to_program_space_and_thread (loc->pspace);
8935   make_show_memory_breakpoints_cleanup (0);
8936
8937   if (target_read_memory (loc->address, target_mem, len) == 0
8938       && memcmp (target_mem, bpoint, len) == 0)
8939     retval = 1;
8940
8941   do_cleanups (cleanup);
8942
8943   return retval;
8944 }
8945
8946 /* Build a command list for the dprintf corresponding to the current
8947    settings of the dprintf style options.  */
8948
8949 static void
8950 update_dprintf_command_list (struct breakpoint *b)
8951 {
8952   char *dprintf_args = b->extra_string;
8953   char *printf_line = NULL;
8954
8955   if (!dprintf_args)
8956     return;
8957
8958   dprintf_args = skip_spaces (dprintf_args);
8959
8960   /* Allow a comma, as it may have terminated a location, but don't
8961      insist on it.  */
8962   if (*dprintf_args == ',')
8963     ++dprintf_args;
8964   dprintf_args = skip_spaces (dprintf_args);
8965
8966   if (*dprintf_args != '"')
8967     error (_("Bad format string, missing '\"'."));
8968
8969   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8970     printf_line = xstrprintf ("printf %s", dprintf_args);
8971   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8972     {
8973       if (!dprintf_function)
8974         error (_("No function supplied for dprintf call"));
8975
8976       if (dprintf_channel && strlen (dprintf_channel) > 0)
8977         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8978                                   dprintf_function,
8979                                   dprintf_channel,
8980                                   dprintf_args);
8981       else
8982         printf_line = xstrprintf ("call (void) %s (%s)",
8983                                   dprintf_function,
8984                                   dprintf_args);
8985     }
8986   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8987     {
8988       if (target_can_run_breakpoint_commands ())
8989         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8990       else
8991         {
8992           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8993           printf_line = xstrprintf ("printf %s", dprintf_args);
8994         }
8995     }
8996   else
8997     internal_error (__FILE__, __LINE__,
8998                     _("Invalid dprintf style."));
8999
9000   gdb_assert (printf_line != NULL);
9001   /* Manufacture a printf sequence.  */
9002   {
9003     struct command_line *printf_cmd_line
9004       = xmalloc (sizeof (struct command_line));
9005
9006     printf_cmd_line = xmalloc (sizeof (struct command_line));
9007     printf_cmd_line->control_type = simple_control;
9008     printf_cmd_line->body_count = 0;
9009     printf_cmd_line->body_list = NULL;
9010     printf_cmd_line->next = NULL;
9011     printf_cmd_line->line = printf_line;
9012
9013     breakpoint_set_commands (b, printf_cmd_line);
9014   }
9015 }
9016
9017 /* Update all dprintf commands, making their command lists reflect
9018    current style settings.  */
9019
9020 static void
9021 update_dprintf_commands (char *args, int from_tty,
9022                          struct cmd_list_element *c)
9023 {
9024   struct breakpoint *b;
9025
9026   ALL_BREAKPOINTS (b)
9027     {
9028       if (b->type == bp_dprintf)
9029         update_dprintf_command_list (b);
9030     }
9031 }
9032
9033 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9034    as textual description of the location, and COND_STRING
9035    as condition expression.  */
9036
9037 static void
9038 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9039                      struct symtabs_and_lines sals, char *addr_string,
9040                      char *filter, char *cond_string,
9041                      char *extra_string,
9042                      enum bptype type, enum bpdisp disposition,
9043                      int thread, int task, int ignore_count,
9044                      const struct breakpoint_ops *ops, int from_tty,
9045                      int enabled, int internal, unsigned flags,
9046                      int display_canonical)
9047 {
9048   int i;
9049
9050   if (type == bp_hardware_breakpoint)
9051     {
9052       int target_resources_ok;
9053
9054       i = hw_breakpoint_used_count ();
9055       target_resources_ok =
9056         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9057                                             i + 1, 0);
9058       if (target_resources_ok == 0)
9059         error (_("No hardware breakpoint support in the target."));
9060       else if (target_resources_ok < 0)
9061         error (_("Hardware breakpoints used exceeds limit."));
9062     }
9063
9064   gdb_assert (sals.nelts > 0);
9065
9066   for (i = 0; i < sals.nelts; ++i)
9067     {
9068       struct symtab_and_line sal = sals.sals[i];
9069       struct bp_location *loc;
9070
9071       if (from_tty)
9072         {
9073           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9074           if (!loc_gdbarch)
9075             loc_gdbarch = gdbarch;
9076
9077           describe_other_breakpoints (loc_gdbarch,
9078                                       sal.pspace, sal.pc, sal.section, thread);
9079         }
9080
9081       if (i == 0)
9082         {
9083           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9084           b->thread = thread;
9085           b->task = task;
9086
9087           b->cond_string = cond_string;
9088           b->extra_string = extra_string;
9089           b->ignore_count = ignore_count;
9090           b->enable_state = enabled ? bp_enabled : bp_disabled;
9091           b->disposition = disposition;
9092
9093           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9094             b->loc->inserted = 1;
9095
9096           if (type == bp_static_tracepoint)
9097             {
9098               struct tracepoint *t = (struct tracepoint *) b;
9099               struct static_tracepoint_marker marker;
9100
9101               if (strace_marker_p (b))
9102                 {
9103                   /* We already know the marker exists, otherwise, we
9104                      wouldn't see a sal for it.  */
9105                   char *p = &addr_string[3];
9106                   char *endp;
9107                   char *marker_str;
9108
9109                   p = skip_spaces (p);
9110
9111                   endp = skip_to_space (p);
9112
9113                   marker_str = savestring (p, endp - p);
9114                   t->static_trace_marker_id = marker_str;
9115
9116                   printf_filtered (_("Probed static tracepoint "
9117                                      "marker \"%s\"\n"),
9118                                    t->static_trace_marker_id);
9119                 }
9120               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9121                 {
9122                   t->static_trace_marker_id = xstrdup (marker.str_id);
9123                   release_static_tracepoint_marker (&marker);
9124
9125                   printf_filtered (_("Probed static tracepoint "
9126                                      "marker \"%s\"\n"),
9127                                    t->static_trace_marker_id);
9128                 }
9129               else
9130                 warning (_("Couldn't determine the static "
9131                            "tracepoint marker to probe"));
9132             }
9133
9134           loc = b->loc;
9135         }
9136       else
9137         {
9138           loc = add_location_to_breakpoint (b, &sal);
9139           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9140             loc->inserted = 1;
9141         }
9142
9143       if (bp_loc_is_permanent (loc))
9144         make_breakpoint_permanent (b);
9145
9146       if (b->cond_string)
9147         {
9148           const char *arg = b->cond_string;
9149
9150           loc->cond = parse_exp_1 (&arg, loc->address,
9151                                    block_for_pc (loc->address), 0);
9152           if (*arg)
9153               error (_("Garbage '%s' follows condition"), arg);
9154         }
9155
9156       /* Dynamic printf requires and uses additional arguments on the
9157          command line, otherwise it's an error.  */
9158       if (type == bp_dprintf)
9159         {
9160           if (b->extra_string)
9161             update_dprintf_command_list (b);
9162           else
9163             error (_("Format string required"));
9164         }
9165       else if (b->extra_string)
9166         error (_("Garbage '%s' at end of command"), b->extra_string);
9167     }
9168
9169   b->display_canonical = display_canonical;
9170   if (addr_string)
9171     b->addr_string = addr_string;
9172   else
9173     /* addr_string has to be used or breakpoint_re_set will delete
9174        me.  */
9175     b->addr_string
9176       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9177   b->filter = filter;
9178 }
9179
9180 static void
9181 create_breakpoint_sal (struct gdbarch *gdbarch,
9182                        struct symtabs_and_lines sals, char *addr_string,
9183                        char *filter, char *cond_string,
9184                        char *extra_string,
9185                        enum bptype type, enum bpdisp disposition,
9186                        int thread, int task, int ignore_count,
9187                        const struct breakpoint_ops *ops, int from_tty,
9188                        int enabled, int internal, unsigned flags,
9189                        int display_canonical)
9190 {
9191   struct breakpoint *b;
9192   struct cleanup *old_chain;
9193
9194   if (is_tracepoint_type (type))
9195     {
9196       struct tracepoint *t;
9197
9198       t = XCNEW (struct tracepoint);
9199       b = &t->base;
9200     }
9201   else
9202     b = XNEW (struct breakpoint);
9203
9204   old_chain = make_cleanup (xfree, b);
9205
9206   init_breakpoint_sal (b, gdbarch,
9207                        sals, addr_string,
9208                        filter, cond_string, extra_string,
9209                        type, disposition,
9210                        thread, task, ignore_count,
9211                        ops, from_tty,
9212                        enabled, internal, flags,
9213                        display_canonical);
9214   discard_cleanups (old_chain);
9215
9216   install_breakpoint (internal, b, 0);
9217 }
9218
9219 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9220    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9221    value.  COND_STRING, if not NULL, specified the condition to be
9222    used for all breakpoints.  Essentially the only case where
9223    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9224    function.  In that case, it's still not possible to specify
9225    separate conditions for different overloaded functions, so
9226    we take just a single condition string.
9227    
9228    NOTE: If the function succeeds, the caller is expected to cleanup
9229    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9230    array contents).  If the function fails (error() is called), the
9231    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9232    COND and SALS arrays and each of those arrays contents.  */
9233
9234 static void
9235 create_breakpoints_sal (struct gdbarch *gdbarch,
9236                         struct linespec_result *canonical,
9237                         char *cond_string, char *extra_string,
9238                         enum bptype type, enum bpdisp disposition,
9239                         int thread, int task, int ignore_count,
9240                         const struct breakpoint_ops *ops, int from_tty,
9241                         int enabled, int internal, unsigned flags)
9242 {
9243   int i;
9244   struct linespec_sals *lsal;
9245
9246   if (canonical->pre_expanded)
9247     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9248
9249   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9250     {
9251       /* Note that 'addr_string' can be NULL in the case of a plain
9252          'break', without arguments.  */
9253       char *addr_string = (canonical->addr_string
9254                            ? xstrdup (canonical->addr_string)
9255                            : NULL);
9256       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9257       struct cleanup *inner = make_cleanup (xfree, addr_string);
9258
9259       make_cleanup (xfree, filter_string);
9260       create_breakpoint_sal (gdbarch, lsal->sals,
9261                              addr_string,
9262                              filter_string,
9263                              cond_string, extra_string,
9264                              type, disposition,
9265                              thread, task, ignore_count, ops,
9266                              from_tty, enabled, internal, flags,
9267                              canonical->special_display);
9268       discard_cleanups (inner);
9269     }
9270 }
9271
9272 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9273    followed by conditionals.  On return, SALS contains an array of SAL
9274    addresses found.  ADDR_STRING contains a vector of (canonical)
9275    address strings.  ADDRESS points to the end of the SAL.
9276
9277    The array and the line spec strings are allocated on the heap, it is
9278    the caller's responsibility to free them.  */
9279
9280 static void
9281 parse_breakpoint_sals (char **address,
9282                        struct linespec_result *canonical)
9283 {
9284   /* If no arg given, or if first arg is 'if ', use the default
9285      breakpoint.  */
9286   if ((*address) == NULL
9287       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9288     {
9289       /* The last displayed codepoint, if it's valid, is our default breakpoint
9290          address.  */
9291       if (last_displayed_sal_is_valid ())
9292         {
9293           struct linespec_sals lsal;
9294           struct symtab_and_line sal;
9295           CORE_ADDR pc;
9296
9297           init_sal (&sal);              /* Initialize to zeroes.  */
9298           lsal.sals.sals = (struct symtab_and_line *)
9299             xmalloc (sizeof (struct symtab_and_line));
9300
9301           /* Set sal's pspace, pc, symtab, and line to the values
9302              corresponding to the last call to print_frame_info.
9303              Be sure to reinitialize LINE with NOTCURRENT == 0
9304              as the breakpoint line number is inappropriate otherwise.
9305              find_pc_line would adjust PC, re-set it back.  */
9306           get_last_displayed_sal (&sal);
9307           pc = sal.pc;
9308           sal = find_pc_line (pc, 0);
9309
9310           /* "break" without arguments is equivalent to "break *PC"
9311              where PC is the last displayed codepoint's address.  So
9312              make sure to set sal.explicit_pc to prevent GDB from
9313              trying to expand the list of sals to include all other
9314              instances with the same symtab and line.  */
9315           sal.pc = pc;
9316           sal.explicit_pc = 1;
9317
9318           lsal.sals.sals[0] = sal;
9319           lsal.sals.nelts = 1;
9320           lsal.canonical = NULL;
9321
9322           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9323         }
9324       else
9325         error (_("No default breakpoint address now."));
9326     }
9327   else
9328     {
9329       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9330
9331       /* Force almost all breakpoints to be in terms of the
9332          current_source_symtab (which is decode_line_1's default).
9333          This should produce the results we want almost all of the
9334          time while leaving default_breakpoint_* alone.
9335
9336          ObjC: However, don't match an Objective-C method name which
9337          may have a '+' or '-' succeeded by a '['.  */
9338       if (last_displayed_sal_is_valid ()
9339           && (!cursal.symtab
9340               || ((strchr ("+-", (*address)[0]) != NULL)
9341                   && ((*address)[1] != '['))))
9342         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9343                           get_last_displayed_symtab (),
9344                           get_last_displayed_line (),
9345                           canonical, NULL, NULL);
9346       else
9347         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9348                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9349     }
9350 }
9351
9352
9353 /* Convert each SAL into a real PC.  Verify that the PC can be
9354    inserted as a breakpoint.  If it can't throw an error.  */
9355
9356 static void
9357 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9358 {    
9359   int i;
9360
9361   for (i = 0; i < sals->nelts; i++)
9362     resolve_sal_pc (&sals->sals[i]);
9363 }
9364
9365 /* Fast tracepoints may have restrictions on valid locations.  For
9366    instance, a fast tracepoint using a jump instead of a trap will
9367    likely have to overwrite more bytes than a trap would, and so can
9368    only be placed where the instruction is longer than the jump, or a
9369    multi-instruction sequence does not have a jump into the middle of
9370    it, etc.  */
9371
9372 static void
9373 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9374                             struct symtabs_and_lines *sals)
9375 {
9376   int i, rslt;
9377   struct symtab_and_line *sal;
9378   char *msg;
9379   struct cleanup *old_chain;
9380
9381   for (i = 0; i < sals->nelts; i++)
9382     {
9383       struct gdbarch *sarch;
9384
9385       sal = &sals->sals[i];
9386
9387       sarch = get_sal_arch (*sal);
9388       /* We fall back to GDBARCH if there is no architecture
9389          associated with SAL.  */
9390       if (sarch == NULL)
9391         sarch = gdbarch;
9392       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9393                                                NULL, &msg);
9394       old_chain = make_cleanup (xfree, msg);
9395
9396       if (!rslt)
9397         error (_("May not have a fast tracepoint at 0x%s%s"),
9398                paddress (sarch, sal->pc), (msg ? msg : ""));
9399
9400       do_cleanups (old_chain);
9401     }
9402 }
9403
9404 /* Issue an invalid thread ID error.  */
9405
9406 static void ATTRIBUTE_NORETURN
9407 invalid_thread_id_error (int id)
9408 {
9409   error (_("Unknown thread %d."), id);
9410 }
9411
9412 /* Given TOK, a string specification of condition and thread, as
9413    accepted by the 'break' command, extract the condition
9414    string and thread number and set *COND_STRING and *THREAD.
9415    PC identifies the context at which the condition should be parsed.
9416    If no condition is found, *COND_STRING is set to NULL.
9417    If no thread is found, *THREAD is set to -1.  */
9418
9419 static void
9420 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9421                            char **cond_string, int *thread, int *task,
9422                            char **rest)
9423 {
9424   *cond_string = NULL;
9425   *thread = -1;
9426   *task = 0;
9427   *rest = NULL;
9428
9429   while (tok && *tok)
9430     {
9431       const char *end_tok;
9432       int toklen;
9433       const char *cond_start = NULL;
9434       const char *cond_end = NULL;
9435
9436       tok = skip_spaces_const (tok);
9437
9438       if ((*tok == '"' || *tok == ',') && rest)
9439         {
9440           *rest = savestring (tok, strlen (tok));
9441           return;
9442         }
9443
9444       end_tok = skip_to_space_const (tok);
9445
9446       toklen = end_tok - tok;
9447
9448       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9449         {
9450           struct expression *expr;
9451
9452           tok = cond_start = end_tok + 1;
9453           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9454           xfree (expr);
9455           cond_end = tok;
9456           *cond_string = savestring (cond_start, cond_end - cond_start);
9457         }
9458       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9459         {
9460           char *tmptok;
9461
9462           tok = end_tok + 1;
9463           *thread = strtol (tok, &tmptok, 0);
9464           if (tok == tmptok)
9465             error (_("Junk after thread keyword."));
9466           if (!valid_thread_id (*thread))
9467             invalid_thread_id_error (*thread);
9468           tok = tmptok;
9469         }
9470       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9471         {
9472           char *tmptok;
9473
9474           tok = end_tok + 1;
9475           *task = strtol (tok, &tmptok, 0);
9476           if (tok == tmptok)
9477             error (_("Junk after task keyword."));
9478           if (!valid_task_id (*task))
9479             error (_("Unknown task %d."), *task);
9480           tok = tmptok;
9481         }
9482       else if (rest)
9483         {
9484           *rest = savestring (tok, strlen (tok));
9485           return;
9486         }
9487       else
9488         error (_("Junk at end of arguments."));
9489     }
9490 }
9491
9492 /* Decode a static tracepoint marker spec.  */
9493
9494 static struct symtabs_and_lines
9495 decode_static_tracepoint_spec (char **arg_p)
9496 {
9497   VEC(static_tracepoint_marker_p) *markers = NULL;
9498   struct symtabs_and_lines sals;
9499   struct cleanup *old_chain;
9500   char *p = &(*arg_p)[3];
9501   char *endp;
9502   char *marker_str;
9503   int i;
9504
9505   p = skip_spaces (p);
9506
9507   endp = skip_to_space (p);
9508
9509   marker_str = savestring (p, endp - p);
9510   old_chain = make_cleanup (xfree, marker_str);
9511
9512   markers = target_static_tracepoint_markers_by_strid (marker_str);
9513   if (VEC_empty(static_tracepoint_marker_p, markers))
9514     error (_("No known static tracepoint marker named %s"), marker_str);
9515
9516   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9517   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9518
9519   for (i = 0; i < sals.nelts; i++)
9520     {
9521       struct static_tracepoint_marker *marker;
9522
9523       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9524
9525       init_sal (&sals.sals[i]);
9526
9527       sals.sals[i] = find_pc_line (marker->address, 0);
9528       sals.sals[i].pc = marker->address;
9529
9530       release_static_tracepoint_marker (marker);
9531     }
9532
9533   do_cleanups (old_chain);
9534
9535   *arg_p = endp;
9536   return sals;
9537 }
9538
9539 /* Set a breakpoint.  This function is shared between CLI and MI
9540    functions for setting a breakpoint.  This function has two major
9541    modes of operations, selected by the PARSE_ARG parameter.  If
9542    non-zero, the function will parse ARG, extracting location,
9543    condition, thread and extra string.  Otherwise, ARG is just the
9544    breakpoint's location, with condition, thread, and extra string
9545    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9546    If INTERNAL is non-zero, the breakpoint number will be allocated
9547    from the internal breakpoint count.  Returns true if any breakpoint
9548    was created; false otherwise.  */
9549
9550 int
9551 create_breakpoint (struct gdbarch *gdbarch,
9552                    char *arg, char *cond_string,
9553                    int thread, char *extra_string,
9554                    int parse_arg,
9555                    int tempflag, enum bptype type_wanted,
9556                    int ignore_count,
9557                    enum auto_boolean pending_break_support,
9558                    const struct breakpoint_ops *ops,
9559                    int from_tty, int enabled, int internal,
9560                    unsigned flags)
9561 {
9562   volatile struct gdb_exception e;
9563   char *copy_arg = NULL;
9564   char *addr_start = arg;
9565   struct linespec_result canonical;
9566   struct cleanup *old_chain;
9567   struct cleanup *bkpt_chain = NULL;
9568   int pending = 0;
9569   int task = 0;
9570   int prev_bkpt_count = breakpoint_count;
9571
9572   gdb_assert (ops != NULL);
9573
9574   init_linespec_result (&canonical);
9575
9576   TRY_CATCH (e, RETURN_MASK_ALL)
9577     {
9578       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9579                                      addr_start, &copy_arg);
9580     }
9581
9582   /* If caller is interested in rc value from parse, set value.  */
9583   switch (e.reason)
9584     {
9585     case GDB_NO_ERROR:
9586       if (VEC_empty (linespec_sals, canonical.sals))
9587         return 0;
9588       break;
9589     case RETURN_ERROR:
9590       switch (e.error)
9591         {
9592         case NOT_FOUND_ERROR:
9593
9594           /* If pending breakpoint support is turned off, throw
9595              error.  */
9596
9597           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9598             throw_exception (e);
9599
9600           exception_print (gdb_stderr, e);
9601
9602           /* If pending breakpoint support is auto query and the user
9603              selects no, then simply return the error code.  */
9604           if (pending_break_support == AUTO_BOOLEAN_AUTO
9605               && !nquery (_("Make %s pending on future shared library load? "),
9606                           bptype_string (type_wanted)))
9607             return 0;
9608
9609           /* At this point, either the user was queried about setting
9610              a pending breakpoint and selected yes, or pending
9611              breakpoint behavior is on and thus a pending breakpoint
9612              is defaulted on behalf of the user.  */
9613           {
9614             struct linespec_sals lsal;
9615
9616             copy_arg = xstrdup (addr_start);
9617             lsal.canonical = xstrdup (copy_arg);
9618             lsal.sals.nelts = 1;
9619             lsal.sals.sals = XNEW (struct symtab_and_line);
9620             init_sal (&lsal.sals.sals[0]);
9621             pending = 1;
9622             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9623           }
9624           break;
9625         default:
9626           throw_exception (e);
9627         }
9628       break;
9629     default:
9630       throw_exception (e);
9631     }
9632
9633   /* Create a chain of things that always need to be cleaned up.  */
9634   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9635
9636   /* ----------------------------- SNIP -----------------------------
9637      Anything added to the cleanup chain beyond this point is assumed
9638      to be part of a breakpoint.  If the breakpoint create succeeds
9639      then the memory is not reclaimed.  */
9640   bkpt_chain = make_cleanup (null_cleanup, 0);
9641
9642   /* Resolve all line numbers to PC's and verify that the addresses
9643      are ok for the target.  */
9644   if (!pending)
9645     {
9646       int ix;
9647       struct linespec_sals *iter;
9648
9649       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9650         breakpoint_sals_to_pc (&iter->sals);
9651     }
9652
9653   /* Fast tracepoints may have additional restrictions on location.  */
9654   if (!pending && type_wanted == bp_fast_tracepoint)
9655     {
9656       int ix;
9657       struct linespec_sals *iter;
9658
9659       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9660         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9661     }
9662
9663   /* Verify that condition can be parsed, before setting any
9664      breakpoints.  Allocate a separate condition expression for each
9665      breakpoint.  */
9666   if (!pending)
9667     {
9668       if (parse_arg)
9669         {
9670           char *rest;
9671           struct linespec_sals *lsal;
9672
9673           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9674
9675           /* Here we only parse 'arg' to separate condition
9676              from thread number, so parsing in context of first
9677              sal is OK.  When setting the breakpoint we'll
9678              re-parse it in context of each sal.  */
9679
9680           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9681                                      &thread, &task, &rest);
9682           if (cond_string)
9683             make_cleanup (xfree, cond_string);
9684           if (rest)
9685             make_cleanup (xfree, rest);
9686           if (rest)
9687             extra_string = rest;
9688         }
9689       else
9690         {
9691           if (*arg != '\0')
9692             error (_("Garbage '%s' at end of location"), arg);
9693
9694           /* Create a private copy of condition string.  */
9695           if (cond_string)
9696             {
9697               cond_string = xstrdup (cond_string);
9698               make_cleanup (xfree, cond_string);
9699             }
9700           /* Create a private copy of any extra string.  */
9701           if (extra_string)
9702             {
9703               extra_string = xstrdup (extra_string);
9704               make_cleanup (xfree, extra_string);
9705             }
9706         }
9707
9708       ops->create_breakpoints_sal (gdbarch, &canonical,
9709                                    cond_string, extra_string, type_wanted,
9710                                    tempflag ? disp_del : disp_donttouch,
9711                                    thread, task, ignore_count, ops,
9712                                    from_tty, enabled, internal, flags);
9713     }
9714   else
9715     {
9716       struct breakpoint *b;
9717
9718       make_cleanup (xfree, copy_arg);
9719
9720       if (is_tracepoint_type (type_wanted))
9721         {
9722           struct tracepoint *t;
9723
9724           t = XCNEW (struct tracepoint);
9725           b = &t->base;
9726         }
9727       else
9728         b = XNEW (struct breakpoint);
9729
9730       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9731
9732       b->addr_string = copy_arg;
9733       if (parse_arg)
9734         b->cond_string = NULL;
9735       else
9736         {
9737           /* Create a private copy of condition string.  */
9738           if (cond_string)
9739             {
9740               cond_string = xstrdup (cond_string);
9741               make_cleanup (xfree, cond_string);
9742             }
9743           b->cond_string = cond_string;
9744         }
9745       b->extra_string = NULL;
9746       b->ignore_count = ignore_count;
9747       b->disposition = tempflag ? disp_del : disp_donttouch;
9748       b->condition_not_parsed = 1;
9749       b->enable_state = enabled ? bp_enabled : bp_disabled;
9750       if ((type_wanted != bp_breakpoint
9751            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9752         b->pspace = current_program_space;
9753
9754       install_breakpoint (internal, b, 0);
9755     }
9756   
9757   if (VEC_length (linespec_sals, canonical.sals) > 1)
9758     {
9759       warning (_("Multiple breakpoints were set.\nUse the "
9760                  "\"delete\" command to delete unwanted breakpoints."));
9761       prev_breakpoint_count = prev_bkpt_count;
9762     }
9763
9764   /* That's it.  Discard the cleanups for data inserted into the
9765      breakpoint.  */
9766   discard_cleanups (bkpt_chain);
9767   /* But cleanup everything else.  */
9768   do_cleanups (old_chain);
9769
9770   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9771   update_global_location_list (1);
9772
9773   return 1;
9774 }
9775
9776 /* Set a breakpoint.
9777    ARG is a string describing breakpoint address,
9778    condition, and thread.
9779    FLAG specifies if a breakpoint is hardware on,
9780    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9781    and BP_TEMPFLAG.  */
9782
9783 static void
9784 break_command_1 (char *arg, int flag, int from_tty)
9785 {
9786   int tempflag = flag & BP_TEMPFLAG;
9787   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9788                              ? bp_hardware_breakpoint
9789                              : bp_breakpoint);
9790   struct breakpoint_ops *ops;
9791   const char *arg_cp = arg;
9792
9793   /* Matching breakpoints on probes.  */
9794   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9795     ops = &bkpt_probe_breakpoint_ops;
9796   else
9797     ops = &bkpt_breakpoint_ops;
9798
9799   create_breakpoint (get_current_arch (),
9800                      arg,
9801                      NULL, 0, NULL, 1 /* parse arg */,
9802                      tempflag, type_wanted,
9803                      0 /* Ignore count */,
9804                      pending_break_support,
9805                      ops,
9806                      from_tty,
9807                      1 /* enabled */,
9808                      0 /* internal */,
9809                      0);
9810 }
9811
9812 /* Helper function for break_command_1 and disassemble_command.  */
9813
9814 void
9815 resolve_sal_pc (struct symtab_and_line *sal)
9816 {
9817   CORE_ADDR pc;
9818
9819   if (sal->pc == 0 && sal->symtab != NULL)
9820     {
9821       if (!find_line_pc (sal->symtab, sal->line, &pc))
9822         error (_("No line %d in file \"%s\"."),
9823                sal->line, symtab_to_filename_for_display (sal->symtab));
9824       sal->pc = pc;
9825
9826       /* If this SAL corresponds to a breakpoint inserted using a line
9827          number, then skip the function prologue if necessary.  */
9828       if (sal->explicit_line)
9829         skip_prologue_sal (sal);
9830     }
9831
9832   if (sal->section == 0 && sal->symtab != NULL)
9833     {
9834       struct blockvector *bv;
9835       struct block *b;
9836       struct symbol *sym;
9837
9838       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9839       if (bv != NULL)
9840         {
9841           sym = block_linkage_function (b);
9842           if (sym != NULL)
9843             {
9844               fixup_symbol_section (sym, sal->symtab->objfile);
9845               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
9846             }
9847           else
9848             {
9849               /* It really is worthwhile to have the section, so we'll
9850                  just have to look harder. This case can be executed
9851                  if we have line numbers but no functions (as can
9852                  happen in assembly source).  */
9853
9854               struct bound_minimal_symbol msym;
9855               struct cleanup *old_chain = save_current_space_and_thread ();
9856
9857               switch_to_program_space_and_thread (sal->pspace);
9858
9859               msym = lookup_minimal_symbol_by_pc (sal->pc);
9860               if (msym.minsym)
9861                 sal->section = SYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
9862
9863               do_cleanups (old_chain);
9864             }
9865         }
9866     }
9867 }
9868
9869 void
9870 break_command (char *arg, int from_tty)
9871 {
9872   break_command_1 (arg, 0, from_tty);
9873 }
9874
9875 void
9876 tbreak_command (char *arg, int from_tty)
9877 {
9878   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9879 }
9880
9881 static void
9882 hbreak_command (char *arg, int from_tty)
9883 {
9884   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9885 }
9886
9887 static void
9888 thbreak_command (char *arg, int from_tty)
9889 {
9890   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9891 }
9892
9893 static void
9894 stop_command (char *arg, int from_tty)
9895 {
9896   printf_filtered (_("Specify the type of breakpoint to set.\n\
9897 Usage: stop in <function | address>\n\
9898        stop at <line>\n"));
9899 }
9900
9901 static void
9902 stopin_command (char *arg, int from_tty)
9903 {
9904   int badInput = 0;
9905
9906   if (arg == (char *) NULL)
9907     badInput = 1;
9908   else if (*arg != '*')
9909     {
9910       char *argptr = arg;
9911       int hasColon = 0;
9912
9913       /* Look for a ':'.  If this is a line number specification, then
9914          say it is bad, otherwise, it should be an address or
9915          function/method name.  */
9916       while (*argptr && !hasColon)
9917         {
9918           hasColon = (*argptr == ':');
9919           argptr++;
9920         }
9921
9922       if (hasColon)
9923         badInput = (*argptr != ':');    /* Not a class::method */
9924       else
9925         badInput = isdigit (*arg);      /* a simple line number */
9926     }
9927
9928   if (badInput)
9929     printf_filtered (_("Usage: stop in <function | address>\n"));
9930   else
9931     break_command_1 (arg, 0, from_tty);
9932 }
9933
9934 static void
9935 stopat_command (char *arg, int from_tty)
9936 {
9937   int badInput = 0;
9938
9939   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9940     badInput = 1;
9941   else
9942     {
9943       char *argptr = arg;
9944       int hasColon = 0;
9945
9946       /* Look for a ':'.  If there is a '::' then get out, otherwise
9947          it is probably a line number.  */
9948       while (*argptr && !hasColon)
9949         {
9950           hasColon = (*argptr == ':');
9951           argptr++;
9952         }
9953
9954       if (hasColon)
9955         badInput = (*argptr == ':');    /* we have class::method */
9956       else
9957         badInput = !isdigit (*arg);     /* not a line number */
9958     }
9959
9960   if (badInput)
9961     printf_filtered (_("Usage: stop at <line>\n"));
9962   else
9963     break_command_1 (arg, 0, from_tty);
9964 }
9965
9966 /* The dynamic printf command is mostly like a regular breakpoint, but
9967    with a prewired command list consisting of a single output command,
9968    built from extra arguments supplied on the dprintf command
9969    line.  */
9970
9971 static void
9972 dprintf_command (char *arg, int from_tty)
9973 {
9974   create_breakpoint (get_current_arch (),
9975                      arg,
9976                      NULL, 0, NULL, 1 /* parse arg */,
9977                      0, bp_dprintf,
9978                      0 /* Ignore count */,
9979                      pending_break_support,
9980                      &dprintf_breakpoint_ops,
9981                      from_tty,
9982                      1 /* enabled */,
9983                      0 /* internal */,
9984                      0);
9985 }
9986
9987 static void
9988 agent_printf_command (char *arg, int from_tty)
9989 {
9990   error (_("May only run agent-printf on the target"));
9991 }
9992
9993 /* Implement the "breakpoint_hit" breakpoint_ops method for
9994    ranged breakpoints.  */
9995
9996 static int
9997 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9998                                   struct address_space *aspace,
9999                                   CORE_ADDR bp_addr,
10000                                   const struct target_waitstatus *ws)
10001 {
10002   if (ws->kind != TARGET_WAITKIND_STOPPED
10003       || ws->value.sig != GDB_SIGNAL_TRAP)
10004     return 0;
10005
10006   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10007                                          bl->length, aspace, bp_addr);
10008 }
10009
10010 /* Implement the "resources_needed" breakpoint_ops method for
10011    ranged breakpoints.  */
10012
10013 static int
10014 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10015 {
10016   return target_ranged_break_num_registers ();
10017 }
10018
10019 /* Implement the "print_it" breakpoint_ops method for
10020    ranged breakpoints.  */
10021
10022 static enum print_stop_action
10023 print_it_ranged_breakpoint (bpstat bs)
10024 {
10025   struct breakpoint *b = bs->breakpoint_at;
10026   struct bp_location *bl = b->loc;
10027   struct ui_out *uiout = current_uiout;
10028
10029   gdb_assert (b->type == bp_hardware_breakpoint);
10030
10031   /* Ranged breakpoints have only one location.  */
10032   gdb_assert (bl && bl->next == NULL);
10033
10034   annotate_breakpoint (b->number);
10035   if (b->disposition == disp_del)
10036     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10037   else
10038     ui_out_text (uiout, "\nRanged breakpoint ");
10039   if (ui_out_is_mi_like_p (uiout))
10040     {
10041       ui_out_field_string (uiout, "reason",
10042                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10043       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10044     }
10045   ui_out_field_int (uiout, "bkptno", b->number);
10046   ui_out_text (uiout, ", ");
10047
10048   return PRINT_SRC_AND_LOC;
10049 }
10050
10051 /* Implement the "print_one" breakpoint_ops method for
10052    ranged breakpoints.  */
10053
10054 static void
10055 print_one_ranged_breakpoint (struct breakpoint *b,
10056                              struct bp_location **last_loc)
10057 {
10058   struct bp_location *bl = b->loc;
10059   struct value_print_options opts;
10060   struct ui_out *uiout = current_uiout;
10061
10062   /* Ranged breakpoints have only one location.  */
10063   gdb_assert (bl && bl->next == NULL);
10064
10065   get_user_print_options (&opts);
10066
10067   if (opts.addressprint)
10068     /* We don't print the address range here, it will be printed later
10069        by print_one_detail_ranged_breakpoint.  */
10070     ui_out_field_skip (uiout, "addr");
10071   annotate_field (5);
10072   print_breakpoint_location (b, bl);
10073   *last_loc = bl;
10074 }
10075
10076 /* Implement the "print_one_detail" breakpoint_ops method for
10077    ranged breakpoints.  */
10078
10079 static void
10080 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10081                                     struct ui_out *uiout)
10082 {
10083   CORE_ADDR address_start, address_end;
10084   struct bp_location *bl = b->loc;
10085   struct ui_file *stb = mem_fileopen ();
10086   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10087
10088   gdb_assert (bl);
10089
10090   address_start = bl->address;
10091   address_end = address_start + bl->length - 1;
10092
10093   ui_out_text (uiout, "\taddress range: ");
10094   fprintf_unfiltered (stb, "[%s, %s]",
10095                       print_core_address (bl->gdbarch, address_start),
10096                       print_core_address (bl->gdbarch, address_end));
10097   ui_out_field_stream (uiout, "addr", stb);
10098   ui_out_text (uiout, "\n");
10099
10100   do_cleanups (cleanup);
10101 }
10102
10103 /* Implement the "print_mention" breakpoint_ops method for
10104    ranged breakpoints.  */
10105
10106 static void
10107 print_mention_ranged_breakpoint (struct breakpoint *b)
10108 {
10109   struct bp_location *bl = b->loc;
10110   struct ui_out *uiout = current_uiout;
10111
10112   gdb_assert (bl);
10113   gdb_assert (b->type == bp_hardware_breakpoint);
10114
10115   if (ui_out_is_mi_like_p (uiout))
10116     return;
10117
10118   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10119                    b->number, paddress (bl->gdbarch, bl->address),
10120                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10121 }
10122
10123 /* Implement the "print_recreate" breakpoint_ops method for
10124    ranged breakpoints.  */
10125
10126 static void
10127 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10128 {
10129   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10130                       b->addr_string_range_end);
10131   print_recreate_thread (b, fp);
10132 }
10133
10134 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10135
10136 static struct breakpoint_ops ranged_breakpoint_ops;
10137
10138 /* Find the address where the end of the breakpoint range should be
10139    placed, given the SAL of the end of the range.  This is so that if
10140    the user provides a line number, the end of the range is set to the
10141    last instruction of the given line.  */
10142
10143 static CORE_ADDR
10144 find_breakpoint_range_end (struct symtab_and_line sal)
10145 {
10146   CORE_ADDR end;
10147
10148   /* If the user provided a PC value, use it.  Otherwise,
10149      find the address of the end of the given location.  */
10150   if (sal.explicit_pc)
10151     end = sal.pc;
10152   else
10153     {
10154       int ret;
10155       CORE_ADDR start;
10156
10157       ret = find_line_pc_range (sal, &start, &end);
10158       if (!ret)
10159         error (_("Could not find location of the end of the range."));
10160
10161       /* find_line_pc_range returns the start of the next line.  */
10162       end--;
10163     }
10164
10165   return end;
10166 }
10167
10168 /* Implement the "break-range" CLI command.  */
10169
10170 static void
10171 break_range_command (char *arg, int from_tty)
10172 {
10173   char *arg_start, *addr_string_start, *addr_string_end;
10174   struct linespec_result canonical_start, canonical_end;
10175   int bp_count, can_use_bp, length;
10176   CORE_ADDR end;
10177   struct breakpoint *b;
10178   struct symtab_and_line sal_start, sal_end;
10179   struct cleanup *cleanup_bkpt;
10180   struct linespec_sals *lsal_start, *lsal_end;
10181
10182   /* We don't support software ranged breakpoints.  */
10183   if (target_ranged_break_num_registers () < 0)
10184     error (_("This target does not support hardware ranged breakpoints."));
10185
10186   bp_count = hw_breakpoint_used_count ();
10187   bp_count += target_ranged_break_num_registers ();
10188   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10189                                                    bp_count, 0);
10190   if (can_use_bp < 0)
10191     error (_("Hardware breakpoints used exceeds limit."));
10192
10193   arg = skip_spaces (arg);
10194   if (arg == NULL || arg[0] == '\0')
10195     error(_("No address range specified."));
10196
10197   init_linespec_result (&canonical_start);
10198
10199   arg_start = arg;
10200   parse_breakpoint_sals (&arg, &canonical_start);
10201
10202   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10203
10204   if (arg[0] != ',')
10205     error (_("Too few arguments."));
10206   else if (VEC_empty (linespec_sals, canonical_start.sals))
10207     error (_("Could not find location of the beginning of the range."));
10208
10209   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10210
10211   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10212       || lsal_start->sals.nelts != 1)
10213     error (_("Cannot create a ranged breakpoint with multiple locations."));
10214
10215   sal_start = lsal_start->sals.sals[0];
10216   addr_string_start = savestring (arg_start, arg - arg_start);
10217   make_cleanup (xfree, addr_string_start);
10218
10219   arg++;        /* Skip the comma.  */
10220   arg = skip_spaces (arg);
10221
10222   /* Parse the end location.  */
10223
10224   init_linespec_result (&canonical_end);
10225   arg_start = arg;
10226
10227   /* We call decode_line_full directly here instead of using
10228      parse_breakpoint_sals because we need to specify the start location's
10229      symtab and line as the default symtab and line for the end of the
10230      range.  This makes it possible to have ranges like "foo.c:27, +14",
10231      where +14 means 14 lines from the start location.  */
10232   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10233                     sal_start.symtab, sal_start.line,
10234                     &canonical_end, NULL, NULL);
10235
10236   make_cleanup_destroy_linespec_result (&canonical_end);
10237
10238   if (VEC_empty (linespec_sals, canonical_end.sals))
10239     error (_("Could not find location of the end of the range."));
10240
10241   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10242   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10243       || lsal_end->sals.nelts != 1)
10244     error (_("Cannot create a ranged breakpoint with multiple locations."));
10245
10246   sal_end = lsal_end->sals.sals[0];
10247   addr_string_end = savestring (arg_start, arg - arg_start);
10248   make_cleanup (xfree, addr_string_end);
10249
10250   end = find_breakpoint_range_end (sal_end);
10251   if (sal_start.pc > end)
10252     error (_("Invalid address range, end precedes start."));
10253
10254   length = end - sal_start.pc + 1;
10255   if (length < 0)
10256     /* Length overflowed.  */
10257     error (_("Address range too large."));
10258   else if (length == 1)
10259     {
10260       /* This range is simple enough to be handled by
10261          the `hbreak' command.  */
10262       hbreak_command (addr_string_start, 1);
10263
10264       do_cleanups (cleanup_bkpt);
10265
10266       return;
10267     }
10268
10269   /* Now set up the breakpoint.  */
10270   b = set_raw_breakpoint (get_current_arch (), sal_start,
10271                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10272   set_breakpoint_count (breakpoint_count + 1);
10273   b->number = breakpoint_count;
10274   b->disposition = disp_donttouch;
10275   b->addr_string = xstrdup (addr_string_start);
10276   b->addr_string_range_end = xstrdup (addr_string_end);
10277   b->loc->length = length;
10278
10279   do_cleanups (cleanup_bkpt);
10280
10281   mention (b);
10282   observer_notify_breakpoint_created (b);
10283   update_global_location_list (1);
10284 }
10285
10286 /*  Return non-zero if EXP is verified as constant.  Returned zero
10287     means EXP is variable.  Also the constant detection may fail for
10288     some constant expressions and in such case still falsely return
10289     zero.  */
10290
10291 static int
10292 watchpoint_exp_is_const (const struct expression *exp)
10293 {
10294   int i = exp->nelts;
10295
10296   while (i > 0)
10297     {
10298       int oplenp, argsp;
10299
10300       /* We are only interested in the descriptor of each element.  */
10301       operator_length (exp, i, &oplenp, &argsp);
10302       i -= oplenp;
10303
10304       switch (exp->elts[i].opcode)
10305         {
10306         case BINOP_ADD:
10307         case BINOP_SUB:
10308         case BINOP_MUL:
10309         case BINOP_DIV:
10310         case BINOP_REM:
10311         case BINOP_MOD:
10312         case BINOP_LSH:
10313         case BINOP_RSH:
10314         case BINOP_LOGICAL_AND:
10315         case BINOP_LOGICAL_OR:
10316         case BINOP_BITWISE_AND:
10317         case BINOP_BITWISE_IOR:
10318         case BINOP_BITWISE_XOR:
10319         case BINOP_EQUAL:
10320         case BINOP_NOTEQUAL:
10321         case BINOP_LESS:
10322         case BINOP_GTR:
10323         case BINOP_LEQ:
10324         case BINOP_GEQ:
10325         case BINOP_REPEAT:
10326         case BINOP_COMMA:
10327         case BINOP_EXP:
10328         case BINOP_MIN:
10329         case BINOP_MAX:
10330         case BINOP_INTDIV:
10331         case BINOP_CONCAT:
10332         case BINOP_IN:
10333         case BINOP_RANGE:
10334         case TERNOP_COND:
10335         case TERNOP_SLICE:
10336
10337         case OP_LONG:
10338         case OP_DOUBLE:
10339         case OP_DECFLOAT:
10340         case OP_LAST:
10341         case OP_COMPLEX:
10342         case OP_STRING:
10343         case OP_ARRAY:
10344         case OP_TYPE:
10345         case OP_TYPEOF:
10346         case OP_DECLTYPE:
10347         case OP_TYPEID:
10348         case OP_NAME:
10349         case OP_OBJC_NSSTRING:
10350
10351         case UNOP_NEG:
10352         case UNOP_LOGICAL_NOT:
10353         case UNOP_COMPLEMENT:
10354         case UNOP_ADDR:
10355         case UNOP_HIGH:
10356         case UNOP_CAST:
10357
10358         case UNOP_CAST_TYPE:
10359         case UNOP_REINTERPRET_CAST:
10360         case UNOP_DYNAMIC_CAST:
10361           /* Unary, binary and ternary operators: We have to check
10362              their operands.  If they are constant, then so is the
10363              result of that operation.  For instance, if A and B are
10364              determined to be constants, then so is "A + B".
10365
10366              UNOP_IND is one exception to the rule above, because the
10367              value of *ADDR is not necessarily a constant, even when
10368              ADDR is.  */
10369           break;
10370
10371         case OP_VAR_VALUE:
10372           /* Check whether the associated symbol is a constant.
10373
10374              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10375              possible that a buggy compiler could mark a variable as
10376              constant even when it is not, and TYPE_CONST would return
10377              true in this case, while SYMBOL_CLASS wouldn't.
10378
10379              We also have to check for function symbols because they
10380              are always constant.  */
10381           {
10382             struct symbol *s = exp->elts[i + 2].symbol;
10383
10384             if (SYMBOL_CLASS (s) != LOC_BLOCK
10385                 && SYMBOL_CLASS (s) != LOC_CONST
10386                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10387               return 0;
10388             break;
10389           }
10390
10391         /* The default action is to return 0 because we are using
10392            the optimistic approach here: If we don't know something,
10393            then it is not a constant.  */
10394         default:
10395           return 0;
10396         }
10397     }
10398
10399   return 1;
10400 }
10401
10402 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10403
10404 static void
10405 dtor_watchpoint (struct breakpoint *self)
10406 {
10407   struct watchpoint *w = (struct watchpoint *) self;
10408
10409   xfree (w->cond_exp);
10410   xfree (w->exp);
10411   xfree (w->exp_string);
10412   xfree (w->exp_string_reparse);
10413   value_free (w->val);
10414
10415   base_breakpoint_ops.dtor (self);
10416 }
10417
10418 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10419
10420 static void
10421 re_set_watchpoint (struct breakpoint *b)
10422 {
10423   struct watchpoint *w = (struct watchpoint *) b;
10424
10425   /* Watchpoint can be either on expression using entirely global
10426      variables, or it can be on local variables.
10427
10428      Watchpoints of the first kind are never auto-deleted, and even
10429      persist across program restarts.  Since they can use variables
10430      from shared libraries, we need to reparse expression as libraries
10431      are loaded and unloaded.
10432
10433      Watchpoints on local variables can also change meaning as result
10434      of solib event.  For example, if a watchpoint uses both a local
10435      and a global variables in expression, it's a local watchpoint,
10436      but unloading of a shared library will make the expression
10437      invalid.  This is not a very common use case, but we still
10438      re-evaluate expression, to avoid surprises to the user.
10439
10440      Note that for local watchpoints, we re-evaluate it only if
10441      watchpoints frame id is still valid.  If it's not, it means the
10442      watchpoint is out of scope and will be deleted soon.  In fact,
10443      I'm not sure we'll ever be called in this case.
10444
10445      If a local watchpoint's frame id is still valid, then
10446      w->exp_valid_block is likewise valid, and we can safely use it.
10447
10448      Don't do anything about disabled watchpoints, since they will be
10449      reevaluated again when enabled.  */
10450   update_watchpoint (w, 1 /* reparse */);
10451 }
10452
10453 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10454
10455 static int
10456 insert_watchpoint (struct bp_location *bl)
10457 {
10458   struct watchpoint *w = (struct watchpoint *) bl->owner;
10459   int length = w->exact ? 1 : bl->length;
10460
10461   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10462                                    w->cond_exp);
10463 }
10464
10465 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10466
10467 static int
10468 remove_watchpoint (struct bp_location *bl)
10469 {
10470   struct watchpoint *w = (struct watchpoint *) bl->owner;
10471   int length = w->exact ? 1 : bl->length;
10472
10473   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10474                                    w->cond_exp);
10475 }
10476
10477 static int
10478 breakpoint_hit_watchpoint (const struct bp_location *bl,
10479                            struct address_space *aspace, CORE_ADDR bp_addr,
10480                            const struct target_waitstatus *ws)
10481 {
10482   struct breakpoint *b = bl->owner;
10483   struct watchpoint *w = (struct watchpoint *) b;
10484
10485   /* Continuable hardware watchpoints are treated as non-existent if the
10486      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10487      some data address).  Otherwise gdb won't stop on a break instruction
10488      in the code (not from a breakpoint) when a hardware watchpoint has
10489      been defined.  Also skip watchpoints which we know did not trigger
10490      (did not match the data address).  */
10491   if (is_hardware_watchpoint (b)
10492       && w->watchpoint_triggered == watch_triggered_no)
10493     return 0;
10494
10495   return 1;
10496 }
10497
10498 static void
10499 check_status_watchpoint (bpstat bs)
10500 {
10501   gdb_assert (is_watchpoint (bs->breakpoint_at));
10502
10503   bpstat_check_watchpoint (bs);
10504 }
10505
10506 /* Implement the "resources_needed" breakpoint_ops method for
10507    hardware watchpoints.  */
10508
10509 static int
10510 resources_needed_watchpoint (const struct bp_location *bl)
10511 {
10512   struct watchpoint *w = (struct watchpoint *) bl->owner;
10513   int length = w->exact? 1 : bl->length;
10514
10515   return target_region_ok_for_hw_watchpoint (bl->address, length);
10516 }
10517
10518 /* Implement the "works_in_software_mode" breakpoint_ops method for
10519    hardware watchpoints.  */
10520
10521 static int
10522 works_in_software_mode_watchpoint (const struct breakpoint *b)
10523 {
10524   /* Read and access watchpoints only work with hardware support.  */
10525   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10526 }
10527
10528 static enum print_stop_action
10529 print_it_watchpoint (bpstat bs)
10530 {
10531   struct cleanup *old_chain;
10532   struct breakpoint *b;
10533   struct ui_file *stb;
10534   enum print_stop_action result;
10535   struct watchpoint *w;
10536   struct ui_out *uiout = current_uiout;
10537
10538   gdb_assert (bs->bp_location_at != NULL);
10539
10540   b = bs->breakpoint_at;
10541   w = (struct watchpoint *) b;
10542
10543   stb = mem_fileopen ();
10544   old_chain = make_cleanup_ui_file_delete (stb);
10545
10546   switch (b->type)
10547     {
10548     case bp_watchpoint:
10549     case bp_hardware_watchpoint:
10550       annotate_watchpoint (b->number);
10551       if (ui_out_is_mi_like_p (uiout))
10552         ui_out_field_string
10553           (uiout, "reason",
10554            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10555       mention (b);
10556       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10557       ui_out_text (uiout, "\nOld value = ");
10558       watchpoint_value_print (bs->old_val, stb);
10559       ui_out_field_stream (uiout, "old", stb);
10560       ui_out_text (uiout, "\nNew value = ");
10561       watchpoint_value_print (w->val, stb);
10562       ui_out_field_stream (uiout, "new", stb);
10563       ui_out_text (uiout, "\n");
10564       /* More than one watchpoint may have been triggered.  */
10565       result = PRINT_UNKNOWN;
10566       break;
10567
10568     case bp_read_watchpoint:
10569       if (ui_out_is_mi_like_p (uiout))
10570         ui_out_field_string
10571           (uiout, "reason",
10572            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10573       mention (b);
10574       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10575       ui_out_text (uiout, "\nValue = ");
10576       watchpoint_value_print (w->val, stb);
10577       ui_out_field_stream (uiout, "value", stb);
10578       ui_out_text (uiout, "\n");
10579       result = PRINT_UNKNOWN;
10580       break;
10581
10582     case bp_access_watchpoint:
10583       if (bs->old_val != NULL)
10584         {
10585           annotate_watchpoint (b->number);
10586           if (ui_out_is_mi_like_p (uiout))
10587             ui_out_field_string
10588               (uiout, "reason",
10589                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10590           mention (b);
10591           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10592           ui_out_text (uiout, "\nOld value = ");
10593           watchpoint_value_print (bs->old_val, stb);
10594           ui_out_field_stream (uiout, "old", stb);
10595           ui_out_text (uiout, "\nNew value = ");
10596         }
10597       else
10598         {
10599           mention (b);
10600           if (ui_out_is_mi_like_p (uiout))
10601             ui_out_field_string
10602               (uiout, "reason",
10603                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10604           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10605           ui_out_text (uiout, "\nValue = ");
10606         }
10607       watchpoint_value_print (w->val, stb);
10608       ui_out_field_stream (uiout, "new", stb);
10609       ui_out_text (uiout, "\n");
10610       result = PRINT_UNKNOWN;
10611       break;
10612     default:
10613       result = PRINT_UNKNOWN;
10614     }
10615
10616   do_cleanups (old_chain);
10617   return result;
10618 }
10619
10620 /* Implement the "print_mention" breakpoint_ops method for hardware
10621    watchpoints.  */
10622
10623 static void
10624 print_mention_watchpoint (struct breakpoint *b)
10625 {
10626   struct cleanup *ui_out_chain;
10627   struct watchpoint *w = (struct watchpoint *) b;
10628   struct ui_out *uiout = current_uiout;
10629
10630   switch (b->type)
10631     {
10632     case bp_watchpoint:
10633       ui_out_text (uiout, "Watchpoint ");
10634       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10635       break;
10636     case bp_hardware_watchpoint:
10637       ui_out_text (uiout, "Hardware watchpoint ");
10638       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10639       break;
10640     case bp_read_watchpoint:
10641       ui_out_text (uiout, "Hardware read watchpoint ");
10642       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10643       break;
10644     case bp_access_watchpoint:
10645       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10646       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10647       break;
10648     default:
10649       internal_error (__FILE__, __LINE__,
10650                       _("Invalid hardware watchpoint type."));
10651     }
10652
10653   ui_out_field_int (uiout, "number", b->number);
10654   ui_out_text (uiout, ": ");
10655   ui_out_field_string (uiout, "exp", w->exp_string);
10656   do_cleanups (ui_out_chain);
10657 }
10658
10659 /* Implement the "print_recreate" breakpoint_ops method for
10660    watchpoints.  */
10661
10662 static void
10663 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10664 {
10665   struct watchpoint *w = (struct watchpoint *) b;
10666
10667   switch (b->type)
10668     {
10669     case bp_watchpoint:
10670     case bp_hardware_watchpoint:
10671       fprintf_unfiltered (fp, "watch");
10672       break;
10673     case bp_read_watchpoint:
10674       fprintf_unfiltered (fp, "rwatch");
10675       break;
10676     case bp_access_watchpoint:
10677       fprintf_unfiltered (fp, "awatch");
10678       break;
10679     default:
10680       internal_error (__FILE__, __LINE__,
10681                       _("Invalid watchpoint type."));
10682     }
10683
10684   fprintf_unfiltered (fp, " %s", w->exp_string);
10685   print_recreate_thread (b, fp);
10686 }
10687
10688 /* Implement the "explains_signal" breakpoint_ops method for
10689    watchpoints.  */
10690
10691 static enum bpstat_signal_value
10692 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10693 {
10694   /* A software watchpoint cannot cause a signal other than
10695      GDB_SIGNAL_TRAP.  */
10696   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10697     return BPSTAT_SIGNAL_NO;
10698
10699   return BPSTAT_SIGNAL_HIDE;
10700 }
10701
10702 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10703
10704 static struct breakpoint_ops watchpoint_breakpoint_ops;
10705
10706 /* Implement the "insert" breakpoint_ops method for
10707    masked hardware watchpoints.  */
10708
10709 static int
10710 insert_masked_watchpoint (struct bp_location *bl)
10711 {
10712   struct watchpoint *w = (struct watchpoint *) bl->owner;
10713
10714   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10715                                         bl->watchpoint_type);
10716 }
10717
10718 /* Implement the "remove" breakpoint_ops method for
10719    masked hardware watchpoints.  */
10720
10721 static int
10722 remove_masked_watchpoint (struct bp_location *bl)
10723 {
10724   struct watchpoint *w = (struct watchpoint *) bl->owner;
10725
10726   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10727                                         bl->watchpoint_type);
10728 }
10729
10730 /* Implement the "resources_needed" breakpoint_ops method for
10731    masked hardware watchpoints.  */
10732
10733 static int
10734 resources_needed_masked_watchpoint (const struct bp_location *bl)
10735 {
10736   struct watchpoint *w = (struct watchpoint *) bl->owner;
10737
10738   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10739 }
10740
10741 /* Implement the "works_in_software_mode" breakpoint_ops method for
10742    masked hardware watchpoints.  */
10743
10744 static int
10745 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10746 {
10747   return 0;
10748 }
10749
10750 /* Implement the "print_it" breakpoint_ops method for
10751    masked hardware watchpoints.  */
10752
10753 static enum print_stop_action
10754 print_it_masked_watchpoint (bpstat bs)
10755 {
10756   struct breakpoint *b = bs->breakpoint_at;
10757   struct ui_out *uiout = current_uiout;
10758
10759   /* Masked watchpoints have only one location.  */
10760   gdb_assert (b->loc && b->loc->next == NULL);
10761
10762   switch (b->type)
10763     {
10764     case bp_hardware_watchpoint:
10765       annotate_watchpoint (b->number);
10766       if (ui_out_is_mi_like_p (uiout))
10767         ui_out_field_string
10768           (uiout, "reason",
10769            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10770       break;
10771
10772     case bp_read_watchpoint:
10773       if (ui_out_is_mi_like_p (uiout))
10774         ui_out_field_string
10775           (uiout, "reason",
10776            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10777       break;
10778
10779     case bp_access_watchpoint:
10780       if (ui_out_is_mi_like_p (uiout))
10781         ui_out_field_string
10782           (uiout, "reason",
10783            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10784       break;
10785     default:
10786       internal_error (__FILE__, __LINE__,
10787                       _("Invalid hardware watchpoint type."));
10788     }
10789
10790   mention (b);
10791   ui_out_text (uiout, _("\n\
10792 Check the underlying instruction at PC for the memory\n\
10793 address and value which triggered this watchpoint.\n"));
10794   ui_out_text (uiout, "\n");
10795
10796   /* More than one watchpoint may have been triggered.  */
10797   return PRINT_UNKNOWN;
10798 }
10799
10800 /* Implement the "print_one_detail" breakpoint_ops method for
10801    masked hardware watchpoints.  */
10802
10803 static void
10804 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10805                                     struct ui_out *uiout)
10806 {
10807   struct watchpoint *w = (struct watchpoint *) b;
10808
10809   /* Masked watchpoints have only one location.  */
10810   gdb_assert (b->loc && b->loc->next == NULL);
10811
10812   ui_out_text (uiout, "\tmask ");
10813   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10814   ui_out_text (uiout, "\n");
10815 }
10816
10817 /* Implement the "print_mention" breakpoint_ops method for
10818    masked hardware watchpoints.  */
10819
10820 static void
10821 print_mention_masked_watchpoint (struct breakpoint *b)
10822 {
10823   struct watchpoint *w = (struct watchpoint *) b;
10824   struct ui_out *uiout = current_uiout;
10825   struct cleanup *ui_out_chain;
10826
10827   switch (b->type)
10828     {
10829     case bp_hardware_watchpoint:
10830       ui_out_text (uiout, "Masked hardware watchpoint ");
10831       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10832       break;
10833     case bp_read_watchpoint:
10834       ui_out_text (uiout, "Masked hardware read watchpoint ");
10835       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10836       break;
10837     case bp_access_watchpoint:
10838       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10839       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10840       break;
10841     default:
10842       internal_error (__FILE__, __LINE__,
10843                       _("Invalid hardware watchpoint type."));
10844     }
10845
10846   ui_out_field_int (uiout, "number", b->number);
10847   ui_out_text (uiout, ": ");
10848   ui_out_field_string (uiout, "exp", w->exp_string);
10849   do_cleanups (ui_out_chain);
10850 }
10851
10852 /* Implement the "print_recreate" breakpoint_ops method for
10853    masked hardware watchpoints.  */
10854
10855 static void
10856 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10857 {
10858   struct watchpoint *w = (struct watchpoint *) b;
10859   char tmp[40];
10860
10861   switch (b->type)
10862     {
10863     case bp_hardware_watchpoint:
10864       fprintf_unfiltered (fp, "watch");
10865       break;
10866     case bp_read_watchpoint:
10867       fprintf_unfiltered (fp, "rwatch");
10868       break;
10869     case bp_access_watchpoint:
10870       fprintf_unfiltered (fp, "awatch");
10871       break;
10872     default:
10873       internal_error (__FILE__, __LINE__,
10874                       _("Invalid hardware watchpoint type."));
10875     }
10876
10877   sprintf_vma (tmp, w->hw_wp_mask);
10878   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10879   print_recreate_thread (b, fp);
10880 }
10881
10882 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10883
10884 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10885
10886 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10887
10888 static int
10889 is_masked_watchpoint (const struct breakpoint *b)
10890 {
10891   return b->ops == &masked_watchpoint_breakpoint_ops;
10892 }
10893
10894 /* accessflag:  hw_write:  watch write, 
10895                 hw_read:   watch read, 
10896                 hw_access: watch access (read or write) */
10897 static void
10898 watch_command_1 (const char *arg, int accessflag, int from_tty,
10899                  int just_location, int internal)
10900 {
10901   volatile struct gdb_exception e;
10902   struct breakpoint *b, *scope_breakpoint = NULL;
10903   struct expression *exp;
10904   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10905   struct value *val, *mark, *result;
10906   struct frame_info *frame;
10907   const char *exp_start = NULL;
10908   const char *exp_end = NULL;
10909   const char *tok, *end_tok;
10910   int toklen = -1;
10911   const char *cond_start = NULL;
10912   const char *cond_end = NULL;
10913   enum bptype bp_type;
10914   int thread = -1;
10915   int pc = 0;
10916   /* Flag to indicate whether we are going to use masks for
10917      the hardware watchpoint.  */
10918   int use_mask = 0;
10919   CORE_ADDR mask = 0;
10920   struct watchpoint *w;
10921   char *expression;
10922   struct cleanup *back_to;
10923
10924   /* Make sure that we actually have parameters to parse.  */
10925   if (arg != NULL && arg[0] != '\0')
10926     {
10927       const char *value_start;
10928
10929       exp_end = arg + strlen (arg);
10930
10931       /* Look for "parameter value" pairs at the end
10932          of the arguments string.  */
10933       for (tok = exp_end - 1; tok > arg; tok--)
10934         {
10935           /* Skip whitespace at the end of the argument list.  */
10936           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10937             tok--;
10938
10939           /* Find the beginning of the last token.
10940              This is the value of the parameter.  */
10941           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10942             tok--;
10943           value_start = tok + 1;
10944
10945           /* Skip whitespace.  */
10946           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10947             tok--;
10948
10949           end_tok = tok;
10950
10951           /* Find the beginning of the second to last token.
10952              This is the parameter itself.  */
10953           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10954             tok--;
10955           tok++;
10956           toklen = end_tok - tok + 1;
10957
10958           if (toklen == 6 && !strncmp (tok, "thread", 6))
10959             {
10960               /* At this point we've found a "thread" token, which means
10961                  the user is trying to set a watchpoint that triggers
10962                  only in a specific thread.  */
10963               char *endp;
10964
10965               if (thread != -1)
10966                 error(_("You can specify only one thread."));
10967
10968               /* Extract the thread ID from the next token.  */
10969               thread = strtol (value_start, &endp, 0);
10970
10971               /* Check if the user provided a valid numeric value for the
10972                  thread ID.  */
10973               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10974                 error (_("Invalid thread ID specification %s."), value_start);
10975
10976               /* Check if the thread actually exists.  */
10977               if (!valid_thread_id (thread))
10978                 invalid_thread_id_error (thread);
10979             }
10980           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10981             {
10982               /* We've found a "mask" token, which means the user wants to
10983                  create a hardware watchpoint that is going to have the mask
10984                  facility.  */
10985               struct value *mask_value, *mark;
10986
10987               if (use_mask)
10988                 error(_("You can specify only one mask."));
10989
10990               use_mask = just_location = 1;
10991
10992               mark = value_mark ();
10993               mask_value = parse_to_comma_and_eval (&value_start);
10994               mask = value_as_address (mask_value);
10995               value_free_to_mark (mark);
10996             }
10997           else
10998             /* We didn't recognize what we found.  We should stop here.  */
10999             break;
11000
11001           /* Truncate the string and get rid of the "parameter value" pair before
11002              the arguments string is parsed by the parse_exp_1 function.  */
11003           exp_end = tok;
11004         }
11005     }
11006   else
11007     exp_end = arg;
11008
11009   /* Parse the rest of the arguments.  From here on out, everything
11010      is in terms of a newly allocated string instead of the original
11011      ARG.  */
11012   innermost_block = NULL;
11013   expression = savestring (arg, exp_end - arg);
11014   back_to = make_cleanup (xfree, expression);
11015   exp_start = arg = expression;
11016   exp = parse_exp_1 (&arg, 0, 0, 0);
11017   exp_end = arg;
11018   /* Remove trailing whitespace from the expression before saving it.
11019      This makes the eventual display of the expression string a bit
11020      prettier.  */
11021   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11022     --exp_end;
11023
11024   /* Checking if the expression is not constant.  */
11025   if (watchpoint_exp_is_const (exp))
11026     {
11027       int len;
11028
11029       len = exp_end - exp_start;
11030       while (len > 0 && isspace (exp_start[len - 1]))
11031         len--;
11032       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11033     }
11034
11035   exp_valid_block = innermost_block;
11036   mark = value_mark ();
11037   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11038
11039   if (just_location)
11040     {
11041       int ret;
11042
11043       exp_valid_block = NULL;
11044       val = value_addr (result);
11045       release_value (val);
11046       value_free_to_mark (mark);
11047
11048       if (use_mask)
11049         {
11050           ret = target_masked_watch_num_registers (value_as_address (val),
11051                                                    mask);
11052           if (ret == -1)
11053             error (_("This target does not support masked watchpoints."));
11054           else if (ret == -2)
11055             error (_("Invalid mask or memory region."));
11056         }
11057     }
11058   else if (val != NULL)
11059     release_value (val);
11060
11061   tok = skip_spaces_const (arg);
11062   end_tok = skip_to_space_const (tok);
11063
11064   toklen = end_tok - tok;
11065   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11066     {
11067       struct expression *cond;
11068
11069       innermost_block = NULL;
11070       tok = cond_start = end_tok + 1;
11071       cond = parse_exp_1 (&tok, 0, 0, 0);
11072
11073       /* The watchpoint expression may not be local, but the condition
11074          may still be.  E.g.: `watch global if local > 0'.  */
11075       cond_exp_valid_block = innermost_block;
11076
11077       xfree (cond);
11078       cond_end = tok;
11079     }
11080   if (*tok)
11081     error (_("Junk at end of command."));
11082
11083   if (accessflag == hw_read)
11084     bp_type = bp_read_watchpoint;
11085   else if (accessflag == hw_access)
11086     bp_type = bp_access_watchpoint;
11087   else
11088     bp_type = bp_hardware_watchpoint;
11089
11090   frame = block_innermost_frame (exp_valid_block);
11091
11092   /* If the expression is "local", then set up a "watchpoint scope"
11093      breakpoint at the point where we've left the scope of the watchpoint
11094      expression.  Create the scope breakpoint before the watchpoint, so
11095      that we will encounter it first in bpstat_stop_status.  */
11096   if (exp_valid_block && frame)
11097     {
11098       if (frame_id_p (frame_unwind_caller_id (frame)))
11099         {
11100           scope_breakpoint
11101             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11102                                           frame_unwind_caller_pc (frame),
11103                                           bp_watchpoint_scope,
11104                                           &momentary_breakpoint_ops);
11105
11106           scope_breakpoint->enable_state = bp_enabled;
11107
11108           /* Automatically delete the breakpoint when it hits.  */
11109           scope_breakpoint->disposition = disp_del;
11110
11111           /* Only break in the proper frame (help with recursion).  */
11112           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11113
11114           /* Set the address at which we will stop.  */
11115           scope_breakpoint->loc->gdbarch
11116             = frame_unwind_caller_arch (frame);
11117           scope_breakpoint->loc->requested_address
11118             = frame_unwind_caller_pc (frame);
11119           scope_breakpoint->loc->address
11120             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11121                                          scope_breakpoint->loc->requested_address,
11122                                          scope_breakpoint->type);
11123         }
11124     }
11125
11126   /* Now set up the breakpoint.  */
11127
11128   w = XCNEW (struct watchpoint);
11129   b = &w->base;
11130   if (use_mask)
11131     init_raw_breakpoint_without_location (b, NULL, bp_type,
11132                                           &masked_watchpoint_breakpoint_ops);
11133   else
11134     init_raw_breakpoint_without_location (b, NULL, bp_type,
11135                                           &watchpoint_breakpoint_ops);
11136   b->thread = thread;
11137   b->disposition = disp_donttouch;
11138   b->pspace = current_program_space;
11139   w->exp = exp;
11140   w->exp_valid_block = exp_valid_block;
11141   w->cond_exp_valid_block = cond_exp_valid_block;
11142   if (just_location)
11143     {
11144       struct type *t = value_type (val);
11145       CORE_ADDR addr = value_as_address (val);
11146       char *name;
11147
11148       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11149       name = type_to_string (t);
11150
11151       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11152                                           core_addr_to_string (addr));
11153       xfree (name);
11154
11155       w->exp_string = xstrprintf ("-location %.*s",
11156                                   (int) (exp_end - exp_start), exp_start);
11157
11158       /* The above expression is in C.  */
11159       b->language = language_c;
11160     }
11161   else
11162     w->exp_string = savestring (exp_start, exp_end - exp_start);
11163
11164   if (use_mask)
11165     {
11166       w->hw_wp_mask = mask;
11167     }
11168   else
11169     {
11170       w->val = val;
11171       w->val_valid = 1;
11172     }
11173
11174   if (cond_start)
11175     b->cond_string = savestring (cond_start, cond_end - cond_start);
11176   else
11177     b->cond_string = 0;
11178
11179   if (frame)
11180     {
11181       w->watchpoint_frame = get_frame_id (frame);
11182       w->watchpoint_thread = inferior_ptid;
11183     }
11184   else
11185     {
11186       w->watchpoint_frame = null_frame_id;
11187       w->watchpoint_thread = null_ptid;
11188     }
11189
11190   if (scope_breakpoint != NULL)
11191     {
11192       /* The scope breakpoint is related to the watchpoint.  We will
11193          need to act on them together.  */
11194       b->related_breakpoint = scope_breakpoint;
11195       scope_breakpoint->related_breakpoint = b;
11196     }
11197
11198   if (!just_location)
11199     value_free_to_mark (mark);
11200
11201   TRY_CATCH (e, RETURN_MASK_ALL)
11202     {
11203       /* Finally update the new watchpoint.  This creates the locations
11204          that should be inserted.  */
11205       update_watchpoint (w, 1);
11206     }
11207   if (e.reason < 0)
11208     {
11209       delete_breakpoint (b);
11210       throw_exception (e);
11211     }
11212
11213   install_breakpoint (internal, b, 1);
11214   do_cleanups (back_to);
11215 }
11216
11217 /* Return count of debug registers needed to watch the given expression.
11218    If the watchpoint cannot be handled in hardware return zero.  */
11219
11220 static int
11221 can_use_hardware_watchpoint (struct value *v)
11222 {
11223   int found_memory_cnt = 0;
11224   struct value *head = v;
11225
11226   /* Did the user specifically forbid us to use hardware watchpoints? */
11227   if (!can_use_hw_watchpoints)
11228     return 0;
11229
11230   /* Make sure that the value of the expression depends only upon
11231      memory contents, and values computed from them within GDB.  If we
11232      find any register references or function calls, we can't use a
11233      hardware watchpoint.
11234
11235      The idea here is that evaluating an expression generates a series
11236      of values, one holding the value of every subexpression.  (The
11237      expression a*b+c has five subexpressions: a, b, a*b, c, and
11238      a*b+c.)  GDB's values hold almost enough information to establish
11239      the criteria given above --- they identify memory lvalues,
11240      register lvalues, computed values, etcetera.  So we can evaluate
11241      the expression, and then scan the chain of values that leaves
11242      behind to decide whether we can detect any possible change to the
11243      expression's final value using only hardware watchpoints.
11244
11245      However, I don't think that the values returned by inferior
11246      function calls are special in any way.  So this function may not
11247      notice that an expression involving an inferior function call
11248      can't be watched with hardware watchpoints.  FIXME.  */
11249   for (; v; v = value_next (v))
11250     {
11251       if (VALUE_LVAL (v) == lval_memory)
11252         {
11253           if (v != head && value_lazy (v))
11254             /* A lazy memory lvalue in the chain is one that GDB never
11255                needed to fetch; we either just used its address (e.g.,
11256                `a' in `a.b') or we never needed it at all (e.g., `a'
11257                in `a,b').  This doesn't apply to HEAD; if that is
11258                lazy then it was not readable, but watch it anyway.  */
11259             ;
11260           else
11261             {
11262               /* Ahh, memory we actually used!  Check if we can cover
11263                  it with hardware watchpoints.  */
11264               struct type *vtype = check_typedef (value_type (v));
11265
11266               /* We only watch structs and arrays if user asked for it
11267                  explicitly, never if they just happen to appear in a
11268                  middle of some value chain.  */
11269               if (v == head
11270                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11271                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11272                 {
11273                   CORE_ADDR vaddr = value_address (v);
11274                   int len;
11275                   int num_regs;
11276
11277                   len = (target_exact_watchpoints
11278                          && is_scalar_type_recursive (vtype))?
11279                     1 : TYPE_LENGTH (value_type (v));
11280
11281                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11282                   if (!num_regs)
11283                     return 0;
11284                   else
11285                     found_memory_cnt += num_regs;
11286                 }
11287             }
11288         }
11289       else if (VALUE_LVAL (v) != not_lval
11290                && deprecated_value_modifiable (v) == 0)
11291         return 0;       /* These are values from the history (e.g., $1).  */
11292       else if (VALUE_LVAL (v) == lval_register)
11293         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11294     }
11295
11296   /* The expression itself looks suitable for using a hardware
11297      watchpoint, but give the target machine a chance to reject it.  */
11298   return found_memory_cnt;
11299 }
11300
11301 void
11302 watch_command_wrapper (char *arg, int from_tty, int internal)
11303 {
11304   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11305 }
11306
11307 /* A helper function that looks for the "-location" argument and then
11308    calls watch_command_1.  */
11309
11310 static void
11311 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11312 {
11313   int just_location = 0;
11314
11315   if (arg
11316       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11317           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11318     {
11319       arg = skip_spaces (arg);
11320       just_location = 1;
11321     }
11322
11323   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11324 }
11325
11326 static void
11327 watch_command (char *arg, int from_tty)
11328 {
11329   watch_maybe_just_location (arg, hw_write, from_tty);
11330 }
11331
11332 void
11333 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11334 {
11335   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11336 }
11337
11338 static void
11339 rwatch_command (char *arg, int from_tty)
11340 {
11341   watch_maybe_just_location (arg, hw_read, from_tty);
11342 }
11343
11344 void
11345 awatch_command_wrapper (char *arg, int from_tty, int internal)
11346 {
11347   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11348 }
11349
11350 static void
11351 awatch_command (char *arg, int from_tty)
11352 {
11353   watch_maybe_just_location (arg, hw_access, from_tty);
11354 }
11355 \f
11356
11357 /* Helper routines for the until_command routine in infcmd.c.  Here
11358    because it uses the mechanisms of breakpoints.  */
11359
11360 struct until_break_command_continuation_args
11361 {
11362   struct breakpoint *breakpoint;
11363   struct breakpoint *breakpoint2;
11364   int thread_num;
11365 };
11366
11367 /* This function is called by fetch_inferior_event via the
11368    cmd_continuation pointer, to complete the until command.  It takes
11369    care of cleaning up the temporary breakpoints set up by the until
11370    command.  */
11371 static void
11372 until_break_command_continuation (void *arg, int err)
11373 {
11374   struct until_break_command_continuation_args *a = arg;
11375
11376   delete_breakpoint (a->breakpoint);
11377   if (a->breakpoint2)
11378     delete_breakpoint (a->breakpoint2);
11379   delete_longjmp_breakpoint (a->thread_num);
11380 }
11381
11382 void
11383 until_break_command (char *arg, int from_tty, int anywhere)
11384 {
11385   struct symtabs_and_lines sals;
11386   struct symtab_and_line sal;
11387   struct frame_info *frame;
11388   struct gdbarch *frame_gdbarch;
11389   struct frame_id stack_frame_id;
11390   struct frame_id caller_frame_id;
11391   struct breakpoint *breakpoint;
11392   struct breakpoint *breakpoint2 = NULL;
11393   struct cleanup *old_chain;
11394   int thread;
11395   struct thread_info *tp;
11396
11397   clear_proceed_status ();
11398
11399   /* Set a breakpoint where the user wants it and at return from
11400      this function.  */
11401
11402   if (last_displayed_sal_is_valid ())
11403     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11404                           get_last_displayed_symtab (),
11405                           get_last_displayed_line ());
11406   else
11407     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11408                           (struct symtab *) NULL, 0);
11409
11410   if (sals.nelts != 1)
11411     error (_("Couldn't get information on specified line."));
11412
11413   sal = sals.sals[0];
11414   xfree (sals.sals);    /* malloc'd, so freed.  */
11415
11416   if (*arg)
11417     error (_("Junk at end of arguments."));
11418
11419   resolve_sal_pc (&sal);
11420
11421   tp = inferior_thread ();
11422   thread = tp->num;
11423
11424   old_chain = make_cleanup (null_cleanup, NULL);
11425
11426   /* Note linespec handling above invalidates the frame chain.
11427      Installing a breakpoint also invalidates the frame chain (as it
11428      may need to switch threads), so do any frame handling before
11429      that.  */
11430
11431   frame = get_selected_frame (NULL);
11432   frame_gdbarch = get_frame_arch (frame);
11433   stack_frame_id = get_stack_frame_id (frame);
11434   caller_frame_id = frame_unwind_caller_id (frame);
11435
11436   /* Keep within the current frame, or in frames called by the current
11437      one.  */
11438
11439   if (frame_id_p (caller_frame_id))
11440     {
11441       struct symtab_and_line sal2;
11442
11443       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11444       sal2.pc = frame_unwind_caller_pc (frame);
11445       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11446                                               sal2,
11447                                               caller_frame_id,
11448                                               bp_until);
11449       make_cleanup_delete_breakpoint (breakpoint2);
11450
11451       set_longjmp_breakpoint (tp, caller_frame_id);
11452       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11453     }
11454
11455   /* set_momentary_breakpoint could invalidate FRAME.  */
11456   frame = NULL;
11457
11458   if (anywhere)
11459     /* If the user told us to continue until a specified location,
11460        we don't specify a frame at which we need to stop.  */
11461     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11462                                            null_frame_id, bp_until);
11463   else
11464     /* Otherwise, specify the selected frame, because we want to stop
11465        only at the very same frame.  */
11466     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11467                                            stack_frame_id, bp_until);
11468   make_cleanup_delete_breakpoint (breakpoint);
11469
11470   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11471
11472   /* If we are running asynchronously, and proceed call above has
11473      actually managed to start the target, arrange for breakpoints to
11474      be deleted when the target stops.  Otherwise, we're already
11475      stopped and delete breakpoints via cleanup chain.  */
11476
11477   if (target_can_async_p () && is_running (inferior_ptid))
11478     {
11479       struct until_break_command_continuation_args *args;
11480       args = xmalloc (sizeof (*args));
11481
11482       args->breakpoint = breakpoint;
11483       args->breakpoint2 = breakpoint2;
11484       args->thread_num = thread;
11485
11486       discard_cleanups (old_chain);
11487       add_continuation (inferior_thread (),
11488                         until_break_command_continuation, args,
11489                         xfree);
11490     }
11491   else
11492     do_cleanups (old_chain);
11493 }
11494
11495 /* This function attempts to parse an optional "if <cond>" clause
11496    from the arg string.  If one is not found, it returns NULL.
11497
11498    Else, it returns a pointer to the condition string.  (It does not
11499    attempt to evaluate the string against a particular block.)  And,
11500    it updates arg to point to the first character following the parsed
11501    if clause in the arg string.  */
11502
11503 char *
11504 ep_parse_optional_if_clause (char **arg)
11505 {
11506   char *cond_string;
11507
11508   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11509     return NULL;
11510
11511   /* Skip the "if" keyword.  */
11512   (*arg) += 2;
11513
11514   /* Skip any extra leading whitespace, and record the start of the
11515      condition string.  */
11516   *arg = skip_spaces (*arg);
11517   cond_string = *arg;
11518
11519   /* Assume that the condition occupies the remainder of the arg
11520      string.  */
11521   (*arg) += strlen (cond_string);
11522
11523   return cond_string;
11524 }
11525
11526 /* Commands to deal with catching events, such as signals, exceptions,
11527    process start/exit, etc.  */
11528
11529 typedef enum
11530 {
11531   catch_fork_temporary, catch_vfork_temporary,
11532   catch_fork_permanent, catch_vfork_permanent
11533 }
11534 catch_fork_kind;
11535
11536 static void
11537 catch_fork_command_1 (char *arg, int from_tty, 
11538                       struct cmd_list_element *command)
11539 {
11540   struct gdbarch *gdbarch = get_current_arch ();
11541   char *cond_string = NULL;
11542   catch_fork_kind fork_kind;
11543   int tempflag;
11544
11545   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11546   tempflag = (fork_kind == catch_fork_temporary
11547               || fork_kind == catch_vfork_temporary);
11548
11549   if (!arg)
11550     arg = "";
11551   arg = skip_spaces (arg);
11552
11553   /* The allowed syntax is:
11554      catch [v]fork
11555      catch [v]fork if <cond>
11556
11557      First, check if there's an if clause.  */
11558   cond_string = ep_parse_optional_if_clause (&arg);
11559
11560   if ((*arg != '\0') && !isspace (*arg))
11561     error (_("Junk at end of arguments."));
11562
11563   /* If this target supports it, create a fork or vfork catchpoint
11564      and enable reporting of such events.  */
11565   switch (fork_kind)
11566     {
11567     case catch_fork_temporary:
11568     case catch_fork_permanent:
11569       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11570                                           &catch_fork_breakpoint_ops);
11571       break;
11572     case catch_vfork_temporary:
11573     case catch_vfork_permanent:
11574       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11575                                           &catch_vfork_breakpoint_ops);
11576       break;
11577     default:
11578       error (_("unsupported or unknown fork kind; cannot catch it"));
11579       break;
11580     }
11581 }
11582
11583 static void
11584 catch_exec_command_1 (char *arg, int from_tty, 
11585                       struct cmd_list_element *command)
11586 {
11587   struct exec_catchpoint *c;
11588   struct gdbarch *gdbarch = get_current_arch ();
11589   int tempflag;
11590   char *cond_string = NULL;
11591
11592   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11593
11594   if (!arg)
11595     arg = "";
11596   arg = skip_spaces (arg);
11597
11598   /* The allowed syntax is:
11599      catch exec
11600      catch exec if <cond>
11601
11602      First, check if there's an if clause.  */
11603   cond_string = ep_parse_optional_if_clause (&arg);
11604
11605   if ((*arg != '\0') && !isspace (*arg))
11606     error (_("Junk at end of arguments."));
11607
11608   c = XNEW (struct exec_catchpoint);
11609   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11610                    &catch_exec_breakpoint_ops);
11611   c->exec_pathname = NULL;
11612
11613   install_breakpoint (0, &c->base, 1);
11614 }
11615
11616 void
11617 init_ada_exception_breakpoint (struct breakpoint *b,
11618                                struct gdbarch *gdbarch,
11619                                struct symtab_and_line sal,
11620                                char *addr_string,
11621                                const struct breakpoint_ops *ops,
11622                                int tempflag,
11623                                int from_tty)
11624 {
11625   if (from_tty)
11626     {
11627       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11628       if (!loc_gdbarch)
11629         loc_gdbarch = gdbarch;
11630
11631       describe_other_breakpoints (loc_gdbarch,
11632                                   sal.pspace, sal.pc, sal.section, -1);
11633       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11634          version for exception catchpoints, because two catchpoints
11635          used for different exception names will use the same address.
11636          In this case, a "breakpoint ... also set at..." warning is
11637          unproductive.  Besides, the warning phrasing is also a bit
11638          inappropriate, we should use the word catchpoint, and tell
11639          the user what type of catchpoint it is.  The above is good
11640          enough for now, though.  */
11641     }
11642
11643   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11644
11645   b->enable_state = bp_enabled;
11646   b->disposition = tempflag ? disp_del : disp_donttouch;
11647   b->addr_string = addr_string;
11648   b->language = language_ada;
11649 }
11650
11651 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11652    filter list, or NULL if no filtering is required.  */
11653 static VEC(int) *
11654 catch_syscall_split_args (char *arg)
11655 {
11656   VEC(int) *result = NULL;
11657   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11658
11659   while (*arg != '\0')
11660     {
11661       int i, syscall_number;
11662       char *endptr;
11663       char cur_name[128];
11664       struct syscall s;
11665
11666       /* Skip whitespace.  */
11667       arg = skip_spaces (arg);
11668
11669       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11670         cur_name[i] = arg[i];
11671       cur_name[i] = '\0';
11672       arg += i;
11673
11674       /* Check if the user provided a syscall name or a number.  */
11675       syscall_number = (int) strtol (cur_name, &endptr, 0);
11676       if (*endptr == '\0')
11677         get_syscall_by_number (syscall_number, &s);
11678       else
11679         {
11680           /* We have a name.  Let's check if it's valid and convert it
11681              to a number.  */
11682           get_syscall_by_name (cur_name, &s);
11683
11684           if (s.number == UNKNOWN_SYSCALL)
11685             /* Here we have to issue an error instead of a warning,
11686                because GDB cannot do anything useful if there's no
11687                syscall number to be caught.  */
11688             error (_("Unknown syscall name '%s'."), cur_name);
11689         }
11690
11691       /* Ok, it's valid.  */
11692       VEC_safe_push (int, result, s.number);
11693     }
11694
11695   discard_cleanups (cleanup);
11696   return result;
11697 }
11698
11699 /* Implement the "catch syscall" command.  */
11700
11701 static void
11702 catch_syscall_command_1 (char *arg, int from_tty, 
11703                          struct cmd_list_element *command)
11704 {
11705   int tempflag;
11706   VEC(int) *filter;
11707   struct syscall s;
11708   struct gdbarch *gdbarch = get_current_arch ();
11709
11710   /* Checking if the feature if supported.  */
11711   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11712     error (_("The feature 'catch syscall' is not supported on \
11713 this architecture yet."));
11714
11715   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11716
11717   arg = skip_spaces (arg);
11718
11719   /* We need to do this first "dummy" translation in order
11720      to get the syscall XML file loaded or, most important,
11721      to display a warning to the user if there's no XML file
11722      for his/her architecture.  */
11723   get_syscall_by_number (0, &s);
11724
11725   /* The allowed syntax is:
11726      catch syscall
11727      catch syscall <name | number> [<name | number> ... <name | number>]
11728
11729      Let's check if there's a syscall name.  */
11730
11731   if (arg != NULL)
11732     filter = catch_syscall_split_args (arg);
11733   else
11734     filter = NULL;
11735
11736   create_syscall_event_catchpoint (tempflag, filter,
11737                                    &catch_syscall_breakpoint_ops);
11738 }
11739
11740 static void
11741 catch_command (char *arg, int from_tty)
11742 {
11743   error (_("Catch requires an event name."));
11744 }
11745 \f
11746
11747 static void
11748 tcatch_command (char *arg, int from_tty)
11749 {
11750   error (_("Catch requires an event name."));
11751 }
11752
11753 /* A qsort comparison function that sorts breakpoints in order.  */
11754
11755 static int
11756 compare_breakpoints (const void *a, const void *b)
11757 {
11758   const breakpoint_p *ba = a;
11759   uintptr_t ua = (uintptr_t) *ba;
11760   const breakpoint_p *bb = b;
11761   uintptr_t ub = (uintptr_t) *bb;
11762
11763   if ((*ba)->number < (*bb)->number)
11764     return -1;
11765   else if ((*ba)->number > (*bb)->number)
11766     return 1;
11767
11768   /* Now sort by address, in case we see, e..g, two breakpoints with
11769      the number 0.  */
11770   if (ua < ub)
11771     return -1;
11772   return ua > ub ? 1 : 0;
11773 }
11774
11775 /* Delete breakpoints by address or line.  */
11776
11777 static void
11778 clear_command (char *arg, int from_tty)
11779 {
11780   struct breakpoint *b, *prev;
11781   VEC(breakpoint_p) *found = 0;
11782   int ix;
11783   int default_match;
11784   struct symtabs_and_lines sals;
11785   struct symtab_and_line sal;
11786   int i;
11787   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11788
11789   if (arg)
11790     {
11791       sals = decode_line_with_current_source (arg,
11792                                               (DECODE_LINE_FUNFIRSTLINE
11793                                                | DECODE_LINE_LIST_MODE));
11794       make_cleanup (xfree, sals.sals);
11795       default_match = 0;
11796     }
11797   else
11798     {
11799       sals.sals = (struct symtab_and_line *)
11800         xmalloc (sizeof (struct symtab_and_line));
11801       make_cleanup (xfree, sals.sals);
11802       init_sal (&sal);          /* Initialize to zeroes.  */
11803
11804       /* Set sal's line, symtab, pc, and pspace to the values
11805          corresponding to the last call to print_frame_info.  If the
11806          codepoint is not valid, this will set all the fields to 0.  */
11807       get_last_displayed_sal (&sal);
11808       if (sal.symtab == 0)
11809         error (_("No source file specified."));
11810
11811       sals.sals[0] = sal;
11812       sals.nelts = 1;
11813
11814       default_match = 1;
11815     }
11816
11817   /* We don't call resolve_sal_pc here.  That's not as bad as it
11818      seems, because all existing breakpoints typically have both
11819      file/line and pc set.  So, if clear is given file/line, we can
11820      match this to existing breakpoint without obtaining pc at all.
11821
11822      We only support clearing given the address explicitly 
11823      present in breakpoint table.  Say, we've set breakpoint 
11824      at file:line.  There were several PC values for that file:line,
11825      due to optimization, all in one block.
11826
11827      We've picked one PC value.  If "clear" is issued with another
11828      PC corresponding to the same file:line, the breakpoint won't
11829      be cleared.  We probably can still clear the breakpoint, but 
11830      since the other PC value is never presented to user, user
11831      can only find it by guessing, and it does not seem important
11832      to support that.  */
11833
11834   /* For each line spec given, delete bps which correspond to it.  Do
11835      it in two passes, solely to preserve the current behavior that
11836      from_tty is forced true if we delete more than one
11837      breakpoint.  */
11838
11839   found = NULL;
11840   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11841   for (i = 0; i < sals.nelts; i++)
11842     {
11843       const char *sal_fullname;
11844
11845       /* If exact pc given, clear bpts at that pc.
11846          If line given (pc == 0), clear all bpts on specified line.
11847          If defaulting, clear all bpts on default line
11848          or at default pc.
11849
11850          defaulting    sal.pc != 0    tests to do
11851
11852          0              1             pc
11853          1              1             pc _and_ line
11854          0              0             line
11855          1              0             <can't happen> */
11856
11857       sal = sals.sals[i];
11858       sal_fullname = (sal.symtab == NULL
11859                       ? NULL : symtab_to_fullname (sal.symtab));
11860
11861       /* Find all matching breakpoints and add them to 'found'.  */
11862       ALL_BREAKPOINTS (b)
11863         {
11864           int match = 0;
11865           /* Are we going to delete b?  */
11866           if (b->type != bp_none && !is_watchpoint (b))
11867             {
11868               struct bp_location *loc = b->loc;
11869               for (; loc; loc = loc->next)
11870                 {
11871                   /* If the user specified file:line, don't allow a PC
11872                      match.  This matches historical gdb behavior.  */
11873                   int pc_match = (!sal.explicit_line
11874                                   && sal.pc
11875                                   && (loc->pspace == sal.pspace)
11876                                   && (loc->address == sal.pc)
11877                                   && (!section_is_overlay (loc->section)
11878                                       || loc->section == sal.section));
11879                   int line_match = 0;
11880
11881                   if ((default_match || sal.explicit_line)
11882                       && loc->symtab != NULL
11883                       && sal_fullname != NULL
11884                       && sal.pspace == loc->pspace
11885                       && loc->line_number == sal.line
11886                       && filename_cmp (symtab_to_fullname (loc->symtab),
11887                                        sal_fullname) == 0)
11888                     line_match = 1;
11889
11890                   if (pc_match || line_match)
11891                     {
11892                       match = 1;
11893                       break;
11894                     }
11895                 }
11896             }
11897
11898           if (match)
11899             VEC_safe_push(breakpoint_p, found, b);
11900         }
11901     }
11902
11903   /* Now go thru the 'found' chain and delete them.  */
11904   if (VEC_empty(breakpoint_p, found))
11905     {
11906       if (arg)
11907         error (_("No breakpoint at %s."), arg);
11908       else
11909         error (_("No breakpoint at this line."));
11910     }
11911
11912   /* Remove duplicates from the vec.  */
11913   qsort (VEC_address (breakpoint_p, found),
11914          VEC_length (breakpoint_p, found),
11915          sizeof (breakpoint_p),
11916          compare_breakpoints);
11917   prev = VEC_index (breakpoint_p, found, 0);
11918   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11919     {
11920       if (b == prev)
11921         {
11922           VEC_ordered_remove (breakpoint_p, found, ix);
11923           --ix;
11924         }
11925     }
11926
11927   if (VEC_length(breakpoint_p, found) > 1)
11928     from_tty = 1;       /* Always report if deleted more than one.  */
11929   if (from_tty)
11930     {
11931       if (VEC_length(breakpoint_p, found) == 1)
11932         printf_unfiltered (_("Deleted breakpoint "));
11933       else
11934         printf_unfiltered (_("Deleted breakpoints "));
11935     }
11936
11937   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11938     {
11939       if (from_tty)
11940         printf_unfiltered ("%d ", b->number);
11941       delete_breakpoint (b);
11942     }
11943   if (from_tty)
11944     putchar_unfiltered ('\n');
11945
11946   do_cleanups (cleanups);
11947 }
11948 \f
11949 /* Delete breakpoint in BS if they are `delete' breakpoints and
11950    all breakpoints that are marked for deletion, whether hit or not.
11951    This is called after any breakpoint is hit, or after errors.  */
11952
11953 void
11954 breakpoint_auto_delete (bpstat bs)
11955 {
11956   struct breakpoint *b, *b_tmp;
11957
11958   for (; bs; bs = bs->next)
11959     if (bs->breakpoint_at
11960         && bs->breakpoint_at->disposition == disp_del
11961         && bs->stop)
11962       delete_breakpoint (bs->breakpoint_at);
11963
11964   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11965   {
11966     if (b->disposition == disp_del_at_next_stop)
11967       delete_breakpoint (b);
11968   }
11969 }
11970
11971 /* A comparison function for bp_location AP and BP being interfaced to
11972    qsort.  Sort elements primarily by their ADDRESS (no matter what
11973    does breakpoint_address_is_meaningful say for its OWNER),
11974    secondarily by ordering first bp_permanent OWNERed elements and
11975    terciarily just ensuring the array is sorted stable way despite
11976    qsort being an unstable algorithm.  */
11977
11978 static int
11979 bp_location_compare (const void *ap, const void *bp)
11980 {
11981   struct bp_location *a = *(void **) ap;
11982   struct bp_location *b = *(void **) bp;
11983   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11984   int a_perm = a->owner->enable_state == bp_permanent;
11985   int b_perm = b->owner->enable_state == bp_permanent;
11986
11987   if (a->address != b->address)
11988     return (a->address > b->address) - (a->address < b->address);
11989
11990   /* Sort locations at the same address by their pspace number, keeping
11991      locations of the same inferior (in a multi-inferior environment)
11992      grouped.  */
11993
11994   if (a->pspace->num != b->pspace->num)
11995     return ((a->pspace->num > b->pspace->num)
11996             - (a->pspace->num < b->pspace->num));
11997
11998   /* Sort permanent breakpoints first.  */
11999   if (a_perm != b_perm)
12000     return (a_perm < b_perm) - (a_perm > b_perm);
12001
12002   /* Make the internal GDB representation stable across GDB runs
12003      where A and B memory inside GDB can differ.  Breakpoint locations of
12004      the same type at the same address can be sorted in arbitrary order.  */
12005
12006   if (a->owner->number != b->owner->number)
12007     return ((a->owner->number > b->owner->number)
12008             - (a->owner->number < b->owner->number));
12009
12010   return (a > b) - (a < b);
12011 }
12012
12013 /* Set bp_location_placed_address_before_address_max and
12014    bp_location_shadow_len_after_address_max according to the current
12015    content of the bp_location array.  */
12016
12017 static void
12018 bp_location_target_extensions_update (void)
12019 {
12020   struct bp_location *bl, **blp_tmp;
12021
12022   bp_location_placed_address_before_address_max = 0;
12023   bp_location_shadow_len_after_address_max = 0;
12024
12025   ALL_BP_LOCATIONS (bl, blp_tmp)
12026     {
12027       CORE_ADDR start, end, addr;
12028
12029       if (!bp_location_has_shadow (bl))
12030         continue;
12031
12032       start = bl->target_info.placed_address;
12033       end = start + bl->target_info.shadow_len;
12034
12035       gdb_assert (bl->address >= start);
12036       addr = bl->address - start;
12037       if (addr > bp_location_placed_address_before_address_max)
12038         bp_location_placed_address_before_address_max = addr;
12039
12040       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12041
12042       gdb_assert (bl->address < end);
12043       addr = end - bl->address;
12044       if (addr > bp_location_shadow_len_after_address_max)
12045         bp_location_shadow_len_after_address_max = addr;
12046     }
12047 }
12048
12049 /* Download tracepoint locations if they haven't been.  */
12050
12051 static void
12052 download_tracepoint_locations (void)
12053 {
12054   struct breakpoint *b;
12055   struct cleanup *old_chain;
12056
12057   if (!target_can_download_tracepoint ())
12058     return;
12059
12060   old_chain = save_current_space_and_thread ();
12061
12062   ALL_TRACEPOINTS (b)
12063     {
12064       struct bp_location *bl;
12065       struct tracepoint *t;
12066       int bp_location_downloaded = 0;
12067
12068       if ((b->type == bp_fast_tracepoint
12069            ? !may_insert_fast_tracepoints
12070            : !may_insert_tracepoints))
12071         continue;
12072
12073       for (bl = b->loc; bl; bl = bl->next)
12074         {
12075           /* In tracepoint, locations are _never_ duplicated, so
12076              should_be_inserted is equivalent to
12077              unduplicated_should_be_inserted.  */
12078           if (!should_be_inserted (bl) || bl->inserted)
12079             continue;
12080
12081           switch_to_program_space_and_thread (bl->pspace);
12082
12083           target_download_tracepoint (bl);
12084
12085           bl->inserted = 1;
12086           bp_location_downloaded = 1;
12087         }
12088       t = (struct tracepoint *) b;
12089       t->number_on_target = b->number;
12090       if (bp_location_downloaded)
12091         observer_notify_breakpoint_modified (b);
12092     }
12093
12094   do_cleanups (old_chain);
12095 }
12096
12097 /* Swap the insertion/duplication state between two locations.  */
12098
12099 static void
12100 swap_insertion (struct bp_location *left, struct bp_location *right)
12101 {
12102   const int left_inserted = left->inserted;
12103   const int left_duplicate = left->duplicate;
12104   const int left_needs_update = left->needs_update;
12105   const struct bp_target_info left_target_info = left->target_info;
12106
12107   /* Locations of tracepoints can never be duplicated.  */
12108   if (is_tracepoint (left->owner))
12109     gdb_assert (!left->duplicate);
12110   if (is_tracepoint (right->owner))
12111     gdb_assert (!right->duplicate);
12112
12113   left->inserted = right->inserted;
12114   left->duplicate = right->duplicate;
12115   left->needs_update = right->needs_update;
12116   left->target_info = right->target_info;
12117   right->inserted = left_inserted;
12118   right->duplicate = left_duplicate;
12119   right->needs_update = left_needs_update;
12120   right->target_info = left_target_info;
12121 }
12122
12123 /* Force the re-insertion of the locations at ADDRESS.  This is called
12124    once a new/deleted/modified duplicate location is found and we are evaluating
12125    conditions on the target's side.  Such conditions need to be updated on
12126    the target.  */
12127
12128 static void
12129 force_breakpoint_reinsertion (struct bp_location *bl)
12130 {
12131   struct bp_location **locp = NULL, **loc2p;
12132   struct bp_location *loc;
12133   CORE_ADDR address = 0;
12134   int pspace_num;
12135
12136   address = bl->address;
12137   pspace_num = bl->pspace->num;
12138
12139   /* This is only meaningful if the target is
12140      evaluating conditions and if the user has
12141      opted for condition evaluation on the target's
12142      side.  */
12143   if (gdb_evaluates_breakpoint_condition_p ()
12144       || !target_supports_evaluation_of_breakpoint_conditions ())
12145     return;
12146
12147   /* Flag all breakpoint locations with this address and
12148      the same program space as the location
12149      as "its condition has changed".  We need to
12150      update the conditions on the target's side.  */
12151   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12152     {
12153       loc = *loc2p;
12154
12155       if (!is_breakpoint (loc->owner)
12156           || pspace_num != loc->pspace->num)
12157         continue;
12158
12159       /* Flag the location appropriately.  We use a different state to
12160          let everyone know that we already updated the set of locations
12161          with addr bl->address and program space bl->pspace.  This is so
12162          we don't have to keep calling these functions just to mark locations
12163          that have already been marked.  */
12164       loc->condition_changed = condition_updated;
12165
12166       /* Free the agent expression bytecode as well.  We will compute
12167          it later on.  */
12168       if (loc->cond_bytecode)
12169         {
12170           free_agent_expr (loc->cond_bytecode);
12171           loc->cond_bytecode = NULL;
12172         }
12173     }
12174 }
12175
12176 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12177    into the inferior, only remove already-inserted locations that no
12178    longer should be inserted.  Functions that delete a breakpoint or
12179    breakpoints should pass false, so that deleting a breakpoint
12180    doesn't have the side effect of inserting the locations of other
12181    breakpoints that are marked not-inserted, but should_be_inserted
12182    returns true on them.
12183
12184    This behaviour is useful is situations close to tear-down -- e.g.,
12185    after an exec, while the target still has execution, but breakpoint
12186    shadows of the previous executable image should *NOT* be restored
12187    to the new image; or before detaching, where the target still has
12188    execution and wants to delete breakpoints from GDB's lists, and all
12189    breakpoints had already been removed from the inferior.  */
12190
12191 static void
12192 update_global_location_list (int should_insert)
12193 {
12194   struct breakpoint *b;
12195   struct bp_location **locp, *loc;
12196   struct cleanup *cleanups;
12197   /* Last breakpoint location address that was marked for update.  */
12198   CORE_ADDR last_addr = 0;
12199   /* Last breakpoint location program space that was marked for update.  */
12200   int last_pspace_num = -1;
12201
12202   /* Used in the duplicates detection below.  When iterating over all
12203      bp_locations, points to the first bp_location of a given address.
12204      Breakpoints and watchpoints of different types are never
12205      duplicates of each other.  Keep one pointer for each type of
12206      breakpoint/watchpoint, so we only need to loop over all locations
12207      once.  */
12208   struct bp_location *bp_loc_first;  /* breakpoint */
12209   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12210   struct bp_location *awp_loc_first; /* access watchpoint */
12211   struct bp_location *rwp_loc_first; /* read watchpoint */
12212
12213   /* Saved former bp_location array which we compare against the newly
12214      built bp_location from the current state of ALL_BREAKPOINTS.  */
12215   struct bp_location **old_location, **old_locp;
12216   unsigned old_location_count;
12217
12218   old_location = bp_location;
12219   old_location_count = bp_location_count;
12220   bp_location = NULL;
12221   bp_location_count = 0;
12222   cleanups = make_cleanup (xfree, old_location);
12223
12224   ALL_BREAKPOINTS (b)
12225     for (loc = b->loc; loc; loc = loc->next)
12226       bp_location_count++;
12227
12228   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12229   locp = bp_location;
12230   ALL_BREAKPOINTS (b)
12231     for (loc = b->loc; loc; loc = loc->next)
12232       *locp++ = loc;
12233   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12234          bp_location_compare);
12235
12236   bp_location_target_extensions_update ();
12237
12238   /* Identify bp_location instances that are no longer present in the
12239      new list, and therefore should be freed.  Note that it's not
12240      necessary that those locations should be removed from inferior --
12241      if there's another location at the same address (previously
12242      marked as duplicate), we don't need to remove/insert the
12243      location.
12244      
12245      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12246      and former bp_location array state respectively.  */
12247
12248   locp = bp_location;
12249   for (old_locp = old_location; old_locp < old_location + old_location_count;
12250        old_locp++)
12251     {
12252       struct bp_location *old_loc = *old_locp;
12253       struct bp_location **loc2p;
12254
12255       /* Tells if 'old_loc' is found among the new locations.  If
12256          not, we have to free it.  */
12257       int found_object = 0;
12258       /* Tells if the location should remain inserted in the target.  */
12259       int keep_in_target = 0;
12260       int removed = 0;
12261
12262       /* Skip LOCP entries which will definitely never be needed.
12263          Stop either at or being the one matching OLD_LOC.  */
12264       while (locp < bp_location + bp_location_count
12265              && (*locp)->address < old_loc->address)
12266         locp++;
12267
12268       for (loc2p = locp;
12269            (loc2p < bp_location + bp_location_count
12270             && (*loc2p)->address == old_loc->address);
12271            loc2p++)
12272         {
12273           /* Check if this is a new/duplicated location or a duplicated
12274              location that had its condition modified.  If so, we want to send
12275              its condition to the target if evaluation of conditions is taking
12276              place there.  */
12277           if ((*loc2p)->condition_changed == condition_modified
12278               && (last_addr != old_loc->address
12279                   || last_pspace_num != old_loc->pspace->num))
12280             {
12281               force_breakpoint_reinsertion (*loc2p);
12282               last_pspace_num = old_loc->pspace->num;
12283             }
12284
12285           if (*loc2p == old_loc)
12286             found_object = 1;
12287         }
12288
12289       /* We have already handled this address, update it so that we don't
12290          have to go through updates again.  */
12291       last_addr = old_loc->address;
12292
12293       /* Target-side condition evaluation: Handle deleted locations.  */
12294       if (!found_object)
12295         force_breakpoint_reinsertion (old_loc);
12296
12297       /* If this location is no longer present, and inserted, look if
12298          there's maybe a new location at the same address.  If so,
12299          mark that one inserted, and don't remove this one.  This is
12300          needed so that we don't have a time window where a breakpoint
12301          at certain location is not inserted.  */
12302
12303       if (old_loc->inserted)
12304         {
12305           /* If the location is inserted now, we might have to remove
12306              it.  */
12307
12308           if (found_object && should_be_inserted (old_loc))
12309             {
12310               /* The location is still present in the location list,
12311                  and still should be inserted.  Don't do anything.  */
12312               keep_in_target = 1;
12313             }
12314           else
12315             {
12316               /* This location still exists, but it won't be kept in the
12317                  target since it may have been disabled.  We proceed to
12318                  remove its target-side condition.  */
12319
12320               /* The location is either no longer present, or got
12321                  disabled.  See if there's another location at the
12322                  same address, in which case we don't need to remove
12323                  this one from the target.  */
12324
12325               /* OLD_LOC comes from existing struct breakpoint.  */
12326               if (breakpoint_address_is_meaningful (old_loc->owner))
12327                 {
12328                   for (loc2p = locp;
12329                        (loc2p < bp_location + bp_location_count
12330                         && (*loc2p)->address == old_loc->address);
12331                        loc2p++)
12332                     {
12333                       struct bp_location *loc2 = *loc2p;
12334
12335                       if (breakpoint_locations_match (loc2, old_loc))
12336                         {
12337                           /* Read watchpoint locations are switched to
12338                              access watchpoints, if the former are not
12339                              supported, but the latter are.  */
12340                           if (is_hardware_watchpoint (old_loc->owner))
12341                             {
12342                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12343                               loc2->watchpoint_type = old_loc->watchpoint_type;
12344                             }
12345
12346                           /* loc2 is a duplicated location. We need to check
12347                              if it should be inserted in case it will be
12348                              unduplicated.  */
12349                           if (loc2 != old_loc
12350                               && unduplicated_should_be_inserted (loc2))
12351                             {
12352                               swap_insertion (old_loc, loc2);
12353                               keep_in_target = 1;
12354                               break;
12355                             }
12356                         }
12357                     }
12358                 }
12359             }
12360
12361           if (!keep_in_target)
12362             {
12363               if (remove_breakpoint (old_loc, mark_uninserted))
12364                 {
12365                   /* This is just about all we can do.  We could keep
12366                      this location on the global list, and try to
12367                      remove it next time, but there's no particular
12368                      reason why we will succeed next time.
12369                      
12370                      Note that at this point, old_loc->owner is still
12371                      valid, as delete_breakpoint frees the breakpoint
12372                      only after calling us.  */
12373                   printf_filtered (_("warning: Error removing "
12374                                      "breakpoint %d\n"), 
12375                                    old_loc->owner->number);
12376                 }
12377               removed = 1;
12378             }
12379         }
12380
12381       if (!found_object)
12382         {
12383           if (removed && non_stop
12384               && breakpoint_address_is_meaningful (old_loc->owner)
12385               && !is_hardware_watchpoint (old_loc->owner))
12386             {
12387               /* This location was removed from the target.  In
12388                  non-stop mode, a race condition is possible where
12389                  we've removed a breakpoint, but stop events for that
12390                  breakpoint are already queued and will arrive later.
12391                  We apply an heuristic to be able to distinguish such
12392                  SIGTRAPs from other random SIGTRAPs: we keep this
12393                  breakpoint location for a bit, and will retire it
12394                  after we see some number of events.  The theory here
12395                  is that reporting of events should, "on the average",
12396                  be fair, so after a while we'll see events from all
12397                  threads that have anything of interest, and no longer
12398                  need to keep this breakpoint location around.  We
12399                  don't hold locations forever so to reduce chances of
12400                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12401                  SIGTRAP.
12402
12403                  The heuristic failing can be disastrous on
12404                  decr_pc_after_break targets.
12405
12406                  On decr_pc_after_break targets, like e.g., x86-linux,
12407                  if we fail to recognize a late breakpoint SIGTRAP,
12408                  because events_till_retirement has reached 0 too
12409                  soon, we'll fail to do the PC adjustment, and report
12410                  a random SIGTRAP to the user.  When the user resumes
12411                  the inferior, it will most likely immediately crash
12412                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12413                  corrupted, because of being resumed e.g., in the
12414                  middle of a multi-byte instruction, or skipped a
12415                  one-byte instruction.  This was actually seen happen
12416                  on native x86-linux, and should be less rare on
12417                  targets that do not support new thread events, like
12418                  remote, due to the heuristic depending on
12419                  thread_count.
12420
12421                  Mistaking a random SIGTRAP for a breakpoint trap
12422                  causes similar symptoms (PC adjustment applied when
12423                  it shouldn't), but then again, playing with SIGTRAPs
12424                  behind the debugger's back is asking for trouble.
12425
12426                  Since hardware watchpoint traps are always
12427                  distinguishable from other traps, so we don't need to
12428                  apply keep hardware watchpoint moribund locations
12429                  around.  We simply always ignore hardware watchpoint
12430                  traps we can no longer explain.  */
12431
12432               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12433               old_loc->owner = NULL;
12434
12435               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12436             }
12437           else
12438             {
12439               old_loc->owner = NULL;
12440               decref_bp_location (&old_loc);
12441             }
12442         }
12443     }
12444
12445   /* Rescan breakpoints at the same address and section, marking the
12446      first one as "first" and any others as "duplicates".  This is so
12447      that the bpt instruction is only inserted once.  If we have a
12448      permanent breakpoint at the same place as BPT, make that one the
12449      official one, and the rest as duplicates.  Permanent breakpoints
12450      are sorted first for the same address.
12451
12452      Do the same for hardware watchpoints, but also considering the
12453      watchpoint's type (regular/access/read) and length.  */
12454
12455   bp_loc_first = NULL;
12456   wp_loc_first = NULL;
12457   awp_loc_first = NULL;
12458   rwp_loc_first = NULL;
12459   ALL_BP_LOCATIONS (loc, locp)
12460     {
12461       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12462          non-NULL.  */
12463       struct bp_location **loc_first_p;
12464       b = loc->owner;
12465
12466       if (!unduplicated_should_be_inserted (loc)
12467           || !breakpoint_address_is_meaningful (b)
12468           /* Don't detect duplicate for tracepoint locations because they are
12469            never duplicated.  See the comments in field `duplicate' of
12470            `struct bp_location'.  */
12471           || is_tracepoint (b))
12472         {
12473           /* Clear the condition modification flag.  */
12474           loc->condition_changed = condition_unchanged;
12475           continue;
12476         }
12477
12478       /* Permanent breakpoint should always be inserted.  */
12479       if (b->enable_state == bp_permanent && ! loc->inserted)
12480         internal_error (__FILE__, __LINE__,
12481                         _("allegedly permanent breakpoint is not "
12482                         "actually inserted"));
12483
12484       if (b->type == bp_hardware_watchpoint)
12485         loc_first_p = &wp_loc_first;
12486       else if (b->type == bp_read_watchpoint)
12487         loc_first_p = &rwp_loc_first;
12488       else if (b->type == bp_access_watchpoint)
12489         loc_first_p = &awp_loc_first;
12490       else
12491         loc_first_p = &bp_loc_first;
12492
12493       if (*loc_first_p == NULL
12494           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12495           || !breakpoint_locations_match (loc, *loc_first_p))
12496         {
12497           *loc_first_p = loc;
12498           loc->duplicate = 0;
12499
12500           if (is_breakpoint (loc->owner) && loc->condition_changed)
12501             {
12502               loc->needs_update = 1;
12503               /* Clear the condition modification flag.  */
12504               loc->condition_changed = condition_unchanged;
12505             }
12506           continue;
12507         }
12508
12509
12510       /* This and the above ensure the invariant that the first location
12511          is not duplicated, and is the inserted one.
12512          All following are marked as duplicated, and are not inserted.  */
12513       if (loc->inserted)
12514         swap_insertion (loc, *loc_first_p);
12515       loc->duplicate = 1;
12516
12517       /* Clear the condition modification flag.  */
12518       loc->condition_changed = condition_unchanged;
12519
12520       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12521           && b->enable_state != bp_permanent)
12522         internal_error (__FILE__, __LINE__,
12523                         _("another breakpoint was inserted on top of "
12524                         "a permanent breakpoint"));
12525     }
12526
12527   if (breakpoints_always_inserted_mode ()
12528       && (have_live_inferiors ()
12529           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12530     {
12531       if (should_insert)
12532         insert_breakpoint_locations ();
12533       else
12534         {
12535           /* Though should_insert is false, we may need to update conditions
12536              on the target's side if it is evaluating such conditions.  We
12537              only update conditions for locations that are marked
12538              "needs_update".  */
12539           update_inserted_breakpoint_locations ();
12540         }
12541     }
12542
12543   if (should_insert)
12544     download_tracepoint_locations ();
12545
12546   do_cleanups (cleanups);
12547 }
12548
12549 void
12550 breakpoint_retire_moribund (void)
12551 {
12552   struct bp_location *loc;
12553   int ix;
12554
12555   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12556     if (--(loc->events_till_retirement) == 0)
12557       {
12558         decref_bp_location (&loc);
12559         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12560         --ix;
12561       }
12562 }
12563
12564 static void
12565 update_global_location_list_nothrow (int inserting)
12566 {
12567   volatile struct gdb_exception e;
12568
12569   TRY_CATCH (e, RETURN_MASK_ERROR)
12570     update_global_location_list (inserting);
12571 }
12572
12573 /* Clear BKP from a BPS.  */
12574
12575 static void
12576 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12577 {
12578   bpstat bs;
12579
12580   for (bs = bps; bs; bs = bs->next)
12581     if (bs->breakpoint_at == bpt)
12582       {
12583         bs->breakpoint_at = NULL;
12584         bs->old_val = NULL;
12585         /* bs->commands will be freed later.  */
12586       }
12587 }
12588
12589 /* Callback for iterate_over_threads.  */
12590 static int
12591 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12592 {
12593   struct breakpoint *bpt = data;
12594
12595   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12596   return 0;
12597 }
12598
12599 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12600    callbacks.  */
12601
12602 static void
12603 say_where (struct breakpoint *b)
12604 {
12605   struct value_print_options opts;
12606
12607   get_user_print_options (&opts);
12608
12609   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12610      single string.  */
12611   if (b->loc == NULL)
12612     {
12613       printf_filtered (_(" (%s) pending."), b->addr_string);
12614     }
12615   else
12616     {
12617       if (opts.addressprint || b->loc->symtab == NULL)
12618         {
12619           printf_filtered (" at ");
12620           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12621                           gdb_stdout);
12622         }
12623       if (b->loc->symtab != NULL)
12624         {
12625           /* If there is a single location, we can print the location
12626              more nicely.  */
12627           if (b->loc->next == NULL)
12628             printf_filtered (": file %s, line %d.",
12629                              symtab_to_filename_for_display (b->loc->symtab),
12630                              b->loc->line_number);
12631           else
12632             /* This is not ideal, but each location may have a
12633                different file name, and this at least reflects the
12634                real situation somewhat.  */
12635             printf_filtered (": %s.", b->addr_string);
12636         }
12637
12638       if (b->loc->next)
12639         {
12640           struct bp_location *loc = b->loc;
12641           int n = 0;
12642           for (; loc; loc = loc->next)
12643             ++n;
12644           printf_filtered (" (%d locations)", n);
12645         }
12646     }
12647 }
12648
12649 /* Default bp_location_ops methods.  */
12650
12651 static void
12652 bp_location_dtor (struct bp_location *self)
12653 {
12654   xfree (self->cond);
12655   if (self->cond_bytecode)
12656     free_agent_expr (self->cond_bytecode);
12657   xfree (self->function_name);
12658 }
12659
12660 static const struct bp_location_ops bp_location_ops =
12661 {
12662   bp_location_dtor
12663 };
12664
12665 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12666    inherit from.  */
12667
12668 static void
12669 base_breakpoint_dtor (struct breakpoint *self)
12670 {
12671   decref_counted_command_line (&self->commands);
12672   xfree (self->cond_string);
12673   xfree (self->extra_string);
12674   xfree (self->addr_string);
12675   xfree (self->filter);
12676   xfree (self->addr_string_range_end);
12677 }
12678
12679 static struct bp_location *
12680 base_breakpoint_allocate_location (struct breakpoint *self)
12681 {
12682   struct bp_location *loc;
12683
12684   loc = XNEW (struct bp_location);
12685   init_bp_location (loc, &bp_location_ops, self);
12686   return loc;
12687 }
12688
12689 static void
12690 base_breakpoint_re_set (struct breakpoint *b)
12691 {
12692   /* Nothing to re-set. */
12693 }
12694
12695 #define internal_error_pure_virtual_called() \
12696   gdb_assert_not_reached ("pure virtual function called")
12697
12698 static int
12699 base_breakpoint_insert_location (struct bp_location *bl)
12700 {
12701   internal_error_pure_virtual_called ();
12702 }
12703
12704 static int
12705 base_breakpoint_remove_location (struct bp_location *bl)
12706 {
12707   internal_error_pure_virtual_called ();
12708 }
12709
12710 static int
12711 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12712                                 struct address_space *aspace,
12713                                 CORE_ADDR bp_addr,
12714                                 const struct target_waitstatus *ws)
12715 {
12716   internal_error_pure_virtual_called ();
12717 }
12718
12719 static void
12720 base_breakpoint_check_status (bpstat bs)
12721 {
12722   /* Always stop.   */
12723 }
12724
12725 /* A "works_in_software_mode" breakpoint_ops method that just internal
12726    errors.  */
12727
12728 static int
12729 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12730 {
12731   internal_error_pure_virtual_called ();
12732 }
12733
12734 /* A "resources_needed" breakpoint_ops method that just internal
12735    errors.  */
12736
12737 static int
12738 base_breakpoint_resources_needed (const struct bp_location *bl)
12739 {
12740   internal_error_pure_virtual_called ();
12741 }
12742
12743 static enum print_stop_action
12744 base_breakpoint_print_it (bpstat bs)
12745 {
12746   internal_error_pure_virtual_called ();
12747 }
12748
12749 static void
12750 base_breakpoint_print_one_detail (const struct breakpoint *self,
12751                                   struct ui_out *uiout)
12752 {
12753   /* nothing */
12754 }
12755
12756 static void
12757 base_breakpoint_print_mention (struct breakpoint *b)
12758 {
12759   internal_error_pure_virtual_called ();
12760 }
12761
12762 static void
12763 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12764 {
12765   internal_error_pure_virtual_called ();
12766 }
12767
12768 static void
12769 base_breakpoint_create_sals_from_address (char **arg,
12770                                           struct linespec_result *canonical,
12771                                           enum bptype type_wanted,
12772                                           char *addr_start,
12773                                           char **copy_arg)
12774 {
12775   internal_error_pure_virtual_called ();
12776 }
12777
12778 static void
12779 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12780                                         struct linespec_result *c,
12781                                         char *cond_string,
12782                                         char *extra_string,
12783                                         enum bptype type_wanted,
12784                                         enum bpdisp disposition,
12785                                         int thread,
12786                                         int task, int ignore_count,
12787                                         const struct breakpoint_ops *o,
12788                                         int from_tty, int enabled,
12789                                         int internal, unsigned flags)
12790 {
12791   internal_error_pure_virtual_called ();
12792 }
12793
12794 static void
12795 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12796                                  struct symtabs_and_lines *sals)
12797 {
12798   internal_error_pure_virtual_called ();
12799 }
12800
12801 /* The default 'explains_signal' method.  */
12802
12803 static enum bpstat_signal_value
12804 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12805 {
12806   return BPSTAT_SIGNAL_HIDE;
12807 }
12808
12809 /* The default "after_condition_true" method.  */
12810
12811 static void
12812 base_breakpoint_after_condition_true (struct bpstats *bs)
12813 {
12814   /* Nothing to do.   */
12815 }
12816
12817 struct breakpoint_ops base_breakpoint_ops =
12818 {
12819   base_breakpoint_dtor,
12820   base_breakpoint_allocate_location,
12821   base_breakpoint_re_set,
12822   base_breakpoint_insert_location,
12823   base_breakpoint_remove_location,
12824   base_breakpoint_breakpoint_hit,
12825   base_breakpoint_check_status,
12826   base_breakpoint_resources_needed,
12827   base_breakpoint_works_in_software_mode,
12828   base_breakpoint_print_it,
12829   NULL,
12830   base_breakpoint_print_one_detail,
12831   base_breakpoint_print_mention,
12832   base_breakpoint_print_recreate,
12833   base_breakpoint_create_sals_from_address,
12834   base_breakpoint_create_breakpoints_sal,
12835   base_breakpoint_decode_linespec,
12836   base_breakpoint_explains_signal,
12837   base_breakpoint_after_condition_true,
12838 };
12839
12840 /* Default breakpoint_ops methods.  */
12841
12842 static void
12843 bkpt_re_set (struct breakpoint *b)
12844 {
12845   /* FIXME: is this still reachable?  */
12846   if (b->addr_string == NULL)
12847     {
12848       /* Anything without a string can't be re-set.  */
12849       delete_breakpoint (b);
12850       return;
12851     }
12852
12853   breakpoint_re_set_default (b);
12854 }
12855
12856 static int
12857 bkpt_insert_location (struct bp_location *bl)
12858 {
12859   if (bl->loc_type == bp_loc_hardware_breakpoint)
12860     return target_insert_hw_breakpoint (bl->gdbarch,
12861                                         &bl->target_info);
12862   else
12863     return target_insert_breakpoint (bl->gdbarch,
12864                                      &bl->target_info);
12865 }
12866
12867 static int
12868 bkpt_remove_location (struct bp_location *bl)
12869 {
12870   if (bl->loc_type == bp_loc_hardware_breakpoint)
12871     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12872   else
12873     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12874 }
12875
12876 static int
12877 bkpt_breakpoint_hit (const struct bp_location *bl,
12878                      struct address_space *aspace, CORE_ADDR bp_addr,
12879                      const struct target_waitstatus *ws)
12880 {
12881   if (ws->kind != TARGET_WAITKIND_STOPPED
12882       || ws->value.sig != GDB_SIGNAL_TRAP)
12883     return 0;
12884
12885   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12886                                  aspace, bp_addr))
12887     return 0;
12888
12889   if (overlay_debugging         /* unmapped overlay section */
12890       && section_is_overlay (bl->section)
12891       && !section_is_mapped (bl->section))
12892     return 0;
12893
12894   return 1;
12895 }
12896
12897 static int
12898 bkpt_resources_needed (const struct bp_location *bl)
12899 {
12900   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12901
12902   return 1;
12903 }
12904
12905 static enum print_stop_action
12906 bkpt_print_it (bpstat bs)
12907 {
12908   struct breakpoint *b;
12909   const struct bp_location *bl;
12910   int bp_temp;
12911   struct ui_out *uiout = current_uiout;
12912
12913   gdb_assert (bs->bp_location_at != NULL);
12914
12915   bl = bs->bp_location_at;
12916   b = bs->breakpoint_at;
12917
12918   bp_temp = b->disposition == disp_del;
12919   if (bl->address != bl->requested_address)
12920     breakpoint_adjustment_warning (bl->requested_address,
12921                                    bl->address,
12922                                    b->number, 1);
12923   annotate_breakpoint (b->number);
12924   if (bp_temp)
12925     ui_out_text (uiout, "\nTemporary breakpoint ");
12926   else
12927     ui_out_text (uiout, "\nBreakpoint ");
12928   if (ui_out_is_mi_like_p (uiout))
12929     {
12930       ui_out_field_string (uiout, "reason",
12931                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12932       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12933     }
12934   ui_out_field_int (uiout, "bkptno", b->number);
12935   ui_out_text (uiout, ", ");
12936
12937   return PRINT_SRC_AND_LOC;
12938 }
12939
12940 static void
12941 bkpt_print_mention (struct breakpoint *b)
12942 {
12943   if (ui_out_is_mi_like_p (current_uiout))
12944     return;
12945
12946   switch (b->type)
12947     {
12948     case bp_breakpoint:
12949     case bp_gnu_ifunc_resolver:
12950       if (b->disposition == disp_del)
12951         printf_filtered (_("Temporary breakpoint"));
12952       else
12953         printf_filtered (_("Breakpoint"));
12954       printf_filtered (_(" %d"), b->number);
12955       if (b->type == bp_gnu_ifunc_resolver)
12956         printf_filtered (_(" at gnu-indirect-function resolver"));
12957       break;
12958     case bp_hardware_breakpoint:
12959       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12960       break;
12961     case bp_dprintf:
12962       printf_filtered (_("Dprintf %d"), b->number);
12963       break;
12964     }
12965
12966   say_where (b);
12967 }
12968
12969 static void
12970 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12971 {
12972   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12973     fprintf_unfiltered (fp, "tbreak");
12974   else if (tp->type == bp_breakpoint)
12975     fprintf_unfiltered (fp, "break");
12976   else if (tp->type == bp_hardware_breakpoint
12977            && tp->disposition == disp_del)
12978     fprintf_unfiltered (fp, "thbreak");
12979   else if (tp->type == bp_hardware_breakpoint)
12980     fprintf_unfiltered (fp, "hbreak");
12981   else
12982     internal_error (__FILE__, __LINE__,
12983                     _("unhandled breakpoint type %d"), (int) tp->type);
12984
12985   fprintf_unfiltered (fp, " %s", tp->addr_string);
12986   print_recreate_thread (tp, fp);
12987 }
12988
12989 static void
12990 bkpt_create_sals_from_address (char **arg,
12991                                struct linespec_result *canonical,
12992                                enum bptype type_wanted,
12993                                char *addr_start, char **copy_arg)
12994 {
12995   create_sals_from_address_default (arg, canonical, type_wanted,
12996                                     addr_start, copy_arg);
12997 }
12998
12999 static void
13000 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13001                              struct linespec_result *canonical,
13002                              char *cond_string,
13003                              char *extra_string,
13004                              enum bptype type_wanted,
13005                              enum bpdisp disposition,
13006                              int thread,
13007                              int task, int ignore_count,
13008                              const struct breakpoint_ops *ops,
13009                              int from_tty, int enabled,
13010                              int internal, unsigned flags)
13011 {
13012   create_breakpoints_sal_default (gdbarch, canonical,
13013                                   cond_string, extra_string,
13014                                   type_wanted,
13015                                   disposition, thread, task,
13016                                   ignore_count, ops, from_tty,
13017                                   enabled, internal, flags);
13018 }
13019
13020 static void
13021 bkpt_decode_linespec (struct breakpoint *b, char **s,
13022                       struct symtabs_and_lines *sals)
13023 {
13024   decode_linespec_default (b, s, sals);
13025 }
13026
13027 /* Virtual table for internal breakpoints.  */
13028
13029 static void
13030 internal_bkpt_re_set (struct breakpoint *b)
13031 {
13032   switch (b->type)
13033     {
13034       /* Delete overlay event and longjmp master breakpoints; they
13035          will be reset later by breakpoint_re_set.  */
13036     case bp_overlay_event:
13037     case bp_longjmp_master:
13038     case bp_std_terminate_master:
13039     case bp_exception_master:
13040       delete_breakpoint (b);
13041       break;
13042
13043       /* This breakpoint is special, it's set up when the inferior
13044          starts and we really don't want to touch it.  */
13045     case bp_shlib_event:
13046
13047       /* Like bp_shlib_event, this breakpoint type is special.  Once
13048          it is set up, we do not want to touch it.  */
13049     case bp_thread_event:
13050       break;
13051     }
13052 }
13053
13054 static void
13055 internal_bkpt_check_status (bpstat bs)
13056 {
13057   if (bs->breakpoint_at->type == bp_shlib_event)
13058     {
13059       /* If requested, stop when the dynamic linker notifies GDB of
13060          events.  This allows the user to get control and place
13061          breakpoints in initializer routines for dynamically loaded
13062          objects (among other things).  */
13063       bs->stop = stop_on_solib_events;
13064       bs->print = stop_on_solib_events;
13065     }
13066   else
13067     bs->stop = 0;
13068 }
13069
13070 static enum print_stop_action
13071 internal_bkpt_print_it (bpstat bs)
13072 {
13073   struct breakpoint *b;
13074
13075   b = bs->breakpoint_at;
13076
13077   switch (b->type)
13078     {
13079     case bp_shlib_event:
13080       /* Did we stop because the user set the stop_on_solib_events
13081          variable?  (If so, we report this as a generic, "Stopped due
13082          to shlib event" message.) */
13083       print_solib_event (0);
13084       break;
13085
13086     case bp_thread_event:
13087       /* Not sure how we will get here.
13088          GDB should not stop for these breakpoints.  */
13089       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13090       break;
13091
13092     case bp_overlay_event:
13093       /* By analogy with the thread event, GDB should not stop for these.  */
13094       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13095       break;
13096
13097     case bp_longjmp_master:
13098       /* These should never be enabled.  */
13099       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13100       break;
13101
13102     case bp_std_terminate_master:
13103       /* These should never be enabled.  */
13104       printf_filtered (_("std::terminate Master Breakpoint: "
13105                          "gdb should not stop!\n"));
13106       break;
13107
13108     case bp_exception_master:
13109       /* These should never be enabled.  */
13110       printf_filtered (_("Exception Master Breakpoint: "
13111                          "gdb should not stop!\n"));
13112       break;
13113     }
13114
13115   return PRINT_NOTHING;
13116 }
13117
13118 static void
13119 internal_bkpt_print_mention (struct breakpoint *b)
13120 {
13121   /* Nothing to mention.  These breakpoints are internal.  */
13122 }
13123
13124 /* Virtual table for momentary breakpoints  */
13125
13126 static void
13127 momentary_bkpt_re_set (struct breakpoint *b)
13128 {
13129   /* Keep temporary breakpoints, which can be encountered when we step
13130      over a dlopen call and solib_add is resetting the breakpoints.
13131      Otherwise these should have been blown away via the cleanup chain
13132      or by breakpoint_init_inferior when we rerun the executable.  */
13133 }
13134
13135 static void
13136 momentary_bkpt_check_status (bpstat bs)
13137 {
13138   /* Nothing.  The point of these breakpoints is causing a stop.  */
13139 }
13140
13141 static enum print_stop_action
13142 momentary_bkpt_print_it (bpstat bs)
13143 {
13144   struct ui_out *uiout = current_uiout;
13145
13146   if (ui_out_is_mi_like_p (uiout))
13147     {
13148       struct breakpoint *b = bs->breakpoint_at;
13149
13150       switch (b->type)
13151         {
13152         case bp_finish:
13153           ui_out_field_string
13154             (uiout, "reason",
13155              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13156           break;
13157
13158         case bp_until:
13159           ui_out_field_string
13160             (uiout, "reason",
13161              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13162           break;
13163         }
13164     }
13165
13166   return PRINT_UNKNOWN;
13167 }
13168
13169 static void
13170 momentary_bkpt_print_mention (struct breakpoint *b)
13171 {
13172   /* Nothing to mention.  These breakpoints are internal.  */
13173 }
13174
13175 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13176
13177    It gets cleared already on the removal of the first one of such placed
13178    breakpoints.  This is OK as they get all removed altogether.  */
13179
13180 static void
13181 longjmp_bkpt_dtor (struct breakpoint *self)
13182 {
13183   struct thread_info *tp = find_thread_id (self->thread);
13184
13185   if (tp)
13186     tp->initiating_frame = null_frame_id;
13187
13188   momentary_breakpoint_ops.dtor (self);
13189 }
13190
13191 /* Specific methods for probe breakpoints.  */
13192
13193 static int
13194 bkpt_probe_insert_location (struct bp_location *bl)
13195 {
13196   int v = bkpt_insert_location (bl);
13197
13198   if (v == 0)
13199     {
13200       /* The insertion was successful, now let's set the probe's semaphore
13201          if needed.  */
13202       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
13203     }
13204
13205   return v;
13206 }
13207
13208 static int
13209 bkpt_probe_remove_location (struct bp_location *bl)
13210 {
13211   /* Let's clear the semaphore before removing the location.  */
13212   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
13213
13214   return bkpt_remove_location (bl);
13215 }
13216
13217 static void
13218 bkpt_probe_create_sals_from_address (char **arg,
13219                                      struct linespec_result *canonical,
13220                                      enum bptype type_wanted,
13221                                      char *addr_start, char **copy_arg)
13222 {
13223   struct linespec_sals lsal;
13224
13225   lsal.sals = parse_probes (arg, canonical);
13226
13227   *copy_arg = xstrdup (canonical->addr_string);
13228   lsal.canonical = xstrdup (*copy_arg);
13229
13230   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13231 }
13232
13233 static void
13234 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13235                             struct symtabs_and_lines *sals)
13236 {
13237   *sals = parse_probes (s, NULL);
13238   if (!sals->sals)
13239     error (_("probe not found"));
13240 }
13241
13242 /* The breakpoint_ops structure to be used in tracepoints.  */
13243
13244 static void
13245 tracepoint_re_set (struct breakpoint *b)
13246 {
13247   breakpoint_re_set_default (b);
13248 }
13249
13250 static int
13251 tracepoint_breakpoint_hit (const struct bp_location *bl,
13252                            struct address_space *aspace, CORE_ADDR bp_addr,
13253                            const struct target_waitstatus *ws)
13254 {
13255   /* By definition, the inferior does not report stops at
13256      tracepoints.  */
13257   return 0;
13258 }
13259
13260 static void
13261 tracepoint_print_one_detail (const struct breakpoint *self,
13262                              struct ui_out *uiout)
13263 {
13264   struct tracepoint *tp = (struct tracepoint *) self;
13265   if (tp->static_trace_marker_id)
13266     {
13267       gdb_assert (self->type == bp_static_tracepoint);
13268
13269       ui_out_text (uiout, "\tmarker id is ");
13270       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13271                            tp->static_trace_marker_id);
13272       ui_out_text (uiout, "\n");
13273     }
13274 }
13275
13276 static void
13277 tracepoint_print_mention (struct breakpoint *b)
13278 {
13279   if (ui_out_is_mi_like_p (current_uiout))
13280     return;
13281
13282   switch (b->type)
13283     {
13284     case bp_tracepoint:
13285       printf_filtered (_("Tracepoint"));
13286       printf_filtered (_(" %d"), b->number);
13287       break;
13288     case bp_fast_tracepoint:
13289       printf_filtered (_("Fast tracepoint"));
13290       printf_filtered (_(" %d"), b->number);
13291       break;
13292     case bp_static_tracepoint:
13293       printf_filtered (_("Static tracepoint"));
13294       printf_filtered (_(" %d"), b->number);
13295       break;
13296     default:
13297       internal_error (__FILE__, __LINE__,
13298                       _("unhandled tracepoint type %d"), (int) b->type);
13299     }
13300
13301   say_where (b);
13302 }
13303
13304 static void
13305 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13306 {
13307   struct tracepoint *tp = (struct tracepoint *) self;
13308
13309   if (self->type == bp_fast_tracepoint)
13310     fprintf_unfiltered (fp, "ftrace");
13311   if (self->type == bp_static_tracepoint)
13312     fprintf_unfiltered (fp, "strace");
13313   else if (self->type == bp_tracepoint)
13314     fprintf_unfiltered (fp, "trace");
13315   else
13316     internal_error (__FILE__, __LINE__,
13317                     _("unhandled tracepoint type %d"), (int) self->type);
13318
13319   fprintf_unfiltered (fp, " %s", self->addr_string);
13320   print_recreate_thread (self, fp);
13321
13322   if (tp->pass_count)
13323     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13324 }
13325
13326 static void
13327 tracepoint_create_sals_from_address (char **arg,
13328                                      struct linespec_result *canonical,
13329                                      enum bptype type_wanted,
13330                                      char *addr_start, char **copy_arg)
13331 {
13332   create_sals_from_address_default (arg, canonical, type_wanted,
13333                                     addr_start, copy_arg);
13334 }
13335
13336 static void
13337 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13338                                    struct linespec_result *canonical,
13339                                    char *cond_string,
13340                                    char *extra_string,
13341                                    enum bptype type_wanted,
13342                                    enum bpdisp disposition,
13343                                    int thread,
13344                                    int task, int ignore_count,
13345                                    const struct breakpoint_ops *ops,
13346                                    int from_tty, int enabled,
13347                                    int internal, unsigned flags)
13348 {
13349   create_breakpoints_sal_default (gdbarch, canonical,
13350                                   cond_string, extra_string,
13351                                   type_wanted,
13352                                   disposition, thread, task,
13353                                   ignore_count, ops, from_tty,
13354                                   enabled, internal, flags);
13355 }
13356
13357 static void
13358 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13359                             struct symtabs_and_lines *sals)
13360 {
13361   decode_linespec_default (b, s, sals);
13362 }
13363
13364 struct breakpoint_ops tracepoint_breakpoint_ops;
13365
13366 /* The breakpoint_ops structure to be use on tracepoints placed in a
13367    static probe.  */
13368
13369 static void
13370 tracepoint_probe_create_sals_from_address (char **arg,
13371                                            struct linespec_result *canonical,
13372                                            enum bptype type_wanted,
13373                                            char *addr_start, char **copy_arg)
13374 {
13375   /* We use the same method for breakpoint on probes.  */
13376   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13377                                        addr_start, copy_arg);
13378 }
13379
13380 static void
13381 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13382                                   struct symtabs_and_lines *sals)
13383 {
13384   /* We use the same method for breakpoint on probes.  */
13385   bkpt_probe_decode_linespec (b, s, sals);
13386 }
13387
13388 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13389
13390 /* Dprintf breakpoint_ops methods.  */
13391
13392 static void
13393 dprintf_re_set (struct breakpoint *b)
13394 {
13395   breakpoint_re_set_default (b);
13396
13397   /* This breakpoint could have been pending, and be resolved now, and
13398      if so, we should now have the extra string.  If we don't, the
13399      dprintf was malformed when created, but we couldn't tell because
13400      we can't extract the extra string until the location is
13401      resolved.  */
13402   if (b->loc != NULL && b->extra_string == NULL)
13403     error (_("Format string required"));
13404
13405   /* 1 - connect to target 1, that can run breakpoint commands.
13406      2 - create a dprintf, which resolves fine.
13407      3 - disconnect from target 1
13408      4 - connect to target 2, that can NOT run breakpoint commands.
13409
13410      After steps #3/#4, you'll want the dprintf command list to
13411      be updated, because target 1 and 2 may well return different
13412      answers for target_can_run_breakpoint_commands().
13413      Given absence of finer grained resetting, we get to do
13414      it all the time.  */
13415   if (b->extra_string != NULL)
13416     update_dprintf_command_list (b);
13417 }
13418
13419 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13420
13421 static void
13422 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13423 {
13424   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13425                       tp->extra_string);
13426   print_recreate_thread (tp, fp);
13427 }
13428
13429 /* Implement the "after_condition_true" breakpoint_ops method for
13430    dprintf.
13431
13432    dprintf's are implemented with regular commands in their command
13433    list, but we run the commands here instead of before presenting the
13434    stop to the user, as dprintf's don't actually cause a stop.  This
13435    also makes it so that the commands of multiple dprintfs at the same
13436    address are all handled.  */
13437
13438 static void
13439 dprintf_after_condition_true (struct bpstats *bs)
13440 {
13441   struct cleanup *old_chain;
13442   struct bpstats tmp_bs = { NULL };
13443   struct bpstats *tmp_bs_p = &tmp_bs;
13444
13445   /* dprintf's never cause a stop.  This wasn't set in the
13446      check_status hook instead because that would make the dprintf's
13447      condition not be evaluated.  */
13448   bs->stop = 0;
13449
13450   /* Run the command list here.  Take ownership of it instead of
13451      copying.  We never want these commands to run later in
13452      bpstat_do_actions, if a breakpoint that causes a stop happens to
13453      be set at same address as this dprintf, or even if running the
13454      commands here throws.  */
13455   tmp_bs.commands = bs->commands;
13456   bs->commands = NULL;
13457   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13458
13459   bpstat_do_actions_1 (&tmp_bs_p);
13460
13461   /* 'tmp_bs.commands' will usually be NULL by now, but
13462      bpstat_do_actions_1 may return early without processing the whole
13463      list.  */
13464   do_cleanups (old_chain);
13465 }
13466
13467 /* The breakpoint_ops structure to be used on static tracepoints with
13468    markers (`-m').  */
13469
13470 static void
13471 strace_marker_create_sals_from_address (char **arg,
13472                                         struct linespec_result *canonical,
13473                                         enum bptype type_wanted,
13474                                         char *addr_start, char **copy_arg)
13475 {
13476   struct linespec_sals lsal;
13477
13478   lsal.sals = decode_static_tracepoint_spec (arg);
13479
13480   *copy_arg = savestring (addr_start, *arg - addr_start);
13481
13482   canonical->addr_string = xstrdup (*copy_arg);
13483   lsal.canonical = xstrdup (*copy_arg);
13484   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13485 }
13486
13487 static void
13488 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13489                                       struct linespec_result *canonical,
13490                                       char *cond_string,
13491                                       char *extra_string,
13492                                       enum bptype type_wanted,
13493                                       enum bpdisp disposition,
13494                                       int thread,
13495                                       int task, int ignore_count,
13496                                       const struct breakpoint_ops *ops,
13497                                       int from_tty, int enabled,
13498                                       int internal, unsigned flags)
13499 {
13500   int i;
13501   struct linespec_sals *lsal = VEC_index (linespec_sals,
13502                                           canonical->sals, 0);
13503
13504   /* If the user is creating a static tracepoint by marker id
13505      (strace -m MARKER_ID), then store the sals index, so that
13506      breakpoint_re_set can try to match up which of the newly
13507      found markers corresponds to this one, and, don't try to
13508      expand multiple locations for each sal, given than SALS
13509      already should contain all sals for MARKER_ID.  */
13510
13511   for (i = 0; i < lsal->sals.nelts; ++i)
13512     {
13513       struct symtabs_and_lines expanded;
13514       struct tracepoint *tp;
13515       struct cleanup *old_chain;
13516       char *addr_string;
13517
13518       expanded.nelts = 1;
13519       expanded.sals = &lsal->sals.sals[i];
13520
13521       addr_string = xstrdup (canonical->addr_string);
13522       old_chain = make_cleanup (xfree, addr_string);
13523
13524       tp = XCNEW (struct tracepoint);
13525       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13526                            addr_string, NULL,
13527                            cond_string, extra_string,
13528                            type_wanted, disposition,
13529                            thread, task, ignore_count, ops,
13530                            from_tty, enabled, internal, flags,
13531                            canonical->special_display);
13532       /* Given that its possible to have multiple markers with
13533          the same string id, if the user is creating a static
13534          tracepoint by marker id ("strace -m MARKER_ID"), then
13535          store the sals index, so that breakpoint_re_set can
13536          try to match up which of the newly found markers
13537          corresponds to this one  */
13538       tp->static_trace_marker_id_idx = i;
13539
13540       install_breakpoint (internal, &tp->base, 0);
13541
13542       discard_cleanups (old_chain);
13543     }
13544 }
13545
13546 static void
13547 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13548                                struct symtabs_and_lines *sals)
13549 {
13550   struct tracepoint *tp = (struct tracepoint *) b;
13551
13552   *sals = decode_static_tracepoint_spec (s);
13553   if (sals->nelts > tp->static_trace_marker_id_idx)
13554     {
13555       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13556       sals->nelts = 1;
13557     }
13558   else
13559     error (_("marker %s not found"), tp->static_trace_marker_id);
13560 }
13561
13562 static struct breakpoint_ops strace_marker_breakpoint_ops;
13563
13564 static int
13565 strace_marker_p (struct breakpoint *b)
13566 {
13567   return b->ops == &strace_marker_breakpoint_ops;
13568 }
13569
13570 /* Delete a breakpoint and clean up all traces of it in the data
13571    structures.  */
13572
13573 void
13574 delete_breakpoint (struct breakpoint *bpt)
13575 {
13576   struct breakpoint *b;
13577
13578   gdb_assert (bpt != NULL);
13579
13580   /* Has this bp already been deleted?  This can happen because
13581      multiple lists can hold pointers to bp's.  bpstat lists are
13582      especial culprits.
13583
13584      One example of this happening is a watchpoint's scope bp.  When
13585      the scope bp triggers, we notice that the watchpoint is out of
13586      scope, and delete it.  We also delete its scope bp.  But the
13587      scope bp is marked "auto-deleting", and is already on a bpstat.
13588      That bpstat is then checked for auto-deleting bp's, which are
13589      deleted.
13590
13591      A real solution to this problem might involve reference counts in
13592      bp's, and/or giving them pointers back to their referencing
13593      bpstat's, and teaching delete_breakpoint to only free a bp's
13594      storage when no more references were extent.  A cheaper bandaid
13595      was chosen.  */
13596   if (bpt->type == bp_none)
13597     return;
13598
13599   /* At least avoid this stale reference until the reference counting
13600      of breakpoints gets resolved.  */
13601   if (bpt->related_breakpoint != bpt)
13602     {
13603       struct breakpoint *related;
13604       struct watchpoint *w;
13605
13606       if (bpt->type == bp_watchpoint_scope)
13607         w = (struct watchpoint *) bpt->related_breakpoint;
13608       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13609         w = (struct watchpoint *) bpt;
13610       else
13611         w = NULL;
13612       if (w != NULL)
13613         watchpoint_del_at_next_stop (w);
13614
13615       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13616       for (related = bpt; related->related_breakpoint != bpt;
13617            related = related->related_breakpoint);
13618       related->related_breakpoint = bpt->related_breakpoint;
13619       bpt->related_breakpoint = bpt;
13620     }
13621
13622   /* watch_command_1 creates a watchpoint but only sets its number if
13623      update_watchpoint succeeds in creating its bp_locations.  If there's
13624      a problem in that process, we'll be asked to delete the half-created
13625      watchpoint.  In that case, don't announce the deletion.  */
13626   if (bpt->number)
13627     observer_notify_breakpoint_deleted (bpt);
13628
13629   if (breakpoint_chain == bpt)
13630     breakpoint_chain = bpt->next;
13631
13632   ALL_BREAKPOINTS (b)
13633     if (b->next == bpt)
13634     {
13635       b->next = bpt->next;
13636       break;
13637     }
13638
13639   /* Be sure no bpstat's are pointing at the breakpoint after it's
13640      been freed.  */
13641   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13642      in all threads for now.  Note that we cannot just remove bpstats
13643      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13644      commands are associated with the bpstat; if we remove it here,
13645      then the later call to bpstat_do_actions (&stop_bpstat); in
13646      event-top.c won't do anything, and temporary breakpoints with
13647      commands won't work.  */
13648
13649   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13650
13651   /* Now that breakpoint is removed from breakpoint list, update the
13652      global location list.  This will remove locations that used to
13653      belong to this breakpoint.  Do this before freeing the breakpoint
13654      itself, since remove_breakpoint looks at location's owner.  It
13655      might be better design to have location completely
13656      self-contained, but it's not the case now.  */
13657   update_global_location_list (0);
13658
13659   bpt->ops->dtor (bpt);
13660   /* On the chance that someone will soon try again to delete this
13661      same bp, we mark it as deleted before freeing its storage.  */
13662   bpt->type = bp_none;
13663   xfree (bpt);
13664 }
13665
13666 static void
13667 do_delete_breakpoint_cleanup (void *b)
13668 {
13669   delete_breakpoint (b);
13670 }
13671
13672 struct cleanup *
13673 make_cleanup_delete_breakpoint (struct breakpoint *b)
13674 {
13675   return make_cleanup (do_delete_breakpoint_cleanup, b);
13676 }
13677
13678 /* Iterator function to call a user-provided callback function once
13679    for each of B and its related breakpoints.  */
13680
13681 static void
13682 iterate_over_related_breakpoints (struct breakpoint *b,
13683                                   void (*function) (struct breakpoint *,
13684                                                     void *),
13685                                   void *data)
13686 {
13687   struct breakpoint *related;
13688
13689   related = b;
13690   do
13691     {
13692       struct breakpoint *next;
13693
13694       /* FUNCTION may delete RELATED.  */
13695       next = related->related_breakpoint;
13696
13697       if (next == related)
13698         {
13699           /* RELATED is the last ring entry.  */
13700           function (related, data);
13701
13702           /* FUNCTION may have deleted it, so we'd never reach back to
13703              B.  There's nothing left to do anyway, so just break
13704              out.  */
13705           break;
13706         }
13707       else
13708         function (related, data);
13709
13710       related = next;
13711     }
13712   while (related != b);
13713 }
13714
13715 static void
13716 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13717 {
13718   delete_breakpoint (b);
13719 }
13720
13721 /* A callback for map_breakpoint_numbers that calls
13722    delete_breakpoint.  */
13723
13724 static void
13725 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13726 {
13727   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13728 }
13729
13730 void
13731 delete_command (char *arg, int from_tty)
13732 {
13733   struct breakpoint *b, *b_tmp;
13734
13735   dont_repeat ();
13736
13737   if (arg == 0)
13738     {
13739       int breaks_to_delete = 0;
13740
13741       /* Delete all breakpoints if no argument.  Do not delete
13742          internal breakpoints, these have to be deleted with an
13743          explicit breakpoint number argument.  */
13744       ALL_BREAKPOINTS (b)
13745         if (user_breakpoint_p (b))
13746           {
13747             breaks_to_delete = 1;
13748             break;
13749           }
13750
13751       /* Ask user only if there are some breakpoints to delete.  */
13752       if (!from_tty
13753           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13754         {
13755           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13756             if (user_breakpoint_p (b))
13757               delete_breakpoint (b);
13758         }
13759     }
13760   else
13761     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13762 }
13763
13764 static int
13765 all_locations_are_pending (struct bp_location *loc)
13766 {
13767   for (; loc; loc = loc->next)
13768     if (!loc->shlib_disabled
13769         && !loc->pspace->executing_startup)
13770       return 0;
13771   return 1;
13772 }
13773
13774 /* Subroutine of update_breakpoint_locations to simplify it.
13775    Return non-zero if multiple fns in list LOC have the same name.
13776    Null names are ignored.  */
13777
13778 static int
13779 ambiguous_names_p (struct bp_location *loc)
13780 {
13781   struct bp_location *l;
13782   htab_t htab = htab_create_alloc (13, htab_hash_string,
13783                                    (int (*) (const void *, 
13784                                              const void *)) streq,
13785                                    NULL, xcalloc, xfree);
13786
13787   for (l = loc; l != NULL; l = l->next)
13788     {
13789       const char **slot;
13790       const char *name = l->function_name;
13791
13792       /* Allow for some names to be NULL, ignore them.  */
13793       if (name == NULL)
13794         continue;
13795
13796       slot = (const char **) htab_find_slot (htab, (const void *) name,
13797                                              INSERT);
13798       /* NOTE: We can assume slot != NULL here because xcalloc never
13799          returns NULL.  */
13800       if (*slot != NULL)
13801         {
13802           htab_delete (htab);
13803           return 1;
13804         }
13805       *slot = name;
13806     }
13807
13808   htab_delete (htab);
13809   return 0;
13810 }
13811
13812 /* When symbols change, it probably means the sources changed as well,
13813    and it might mean the static tracepoint markers are no longer at
13814    the same address or line numbers they used to be at last we
13815    checked.  Losing your static tracepoints whenever you rebuild is
13816    undesirable.  This function tries to resync/rematch gdb static
13817    tracepoints with the markers on the target, for static tracepoints
13818    that have not been set by marker id.  Static tracepoint that have
13819    been set by marker id are reset by marker id in breakpoint_re_set.
13820    The heuristic is:
13821
13822    1) For a tracepoint set at a specific address, look for a marker at
13823    the old PC.  If one is found there, assume to be the same marker.
13824    If the name / string id of the marker found is different from the
13825    previous known name, assume that means the user renamed the marker
13826    in the sources, and output a warning.
13827
13828    2) For a tracepoint set at a given line number, look for a marker
13829    at the new address of the old line number.  If one is found there,
13830    assume to be the same marker.  If the name / string id of the
13831    marker found is different from the previous known name, assume that
13832    means the user renamed the marker in the sources, and output a
13833    warning.
13834
13835    3) If a marker is no longer found at the same address or line, it
13836    may mean the marker no longer exists.  But it may also just mean
13837    the code changed a bit.  Maybe the user added a few lines of code
13838    that made the marker move up or down (in line number terms).  Ask
13839    the target for info about the marker with the string id as we knew
13840    it.  If found, update line number and address in the matching
13841    static tracepoint.  This will get confused if there's more than one
13842    marker with the same ID (possible in UST, although unadvised
13843    precisely because it confuses tools).  */
13844
13845 static struct symtab_and_line
13846 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13847 {
13848   struct tracepoint *tp = (struct tracepoint *) b;
13849   struct static_tracepoint_marker marker;
13850   CORE_ADDR pc;
13851
13852   pc = sal.pc;
13853   if (sal.line)
13854     find_line_pc (sal.symtab, sal.line, &pc);
13855
13856   if (target_static_tracepoint_marker_at (pc, &marker))
13857     {
13858       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13859         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13860                  b->number,
13861                  tp->static_trace_marker_id, marker.str_id);
13862
13863       xfree (tp->static_trace_marker_id);
13864       tp->static_trace_marker_id = xstrdup (marker.str_id);
13865       release_static_tracepoint_marker (&marker);
13866
13867       return sal;
13868     }
13869
13870   /* Old marker wasn't found on target at lineno.  Try looking it up
13871      by string ID.  */
13872   if (!sal.explicit_pc
13873       && sal.line != 0
13874       && sal.symtab != NULL
13875       && tp->static_trace_marker_id != NULL)
13876     {
13877       VEC(static_tracepoint_marker_p) *markers;
13878
13879       markers
13880         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13881
13882       if (!VEC_empty(static_tracepoint_marker_p, markers))
13883         {
13884           struct symtab_and_line sal2;
13885           struct symbol *sym;
13886           struct static_tracepoint_marker *tpmarker;
13887           struct ui_out *uiout = current_uiout;
13888
13889           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13890
13891           xfree (tp->static_trace_marker_id);
13892           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13893
13894           warning (_("marker for static tracepoint %d (%s) not "
13895                      "found at previous line number"),
13896                    b->number, tp->static_trace_marker_id);
13897
13898           init_sal (&sal2);
13899
13900           sal2.pc = tpmarker->address;
13901
13902           sal2 = find_pc_line (tpmarker->address, 0);
13903           sym = find_pc_sect_function (tpmarker->address, NULL);
13904           ui_out_text (uiout, "Now in ");
13905           if (sym)
13906             {
13907               ui_out_field_string (uiout, "func",
13908                                    SYMBOL_PRINT_NAME (sym));
13909               ui_out_text (uiout, " at ");
13910             }
13911           ui_out_field_string (uiout, "file",
13912                                symtab_to_filename_for_display (sal2.symtab));
13913           ui_out_text (uiout, ":");
13914
13915           if (ui_out_is_mi_like_p (uiout))
13916             {
13917               const char *fullname = symtab_to_fullname (sal2.symtab);
13918
13919               ui_out_field_string (uiout, "fullname", fullname);
13920             }
13921
13922           ui_out_field_int (uiout, "line", sal2.line);
13923           ui_out_text (uiout, "\n");
13924
13925           b->loc->line_number = sal2.line;
13926           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
13927
13928           xfree (b->addr_string);
13929           b->addr_string = xstrprintf ("%s:%d",
13930                                    symtab_to_filename_for_display (sal2.symtab),
13931                                        b->loc->line_number);
13932
13933           /* Might be nice to check if function changed, and warn if
13934              so.  */
13935
13936           release_static_tracepoint_marker (tpmarker);
13937         }
13938     }
13939   return sal;
13940 }
13941
13942 /* Returns 1 iff locations A and B are sufficiently same that
13943    we don't need to report breakpoint as changed.  */
13944
13945 static int
13946 locations_are_equal (struct bp_location *a, struct bp_location *b)
13947 {
13948   while (a && b)
13949     {
13950       if (a->address != b->address)
13951         return 0;
13952
13953       if (a->shlib_disabled != b->shlib_disabled)
13954         return 0;
13955
13956       if (a->enabled != b->enabled)
13957         return 0;
13958
13959       a = a->next;
13960       b = b->next;
13961     }
13962
13963   if ((a == NULL) != (b == NULL))
13964     return 0;
13965
13966   return 1;
13967 }
13968
13969 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13970    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13971    a ranged breakpoint.  */
13972
13973 void
13974 update_breakpoint_locations (struct breakpoint *b,
13975                              struct symtabs_and_lines sals,
13976                              struct symtabs_and_lines sals_end)
13977 {
13978   int i;
13979   struct bp_location *existing_locations = b->loc;
13980
13981   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13982     {
13983       /* Ranged breakpoints have only one start location and one end
13984          location.  */
13985       b->enable_state = bp_disabled;
13986       update_global_location_list (1);
13987       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13988                            "multiple locations found\n"),
13989                          b->number);
13990       return;
13991     }
13992
13993   /* If there's no new locations, and all existing locations are
13994      pending, don't do anything.  This optimizes the common case where
13995      all locations are in the same shared library, that was unloaded.
13996      We'd like to retain the location, so that when the library is
13997      loaded again, we don't loose the enabled/disabled status of the
13998      individual locations.  */
13999   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14000     return;
14001
14002   b->loc = NULL;
14003
14004   for (i = 0; i < sals.nelts; ++i)
14005     {
14006       struct bp_location *new_loc;
14007
14008       switch_to_program_space_and_thread (sals.sals[i].pspace);
14009
14010       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14011
14012       /* Reparse conditions, they might contain references to the
14013          old symtab.  */
14014       if (b->cond_string != NULL)
14015         {
14016           const char *s;
14017           volatile struct gdb_exception e;
14018
14019           s = b->cond_string;
14020           TRY_CATCH (e, RETURN_MASK_ERROR)
14021             {
14022               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14023                                            block_for_pc (sals.sals[i].pc), 
14024                                            0);
14025             }
14026           if (e.reason < 0)
14027             {
14028               warning (_("failed to reevaluate condition "
14029                          "for breakpoint %d: %s"), 
14030                        b->number, e.message);
14031               new_loc->enabled = 0;
14032             }
14033         }
14034
14035       if (sals_end.nelts)
14036         {
14037           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14038
14039           new_loc->length = end - sals.sals[0].pc + 1;
14040         }
14041     }
14042
14043   /* Update locations of permanent breakpoints.  */
14044   if (b->enable_state == bp_permanent)
14045     make_breakpoint_permanent (b);
14046
14047   /* If possible, carry over 'disable' status from existing
14048      breakpoints.  */
14049   {
14050     struct bp_location *e = existing_locations;
14051     /* If there are multiple breakpoints with the same function name,
14052        e.g. for inline functions, comparing function names won't work.
14053        Instead compare pc addresses; this is just a heuristic as things
14054        may have moved, but in practice it gives the correct answer
14055        often enough until a better solution is found.  */
14056     int have_ambiguous_names = ambiguous_names_p (b->loc);
14057
14058     for (; e; e = e->next)
14059       {
14060         if (!e->enabled && e->function_name)
14061           {
14062             struct bp_location *l = b->loc;
14063             if (have_ambiguous_names)
14064               {
14065                 for (; l; l = l->next)
14066                   if (breakpoint_locations_match (e, l))
14067                     {
14068                       l->enabled = 0;
14069                       break;
14070                     }
14071               }
14072             else
14073               {
14074                 for (; l; l = l->next)
14075                   if (l->function_name
14076                       && strcmp (e->function_name, l->function_name) == 0)
14077                     {
14078                       l->enabled = 0;
14079                       break;
14080                     }
14081               }
14082           }
14083       }
14084   }
14085
14086   if (!locations_are_equal (existing_locations, b->loc))
14087     observer_notify_breakpoint_modified (b);
14088
14089   update_global_location_list (1);
14090 }
14091
14092 /* Find the SaL locations corresponding to the given ADDR_STRING.
14093    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14094
14095 static struct symtabs_and_lines
14096 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14097 {
14098   char *s;
14099   struct symtabs_and_lines sals = {0};
14100   volatile struct gdb_exception e;
14101
14102   gdb_assert (b->ops != NULL);
14103   s = addr_string;
14104
14105   TRY_CATCH (e, RETURN_MASK_ERROR)
14106     {
14107       b->ops->decode_linespec (b, &s, &sals);
14108     }
14109   if (e.reason < 0)
14110     {
14111       int not_found_and_ok = 0;
14112       /* For pending breakpoints, it's expected that parsing will
14113          fail until the right shared library is loaded.  User has
14114          already told to create pending breakpoints and don't need
14115          extra messages.  If breakpoint is in bp_shlib_disabled
14116          state, then user already saw the message about that
14117          breakpoint being disabled, and don't want to see more
14118          errors.  */
14119       if (e.error == NOT_FOUND_ERROR
14120           && (b->condition_not_parsed 
14121               || (b->loc && b->loc->shlib_disabled)
14122               || (b->loc && b->loc->pspace->executing_startup)
14123               || b->enable_state == bp_disabled))
14124         not_found_and_ok = 1;
14125
14126       if (!not_found_and_ok)
14127         {
14128           /* We surely don't want to warn about the same breakpoint
14129              10 times.  One solution, implemented here, is disable
14130              the breakpoint on error.  Another solution would be to
14131              have separate 'warning emitted' flag.  Since this
14132              happens only when a binary has changed, I don't know
14133              which approach is better.  */
14134           b->enable_state = bp_disabled;
14135           throw_exception (e);
14136         }
14137     }
14138
14139   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14140     {
14141       int i;
14142
14143       for (i = 0; i < sals.nelts; ++i)
14144         resolve_sal_pc (&sals.sals[i]);
14145       if (b->condition_not_parsed && s && s[0])
14146         {
14147           char *cond_string, *extra_string;
14148           int thread, task;
14149
14150           find_condition_and_thread (s, sals.sals[0].pc,
14151                                      &cond_string, &thread, &task,
14152                                      &extra_string);
14153           if (cond_string)
14154             b->cond_string = cond_string;
14155           b->thread = thread;
14156           b->task = task;
14157           if (extra_string)
14158             b->extra_string = extra_string;
14159           b->condition_not_parsed = 0;
14160         }
14161
14162       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14163         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14164
14165       *found = 1;
14166     }
14167   else
14168     *found = 0;
14169
14170   return sals;
14171 }
14172
14173 /* The default re_set method, for typical hardware or software
14174    breakpoints.  Reevaluate the breakpoint and recreate its
14175    locations.  */
14176
14177 static void
14178 breakpoint_re_set_default (struct breakpoint *b)
14179 {
14180   int found;
14181   struct symtabs_and_lines sals, sals_end;
14182   struct symtabs_and_lines expanded = {0};
14183   struct symtabs_and_lines expanded_end = {0};
14184
14185   sals = addr_string_to_sals (b, b->addr_string, &found);
14186   if (found)
14187     {
14188       make_cleanup (xfree, sals.sals);
14189       expanded = sals;
14190     }
14191
14192   if (b->addr_string_range_end)
14193     {
14194       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14195       if (found)
14196         {
14197           make_cleanup (xfree, sals_end.sals);
14198           expanded_end = sals_end;
14199         }
14200     }
14201
14202   update_breakpoint_locations (b, expanded, expanded_end);
14203 }
14204
14205 /* Default method for creating SALs from an address string.  It basically
14206    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14207
14208 static void
14209 create_sals_from_address_default (char **arg,
14210                                   struct linespec_result *canonical,
14211                                   enum bptype type_wanted,
14212                                   char *addr_start, char **copy_arg)
14213 {
14214   parse_breakpoint_sals (arg, canonical);
14215 }
14216
14217 /* Call create_breakpoints_sal for the given arguments.  This is the default
14218    function for the `create_breakpoints_sal' method of
14219    breakpoint_ops.  */
14220
14221 static void
14222 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14223                                 struct linespec_result *canonical,
14224                                 char *cond_string,
14225                                 char *extra_string,
14226                                 enum bptype type_wanted,
14227                                 enum bpdisp disposition,
14228                                 int thread,
14229                                 int task, int ignore_count,
14230                                 const struct breakpoint_ops *ops,
14231                                 int from_tty, int enabled,
14232                                 int internal, unsigned flags)
14233 {
14234   create_breakpoints_sal (gdbarch, canonical, cond_string,
14235                           extra_string,
14236                           type_wanted, disposition,
14237                           thread, task, ignore_count, ops, from_tty,
14238                           enabled, internal, flags);
14239 }
14240
14241 /* Decode the line represented by S by calling decode_line_full.  This is the
14242    default function for the `decode_linespec' method of breakpoint_ops.  */
14243
14244 static void
14245 decode_linespec_default (struct breakpoint *b, char **s,
14246                          struct symtabs_and_lines *sals)
14247 {
14248   struct linespec_result canonical;
14249
14250   init_linespec_result (&canonical);
14251   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14252                     (struct symtab *) NULL, 0,
14253                     &canonical, multiple_symbols_all,
14254                     b->filter);
14255
14256   /* We should get 0 or 1 resulting SALs.  */
14257   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14258
14259   if (VEC_length (linespec_sals, canonical.sals) > 0)
14260     {
14261       struct linespec_sals *lsal;
14262
14263       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14264       *sals = lsal->sals;
14265       /* Arrange it so the destructor does not free the
14266          contents.  */
14267       lsal->sals.sals = NULL;
14268     }
14269
14270   destroy_linespec_result (&canonical);
14271 }
14272
14273 /* Prepare the global context for a re-set of breakpoint B.  */
14274
14275 static struct cleanup *
14276 prepare_re_set_context (struct breakpoint *b)
14277 {
14278   struct cleanup *cleanups;
14279
14280   input_radix = b->input_radix;
14281   cleanups = save_current_space_and_thread ();
14282   if (b->pspace != NULL)
14283     switch_to_program_space_and_thread (b->pspace);
14284   set_language (b->language);
14285
14286   return cleanups;
14287 }
14288
14289 /* Reset a breakpoint given it's struct breakpoint * BINT.
14290    The value we return ends up being the return value from catch_errors.
14291    Unused in this case.  */
14292
14293 static int
14294 breakpoint_re_set_one (void *bint)
14295 {
14296   /* Get past catch_errs.  */
14297   struct breakpoint *b = (struct breakpoint *) bint;
14298   struct cleanup *cleanups;
14299
14300   cleanups = prepare_re_set_context (b);
14301   b->ops->re_set (b);
14302   do_cleanups (cleanups);
14303   return 0;
14304 }
14305
14306 /* Re-set all breakpoints after symbols have been re-loaded.  */
14307 void
14308 breakpoint_re_set (void)
14309 {
14310   struct breakpoint *b, *b_tmp;
14311   enum language save_language;
14312   int save_input_radix;
14313   struct cleanup *old_chain;
14314
14315   save_language = current_language->la_language;
14316   save_input_radix = input_radix;
14317   old_chain = save_current_program_space ();
14318
14319   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14320   {
14321     /* Format possible error msg.  */
14322     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14323                                 b->number);
14324     struct cleanup *cleanups = make_cleanup (xfree, message);
14325     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14326     do_cleanups (cleanups);
14327   }
14328   set_language (save_language);
14329   input_radix = save_input_radix;
14330
14331   jit_breakpoint_re_set ();
14332
14333   do_cleanups (old_chain);
14334
14335   create_overlay_event_breakpoint ();
14336   create_longjmp_master_breakpoint ();
14337   create_std_terminate_master_breakpoint ();
14338   create_exception_master_breakpoint ();
14339 }
14340 \f
14341 /* Reset the thread number of this breakpoint:
14342
14343    - If the breakpoint is for all threads, leave it as-is.
14344    - Else, reset it to the current thread for inferior_ptid.  */
14345 void
14346 breakpoint_re_set_thread (struct breakpoint *b)
14347 {
14348   if (b->thread != -1)
14349     {
14350       if (in_thread_list (inferior_ptid))
14351         b->thread = pid_to_thread_id (inferior_ptid);
14352
14353       /* We're being called after following a fork.  The new fork is
14354          selected as current, and unless this was a vfork will have a
14355          different program space from the original thread.  Reset that
14356          as well.  */
14357       b->loc->pspace = current_program_space;
14358     }
14359 }
14360
14361 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14362    If from_tty is nonzero, it prints a message to that effect,
14363    which ends with a period (no newline).  */
14364
14365 void
14366 set_ignore_count (int bptnum, int count, int from_tty)
14367 {
14368   struct breakpoint *b;
14369
14370   if (count < 0)
14371     count = 0;
14372
14373   ALL_BREAKPOINTS (b)
14374     if (b->number == bptnum)
14375     {
14376       if (is_tracepoint (b))
14377         {
14378           if (from_tty && count != 0)
14379             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14380                              bptnum);
14381           return;
14382         }
14383       
14384       b->ignore_count = count;
14385       if (from_tty)
14386         {
14387           if (count == 0)
14388             printf_filtered (_("Will stop next time "
14389                                "breakpoint %d is reached."),
14390                              bptnum);
14391           else if (count == 1)
14392             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14393                              bptnum);
14394           else
14395             printf_filtered (_("Will ignore next %d "
14396                                "crossings of breakpoint %d."),
14397                              count, bptnum);
14398         }
14399       observer_notify_breakpoint_modified (b);
14400       return;
14401     }
14402
14403   error (_("No breakpoint number %d."), bptnum);
14404 }
14405
14406 /* Command to set ignore-count of breakpoint N to COUNT.  */
14407
14408 static void
14409 ignore_command (char *args, int from_tty)
14410 {
14411   char *p = args;
14412   int num;
14413
14414   if (p == 0)
14415     error_no_arg (_("a breakpoint number"));
14416
14417   num = get_number (&p);
14418   if (num == 0)
14419     error (_("bad breakpoint number: '%s'"), args);
14420   if (*p == 0)
14421     error (_("Second argument (specified ignore-count) is missing."));
14422
14423   set_ignore_count (num,
14424                     longest_to_int (value_as_long (parse_and_eval (p))),
14425                     from_tty);
14426   if (from_tty)
14427     printf_filtered ("\n");
14428 }
14429 \f
14430 /* Call FUNCTION on each of the breakpoints
14431    whose numbers are given in ARGS.  */
14432
14433 static void
14434 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14435                                                       void *),
14436                         void *data)
14437 {
14438   int num;
14439   struct breakpoint *b, *tmp;
14440   int match;
14441   struct get_number_or_range_state state;
14442
14443   if (args == 0)
14444     error_no_arg (_("one or more breakpoint numbers"));
14445
14446   init_number_or_range (&state, args);
14447
14448   while (!state.finished)
14449     {
14450       char *p = state.string;
14451
14452       match = 0;
14453
14454       num = get_number_or_range (&state);
14455       if (num == 0)
14456         {
14457           warning (_("bad breakpoint number at or near '%s'"), p);
14458         }
14459       else
14460         {
14461           ALL_BREAKPOINTS_SAFE (b, tmp)
14462             if (b->number == num)
14463               {
14464                 match = 1;
14465                 function (b, data);
14466                 break;
14467               }
14468           if (match == 0)
14469             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14470         }
14471     }
14472 }
14473
14474 static struct bp_location *
14475 find_location_by_number (char *number)
14476 {
14477   char *dot = strchr (number, '.');
14478   char *p1;
14479   int bp_num;
14480   int loc_num;
14481   struct breakpoint *b;
14482   struct bp_location *loc;  
14483
14484   *dot = '\0';
14485
14486   p1 = number;
14487   bp_num = get_number (&p1);
14488   if (bp_num == 0)
14489     error (_("Bad breakpoint number '%s'"), number);
14490
14491   ALL_BREAKPOINTS (b)
14492     if (b->number == bp_num)
14493       {
14494         break;
14495       }
14496
14497   if (!b || b->number != bp_num)
14498     error (_("Bad breakpoint number '%s'"), number);
14499   
14500   p1 = dot+1;
14501   loc_num = get_number (&p1);
14502   if (loc_num == 0)
14503     error (_("Bad breakpoint location number '%s'"), number);
14504
14505   --loc_num;
14506   loc = b->loc;
14507   for (;loc_num && loc; --loc_num, loc = loc->next)
14508     ;
14509   if (!loc)
14510     error (_("Bad breakpoint location number '%s'"), dot+1);
14511     
14512   return loc;  
14513 }
14514
14515
14516 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14517    If from_tty is nonzero, it prints a message to that effect,
14518    which ends with a period (no newline).  */
14519
14520 void
14521 disable_breakpoint (struct breakpoint *bpt)
14522 {
14523   /* Never disable a watchpoint scope breakpoint; we want to
14524      hit them when we leave scope so we can delete both the
14525      watchpoint and its scope breakpoint at that time.  */
14526   if (bpt->type == bp_watchpoint_scope)
14527     return;
14528
14529   /* You can't disable permanent breakpoints.  */
14530   if (bpt->enable_state == bp_permanent)
14531     return;
14532
14533   bpt->enable_state = bp_disabled;
14534
14535   /* Mark breakpoint locations modified.  */
14536   mark_breakpoint_modified (bpt);
14537
14538   if (target_supports_enable_disable_tracepoint ()
14539       && current_trace_status ()->running && is_tracepoint (bpt))
14540     {
14541       struct bp_location *location;
14542      
14543       for (location = bpt->loc; location; location = location->next)
14544         target_disable_tracepoint (location);
14545     }
14546
14547   update_global_location_list (0);
14548
14549   observer_notify_breakpoint_modified (bpt);
14550 }
14551
14552 /* A callback for iterate_over_related_breakpoints.  */
14553
14554 static void
14555 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14556 {
14557   disable_breakpoint (b);
14558 }
14559
14560 /* A callback for map_breakpoint_numbers that calls
14561    disable_breakpoint.  */
14562
14563 static void
14564 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14565 {
14566   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14567 }
14568
14569 static void
14570 disable_command (char *args, int from_tty)
14571 {
14572   if (args == 0)
14573     {
14574       struct breakpoint *bpt;
14575
14576       ALL_BREAKPOINTS (bpt)
14577         if (user_breakpoint_p (bpt))
14578           disable_breakpoint (bpt);
14579     }
14580   else
14581     {
14582       char *num = extract_arg (&args);
14583
14584       while (num)
14585         {
14586           if (strchr (num, '.'))
14587             {
14588               struct bp_location *loc = find_location_by_number (num);
14589
14590               if (loc)
14591                 {
14592                   if (loc->enabled)
14593                     {
14594                       loc->enabled = 0;
14595                       mark_breakpoint_location_modified (loc);
14596                     }
14597                   if (target_supports_enable_disable_tracepoint ()
14598                       && current_trace_status ()->running && loc->owner
14599                       && is_tracepoint (loc->owner))
14600                     target_disable_tracepoint (loc);
14601                 }
14602               update_global_location_list (0);
14603             }
14604           else
14605             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14606           num = extract_arg (&args);
14607         }
14608     }
14609 }
14610
14611 static void
14612 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14613                         int count)
14614 {
14615   int target_resources_ok;
14616
14617   if (bpt->type == bp_hardware_breakpoint)
14618     {
14619       int i;
14620       i = hw_breakpoint_used_count ();
14621       target_resources_ok = 
14622         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14623                                             i + 1, 0);
14624       if (target_resources_ok == 0)
14625         error (_("No hardware breakpoint support in the target."));
14626       else if (target_resources_ok < 0)
14627         error (_("Hardware breakpoints used exceeds limit."));
14628     }
14629
14630   if (is_watchpoint (bpt))
14631     {
14632       /* Initialize it just to avoid a GCC false warning.  */
14633       enum enable_state orig_enable_state = 0;
14634       volatile struct gdb_exception e;
14635
14636       TRY_CATCH (e, RETURN_MASK_ALL)
14637         {
14638           struct watchpoint *w = (struct watchpoint *) bpt;
14639
14640           orig_enable_state = bpt->enable_state;
14641           bpt->enable_state = bp_enabled;
14642           update_watchpoint (w, 1 /* reparse */);
14643         }
14644       if (e.reason < 0)
14645         {
14646           bpt->enable_state = orig_enable_state;
14647           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14648                              bpt->number);
14649           return;
14650         }
14651     }
14652
14653   if (bpt->enable_state != bp_permanent)
14654     bpt->enable_state = bp_enabled;
14655
14656   bpt->enable_state = bp_enabled;
14657
14658   /* Mark breakpoint locations modified.  */
14659   mark_breakpoint_modified (bpt);
14660
14661   if (target_supports_enable_disable_tracepoint ()
14662       && current_trace_status ()->running && is_tracepoint (bpt))
14663     {
14664       struct bp_location *location;
14665
14666       for (location = bpt->loc; location; location = location->next)
14667         target_enable_tracepoint (location);
14668     }
14669
14670   bpt->disposition = disposition;
14671   bpt->enable_count = count;
14672   update_global_location_list (1);
14673
14674   observer_notify_breakpoint_modified (bpt);
14675 }
14676
14677
14678 void
14679 enable_breakpoint (struct breakpoint *bpt)
14680 {
14681   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14682 }
14683
14684 static void
14685 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14686 {
14687   enable_breakpoint (bpt);
14688 }
14689
14690 /* A callback for map_breakpoint_numbers that calls
14691    enable_breakpoint.  */
14692
14693 static void
14694 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14695 {
14696   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14697 }
14698
14699 /* The enable command enables the specified breakpoints (or all defined
14700    breakpoints) so they once again become (or continue to be) effective
14701    in stopping the inferior.  */
14702
14703 static void
14704 enable_command (char *args, int from_tty)
14705 {
14706   if (args == 0)
14707     {
14708       struct breakpoint *bpt;
14709
14710       ALL_BREAKPOINTS (bpt)
14711         if (user_breakpoint_p (bpt))
14712           enable_breakpoint (bpt);
14713     }
14714   else
14715     {
14716       char *num = extract_arg (&args);
14717
14718       while (num)
14719         {
14720           if (strchr (num, '.'))
14721             {
14722               struct bp_location *loc = find_location_by_number (num);
14723
14724               if (loc)
14725                 {
14726                   if (!loc->enabled)
14727                     {
14728                       loc->enabled = 1;
14729                       mark_breakpoint_location_modified (loc);
14730                     }
14731                   if (target_supports_enable_disable_tracepoint ()
14732                       && current_trace_status ()->running && loc->owner
14733                       && is_tracepoint (loc->owner))
14734                     target_enable_tracepoint (loc);
14735                 }
14736               update_global_location_list (1);
14737             }
14738           else
14739             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14740           num = extract_arg (&args);
14741         }
14742     }
14743 }
14744
14745 /* This struct packages up disposition data for application to multiple
14746    breakpoints.  */
14747
14748 struct disp_data
14749 {
14750   enum bpdisp disp;
14751   int count;
14752 };
14753
14754 static void
14755 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14756 {
14757   struct disp_data disp_data = *(struct disp_data *) arg;
14758
14759   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14760 }
14761
14762 static void
14763 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14764 {
14765   struct disp_data disp = { disp_disable, 1 };
14766
14767   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14768 }
14769
14770 static void
14771 enable_once_command (char *args, int from_tty)
14772 {
14773   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14774 }
14775
14776 static void
14777 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14778 {
14779   struct disp_data disp = { disp_disable, *(int *) countptr };
14780
14781   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14782 }
14783
14784 static void
14785 enable_count_command (char *args, int from_tty)
14786 {
14787   int count = get_number (&args);
14788
14789   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14790 }
14791
14792 static void
14793 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14794 {
14795   struct disp_data disp = { disp_del, 1 };
14796
14797   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14798 }
14799
14800 static void
14801 enable_delete_command (char *args, int from_tty)
14802 {
14803   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14804 }
14805 \f
14806 static void
14807 set_breakpoint_cmd (char *args, int from_tty)
14808 {
14809 }
14810
14811 static void
14812 show_breakpoint_cmd (char *args, int from_tty)
14813 {
14814 }
14815
14816 /* Invalidate last known value of any hardware watchpoint if
14817    the memory which that value represents has been written to by
14818    GDB itself.  */
14819
14820 static void
14821 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14822                                       CORE_ADDR addr, ssize_t len,
14823                                       const bfd_byte *data)
14824 {
14825   struct breakpoint *bp;
14826
14827   ALL_BREAKPOINTS (bp)
14828     if (bp->enable_state == bp_enabled
14829         && bp->type == bp_hardware_watchpoint)
14830       {
14831         struct watchpoint *wp = (struct watchpoint *) bp;
14832
14833         if (wp->val_valid && wp->val)
14834           {
14835             struct bp_location *loc;
14836
14837             for (loc = bp->loc; loc != NULL; loc = loc->next)
14838               if (loc->loc_type == bp_loc_hardware_watchpoint
14839                   && loc->address + loc->length > addr
14840                   && addr + len > loc->address)
14841                 {
14842                   value_free (wp->val);
14843                   wp->val = NULL;
14844                   wp->val_valid = 0;
14845                 }
14846           }
14847       }
14848 }
14849
14850 /* Create and insert a raw software breakpoint at PC.  Return an
14851    identifier, which should be used to remove the breakpoint later.
14852    In general, places which call this should be using something on the
14853    breakpoint chain instead; this function should be eliminated
14854    someday.  */
14855
14856 void *
14857 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14858                                   struct address_space *aspace, CORE_ADDR pc)
14859 {
14860   struct bp_target_info *bp_tgt;
14861
14862   bp_tgt = XZALLOC (struct bp_target_info);
14863
14864   bp_tgt->placed_address_space = aspace;
14865   bp_tgt->placed_address = pc;
14866
14867   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14868     {
14869       /* Could not insert the breakpoint.  */
14870       xfree (bp_tgt);
14871       return NULL;
14872     }
14873
14874   return bp_tgt;
14875 }
14876
14877 /* Remove a breakpoint BP inserted by
14878    deprecated_insert_raw_breakpoint.  */
14879
14880 int
14881 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14882 {
14883   struct bp_target_info *bp_tgt = bp;
14884   int ret;
14885
14886   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14887   xfree (bp_tgt);
14888
14889   return ret;
14890 }
14891
14892 /* One (or perhaps two) breakpoints used for software single
14893    stepping.  */
14894
14895 static void *single_step_breakpoints[2];
14896 static struct gdbarch *single_step_gdbarch[2];
14897
14898 /* Create and insert a breakpoint for software single step.  */
14899
14900 void
14901 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14902                                struct address_space *aspace, 
14903                                CORE_ADDR next_pc)
14904 {
14905   void **bpt_p;
14906
14907   if (single_step_breakpoints[0] == NULL)
14908     {
14909       bpt_p = &single_step_breakpoints[0];
14910       single_step_gdbarch[0] = gdbarch;
14911     }
14912   else
14913     {
14914       gdb_assert (single_step_breakpoints[1] == NULL);
14915       bpt_p = &single_step_breakpoints[1];
14916       single_step_gdbarch[1] = gdbarch;
14917     }
14918
14919   /* NOTE drow/2006-04-11: A future improvement to this function would
14920      be to only create the breakpoints once, and actually put them on
14921      the breakpoint chain.  That would let us use set_raw_breakpoint.
14922      We could adjust the addresses each time they were needed.  Doing
14923      this requires corresponding changes elsewhere where single step
14924      breakpoints are handled, however.  So, for now, we use this.  */
14925
14926   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14927   if (*bpt_p == NULL)
14928     error (_("Could not insert single-step breakpoint at %s"),
14929              paddress (gdbarch, next_pc));
14930 }
14931
14932 /* Check if the breakpoints used for software single stepping
14933    were inserted or not.  */
14934
14935 int
14936 single_step_breakpoints_inserted (void)
14937 {
14938   return (single_step_breakpoints[0] != NULL
14939           || single_step_breakpoints[1] != NULL);
14940 }
14941
14942 /* Remove and delete any breakpoints used for software single step.  */
14943
14944 void
14945 remove_single_step_breakpoints (void)
14946 {
14947   gdb_assert (single_step_breakpoints[0] != NULL);
14948
14949   /* See insert_single_step_breakpoint for more about this deprecated
14950      call.  */
14951   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14952                                     single_step_breakpoints[0]);
14953   single_step_gdbarch[0] = NULL;
14954   single_step_breakpoints[0] = NULL;
14955
14956   if (single_step_breakpoints[1] != NULL)
14957     {
14958       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14959                                         single_step_breakpoints[1]);
14960       single_step_gdbarch[1] = NULL;
14961       single_step_breakpoints[1] = NULL;
14962     }
14963 }
14964
14965 /* Delete software single step breakpoints without removing them from
14966    the inferior.  This is intended to be used if the inferior's address
14967    space where they were inserted is already gone, e.g. after exit or
14968    exec.  */
14969
14970 void
14971 cancel_single_step_breakpoints (void)
14972 {
14973   int i;
14974
14975   for (i = 0; i < 2; i++)
14976     if (single_step_breakpoints[i])
14977       {
14978         xfree (single_step_breakpoints[i]);
14979         single_step_breakpoints[i] = NULL;
14980         single_step_gdbarch[i] = NULL;
14981       }
14982 }
14983
14984 /* Detach software single-step breakpoints from INFERIOR_PTID without
14985    removing them.  */
14986
14987 static void
14988 detach_single_step_breakpoints (void)
14989 {
14990   int i;
14991
14992   for (i = 0; i < 2; i++)
14993     if (single_step_breakpoints[i])
14994       target_remove_breakpoint (single_step_gdbarch[i],
14995                                 single_step_breakpoints[i]);
14996 }
14997
14998 /* Check whether a software single-step breakpoint is inserted at
14999    PC.  */
15000
15001 static int
15002 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15003                                         CORE_ADDR pc)
15004 {
15005   int i;
15006
15007   for (i = 0; i < 2; i++)
15008     {
15009       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15010       if (bp_tgt
15011           && breakpoint_address_match (bp_tgt->placed_address_space,
15012                                        bp_tgt->placed_address,
15013                                        aspace, pc))
15014         return 1;
15015     }
15016
15017   return 0;
15018 }
15019
15020 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15021    non-zero otherwise.  */
15022 static int
15023 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15024 {
15025   if (syscall_catchpoint_p (bp)
15026       && bp->enable_state != bp_disabled
15027       && bp->enable_state != bp_call_disabled)
15028     return 1;
15029   else
15030     return 0;
15031 }
15032
15033 int
15034 catch_syscall_enabled (void)
15035 {
15036   struct catch_syscall_inferior_data *inf_data
15037     = get_catch_syscall_inferior_data (current_inferior ());
15038
15039   return inf_data->total_syscalls_count != 0;
15040 }
15041
15042 int
15043 catching_syscall_number (int syscall_number)
15044 {
15045   struct breakpoint *bp;
15046
15047   ALL_BREAKPOINTS (bp)
15048     if (is_syscall_catchpoint_enabled (bp))
15049       {
15050         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15051
15052         if (c->syscalls_to_be_caught)
15053           {
15054             int i, iter;
15055             for (i = 0;
15056                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15057                  i++)
15058               if (syscall_number == iter)
15059                 return 1;
15060           }
15061         else
15062           return 1;
15063       }
15064
15065   return 0;
15066 }
15067
15068 /* Complete syscall names.  Used by "catch syscall".  */
15069 static VEC (char_ptr) *
15070 catch_syscall_completer (struct cmd_list_element *cmd,
15071                          const char *text, const char *word)
15072 {
15073   const char **list = get_syscall_names ();
15074   VEC (char_ptr) *retlist
15075     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15076
15077   xfree (list);
15078   return retlist;
15079 }
15080
15081 /* Tracepoint-specific operations.  */
15082
15083 /* Set tracepoint count to NUM.  */
15084 static void
15085 set_tracepoint_count (int num)
15086 {
15087   tracepoint_count = num;
15088   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15089 }
15090
15091 static void
15092 trace_command (char *arg, int from_tty)
15093 {
15094   struct breakpoint_ops *ops;
15095   const char *arg_cp = arg;
15096
15097   if (arg && probe_linespec_to_ops (&arg_cp))
15098     ops = &tracepoint_probe_breakpoint_ops;
15099   else
15100     ops = &tracepoint_breakpoint_ops;
15101
15102   create_breakpoint (get_current_arch (),
15103                      arg,
15104                      NULL, 0, NULL, 1 /* parse arg */,
15105                      0 /* tempflag */,
15106                      bp_tracepoint /* type_wanted */,
15107                      0 /* Ignore count */,
15108                      pending_break_support,
15109                      ops,
15110                      from_tty,
15111                      1 /* enabled */,
15112                      0 /* internal */, 0);
15113 }
15114
15115 static void
15116 ftrace_command (char *arg, int from_tty)
15117 {
15118   create_breakpoint (get_current_arch (),
15119                      arg,
15120                      NULL, 0, NULL, 1 /* parse arg */,
15121                      0 /* tempflag */,
15122                      bp_fast_tracepoint /* type_wanted */,
15123                      0 /* Ignore count */,
15124                      pending_break_support,
15125                      &tracepoint_breakpoint_ops,
15126                      from_tty,
15127                      1 /* enabled */,
15128                      0 /* internal */, 0);
15129 }
15130
15131 /* strace command implementation.  Creates a static tracepoint.  */
15132
15133 static void
15134 strace_command (char *arg, int from_tty)
15135 {
15136   struct breakpoint_ops *ops;
15137
15138   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15139      or with a normal static tracepoint.  */
15140   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15141     ops = &strace_marker_breakpoint_ops;
15142   else
15143     ops = &tracepoint_breakpoint_ops;
15144
15145   create_breakpoint (get_current_arch (),
15146                      arg,
15147                      NULL, 0, NULL, 1 /* parse arg */,
15148                      0 /* tempflag */,
15149                      bp_static_tracepoint /* type_wanted */,
15150                      0 /* Ignore count */,
15151                      pending_break_support,
15152                      ops,
15153                      from_tty,
15154                      1 /* enabled */,
15155                      0 /* internal */, 0);
15156 }
15157
15158 /* Set up a fake reader function that gets command lines from a linked
15159    list that was acquired during tracepoint uploading.  */
15160
15161 static struct uploaded_tp *this_utp;
15162 static int next_cmd;
15163
15164 static char *
15165 read_uploaded_action (void)
15166 {
15167   char *rslt;
15168
15169   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15170
15171   next_cmd++;
15172
15173   return rslt;
15174 }
15175
15176 /* Given information about a tracepoint as recorded on a target (which
15177    can be either a live system or a trace file), attempt to create an
15178    equivalent GDB tracepoint.  This is not a reliable process, since
15179    the target does not necessarily have all the information used when
15180    the tracepoint was originally defined.  */
15181   
15182 struct tracepoint *
15183 create_tracepoint_from_upload (struct uploaded_tp *utp)
15184 {
15185   char *addr_str, small_buf[100];
15186   struct tracepoint *tp;
15187
15188   if (utp->at_string)
15189     addr_str = utp->at_string;
15190   else
15191     {
15192       /* In the absence of a source location, fall back to raw
15193          address.  Since there is no way to confirm that the address
15194          means the same thing as when the trace was started, warn the
15195          user.  */
15196       warning (_("Uploaded tracepoint %d has no "
15197                  "source location, using raw address"),
15198                utp->number);
15199       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15200       addr_str = small_buf;
15201     }
15202
15203   /* There's not much we can do with a sequence of bytecodes.  */
15204   if (utp->cond && !utp->cond_string)
15205     warning (_("Uploaded tracepoint %d condition "
15206                "has no source form, ignoring it"),
15207              utp->number);
15208
15209   if (!create_breakpoint (get_current_arch (),
15210                           addr_str,
15211                           utp->cond_string, -1, NULL,
15212                           0 /* parse cond/thread */,
15213                           0 /* tempflag */,
15214                           utp->type /* type_wanted */,
15215                           0 /* Ignore count */,
15216                           pending_break_support,
15217                           &tracepoint_breakpoint_ops,
15218                           0 /* from_tty */,
15219                           utp->enabled /* enabled */,
15220                           0 /* internal */,
15221                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15222     return NULL;
15223
15224   /* Get the tracepoint we just created.  */
15225   tp = get_tracepoint (tracepoint_count);
15226   gdb_assert (tp != NULL);
15227
15228   if (utp->pass > 0)
15229     {
15230       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15231                  tp->base.number);
15232
15233       trace_pass_command (small_buf, 0);
15234     }
15235
15236   /* If we have uploaded versions of the original commands, set up a
15237      special-purpose "reader" function and call the usual command line
15238      reader, then pass the result to the breakpoint command-setting
15239      function.  */
15240   if (!VEC_empty (char_ptr, utp->cmd_strings))
15241     {
15242       struct command_line *cmd_list;
15243
15244       this_utp = utp;
15245       next_cmd = 0;
15246
15247       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15248
15249       breakpoint_set_commands (&tp->base, cmd_list);
15250     }
15251   else if (!VEC_empty (char_ptr, utp->actions)
15252            || !VEC_empty (char_ptr, utp->step_actions))
15253     warning (_("Uploaded tracepoint %d actions "
15254                "have no source form, ignoring them"),
15255              utp->number);
15256
15257   /* Copy any status information that might be available.  */
15258   tp->base.hit_count = utp->hit_count;
15259   tp->traceframe_usage = utp->traceframe_usage;
15260
15261   return tp;
15262 }
15263   
15264 /* Print information on tracepoint number TPNUM_EXP, or all if
15265    omitted.  */
15266
15267 static void
15268 tracepoints_info (char *args, int from_tty)
15269 {
15270   struct ui_out *uiout = current_uiout;
15271   int num_printed;
15272
15273   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15274
15275   if (num_printed == 0)
15276     {
15277       if (args == NULL || *args == '\0')
15278         ui_out_message (uiout, 0, "No tracepoints.\n");
15279       else
15280         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15281     }
15282
15283   default_collect_info ();
15284 }
15285
15286 /* The 'enable trace' command enables tracepoints.
15287    Not supported by all targets.  */
15288 static void
15289 enable_trace_command (char *args, int from_tty)
15290 {
15291   enable_command (args, from_tty);
15292 }
15293
15294 /* The 'disable trace' command disables tracepoints.
15295    Not supported by all targets.  */
15296 static void
15297 disable_trace_command (char *args, int from_tty)
15298 {
15299   disable_command (args, from_tty);
15300 }
15301
15302 /* Remove a tracepoint (or all if no argument).  */
15303 static void
15304 delete_trace_command (char *arg, int from_tty)
15305 {
15306   struct breakpoint *b, *b_tmp;
15307
15308   dont_repeat ();
15309
15310   if (arg == 0)
15311     {
15312       int breaks_to_delete = 0;
15313
15314       /* Delete all breakpoints if no argument.
15315          Do not delete internal or call-dummy breakpoints, these
15316          have to be deleted with an explicit breakpoint number 
15317          argument.  */
15318       ALL_TRACEPOINTS (b)
15319         if (is_tracepoint (b) && user_breakpoint_p (b))
15320           {
15321             breaks_to_delete = 1;
15322             break;
15323           }
15324
15325       /* Ask user only if there are some breakpoints to delete.  */
15326       if (!from_tty
15327           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15328         {
15329           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15330             if (is_tracepoint (b) && user_breakpoint_p (b))
15331               delete_breakpoint (b);
15332         }
15333     }
15334   else
15335     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15336 }
15337
15338 /* Helper function for trace_pass_command.  */
15339
15340 static void
15341 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15342 {
15343   tp->pass_count = count;
15344   observer_notify_breakpoint_modified (&tp->base);
15345   if (from_tty)
15346     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15347                      tp->base.number, count);
15348 }
15349
15350 /* Set passcount for tracepoint.
15351
15352    First command argument is passcount, second is tracepoint number.
15353    If tracepoint number omitted, apply to most recently defined.
15354    Also accepts special argument "all".  */
15355
15356 static void
15357 trace_pass_command (char *args, int from_tty)
15358 {
15359   struct tracepoint *t1;
15360   unsigned int count;
15361
15362   if (args == 0 || *args == 0)
15363     error (_("passcount command requires an "
15364              "argument (count + optional TP num)"));
15365
15366   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15367
15368   args = skip_spaces (args);
15369   if (*args && strncasecmp (args, "all", 3) == 0)
15370     {
15371       struct breakpoint *b;
15372
15373       args += 3;                        /* Skip special argument "all".  */
15374       if (*args)
15375         error (_("Junk at end of arguments."));
15376
15377       ALL_TRACEPOINTS (b)
15378       {
15379         t1 = (struct tracepoint *) b;
15380         trace_pass_set_count (t1, count, from_tty);
15381       }
15382     }
15383   else if (*args == '\0')
15384     {
15385       t1 = get_tracepoint_by_number (&args, NULL, 1);
15386       if (t1)
15387         trace_pass_set_count (t1, count, from_tty);
15388     }
15389   else
15390     {
15391       struct get_number_or_range_state state;
15392
15393       init_number_or_range (&state, args);
15394       while (!state.finished)
15395         {
15396           t1 = get_tracepoint_by_number (&args, &state, 1);
15397           if (t1)
15398             trace_pass_set_count (t1, count, from_tty);
15399         }
15400     }
15401 }
15402
15403 struct tracepoint *
15404 get_tracepoint (int num)
15405 {
15406   struct breakpoint *t;
15407
15408   ALL_TRACEPOINTS (t)
15409     if (t->number == num)
15410       return (struct tracepoint *) t;
15411
15412   return NULL;
15413 }
15414
15415 /* Find the tracepoint with the given target-side number (which may be
15416    different from the tracepoint number after disconnecting and
15417    reconnecting).  */
15418
15419 struct tracepoint *
15420 get_tracepoint_by_number_on_target (int num)
15421 {
15422   struct breakpoint *b;
15423
15424   ALL_TRACEPOINTS (b)
15425     {
15426       struct tracepoint *t = (struct tracepoint *) b;
15427
15428       if (t->number_on_target == num)
15429         return t;
15430     }
15431
15432   return NULL;
15433 }
15434
15435 /* Utility: parse a tracepoint number and look it up in the list.
15436    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15437    If OPTIONAL_P is true, then if the argument is missing, the most
15438    recent tracepoint (tracepoint_count) is returned.  */
15439 struct tracepoint *
15440 get_tracepoint_by_number (char **arg,
15441                           struct get_number_or_range_state *state,
15442                           int optional_p)
15443 {
15444   struct breakpoint *t;
15445   int tpnum;
15446   char *instring = arg == NULL ? NULL : *arg;
15447
15448   if (state)
15449     {
15450       gdb_assert (!state->finished);
15451       tpnum = get_number_or_range (state);
15452     }
15453   else if (arg == NULL || *arg == NULL || ! **arg)
15454     {
15455       if (optional_p)
15456         tpnum = tracepoint_count;
15457       else
15458         error_no_arg (_("tracepoint number"));
15459     }
15460   else
15461     tpnum = get_number (arg);
15462
15463   if (tpnum <= 0)
15464     {
15465       if (instring && *instring)
15466         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15467                          instring);
15468       else
15469         printf_filtered (_("Tracepoint argument missing "
15470                            "and no previous tracepoint\n"));
15471       return NULL;
15472     }
15473
15474   ALL_TRACEPOINTS (t)
15475     if (t->number == tpnum)
15476     {
15477       return (struct tracepoint *) t;
15478     }
15479
15480   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15481   return NULL;
15482 }
15483
15484 void
15485 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15486 {
15487   if (b->thread != -1)
15488     fprintf_unfiltered (fp, " thread %d", b->thread);
15489
15490   if (b->task != 0)
15491     fprintf_unfiltered (fp, " task %d", b->task);
15492
15493   fprintf_unfiltered (fp, "\n");
15494 }
15495
15496 /* Save information on user settable breakpoints (watchpoints, etc) to
15497    a new script file named FILENAME.  If FILTER is non-NULL, call it
15498    on each breakpoint and only include the ones for which it returns
15499    non-zero.  */
15500
15501 static void
15502 save_breakpoints (char *filename, int from_tty,
15503                   int (*filter) (const struct breakpoint *))
15504 {
15505   struct breakpoint *tp;
15506   int any = 0;
15507   struct cleanup *cleanup;
15508   struct ui_file *fp;
15509   int extra_trace_bits = 0;
15510
15511   if (filename == 0 || *filename == 0)
15512     error (_("Argument required (file name in which to save)"));
15513
15514   /* See if we have anything to save.  */
15515   ALL_BREAKPOINTS (tp)
15516   {
15517     /* Skip internal and momentary breakpoints.  */
15518     if (!user_breakpoint_p (tp))
15519       continue;
15520
15521     /* If we have a filter, only save the breakpoints it accepts.  */
15522     if (filter && !filter (tp))
15523       continue;
15524
15525     any = 1;
15526
15527     if (is_tracepoint (tp))
15528       {
15529         extra_trace_bits = 1;
15530
15531         /* We can stop searching.  */
15532         break;
15533       }
15534   }
15535
15536   if (!any)
15537     {
15538       warning (_("Nothing to save."));
15539       return;
15540     }
15541
15542   filename = tilde_expand (filename);
15543   cleanup = make_cleanup (xfree, filename);
15544   fp = gdb_fopen (filename, "w");
15545   if (!fp)
15546     error (_("Unable to open file '%s' for saving (%s)"),
15547            filename, safe_strerror (errno));
15548   make_cleanup_ui_file_delete (fp);
15549
15550   if (extra_trace_bits)
15551     save_trace_state_variables (fp);
15552
15553   ALL_BREAKPOINTS (tp)
15554   {
15555     /* Skip internal and momentary breakpoints.  */
15556     if (!user_breakpoint_p (tp))
15557       continue;
15558
15559     /* If we have a filter, only save the breakpoints it accepts.  */
15560     if (filter && !filter (tp))
15561       continue;
15562
15563     tp->ops->print_recreate (tp, fp);
15564
15565     /* Note, we can't rely on tp->number for anything, as we can't
15566        assume the recreated breakpoint numbers will match.  Use $bpnum
15567        instead.  */
15568
15569     if (tp->cond_string)
15570       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15571
15572     if (tp->ignore_count)
15573       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15574
15575     if (tp->type != bp_dprintf && tp->commands)
15576       {
15577         volatile struct gdb_exception ex;       
15578
15579         fprintf_unfiltered (fp, "  commands\n");
15580         
15581         ui_out_redirect (current_uiout, fp);
15582         TRY_CATCH (ex, RETURN_MASK_ALL)
15583           {
15584             print_command_lines (current_uiout, tp->commands->commands, 2);
15585           }
15586         ui_out_redirect (current_uiout, NULL);
15587
15588         if (ex.reason < 0)
15589           throw_exception (ex);
15590
15591         fprintf_unfiltered (fp, "  end\n");
15592       }
15593
15594     if (tp->enable_state == bp_disabled)
15595       fprintf_unfiltered (fp, "disable\n");
15596
15597     /* If this is a multi-location breakpoint, check if the locations
15598        should be individually disabled.  Watchpoint locations are
15599        special, and not user visible.  */
15600     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15601       {
15602         struct bp_location *loc;
15603         int n = 1;
15604
15605         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15606           if (!loc->enabled)
15607             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15608       }
15609   }
15610
15611   if (extra_trace_bits && *default_collect)
15612     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15613
15614   if (from_tty)
15615     printf_filtered (_("Saved to file '%s'.\n"), filename);
15616   do_cleanups (cleanup);
15617 }
15618
15619 /* The `save breakpoints' command.  */
15620
15621 static void
15622 save_breakpoints_command (char *args, int from_tty)
15623 {
15624   save_breakpoints (args, from_tty, NULL);
15625 }
15626
15627 /* The `save tracepoints' command.  */
15628
15629 static void
15630 save_tracepoints_command (char *args, int from_tty)
15631 {
15632   save_breakpoints (args, from_tty, is_tracepoint);
15633 }
15634
15635 /* Create a vector of all tracepoints.  */
15636
15637 VEC(breakpoint_p) *
15638 all_tracepoints (void)
15639 {
15640   VEC(breakpoint_p) *tp_vec = 0;
15641   struct breakpoint *tp;
15642
15643   ALL_TRACEPOINTS (tp)
15644   {
15645     VEC_safe_push (breakpoint_p, tp_vec, tp);
15646   }
15647
15648   return tp_vec;
15649 }
15650
15651 \f
15652 /* This help string is used for the break, hbreak, tbreak and thbreak
15653    commands.  It is defined as a macro to prevent duplication.
15654    COMMAND should be a string constant containing the name of the
15655    command.  */
15656 #define BREAK_ARGS_HELP(command) \
15657 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15658 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15659 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15660 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15661 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15662 If a line number is specified, break at start of code for that line.\n\
15663 If a function is specified, break at start of code for that function.\n\
15664 If an address is specified, break at that exact address.\n\
15665 With no LOCATION, uses current execution address of the selected\n\
15666 stack frame.  This is useful for breaking on return to a stack frame.\n\
15667 \n\
15668 THREADNUM is the number from \"info threads\".\n\
15669 CONDITION is a boolean expression.\n\
15670 \n\
15671 Multiple breakpoints at one place are permitted, and useful if their\n\
15672 conditions are different.\n\
15673 \n\
15674 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15675
15676 /* List of subcommands for "catch".  */
15677 static struct cmd_list_element *catch_cmdlist;
15678
15679 /* List of subcommands for "tcatch".  */
15680 static struct cmd_list_element *tcatch_cmdlist;
15681
15682 void
15683 add_catch_command (char *name, char *docstring,
15684                    void (*sfunc) (char *args, int from_tty,
15685                                   struct cmd_list_element *command),
15686                    completer_ftype *completer,
15687                    void *user_data_catch,
15688                    void *user_data_tcatch)
15689 {
15690   struct cmd_list_element *command;
15691
15692   command = add_cmd (name, class_breakpoint, NULL, docstring,
15693                      &catch_cmdlist);
15694   set_cmd_sfunc (command, sfunc);
15695   set_cmd_context (command, user_data_catch);
15696   set_cmd_completer (command, completer);
15697
15698   command = add_cmd (name, class_breakpoint, NULL, docstring,
15699                      &tcatch_cmdlist);
15700   set_cmd_sfunc (command, sfunc);
15701   set_cmd_context (command, user_data_tcatch);
15702   set_cmd_completer (command, completer);
15703 }
15704
15705 static void
15706 clear_syscall_counts (struct inferior *inf)
15707 {
15708   struct catch_syscall_inferior_data *inf_data
15709     = get_catch_syscall_inferior_data (inf);
15710
15711   inf_data->total_syscalls_count = 0;
15712   inf_data->any_syscall_count = 0;
15713   VEC_free (int, inf_data->syscalls_counts);
15714 }
15715
15716 static void
15717 save_command (char *arg, int from_tty)
15718 {
15719   printf_unfiltered (_("\"save\" must be followed by "
15720                        "the name of a save subcommand.\n"));
15721   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15722 }
15723
15724 struct breakpoint *
15725 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15726                           void *data)
15727 {
15728   struct breakpoint *b, *b_tmp;
15729
15730   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15731     {
15732       if ((*callback) (b, data))
15733         return b;
15734     }
15735
15736   return NULL;
15737 }
15738
15739 /* Zero if any of the breakpoint's locations could be a location where
15740    functions have been inlined, nonzero otherwise.  */
15741
15742 static int
15743 is_non_inline_function (struct breakpoint *b)
15744 {
15745   /* The shared library event breakpoint is set on the address of a
15746      non-inline function.  */
15747   if (b->type == bp_shlib_event)
15748     return 1;
15749
15750   return 0;
15751 }
15752
15753 /* Nonzero if the specified PC cannot be a location where functions
15754    have been inlined.  */
15755
15756 int
15757 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15758                            const struct target_waitstatus *ws)
15759 {
15760   struct breakpoint *b;
15761   struct bp_location *bl;
15762
15763   ALL_BREAKPOINTS (b)
15764     {
15765       if (!is_non_inline_function (b))
15766         continue;
15767
15768       for (bl = b->loc; bl != NULL; bl = bl->next)
15769         {
15770           if (!bl->shlib_disabled
15771               && bpstat_check_location (bl, aspace, pc, ws))
15772             return 1;
15773         }
15774     }
15775
15776   return 0;
15777 }
15778
15779 /* Remove any references to OBJFILE which is going to be freed.  */
15780
15781 void
15782 breakpoint_free_objfile (struct objfile *objfile)
15783 {
15784   struct bp_location **locp, *loc;
15785
15786   ALL_BP_LOCATIONS (loc, locp)
15787     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
15788       loc->symtab = NULL;
15789 }
15790
15791 void
15792 initialize_breakpoint_ops (void)
15793 {
15794   static int initialized = 0;
15795
15796   struct breakpoint_ops *ops;
15797
15798   if (initialized)
15799     return;
15800   initialized = 1;
15801
15802   /* The breakpoint_ops structure to be inherit by all kinds of
15803      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15804      internal and momentary breakpoints, etc.).  */
15805   ops = &bkpt_base_breakpoint_ops;
15806   *ops = base_breakpoint_ops;
15807   ops->re_set = bkpt_re_set;
15808   ops->insert_location = bkpt_insert_location;
15809   ops->remove_location = bkpt_remove_location;
15810   ops->breakpoint_hit = bkpt_breakpoint_hit;
15811   ops->create_sals_from_address = bkpt_create_sals_from_address;
15812   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15813   ops->decode_linespec = bkpt_decode_linespec;
15814
15815   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15816   ops = &bkpt_breakpoint_ops;
15817   *ops = bkpt_base_breakpoint_ops;
15818   ops->re_set = bkpt_re_set;
15819   ops->resources_needed = bkpt_resources_needed;
15820   ops->print_it = bkpt_print_it;
15821   ops->print_mention = bkpt_print_mention;
15822   ops->print_recreate = bkpt_print_recreate;
15823
15824   /* Ranged breakpoints.  */
15825   ops = &ranged_breakpoint_ops;
15826   *ops = bkpt_breakpoint_ops;
15827   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15828   ops->resources_needed = resources_needed_ranged_breakpoint;
15829   ops->print_it = print_it_ranged_breakpoint;
15830   ops->print_one = print_one_ranged_breakpoint;
15831   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15832   ops->print_mention = print_mention_ranged_breakpoint;
15833   ops->print_recreate = print_recreate_ranged_breakpoint;
15834
15835   /* Internal breakpoints.  */
15836   ops = &internal_breakpoint_ops;
15837   *ops = bkpt_base_breakpoint_ops;
15838   ops->re_set = internal_bkpt_re_set;
15839   ops->check_status = internal_bkpt_check_status;
15840   ops->print_it = internal_bkpt_print_it;
15841   ops->print_mention = internal_bkpt_print_mention;
15842
15843   /* Momentary breakpoints.  */
15844   ops = &momentary_breakpoint_ops;
15845   *ops = bkpt_base_breakpoint_ops;
15846   ops->re_set = momentary_bkpt_re_set;
15847   ops->check_status = momentary_bkpt_check_status;
15848   ops->print_it = momentary_bkpt_print_it;
15849   ops->print_mention = momentary_bkpt_print_mention;
15850
15851   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15852   ops = &longjmp_breakpoint_ops;
15853   *ops = momentary_breakpoint_ops;
15854   ops->dtor = longjmp_bkpt_dtor;
15855
15856   /* Probe breakpoints.  */
15857   ops = &bkpt_probe_breakpoint_ops;
15858   *ops = bkpt_breakpoint_ops;
15859   ops->insert_location = bkpt_probe_insert_location;
15860   ops->remove_location = bkpt_probe_remove_location;
15861   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15862   ops->decode_linespec = bkpt_probe_decode_linespec;
15863
15864   /* Watchpoints.  */
15865   ops = &watchpoint_breakpoint_ops;
15866   *ops = base_breakpoint_ops;
15867   ops->dtor = dtor_watchpoint;
15868   ops->re_set = re_set_watchpoint;
15869   ops->insert_location = insert_watchpoint;
15870   ops->remove_location = remove_watchpoint;
15871   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15872   ops->check_status = check_status_watchpoint;
15873   ops->resources_needed = resources_needed_watchpoint;
15874   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15875   ops->print_it = print_it_watchpoint;
15876   ops->print_mention = print_mention_watchpoint;
15877   ops->print_recreate = print_recreate_watchpoint;
15878   ops->explains_signal = explains_signal_watchpoint;
15879
15880   /* Masked watchpoints.  */
15881   ops = &masked_watchpoint_breakpoint_ops;
15882   *ops = watchpoint_breakpoint_ops;
15883   ops->insert_location = insert_masked_watchpoint;
15884   ops->remove_location = remove_masked_watchpoint;
15885   ops->resources_needed = resources_needed_masked_watchpoint;
15886   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15887   ops->print_it = print_it_masked_watchpoint;
15888   ops->print_one_detail = print_one_detail_masked_watchpoint;
15889   ops->print_mention = print_mention_masked_watchpoint;
15890   ops->print_recreate = print_recreate_masked_watchpoint;
15891
15892   /* Tracepoints.  */
15893   ops = &tracepoint_breakpoint_ops;
15894   *ops = base_breakpoint_ops;
15895   ops->re_set = tracepoint_re_set;
15896   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15897   ops->print_one_detail = tracepoint_print_one_detail;
15898   ops->print_mention = tracepoint_print_mention;
15899   ops->print_recreate = tracepoint_print_recreate;
15900   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15901   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15902   ops->decode_linespec = tracepoint_decode_linespec;
15903
15904   /* Probe tracepoints.  */
15905   ops = &tracepoint_probe_breakpoint_ops;
15906   *ops = tracepoint_breakpoint_ops;
15907   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15908   ops->decode_linespec = tracepoint_probe_decode_linespec;
15909
15910   /* Static tracepoints with marker (`-m').  */
15911   ops = &strace_marker_breakpoint_ops;
15912   *ops = tracepoint_breakpoint_ops;
15913   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15914   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15915   ops->decode_linespec = strace_marker_decode_linespec;
15916
15917   /* Fork catchpoints.  */
15918   ops = &catch_fork_breakpoint_ops;
15919   *ops = base_breakpoint_ops;
15920   ops->insert_location = insert_catch_fork;
15921   ops->remove_location = remove_catch_fork;
15922   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15923   ops->print_it = print_it_catch_fork;
15924   ops->print_one = print_one_catch_fork;
15925   ops->print_mention = print_mention_catch_fork;
15926   ops->print_recreate = print_recreate_catch_fork;
15927
15928   /* Vfork catchpoints.  */
15929   ops = &catch_vfork_breakpoint_ops;
15930   *ops = base_breakpoint_ops;
15931   ops->insert_location = insert_catch_vfork;
15932   ops->remove_location = remove_catch_vfork;
15933   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15934   ops->print_it = print_it_catch_vfork;
15935   ops->print_one = print_one_catch_vfork;
15936   ops->print_mention = print_mention_catch_vfork;
15937   ops->print_recreate = print_recreate_catch_vfork;
15938
15939   /* Exec catchpoints.  */
15940   ops = &catch_exec_breakpoint_ops;
15941   *ops = base_breakpoint_ops;
15942   ops->dtor = dtor_catch_exec;
15943   ops->insert_location = insert_catch_exec;
15944   ops->remove_location = remove_catch_exec;
15945   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15946   ops->print_it = print_it_catch_exec;
15947   ops->print_one = print_one_catch_exec;
15948   ops->print_mention = print_mention_catch_exec;
15949   ops->print_recreate = print_recreate_catch_exec;
15950
15951   /* Syscall catchpoints.  */
15952   ops = &catch_syscall_breakpoint_ops;
15953   *ops = base_breakpoint_ops;
15954   ops->dtor = dtor_catch_syscall;
15955   ops->insert_location = insert_catch_syscall;
15956   ops->remove_location = remove_catch_syscall;
15957   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15958   ops->print_it = print_it_catch_syscall;
15959   ops->print_one = print_one_catch_syscall;
15960   ops->print_mention = print_mention_catch_syscall;
15961   ops->print_recreate = print_recreate_catch_syscall;
15962
15963   /* Solib-related catchpoints.  */
15964   ops = &catch_solib_breakpoint_ops;
15965   *ops = base_breakpoint_ops;
15966   ops->dtor = dtor_catch_solib;
15967   ops->insert_location = insert_catch_solib;
15968   ops->remove_location = remove_catch_solib;
15969   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15970   ops->check_status = check_status_catch_solib;
15971   ops->print_it = print_it_catch_solib;
15972   ops->print_one = print_one_catch_solib;
15973   ops->print_mention = print_mention_catch_solib;
15974   ops->print_recreate = print_recreate_catch_solib;
15975
15976   ops = &dprintf_breakpoint_ops;
15977   *ops = bkpt_base_breakpoint_ops;
15978   ops->re_set = dprintf_re_set;
15979   ops->resources_needed = bkpt_resources_needed;
15980   ops->print_it = bkpt_print_it;
15981   ops->print_mention = bkpt_print_mention;
15982   ops->print_recreate = dprintf_print_recreate;
15983   ops->after_condition_true = dprintf_after_condition_true;
15984 }
15985
15986 /* Chain containing all defined "enable breakpoint" subcommands.  */
15987
15988 static struct cmd_list_element *enablebreaklist = NULL;
15989
15990 void
15991 _initialize_breakpoint (void)
15992 {
15993   struct cmd_list_element *c;
15994
15995   initialize_breakpoint_ops ();
15996
15997   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15998   observer_attach_inferior_exit (clear_syscall_counts);
15999   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16000
16001   breakpoint_objfile_key
16002     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16003
16004   catch_syscall_inferior_data
16005     = register_inferior_data_with_cleanup (NULL,
16006                                            catch_syscall_inferior_data_cleanup);
16007
16008   breakpoint_chain = 0;
16009   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16010      before a breakpoint is set.  */
16011   breakpoint_count = 0;
16012
16013   tracepoint_count = 0;
16014
16015   add_com ("ignore", class_breakpoint, ignore_command, _("\
16016 Set ignore-count of breakpoint number N to COUNT.\n\
16017 Usage is `ignore N COUNT'."));
16018   if (xdb_commands)
16019     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16020
16021   add_com ("commands", class_breakpoint, commands_command, _("\
16022 Set commands to be executed when a breakpoint is hit.\n\
16023 Give breakpoint number as argument after \"commands\".\n\
16024 With no argument, the targeted breakpoint is the last one set.\n\
16025 The commands themselves follow starting on the next line.\n\
16026 Type a line containing \"end\" to indicate the end of them.\n\
16027 Give \"silent\" as the first line to make the breakpoint silent;\n\
16028 then no output is printed when it is hit, except what the commands print."));
16029
16030   c = add_com ("condition", class_breakpoint, condition_command, _("\
16031 Specify breakpoint number N to break only if COND is true.\n\
16032 Usage is `condition N COND', where N is an integer and COND is an\n\
16033 expression to be evaluated whenever breakpoint N is reached."));
16034   set_cmd_completer (c, condition_completer);
16035
16036   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16037 Set a temporary breakpoint.\n\
16038 Like \"break\" except the breakpoint is only temporary,\n\
16039 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16040 by using \"enable delete\" on the breakpoint number.\n\
16041 \n"
16042 BREAK_ARGS_HELP ("tbreak")));
16043   set_cmd_completer (c, location_completer);
16044
16045   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16046 Set a hardware assisted breakpoint.\n\
16047 Like \"break\" except the breakpoint requires hardware support,\n\
16048 some target hardware may not have this support.\n\
16049 \n"
16050 BREAK_ARGS_HELP ("hbreak")));
16051   set_cmd_completer (c, location_completer);
16052
16053   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16054 Set a temporary hardware assisted breakpoint.\n\
16055 Like \"hbreak\" except the breakpoint is only temporary,\n\
16056 so it will be deleted when hit.\n\
16057 \n"
16058 BREAK_ARGS_HELP ("thbreak")));
16059   set_cmd_completer (c, location_completer);
16060
16061   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16062 Enable some breakpoints.\n\
16063 Give breakpoint numbers (separated by spaces) as arguments.\n\
16064 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16065 This is used to cancel the effect of the \"disable\" command.\n\
16066 With a subcommand you can enable temporarily."),
16067                   &enablelist, "enable ", 1, &cmdlist);
16068   if (xdb_commands)
16069     add_com ("ab", class_breakpoint, enable_command, _("\
16070 Enable some breakpoints.\n\
16071 Give breakpoint numbers (separated by spaces) as arguments.\n\
16072 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16073 This is used to cancel the effect of the \"disable\" command.\n\
16074 With a subcommand you can enable temporarily."));
16075
16076   add_com_alias ("en", "enable", class_breakpoint, 1);
16077
16078   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16079 Enable some breakpoints.\n\
16080 Give breakpoint numbers (separated by spaces) as arguments.\n\
16081 This is used to cancel the effect of the \"disable\" command.\n\
16082 May be abbreviated to simply \"enable\".\n"),
16083                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16084
16085   add_cmd ("once", no_class, enable_once_command, _("\
16086 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16087 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16088            &enablebreaklist);
16089
16090   add_cmd ("delete", no_class, enable_delete_command, _("\
16091 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16092 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16093            &enablebreaklist);
16094
16095   add_cmd ("count", no_class, enable_count_command, _("\
16096 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16097 If a breakpoint is hit while enabled in this fashion,\n\
16098 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16099            &enablebreaklist);
16100
16101   add_cmd ("delete", no_class, enable_delete_command, _("\
16102 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16103 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16104            &enablelist);
16105
16106   add_cmd ("once", no_class, enable_once_command, _("\
16107 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16108 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16109            &enablelist);
16110
16111   add_cmd ("count", no_class, enable_count_command, _("\
16112 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16113 If a breakpoint is hit while enabled in this fashion,\n\
16114 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16115            &enablelist);
16116
16117   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16118 Disable some breakpoints.\n\
16119 Arguments are breakpoint numbers with spaces in between.\n\
16120 To disable all breakpoints, give no argument.\n\
16121 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16122                   &disablelist, "disable ", 1, &cmdlist);
16123   add_com_alias ("dis", "disable", class_breakpoint, 1);
16124   add_com_alias ("disa", "disable", class_breakpoint, 1);
16125   if (xdb_commands)
16126     add_com ("sb", class_breakpoint, disable_command, _("\
16127 Disable some breakpoints.\n\
16128 Arguments are breakpoint numbers with spaces in between.\n\
16129 To disable all breakpoints, give no argument.\n\
16130 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16131
16132   add_cmd ("breakpoints", class_alias, disable_command, _("\
16133 Disable some breakpoints.\n\
16134 Arguments are breakpoint numbers with spaces in between.\n\
16135 To disable all breakpoints, give no argument.\n\
16136 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16137 This command may be abbreviated \"disable\"."),
16138            &disablelist);
16139
16140   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16141 Delete some breakpoints or auto-display expressions.\n\
16142 Arguments are breakpoint numbers with spaces in between.\n\
16143 To delete all breakpoints, give no argument.\n\
16144 \n\
16145 Also a prefix command for deletion of other GDB objects.\n\
16146 The \"unset\" command is also an alias for \"delete\"."),
16147                   &deletelist, "delete ", 1, &cmdlist);
16148   add_com_alias ("d", "delete", class_breakpoint, 1);
16149   add_com_alias ("del", "delete", class_breakpoint, 1);
16150   if (xdb_commands)
16151     add_com ("db", class_breakpoint, delete_command, _("\
16152 Delete some breakpoints.\n\
16153 Arguments are breakpoint numbers with spaces in between.\n\
16154 To delete all breakpoints, give no argument.\n"));
16155
16156   add_cmd ("breakpoints", class_alias, delete_command, _("\
16157 Delete some breakpoints or auto-display expressions.\n\
16158 Arguments are breakpoint numbers with spaces in between.\n\
16159 To delete all breakpoints, give no argument.\n\
16160 This command may be abbreviated \"delete\"."),
16161            &deletelist);
16162
16163   add_com ("clear", class_breakpoint, clear_command, _("\
16164 Clear breakpoint at specified line or function.\n\
16165 Argument may be line number, function name, or \"*\" and an address.\n\
16166 If line number is specified, all breakpoints in that line are cleared.\n\
16167 If function is specified, breakpoints at beginning of function are cleared.\n\
16168 If an address is specified, breakpoints at that address are cleared.\n\
16169 \n\
16170 With no argument, clears all breakpoints in the line that the selected frame\n\
16171 is executing in.\n\
16172 \n\
16173 See also the \"delete\" command which clears breakpoints by number."));
16174   add_com_alias ("cl", "clear", class_breakpoint, 1);
16175
16176   c = add_com ("break", class_breakpoint, break_command, _("\
16177 Set breakpoint at specified line or function.\n"
16178 BREAK_ARGS_HELP ("break")));
16179   set_cmd_completer (c, location_completer);
16180
16181   add_com_alias ("b", "break", class_run, 1);
16182   add_com_alias ("br", "break", class_run, 1);
16183   add_com_alias ("bre", "break", class_run, 1);
16184   add_com_alias ("brea", "break", class_run, 1);
16185
16186   if (xdb_commands)
16187    add_com_alias ("ba", "break", class_breakpoint, 1);
16188
16189   if (dbx_commands)
16190     {
16191       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16192 Break in function/address or break at a line in the current file."),
16193                              &stoplist, "stop ", 1, &cmdlist);
16194       add_cmd ("in", class_breakpoint, stopin_command,
16195                _("Break in function or address."), &stoplist);
16196       add_cmd ("at", class_breakpoint, stopat_command,
16197                _("Break at a line in the current file."), &stoplist);
16198       add_com ("status", class_info, breakpoints_info, _("\
16199 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16200 The \"Type\" column indicates one of:\n\
16201 \tbreakpoint     - normal breakpoint\n\
16202 \twatchpoint     - watchpoint\n\
16203 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16204 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16205 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16206 address and file/line number respectively.\n\
16207 \n\
16208 Convenience variable \"$_\" and default examine address for \"x\"\n\
16209 are set to the address of the last breakpoint listed unless the command\n\
16210 is prefixed with \"server \".\n\n\
16211 Convenience variable \"$bpnum\" contains the number of the last\n\
16212 breakpoint set."));
16213     }
16214
16215   add_info ("breakpoints", breakpoints_info, _("\
16216 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16217 The \"Type\" column indicates one of:\n\
16218 \tbreakpoint     - normal breakpoint\n\
16219 \twatchpoint     - watchpoint\n\
16220 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16221 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16222 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16223 address and file/line number respectively.\n\
16224 \n\
16225 Convenience variable \"$_\" and default examine address for \"x\"\n\
16226 are set to the address of the last breakpoint listed unless the command\n\
16227 is prefixed with \"server \".\n\n\
16228 Convenience variable \"$bpnum\" contains the number of the last\n\
16229 breakpoint set."));
16230
16231   add_info_alias ("b", "breakpoints", 1);
16232
16233   if (xdb_commands)
16234     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16235 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16236 The \"Type\" column indicates one of:\n\
16237 \tbreakpoint     - normal breakpoint\n\
16238 \twatchpoint     - watchpoint\n\
16239 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16240 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16241 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16242 address and file/line number respectively.\n\
16243 \n\
16244 Convenience variable \"$_\" and default examine address for \"x\"\n\
16245 are set to the address of the last breakpoint listed unless the command\n\
16246 is prefixed with \"server \".\n\n\
16247 Convenience variable \"$bpnum\" contains the number of the last\n\
16248 breakpoint set."));
16249
16250   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16251 Status of all breakpoints, or breakpoint number NUMBER.\n\
16252 The \"Type\" column indicates one of:\n\
16253 \tbreakpoint     - normal breakpoint\n\
16254 \twatchpoint     - watchpoint\n\
16255 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16256 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16257 \tuntil          - internal breakpoint used by the \"until\" command\n\
16258 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16259 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16260 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16261 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16262 address and file/line number respectively.\n\
16263 \n\
16264 Convenience variable \"$_\" and default examine address for \"x\"\n\
16265 are set to the address of the last breakpoint listed unless the command\n\
16266 is prefixed with \"server \".\n\n\
16267 Convenience variable \"$bpnum\" contains the number of the last\n\
16268 breakpoint set."),
16269            &maintenanceinfolist);
16270
16271   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16272 Set catchpoints to catch events."),
16273                   &catch_cmdlist, "catch ",
16274                   0/*allow-unknown*/, &cmdlist);
16275
16276   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16277 Set temporary catchpoints to catch events."),
16278                   &tcatch_cmdlist, "tcatch ",
16279                   0/*allow-unknown*/, &cmdlist);
16280
16281   add_catch_command ("fork", _("Catch calls to fork."),
16282                      catch_fork_command_1,
16283                      NULL,
16284                      (void *) (uintptr_t) catch_fork_permanent,
16285                      (void *) (uintptr_t) catch_fork_temporary);
16286   add_catch_command ("vfork", _("Catch calls to vfork."),
16287                      catch_fork_command_1,
16288                      NULL,
16289                      (void *) (uintptr_t) catch_vfork_permanent,
16290                      (void *) (uintptr_t) catch_vfork_temporary);
16291   add_catch_command ("exec", _("Catch calls to exec."),
16292                      catch_exec_command_1,
16293                      NULL,
16294                      CATCH_PERMANENT,
16295                      CATCH_TEMPORARY);
16296   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16297 Usage: catch load [REGEX]\n\
16298 If REGEX is given, only stop for libraries matching the regular expression."),
16299                      catch_load_command_1,
16300                      NULL,
16301                      CATCH_PERMANENT,
16302                      CATCH_TEMPORARY);
16303   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16304 Usage: catch unload [REGEX]\n\
16305 If REGEX is given, only stop for libraries matching the regular expression."),
16306                      catch_unload_command_1,
16307                      NULL,
16308                      CATCH_PERMANENT,
16309                      CATCH_TEMPORARY);
16310   add_catch_command ("syscall", _("\
16311 Catch system calls by their names and/or numbers.\n\
16312 Arguments say which system calls to catch.  If no arguments\n\
16313 are given, every system call will be caught.\n\
16314 Arguments, if given, should be one or more system call names\n\
16315 (if your system supports that), or system call numbers."),
16316                      catch_syscall_command_1,
16317                      catch_syscall_completer,
16318                      CATCH_PERMANENT,
16319                      CATCH_TEMPORARY);
16320
16321   c = add_com ("watch", class_breakpoint, watch_command, _("\
16322 Set a watchpoint for an expression.\n\
16323 Usage: watch [-l|-location] EXPRESSION\n\
16324 A watchpoint stops execution of your program whenever the value of\n\
16325 an expression changes.\n\
16326 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16327 the memory to which it refers."));
16328   set_cmd_completer (c, expression_completer);
16329
16330   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16331 Set a read watchpoint for an expression.\n\
16332 Usage: rwatch [-l|-location] EXPRESSION\n\
16333 A watchpoint stops execution of your program whenever the value of\n\
16334 an expression is read.\n\
16335 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16336 the memory to which it refers."));
16337   set_cmd_completer (c, expression_completer);
16338
16339   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16340 Set a watchpoint for an expression.\n\
16341 Usage: awatch [-l|-location] EXPRESSION\n\
16342 A watchpoint stops execution of your program whenever the value of\n\
16343 an expression is either read or written.\n\
16344 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16345 the memory to which it refers."));
16346   set_cmd_completer (c, expression_completer);
16347
16348   add_info ("watchpoints", watchpoints_info, _("\
16349 Status of specified watchpoints (all watchpoints if no argument)."));
16350
16351   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16352      respond to changes - contrary to the description.  */
16353   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16354                             &can_use_hw_watchpoints, _("\
16355 Set debugger's willingness to use watchpoint hardware."), _("\
16356 Show debugger's willingness to use watchpoint hardware."), _("\
16357 If zero, gdb will not use hardware for new watchpoints, even if\n\
16358 such is available.  (However, any hardware watchpoints that were\n\
16359 created before setting this to nonzero, will continue to use watchpoint\n\
16360 hardware.)"),
16361                             NULL,
16362                             show_can_use_hw_watchpoints,
16363                             &setlist, &showlist);
16364
16365   can_use_hw_watchpoints = 1;
16366
16367   /* Tracepoint manipulation commands.  */
16368
16369   c = add_com ("trace", class_breakpoint, trace_command, _("\
16370 Set a tracepoint at specified line or function.\n\
16371 \n"
16372 BREAK_ARGS_HELP ("trace") "\n\
16373 Do \"help tracepoints\" for info on other tracepoint commands."));
16374   set_cmd_completer (c, location_completer);
16375
16376   add_com_alias ("tp", "trace", class_alias, 0);
16377   add_com_alias ("tr", "trace", class_alias, 1);
16378   add_com_alias ("tra", "trace", class_alias, 1);
16379   add_com_alias ("trac", "trace", class_alias, 1);
16380
16381   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16382 Set a fast tracepoint at specified line or function.\n\
16383 \n"
16384 BREAK_ARGS_HELP ("ftrace") "\n\
16385 Do \"help tracepoints\" for info on other tracepoint commands."));
16386   set_cmd_completer (c, location_completer);
16387
16388   c = add_com ("strace", class_breakpoint, strace_command, _("\
16389 Set a static tracepoint at specified line, function or marker.\n\
16390 \n\
16391 strace [LOCATION] [if CONDITION]\n\
16392 LOCATION may be a line number, function name, \"*\" and an address,\n\
16393 or -m MARKER_ID.\n\
16394 If a line number is specified, probe the marker at start of code\n\
16395 for that line.  If a function is specified, probe the marker at start\n\
16396 of code for that function.  If an address is specified, probe the marker\n\
16397 at that exact address.  If a marker id is specified, probe the marker\n\
16398 with that name.  With no LOCATION, uses current execution address of\n\
16399 the selected stack frame.\n\
16400 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16401 This collects arbitrary user data passed in the probe point call to the\n\
16402 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16403 by printing the $_sdata variable like any other convenience variable.\n\
16404 \n\
16405 CONDITION is a boolean expression.\n\
16406 \n\
16407 Multiple tracepoints at one place are permitted, and useful if their\n\
16408 conditions are different.\n\
16409 \n\
16410 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16411 Do \"help tracepoints\" for info on other tracepoint commands."));
16412   set_cmd_completer (c, location_completer);
16413
16414   add_info ("tracepoints", tracepoints_info, _("\
16415 Status of specified tracepoints (all tracepoints if no argument).\n\
16416 Convenience variable \"$tpnum\" contains the number of the\n\
16417 last tracepoint set."));
16418
16419   add_info_alias ("tp", "tracepoints", 1);
16420
16421   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16422 Delete specified tracepoints.\n\
16423 Arguments are tracepoint numbers, separated by spaces.\n\
16424 No argument means delete all tracepoints."),
16425            &deletelist);
16426   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16427
16428   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16429 Disable specified tracepoints.\n\
16430 Arguments are tracepoint numbers, separated by spaces.\n\
16431 No argument means disable all tracepoints."),
16432            &disablelist);
16433   deprecate_cmd (c, "disable");
16434
16435   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16436 Enable specified tracepoints.\n\
16437 Arguments are tracepoint numbers, separated by spaces.\n\
16438 No argument means enable all tracepoints."),
16439            &enablelist);
16440   deprecate_cmd (c, "enable");
16441
16442   add_com ("passcount", class_trace, trace_pass_command, _("\
16443 Set the passcount for a tracepoint.\n\
16444 The trace will end when the tracepoint has been passed 'count' times.\n\
16445 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16446 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16447
16448   add_prefix_cmd ("save", class_breakpoint, save_command,
16449                   _("Save breakpoint definitions as a script."),
16450                   &save_cmdlist, "save ",
16451                   0/*allow-unknown*/, &cmdlist);
16452
16453   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16454 Save current breakpoint definitions as a script.\n\
16455 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16456 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16457 session to restore them."),
16458                &save_cmdlist);
16459   set_cmd_completer (c, filename_completer);
16460
16461   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16462 Save current tracepoint definitions as a script.\n\
16463 Use the 'source' command in another debug session to restore them."),
16464                &save_cmdlist);
16465   set_cmd_completer (c, filename_completer);
16466
16467   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16468   deprecate_cmd (c, "save tracepoints");
16469
16470   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16471 Breakpoint specific settings\n\
16472 Configure various breakpoint-specific variables such as\n\
16473 pending breakpoint behavior"),
16474                   &breakpoint_set_cmdlist, "set breakpoint ",
16475                   0/*allow-unknown*/, &setlist);
16476   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16477 Breakpoint specific settings\n\
16478 Configure various breakpoint-specific variables such as\n\
16479 pending breakpoint behavior"),
16480                   &breakpoint_show_cmdlist, "show breakpoint ",
16481                   0/*allow-unknown*/, &showlist);
16482
16483   add_setshow_auto_boolean_cmd ("pending", no_class,
16484                                 &pending_break_support, _("\
16485 Set debugger's behavior regarding pending breakpoints."), _("\
16486 Show debugger's behavior regarding pending breakpoints."), _("\
16487 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16488 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16489 an error.  If auto, an unrecognized breakpoint location results in a\n\
16490 user-query to see if a pending breakpoint should be created."),
16491                                 NULL,
16492                                 show_pending_break_support,
16493                                 &breakpoint_set_cmdlist,
16494                                 &breakpoint_show_cmdlist);
16495
16496   pending_break_support = AUTO_BOOLEAN_AUTO;
16497
16498   add_setshow_boolean_cmd ("auto-hw", no_class,
16499                            &automatic_hardware_breakpoints, _("\
16500 Set automatic usage of hardware breakpoints."), _("\
16501 Show automatic usage of hardware breakpoints."), _("\
16502 If set, the debugger will automatically use hardware breakpoints for\n\
16503 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16504 a warning will be emitted for such breakpoints."),
16505                            NULL,
16506                            show_automatic_hardware_breakpoints,
16507                            &breakpoint_set_cmdlist,
16508                            &breakpoint_show_cmdlist);
16509
16510   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16511                                 &always_inserted_mode, _("\
16512 Set mode for inserting breakpoints."), _("\
16513 Show mode for inserting breakpoints."), _("\
16514 When this mode is off, breakpoints are inserted in inferior when it is\n\
16515 resumed, and removed when execution stops.  When this mode is on,\n\
16516 breakpoints are inserted immediately and removed only when the user\n\
16517 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16518 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16519 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16520 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16521 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16522                                 NULL,
16523                                 &show_always_inserted_mode,
16524                                 &breakpoint_set_cmdlist,
16525                                 &breakpoint_show_cmdlist);
16526
16527   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16528                         condition_evaluation_enums,
16529                         &condition_evaluation_mode_1, _("\
16530 Set mode of breakpoint condition evaluation."), _("\
16531 Show mode of breakpoint condition evaluation."), _("\
16532 When this is set to \"host\", breakpoint conditions will be\n\
16533 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16534 breakpoint conditions will be downloaded to the target (if the target\n\
16535 supports such feature) and conditions will be evaluated on the target's side.\n\
16536 If this is set to \"auto\" (default), this will be automatically set to\n\
16537 \"target\" if it supports condition evaluation, otherwise it will\n\
16538 be set to \"gdb\""),
16539                            &set_condition_evaluation_mode,
16540                            &show_condition_evaluation_mode,
16541                            &breakpoint_set_cmdlist,
16542                            &breakpoint_show_cmdlist);
16543
16544   add_com ("break-range", class_breakpoint, break_range_command, _("\
16545 Set a breakpoint for an address range.\n\
16546 break-range START-LOCATION, END-LOCATION\n\
16547 where START-LOCATION and END-LOCATION can be one of the following:\n\
16548   LINENUM, for that line in the current file,\n\
16549   FILE:LINENUM, for that line in that file,\n\
16550   +OFFSET, for that number of lines after the current line\n\
16551            or the start of the range\n\
16552   FUNCTION, for the first line in that function,\n\
16553   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16554   *ADDRESS, for the instruction at that address.\n\
16555 \n\
16556 The breakpoint will stop execution of the inferior whenever it executes\n\
16557 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16558 range (including START-LOCATION and END-LOCATION)."));
16559
16560   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16561 Set a dynamic printf at specified line or function.\n\
16562 dprintf location,format string,arg1,arg2,...\n\
16563 location may be a line number, function name, or \"*\" and an address.\n\
16564 If a line number is specified, break at start of code for that line.\n\
16565 If a function is specified, break at start of code for that function."));
16566   set_cmd_completer (c, location_completer);
16567
16568   add_setshow_enum_cmd ("dprintf-style", class_support,
16569                         dprintf_style_enums, &dprintf_style, _("\
16570 Set the style of usage for dynamic printf."), _("\
16571 Show the style of usage for dynamic printf."), _("\
16572 This setting chooses how GDB will do a dynamic printf.\n\
16573 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16574 console, as with the \"printf\" command.\n\
16575 If the value is \"call\", the print is done by calling a function in your\n\
16576 program; by default printf(), but you can choose a different function or\n\
16577 output stream by setting dprintf-function and dprintf-channel."),
16578                         update_dprintf_commands, NULL,
16579                         &setlist, &showlist);
16580
16581   dprintf_function = xstrdup ("printf");
16582   add_setshow_string_cmd ("dprintf-function", class_support,
16583                           &dprintf_function, _("\
16584 Set the function to use for dynamic printf"), _("\
16585 Show the function to use for dynamic printf"), NULL,
16586                           update_dprintf_commands, NULL,
16587                           &setlist, &showlist);
16588
16589   dprintf_channel = xstrdup ("");
16590   add_setshow_string_cmd ("dprintf-channel", class_support,
16591                           &dprintf_channel, _("\
16592 Set the channel to use for dynamic printf"), _("\
16593 Show the channel to use for dynamic printf"), NULL,
16594                           update_dprintf_commands, NULL,
16595                           &setlist, &showlist);
16596
16597   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16598                            &disconnected_dprintf, _("\
16599 Set whether dprintf continues after GDB disconnects."), _("\
16600 Show whether dprintf continues after GDB disconnects."), _("\
16601 Use this to let dprintf commands continue to hit and produce output\n\
16602 even if GDB disconnects or detaches from the target."),
16603                            NULL,
16604                            NULL,
16605                            &setlist, &showlist);
16606
16607   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16608 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16609 (target agent only) This is useful for formatted output in user-defined commands."));
16610
16611   automatic_hardware_breakpoints = 1;
16612
16613   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16614   observer_attach_thread_exit (remove_threaded_breakpoints);
16615 }