Upgrade GDB from 7.4.1 to 7.6.1 on the vendor branch
[dragonfly.git] / contrib / gdb-7 / 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_CATCH
90 };
91
92 /* Prototypes for local functions.  */
93
94 static void enable_delete_command (char *, int);
95
96 static void enable_once_command (char *, int);
97
98 static void enable_count_command (char *, int);
99
100 static void disable_command (char *, int);
101
102 static void enable_command (char *, int);
103
104 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
105                                                       void *),
106                                     void *);
107
108 static void ignore_command (char *, int);
109
110 static int breakpoint_re_set_one (void *);
111
112 static void breakpoint_re_set_default (struct breakpoint *);
113
114 static void create_sals_from_address_default (char **,
115                                               struct linespec_result *,
116                                               enum bptype, char *,
117                                               char **);
118
119 static void create_breakpoints_sal_default (struct gdbarch *,
120                                             struct linespec_result *,
121                                             struct linespec_sals *,
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 char *ep_parse_optional_if_clause (char **arg);
234
235 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
236                                        char *arg, int tempflag, int from_tty);
237
238 static void tcatch_command (char *arg, int from_tty);
239
240 static void detach_single_step_breakpoints (void);
241
242 static int single_step_breakpoint_inserted_here_p (struct address_space *,
243                                                    CORE_ADDR pc);
244
245 static void free_bp_location (struct bp_location *loc);
246 static void incref_bp_location (struct bp_location *loc);
247 static void decref_bp_location (struct bp_location **loc);
248
249 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
250
251 static void update_global_location_list (int);
252
253 static void update_global_location_list_nothrow (int);
254
255 static int is_hardware_watchpoint (const struct breakpoint *bpt);
256
257 static void insert_breakpoint_locations (void);
258
259 static int syscall_catchpoint_p (struct breakpoint *b);
260
261 static void tracepoints_info (char *, int);
262
263 static void delete_trace_command (char *, int);
264
265 static void enable_trace_command (char *, int);
266
267 static void disable_trace_command (char *, int);
268
269 static void trace_pass_command (char *, int);
270
271 static void set_tracepoint_count (int num);
272
273 static int is_masked_watchpoint (const struct breakpoint *b);
274
275 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
276
277 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
278    otherwise.  */
279
280 static int strace_marker_p (struct breakpoint *b);
281
282 /* The abstract base class all breakpoint_ops structures inherit
283    from.  */
284 struct breakpoint_ops base_breakpoint_ops;
285
286 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
287    that are implemented on top of software or hardware breakpoints
288    (user breakpoints, internal and momentary breakpoints, etc.).  */
289 static struct breakpoint_ops bkpt_base_breakpoint_ops;
290
291 /* Internal breakpoints class type.  */
292 static struct breakpoint_ops internal_breakpoint_ops;
293
294 /* Momentary breakpoints class type.  */
295 static struct breakpoint_ops momentary_breakpoint_ops;
296
297 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
298 static struct breakpoint_ops longjmp_breakpoint_ops;
299
300 /* The breakpoint_ops structure to be used in regular user created
301    breakpoints.  */
302 struct breakpoint_ops bkpt_breakpoint_ops;
303
304 /* Breakpoints set on probes.  */
305 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
306
307 /* Dynamic printf class type.  */
308 static struct breakpoint_ops dprintf_breakpoint_ops;
309
310 /* The style in which to perform a dynamic printf.  This is a user
311    option because different output options have different tradeoffs;
312    if GDB does the printing, there is better error handling if there
313    is a problem with any of the arguments, but using an inferior
314    function lets you have special-purpose printers and sending of
315    output to the same place as compiled-in print functions.  */
316
317 static const char dprintf_style_gdb[] = "gdb";
318 static const char dprintf_style_call[] = "call";
319 static const char dprintf_style_agent[] = "agent";
320 static const char *const dprintf_style_enums[] = {
321   dprintf_style_gdb,
322   dprintf_style_call,
323   dprintf_style_agent,
324   NULL
325 };
326 static const char *dprintf_style = dprintf_style_gdb;
327
328 /* The function to use for dynamic printf if the preferred style is to
329    call into the inferior.  The value is simply a string that is
330    copied into the command, so it can be anything that GDB can
331    evaluate to a callable address, not necessarily a function name.  */
332
333 static char *dprintf_function = "";
334
335 /* The channel to use for dynamic printf if the preferred style is to
336    call into the inferior; if a nonempty string, it will be passed to
337    the call as the first argument, with the format string as the
338    second.  As with the dprintf function, this can be anything that
339    GDB knows how to evaluate, so in addition to common choices like
340    "stderr", this could be an app-specific expression like
341    "mystreams[curlogger]".  */
342
343 static char *dprintf_channel = "";
344
345 /* True if dprintf commands should continue to operate even if GDB
346    has disconnected.  */
347 static int disconnected_dprintf = 1;
348
349 /* A reference-counted struct command_line.  This lets multiple
350    breakpoints share a single command list.  */
351 struct counted_command_line
352 {
353   /* The reference count.  */
354   int refc;
355
356   /* The command list.  */
357   struct command_line *commands;
358 };
359
360 struct command_line *
361 breakpoint_commands (struct breakpoint *b)
362 {
363   return b->commands ? b->commands->commands : NULL;
364 }
365
366 /* Flag indicating that a command has proceeded the inferior past the
367    current breakpoint.  */
368
369 static int breakpoint_proceeded;
370
371 const char *
372 bpdisp_text (enum bpdisp disp)
373 {
374   /* NOTE: the following values are a part of MI protocol and
375      represent values of 'disp' field returned when inferior stops at
376      a breakpoint.  */
377   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
378
379   return bpdisps[(int) disp];
380 }
381
382 /* Prototypes for exported functions.  */
383 /* If FALSE, gdb will not use hardware support for watchpoints, even
384    if such is available.  */
385 static int can_use_hw_watchpoints;
386
387 static void
388 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
389                              struct cmd_list_element *c,
390                              const char *value)
391 {
392   fprintf_filtered (file,
393                     _("Debugger's willingness to use "
394                       "watchpoint hardware is %s.\n"),
395                     value);
396 }
397
398 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
399    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
400    for unrecognized breakpoint locations.
401    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
402 static enum auto_boolean pending_break_support;
403 static void
404 show_pending_break_support (struct ui_file *file, int from_tty,
405                             struct cmd_list_element *c,
406                             const char *value)
407 {
408   fprintf_filtered (file,
409                     _("Debugger's behavior regarding "
410                       "pending breakpoints is %s.\n"),
411                     value);
412 }
413
414 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
415    set with "break" but falling in read-only memory.
416    If 0, gdb will warn about such breakpoints, but won't automatically
417    use hardware breakpoints.  */
418 static int automatic_hardware_breakpoints;
419 static void
420 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
421                                      struct cmd_list_element *c,
422                                      const char *value)
423 {
424   fprintf_filtered (file,
425                     _("Automatic usage of hardware breakpoints is %s.\n"),
426                     value);
427 }
428
429 /* If on, gdb will keep breakpoints inserted even as inferior is
430    stopped, and immediately insert any new breakpoints.  If off, gdb
431    will insert breakpoints into inferior only when resuming it, and
432    will remove breakpoints upon stop.  If auto, GDB will behave as ON
433    if in non-stop mode, and as OFF if all-stop mode.*/
434
435 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
436
437 static void
438 show_always_inserted_mode (struct ui_file *file, int from_tty,
439                      struct cmd_list_element *c, const char *value)
440 {
441   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
442     fprintf_filtered (file,
443                       _("Always inserted breakpoint "
444                         "mode is %s (currently %s).\n"),
445                       value,
446                       breakpoints_always_inserted_mode () ? "on" : "off");
447   else
448     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
449                       value);
450 }
451
452 int
453 breakpoints_always_inserted_mode (void)
454 {
455   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
456           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
457 }
458
459 static const char condition_evaluation_both[] = "host or target";
460
461 /* Modes for breakpoint condition evaluation.  */
462 static const char condition_evaluation_auto[] = "auto";
463 static const char condition_evaluation_host[] = "host";
464 static const char condition_evaluation_target[] = "target";
465 static const char *const condition_evaluation_enums[] = {
466   condition_evaluation_auto,
467   condition_evaluation_host,
468   condition_evaluation_target,
469   NULL
470 };
471
472 /* Global that holds the current mode for breakpoint condition evaluation.  */
473 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
474
475 /* Global that we use to display information to the user (gets its value from
476    condition_evaluation_mode_1.  */
477 static const char *condition_evaluation_mode = condition_evaluation_auto;
478
479 /* Translate a condition evaluation mode MODE into either "host"
480    or "target".  This is used mostly to translate from "auto" to the
481    real setting that is being used.  It returns the translated
482    evaluation mode.  */
483
484 static const char *
485 translate_condition_evaluation_mode (const char *mode)
486 {
487   if (mode == condition_evaluation_auto)
488     {
489       if (target_supports_evaluation_of_breakpoint_conditions ())
490         return condition_evaluation_target;
491       else
492         return condition_evaluation_host;
493     }
494   else
495     return mode;
496 }
497
498 /* Discovers what condition_evaluation_auto translates to.  */
499
500 static const char *
501 breakpoint_condition_evaluation_mode (void)
502 {
503   return translate_condition_evaluation_mode (condition_evaluation_mode);
504 }
505
506 /* Return true if GDB should evaluate breakpoint conditions or false
507    otherwise.  */
508
509 static int
510 gdb_evaluates_breakpoint_condition_p (void)
511 {
512   const char *mode = breakpoint_condition_evaluation_mode ();
513
514   return (mode == condition_evaluation_host);
515 }
516
517 void _initialize_breakpoint (void);
518
519 /* Are we executing breakpoint commands?  */
520 static int executing_breakpoint_commands;
521
522 /* Are overlay event breakpoints enabled? */
523 static int overlay_events_enabled;
524
525 /* See description in breakpoint.h. */
526 int target_exact_watchpoints = 0;
527
528 /* Walk the following statement or block through all breakpoints.
529    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
530    current breakpoint.  */
531
532 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
533
534 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
535         for (B = breakpoint_chain;      \
536              B ? (TMP=B->next, 1): 0;   \
537              B = TMP)
538
539 /* Similar iterator for the low-level breakpoints.  SAFE variant is
540    not provided so update_global_location_list must not be called
541    while executing the block of ALL_BP_LOCATIONS.  */
542
543 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
544         for (BP_TMP = bp_location;                                      \
545              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
546              BP_TMP++)
547
548 /* Iterates through locations with address ADDRESS for the currently selected
549    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
550    to where the loop should start from.
551    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
552    appropriate location to start with.  */
553
554 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
555         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
556              BP_LOCP_TMP = BP_LOCP_START;                               \
557              BP_LOCP_START                                              \
558              && (BP_LOCP_TMP < bp_location + bp_location_count          \
559              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
560              BP_LOCP_TMP++)
561
562 /* Iterator for tracepoints only.  */
563
564 #define ALL_TRACEPOINTS(B)  \
565   for (B = breakpoint_chain; B; B = B->next)  \
566     if (is_tracepoint (B))
567
568 /* Chains of all breakpoints defined.  */
569
570 struct breakpoint *breakpoint_chain;
571
572 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
573
574 static struct bp_location **bp_location;
575
576 /* Number of elements of BP_LOCATION.  */
577
578 static unsigned bp_location_count;
579
580 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
581    ADDRESS for the current elements of BP_LOCATION which get a valid
582    result from bp_location_has_shadow.  You can use it for roughly
583    limiting the subrange of BP_LOCATION to scan for shadow bytes for
584    an address you need to read.  */
585
586 static CORE_ADDR bp_location_placed_address_before_address_max;
587
588 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
589    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
590    BP_LOCATION which get a valid result from bp_location_has_shadow.
591    You can use it for roughly limiting the subrange of BP_LOCATION to
592    scan for shadow bytes for an address you need to read.  */
593
594 static CORE_ADDR bp_location_shadow_len_after_address_max;
595
596 /* The locations that no longer correspond to any breakpoint, unlinked
597    from bp_location array, but for which a hit may still be reported
598    by a target.  */
599 VEC(bp_location_p) *moribund_locations = NULL;
600
601 /* Number of last breakpoint made.  */
602
603 static int breakpoint_count;
604
605 /* The value of `breakpoint_count' before the last command that
606    created breakpoints.  If the last (break-like) command created more
607    than one breakpoint, then the difference between BREAKPOINT_COUNT
608    and PREV_BREAKPOINT_COUNT is more than one.  */
609 static int prev_breakpoint_count;
610
611 /* Number of last tracepoint made.  */
612
613 static int tracepoint_count;
614
615 static struct cmd_list_element *breakpoint_set_cmdlist;
616 static struct cmd_list_element *breakpoint_show_cmdlist;
617 struct cmd_list_element *save_cmdlist;
618
619 /* Return whether a breakpoint is an active enabled breakpoint.  */
620 static int
621 breakpoint_enabled (struct breakpoint *b)
622 {
623   return (b->enable_state == bp_enabled);
624 }
625
626 /* Set breakpoint count to NUM.  */
627
628 static void
629 set_breakpoint_count (int num)
630 {
631   prev_breakpoint_count = breakpoint_count;
632   breakpoint_count = num;
633   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
634 }
635
636 /* Used by `start_rbreak_breakpoints' below, to record the current
637    breakpoint count before "rbreak" creates any breakpoint.  */
638 static int rbreak_start_breakpoint_count;
639
640 /* Called at the start an "rbreak" command to record the first
641    breakpoint made.  */
642
643 void
644 start_rbreak_breakpoints (void)
645 {
646   rbreak_start_breakpoint_count = breakpoint_count;
647 }
648
649 /* Called at the end of an "rbreak" command to record the last
650    breakpoint made.  */
651
652 void
653 end_rbreak_breakpoints (void)
654 {
655   prev_breakpoint_count = rbreak_start_breakpoint_count;
656 }
657
658 /* Used in run_command to zero the hit count when a new run starts.  */
659
660 void
661 clear_breakpoint_hit_counts (void)
662 {
663   struct breakpoint *b;
664
665   ALL_BREAKPOINTS (b)
666     b->hit_count = 0;
667 }
668
669 /* Allocate a new counted_command_line with reference count of 1.
670    The new structure owns COMMANDS.  */
671
672 static struct counted_command_line *
673 alloc_counted_command_line (struct command_line *commands)
674 {
675   struct counted_command_line *result
676     = xmalloc (sizeof (struct counted_command_line));
677
678   result->refc = 1;
679   result->commands = commands;
680   return result;
681 }
682
683 /* Increment reference count.  This does nothing if CMD is NULL.  */
684
685 static void
686 incref_counted_command_line (struct counted_command_line *cmd)
687 {
688   if (cmd)
689     ++cmd->refc;
690 }
691
692 /* Decrement reference count.  If the reference count reaches 0,
693    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
694    nothing if *CMDP is NULL.  */
695
696 static void
697 decref_counted_command_line (struct counted_command_line **cmdp)
698 {
699   if (*cmdp)
700     {
701       if (--(*cmdp)->refc == 0)
702         {
703           free_command_lines (&(*cmdp)->commands);
704           xfree (*cmdp);
705         }
706       *cmdp = NULL;
707     }
708 }
709
710 /* A cleanup function that calls decref_counted_command_line.  */
711
712 static void
713 do_cleanup_counted_command_line (void *arg)
714 {
715   decref_counted_command_line (arg);
716 }
717
718 /* Create a cleanup that calls decref_counted_command_line on the
719    argument.  */
720
721 static struct cleanup *
722 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
723 {
724   return make_cleanup (do_cleanup_counted_command_line, cmdp);
725 }
726
727 \f
728 /* Return the breakpoint with the specified number, or NULL
729    if the number does not refer to an existing breakpoint.  */
730
731 struct breakpoint *
732 get_breakpoint (int num)
733 {
734   struct breakpoint *b;
735
736   ALL_BREAKPOINTS (b)
737     if (b->number == num)
738       return b;
739   
740   return NULL;
741 }
742
743 \f
744
745 /* Mark locations as "conditions have changed" in case the target supports
746    evaluating conditions on its side.  */
747
748 static void
749 mark_breakpoint_modified (struct breakpoint *b)
750 {
751   struct bp_location *loc;
752
753   /* This is only meaningful if the target is
754      evaluating conditions and if the user has
755      opted for condition evaluation on the target's
756      side.  */
757   if (gdb_evaluates_breakpoint_condition_p ()
758       || !target_supports_evaluation_of_breakpoint_conditions ())
759     return;
760
761   if (!is_breakpoint (b))
762     return;
763
764   for (loc = b->loc; loc; loc = loc->next)
765     loc->condition_changed = condition_modified;
766 }
767
768 /* Mark location as "conditions have changed" in case the target supports
769    evaluating conditions on its side.  */
770
771 static void
772 mark_breakpoint_location_modified (struct bp_location *loc)
773 {
774   /* This is only meaningful if the target is
775      evaluating conditions and if the user has
776      opted for condition evaluation on the target's
777      side.  */
778   if (gdb_evaluates_breakpoint_condition_p ()
779       || !target_supports_evaluation_of_breakpoint_conditions ())
780
781     return;
782
783   if (!is_breakpoint (loc->owner))
784     return;
785
786   loc->condition_changed = condition_modified;
787 }
788
789 /* Sets the condition-evaluation mode using the static global
790    condition_evaluation_mode.  */
791
792 static void
793 set_condition_evaluation_mode (char *args, int from_tty,
794                                struct cmd_list_element *c)
795 {
796   const char *old_mode, *new_mode;
797
798   if ((condition_evaluation_mode_1 == condition_evaluation_target)
799       && !target_supports_evaluation_of_breakpoint_conditions ())
800     {
801       condition_evaluation_mode_1 = condition_evaluation_mode;
802       warning (_("Target does not support breakpoint condition evaluation.\n"
803                  "Using host evaluation mode instead."));
804       return;
805     }
806
807   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
808   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
809
810   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
811      settings was "auto".  */
812   condition_evaluation_mode = condition_evaluation_mode_1;
813
814   /* Only update the mode if the user picked a different one.  */
815   if (new_mode != old_mode)
816     {
817       struct bp_location *loc, **loc_tmp;
818       /* If the user switched to a different evaluation mode, we
819          need to synch the changes with the target as follows:
820
821          "host" -> "target": Send all (valid) conditions to the target.
822          "target" -> "host": Remove all the conditions from the target.
823       */
824
825       if (new_mode == condition_evaluation_target)
826         {
827           /* Mark everything modified and synch conditions with the
828              target.  */
829           ALL_BP_LOCATIONS (loc, loc_tmp)
830             mark_breakpoint_location_modified (loc);
831         }
832       else
833         {
834           /* Manually mark non-duplicate locations to synch conditions
835              with the target.  We do this to remove all the conditions the
836              target knows about.  */
837           ALL_BP_LOCATIONS (loc, loc_tmp)
838             if (is_breakpoint (loc->owner) && loc->inserted)
839               loc->needs_update = 1;
840         }
841
842       /* Do the update.  */
843       update_global_location_list (1);
844     }
845
846   return;
847 }
848
849 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
850    what "auto" is translating to.  */
851
852 static void
853 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
854                                 struct cmd_list_element *c, const char *value)
855 {
856   if (condition_evaluation_mode == condition_evaluation_auto)
857     fprintf_filtered (file,
858                       _("Breakpoint condition evaluation "
859                         "mode is %s (currently %s).\n"),
860                       value,
861                       breakpoint_condition_evaluation_mode ());
862   else
863     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
864                       value);
865 }
866
867 /* A comparison function for bp_location AP and BP that is used by
868    bsearch.  This comparison function only cares about addresses, unlike
869    the more general bp_location_compare function.  */
870
871 static int
872 bp_location_compare_addrs (const void *ap, const void *bp)
873 {
874   struct bp_location *a = *(void **) ap;
875   struct bp_location *b = *(void **) bp;
876
877   if (a->address == b->address)
878     return 0;
879   else
880     return ((a->address > b->address) - (a->address < b->address));
881 }
882
883 /* Helper function to skip all bp_locations with addresses
884    less than ADDRESS.  It returns the first bp_location that
885    is greater than or equal to ADDRESS.  If none is found, just
886    return NULL.  */
887
888 static struct bp_location **
889 get_first_locp_gte_addr (CORE_ADDR address)
890 {
891   struct bp_location dummy_loc;
892   struct bp_location *dummy_locp = &dummy_loc;
893   struct bp_location **locp_found = NULL;
894
895   /* Initialize the dummy location's address field.  */
896   memset (&dummy_loc, 0, sizeof (struct bp_location));
897   dummy_loc.address = address;
898
899   /* Find a close match to the first location at ADDRESS.  */
900   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
901                         sizeof (struct bp_location **),
902                         bp_location_compare_addrs);
903
904   /* Nothing was found, nothing left to do.  */
905   if (locp_found == NULL)
906     return NULL;
907
908   /* We may have found a location that is at ADDRESS but is not the first in the
909      location's list.  Go backwards (if possible) and locate the first one.  */
910   while ((locp_found - 1) >= bp_location
911          && (*(locp_found - 1))->address == address)
912     locp_found--;
913
914   return locp_found;
915 }
916
917 void
918 set_breakpoint_condition (struct breakpoint *b, char *exp,
919                           int from_tty)
920 {
921   xfree (b->cond_string);
922   b->cond_string = NULL;
923
924   if (is_watchpoint (b))
925     {
926       struct watchpoint *w = (struct watchpoint *) b;
927
928       xfree (w->cond_exp);
929       w->cond_exp = NULL;
930     }
931   else
932     {
933       struct bp_location *loc;
934
935       for (loc = b->loc; loc; loc = loc->next)
936         {
937           xfree (loc->cond);
938           loc->cond = NULL;
939
940           /* No need to free the condition agent expression
941              bytecode (if we have one).  We will handle this
942              when we go through update_global_location_list.  */
943         }
944     }
945
946   if (*exp == 0)
947     {
948       if (from_tty)
949         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
950     }
951   else
952     {
953       const char *arg = exp;
954
955       /* I don't know if it matters whether this is the string the user
956          typed in or the decompiled expression.  */
957       b->cond_string = xstrdup (arg);
958       b->condition_not_parsed = 0;
959
960       if (is_watchpoint (b))
961         {
962           struct watchpoint *w = (struct watchpoint *) b;
963
964           innermost_block = NULL;
965           arg = exp;
966           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
967           if (*arg)
968             error (_("Junk at end of expression"));
969           w->cond_exp_valid_block = innermost_block;
970         }
971       else
972         {
973           struct bp_location *loc;
974
975           for (loc = b->loc; loc; loc = loc->next)
976             {
977               arg = exp;
978               loc->cond =
979                 parse_exp_1 (&arg, loc->address,
980                              block_for_pc (loc->address), 0);
981               if (*arg)
982                 error (_("Junk at end of expression"));
983             }
984         }
985     }
986   mark_breakpoint_modified (b);
987
988   observer_notify_breakpoint_modified (b);
989 }
990
991 /* Completion for the "condition" command.  */
992
993 static VEC (char_ptr) *
994 condition_completer (struct cmd_list_element *cmd, char *text, char *word)
995 {
996   char *space;
997
998   text = skip_spaces (text);
999   space = skip_to_space (text);
1000   if (*space == '\0')
1001     {
1002       int len;
1003       struct breakpoint *b;
1004       VEC (char_ptr) *result = NULL;
1005
1006       if (text[0] == '$')
1007         {
1008           /* We don't support completion of history indices.  */
1009           if (isdigit (text[1]))
1010             return NULL;
1011           return complete_internalvar (&text[1]);
1012         }
1013
1014       /* We're completing the breakpoint number.  */
1015       len = strlen (text);
1016
1017       ALL_BREAKPOINTS (b)
1018         {
1019           char number[50];
1020
1021           xsnprintf (number, sizeof (number), "%d", b->number);
1022
1023           if (strncmp (number, text, len) == 0)
1024             VEC_safe_push (char_ptr, result, xstrdup (number));
1025         }
1026
1027       return result;
1028     }
1029
1030   /* We're completing the expression part.  */
1031   text = skip_spaces (space);
1032   return expression_completer (cmd, text, word);
1033 }
1034
1035 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1036
1037 static void
1038 condition_command (char *arg, int from_tty)
1039 {
1040   struct breakpoint *b;
1041   char *p;
1042   int bnum;
1043
1044   if (arg == 0)
1045     error_no_arg (_("breakpoint number"));
1046
1047   p = arg;
1048   bnum = get_number (&p);
1049   if (bnum == 0)
1050     error (_("Bad breakpoint argument: '%s'"), arg);
1051
1052   ALL_BREAKPOINTS (b)
1053     if (b->number == bnum)
1054       {
1055         /* Check if this breakpoint has a Python object assigned to
1056            it, and if it has a definition of the "stop"
1057            method.  This method and conditions entered into GDB from
1058            the CLI are mutually exclusive.  */
1059         if (b->py_bp_object
1060             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
1061           error (_("Cannot set a condition where a Python 'stop' "
1062                    "method has been defined in the breakpoint."));
1063         set_breakpoint_condition (b, p, from_tty);
1064
1065         if (is_breakpoint (b))
1066           update_global_location_list (1);
1067
1068         return;
1069       }
1070
1071   error (_("No breakpoint number %d."), bnum);
1072 }
1073
1074 /* Check that COMMAND do not contain commands that are suitable
1075    only for tracepoints and not suitable for ordinary breakpoints.
1076    Throw if any such commands is found.  */
1077
1078 static void
1079 check_no_tracepoint_commands (struct command_line *commands)
1080 {
1081   struct command_line *c;
1082
1083   for (c = commands; c; c = c->next)
1084     {
1085       int i;
1086
1087       if (c->control_type == while_stepping_control)
1088         error (_("The 'while-stepping' command can "
1089                  "only be used for tracepoints"));
1090
1091       for (i = 0; i < c->body_count; ++i)
1092         check_no_tracepoint_commands ((c->body_list)[i]);
1093
1094       /* Not that command parsing removes leading whitespace and comment
1095          lines and also empty lines.  So, we only need to check for
1096          command directly.  */
1097       if (strstr (c->line, "collect ") == c->line)
1098         error (_("The 'collect' command can only be used for tracepoints"));
1099
1100       if (strstr (c->line, "teval ") == c->line)
1101         error (_("The 'teval' command can only be used for tracepoints"));
1102     }
1103 }
1104
1105 /* Encapsulate tests for different types of tracepoints.  */
1106
1107 static int
1108 is_tracepoint_type (enum bptype type)
1109 {
1110   return (type == bp_tracepoint
1111           || type == bp_fast_tracepoint
1112           || type == bp_static_tracepoint);
1113 }
1114
1115 int
1116 is_tracepoint (const struct breakpoint *b)
1117 {
1118   return is_tracepoint_type (b->type);
1119 }
1120
1121 /* A helper function that validates that COMMANDS are valid for a
1122    breakpoint.  This function will throw an exception if a problem is
1123    found.  */
1124
1125 static void
1126 validate_commands_for_breakpoint (struct breakpoint *b,
1127                                   struct command_line *commands)
1128 {
1129   if (is_tracepoint (b))
1130     {
1131       struct tracepoint *t = (struct tracepoint *) b;
1132       struct command_line *c;
1133       struct command_line *while_stepping = 0;
1134
1135       /* Reset the while-stepping step count.  The previous commands
1136          might have included a while-stepping action, while the new
1137          ones might not.  */
1138       t->step_count = 0;
1139
1140       /* We need to verify that each top-level element of commands is
1141          valid for tracepoints, that there's at most one
1142          while-stepping element, and that the while-stepping's body
1143          has valid tracing commands excluding nested while-stepping.
1144          We also need to validate the tracepoint action line in the
1145          context of the tracepoint --- validate_actionline actually
1146          has side effects, like setting the tracepoint's
1147          while-stepping STEP_COUNT, in addition to checking if the
1148          collect/teval actions parse and make sense in the
1149          tracepoint's context.  */
1150       for (c = commands; c; c = c->next)
1151         {
1152           if (c->control_type == while_stepping_control)
1153             {
1154               if (b->type == bp_fast_tracepoint)
1155                 error (_("The 'while-stepping' command "
1156                          "cannot be used for fast tracepoint"));
1157               else if (b->type == bp_static_tracepoint)
1158                 error (_("The 'while-stepping' command "
1159                          "cannot be used for static tracepoint"));
1160
1161               if (while_stepping)
1162                 error (_("The 'while-stepping' command "
1163                          "can be used only once"));
1164               else
1165                 while_stepping = c;
1166             }
1167
1168           validate_actionline (&c->line, b);
1169         }
1170       if (while_stepping)
1171         {
1172           struct command_line *c2;
1173
1174           gdb_assert (while_stepping->body_count == 1);
1175           c2 = while_stepping->body_list[0];
1176           for (; c2; c2 = c2->next)
1177             {
1178               if (c2->control_type == while_stepping_control)
1179                 error (_("The 'while-stepping' command cannot be nested"));
1180             }
1181         }
1182     }
1183   else
1184     {
1185       check_no_tracepoint_commands (commands);
1186     }
1187 }
1188
1189 /* Return a vector of all the static tracepoints set at ADDR.  The
1190    caller is responsible for releasing the vector.  */
1191
1192 VEC(breakpoint_p) *
1193 static_tracepoints_here (CORE_ADDR addr)
1194 {
1195   struct breakpoint *b;
1196   VEC(breakpoint_p) *found = 0;
1197   struct bp_location *loc;
1198
1199   ALL_BREAKPOINTS (b)
1200     if (b->type == bp_static_tracepoint)
1201       {
1202         for (loc = b->loc; loc; loc = loc->next)
1203           if (loc->address == addr)
1204             VEC_safe_push(breakpoint_p, found, b);
1205       }
1206
1207   return found;
1208 }
1209
1210 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1211    validate that only allowed commands are included.  */
1212
1213 void
1214 breakpoint_set_commands (struct breakpoint *b, 
1215                          struct command_line *commands)
1216 {
1217   validate_commands_for_breakpoint (b, commands);
1218
1219   decref_counted_command_line (&b->commands);
1220   b->commands = alloc_counted_command_line (commands);
1221   observer_notify_breakpoint_modified (b);
1222 }
1223
1224 /* Set the internal `silent' flag on the breakpoint.  Note that this
1225    is not the same as the "silent" that may appear in the breakpoint's
1226    commands.  */
1227
1228 void
1229 breakpoint_set_silent (struct breakpoint *b, int silent)
1230 {
1231   int old_silent = b->silent;
1232
1233   b->silent = silent;
1234   if (old_silent != silent)
1235     observer_notify_breakpoint_modified (b);
1236 }
1237
1238 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1239    breakpoint work for any thread.  */
1240
1241 void
1242 breakpoint_set_thread (struct breakpoint *b, int thread)
1243 {
1244   int old_thread = b->thread;
1245
1246   b->thread = thread;
1247   if (old_thread != thread)
1248     observer_notify_breakpoint_modified (b);
1249 }
1250
1251 /* Set the task for this breakpoint.  If TASK is 0, make the
1252    breakpoint work for any task.  */
1253
1254 void
1255 breakpoint_set_task (struct breakpoint *b, int task)
1256 {
1257   int old_task = b->task;
1258
1259   b->task = task;
1260   if (old_task != task)
1261     observer_notify_breakpoint_modified (b);
1262 }
1263
1264 void
1265 check_tracepoint_command (char *line, void *closure)
1266 {
1267   struct breakpoint *b = closure;
1268
1269   validate_actionline (&line, b);
1270 }
1271
1272 /* A structure used to pass information through
1273    map_breakpoint_numbers.  */
1274
1275 struct commands_info
1276 {
1277   /* True if the command was typed at a tty.  */
1278   int from_tty;
1279
1280   /* The breakpoint range spec.  */
1281   char *arg;
1282
1283   /* Non-NULL if the body of the commands are being read from this
1284      already-parsed command.  */
1285   struct command_line *control;
1286
1287   /* The command lines read from the user, or NULL if they have not
1288      yet been read.  */
1289   struct counted_command_line *cmd;
1290 };
1291
1292 /* A callback for map_breakpoint_numbers that sets the commands for
1293    commands_command.  */
1294
1295 static void
1296 do_map_commands_command (struct breakpoint *b, void *data)
1297 {
1298   struct commands_info *info = data;
1299
1300   if (info->cmd == NULL)
1301     {
1302       struct command_line *l;
1303
1304       if (info->control != NULL)
1305         l = copy_command_lines (info->control->body_list[0]);
1306       else
1307         {
1308           struct cleanup *old_chain;
1309           char *str;
1310
1311           str = xstrprintf (_("Type commands for breakpoint(s) "
1312                               "%s, one per line."),
1313                             info->arg);
1314
1315           old_chain = make_cleanup (xfree, str);
1316
1317           l = read_command_lines (str,
1318                                   info->from_tty, 1,
1319                                   (is_tracepoint (b)
1320                                    ? check_tracepoint_command : 0),
1321                                   b);
1322
1323           do_cleanups (old_chain);
1324         }
1325
1326       info->cmd = alloc_counted_command_line (l);
1327     }
1328
1329   /* If a breakpoint was on the list more than once, we don't need to
1330      do anything.  */
1331   if (b->commands != info->cmd)
1332     {
1333       validate_commands_for_breakpoint (b, info->cmd->commands);
1334       incref_counted_command_line (info->cmd);
1335       decref_counted_command_line (&b->commands);
1336       b->commands = info->cmd;
1337       observer_notify_breakpoint_modified (b);
1338     }
1339 }
1340
1341 static void
1342 commands_command_1 (char *arg, int from_tty, 
1343                     struct command_line *control)
1344 {
1345   struct cleanup *cleanups;
1346   struct commands_info info;
1347
1348   info.from_tty = from_tty;
1349   info.control = control;
1350   info.cmd = NULL;
1351   /* If we read command lines from the user, then `info' will hold an
1352      extra reference to the commands that we must clean up.  */
1353   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1354
1355   if (arg == NULL || !*arg)
1356     {
1357       if (breakpoint_count - prev_breakpoint_count > 1)
1358         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1359                           breakpoint_count);
1360       else if (breakpoint_count > 0)
1361         arg = xstrprintf ("%d", breakpoint_count);
1362       else
1363         {
1364           /* So that we don't try to free the incoming non-NULL
1365              argument in the cleanup below.  Mapping breakpoint
1366              numbers will fail in this case.  */
1367           arg = NULL;
1368         }
1369     }
1370   else
1371     /* The command loop has some static state, so we need to preserve
1372        our argument.  */
1373     arg = xstrdup (arg);
1374
1375   if (arg != NULL)
1376     make_cleanup (xfree, arg);
1377
1378   info.arg = arg;
1379
1380   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1381
1382   if (info.cmd == NULL)
1383     error (_("No breakpoints specified."));
1384
1385   do_cleanups (cleanups);
1386 }
1387
1388 static void
1389 commands_command (char *arg, int from_tty)
1390 {
1391   commands_command_1 (arg, from_tty, NULL);
1392 }
1393
1394 /* Like commands_command, but instead of reading the commands from
1395    input stream, takes them from an already parsed command structure.
1396
1397    This is used by cli-script.c to DTRT with breakpoint commands
1398    that are part of if and while bodies.  */
1399 enum command_control_type
1400 commands_from_control_command (char *arg, struct command_line *cmd)
1401 {
1402   commands_command_1 (arg, 0, cmd);
1403   return simple_control;
1404 }
1405
1406 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1407
1408 static int
1409 bp_location_has_shadow (struct bp_location *bl)
1410 {
1411   if (bl->loc_type != bp_loc_software_breakpoint)
1412     return 0;
1413   if (!bl->inserted)
1414     return 0;
1415   if (bl->target_info.shadow_len == 0)
1416     /* BL isn't valid, or doesn't shadow memory.  */
1417     return 0;
1418   return 1;
1419 }
1420
1421 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1422    by replacing any memory breakpoints with their shadowed contents.
1423
1424    If READBUF is not NULL, this buffer must not overlap with any of
1425    the breakpoint location's shadow_contents buffers.  Otherwise,
1426    a failed assertion internal error will be raised.
1427
1428    The range of shadowed area by each bp_location is:
1429      bl->address - bp_location_placed_address_before_address_max
1430      up to bl->address + bp_location_shadow_len_after_address_max
1431    The range we were requested to resolve shadows for is:
1432      memaddr ... memaddr + len
1433    Thus the safe cutoff boundaries for performance optimization are
1434      memaddr + len <= (bl->address
1435                        - bp_location_placed_address_before_address_max)
1436    and:
1437      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1438
1439 void
1440 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1441                         const gdb_byte *writebuf_org,
1442                         ULONGEST memaddr, LONGEST len)
1443 {
1444   /* Left boundary, right boundary and median element of our binary
1445      search.  */
1446   unsigned bc_l, bc_r, bc;
1447
1448   /* Find BC_L which is a leftmost element which may affect BUF
1449      content.  It is safe to report lower value but a failure to
1450      report higher one.  */
1451
1452   bc_l = 0;
1453   bc_r = bp_location_count;
1454   while (bc_l + 1 < bc_r)
1455     {
1456       struct bp_location *bl;
1457
1458       bc = (bc_l + bc_r) / 2;
1459       bl = bp_location[bc];
1460
1461       /* Check first BL->ADDRESS will not overflow due to the added
1462          constant.  Then advance the left boundary only if we are sure
1463          the BC element can in no way affect the BUF content (MEMADDR
1464          to MEMADDR + LEN range).
1465
1466          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1467          offset so that we cannot miss a breakpoint with its shadow
1468          range tail still reaching MEMADDR.  */
1469
1470       if ((bl->address + bp_location_shadow_len_after_address_max
1471            >= bl->address)
1472           && (bl->address + bp_location_shadow_len_after_address_max
1473               <= memaddr))
1474         bc_l = bc;
1475       else
1476         bc_r = bc;
1477     }
1478
1479   /* Due to the binary search above, we need to make sure we pick the
1480      first location that's at BC_L's address.  E.g., if there are
1481      multiple locations at the same address, BC_L may end up pointing
1482      at a duplicate location, and miss the "master"/"inserted"
1483      location.  Say, given locations L1, L2 and L3 at addresses A and
1484      B:
1485
1486       L1@A, L2@A, L3@B, ...
1487
1488      BC_L could end up pointing at location L2, while the "master"
1489      location could be L1.  Since the `loc->inserted' flag is only set
1490      on "master" locations, we'd forget to restore the shadow of L1
1491      and L2.  */
1492   while (bc_l > 0
1493          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1494     bc_l--;
1495
1496   /* Now do full processing of the found relevant range of elements.  */
1497
1498   for (bc = bc_l; bc < bp_location_count; bc++)
1499   {
1500     struct bp_location *bl = bp_location[bc];
1501     CORE_ADDR bp_addr = 0;
1502     int bp_size = 0;
1503     int bptoffset = 0;
1504
1505     /* bp_location array has BL->OWNER always non-NULL.  */
1506     if (bl->owner->type == bp_none)
1507       warning (_("reading through apparently deleted breakpoint #%d?"),
1508                bl->owner->number);
1509
1510     /* Performance optimization: any further element can no longer affect BUF
1511        content.  */
1512
1513     if (bl->address >= bp_location_placed_address_before_address_max
1514         && memaddr + len <= (bl->address
1515                              - bp_location_placed_address_before_address_max))
1516       break;
1517
1518     if (!bp_location_has_shadow (bl))
1519       continue;
1520     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1521                                    current_program_space->aspace, 0))
1522       continue;
1523
1524     /* Addresses and length of the part of the breakpoint that
1525        we need to copy.  */
1526     bp_addr = bl->target_info.placed_address;
1527     bp_size = bl->target_info.shadow_len;
1528
1529     if (bp_addr + bp_size <= memaddr)
1530       /* The breakpoint is entirely before the chunk of memory we
1531          are reading.  */
1532       continue;
1533
1534     if (bp_addr >= memaddr + len)
1535       /* The breakpoint is entirely after the chunk of memory we are
1536          reading.  */
1537       continue;
1538
1539     /* Offset within shadow_contents.  */
1540     if (bp_addr < memaddr)
1541       {
1542         /* Only copy the second part of the breakpoint.  */
1543         bp_size -= memaddr - bp_addr;
1544         bptoffset = memaddr - bp_addr;
1545         bp_addr = memaddr;
1546       }
1547
1548     if (bp_addr + bp_size > memaddr + len)
1549       {
1550         /* Only copy the first part of the breakpoint.  */
1551         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1552       }
1553
1554     if (readbuf != NULL)
1555       {
1556         /* Verify that the readbuf buffer does not overlap with
1557            the shadow_contents buffer.  */
1558         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1559                     || readbuf >= (bl->target_info.shadow_contents
1560                                    + bl->target_info.shadow_len));
1561
1562         /* Update the read buffer with this inserted breakpoint's
1563            shadow.  */
1564         memcpy (readbuf + bp_addr - memaddr,
1565                 bl->target_info.shadow_contents + bptoffset, bp_size);
1566       }
1567     else
1568       {
1569         struct gdbarch *gdbarch = bl->gdbarch;
1570         const unsigned char *bp;
1571         CORE_ADDR placed_address = bl->target_info.placed_address;
1572         int placed_size = bl->target_info.placed_size;
1573
1574         /* Update the shadow with what we want to write to memory.  */
1575         memcpy (bl->target_info.shadow_contents + bptoffset,
1576                 writebuf_org + bp_addr - memaddr, bp_size);
1577
1578         /* Determine appropriate breakpoint contents and size for this
1579            address.  */
1580         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1581
1582         /* Update the final write buffer with this inserted
1583            breakpoint's INSN.  */
1584         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1585       }
1586   }
1587 }
1588 \f
1589
1590 /* Return true if BPT is either a software breakpoint or a hardware
1591    breakpoint.  */
1592
1593 int
1594 is_breakpoint (const struct breakpoint *bpt)
1595 {
1596   return (bpt->type == bp_breakpoint
1597           || bpt->type == bp_hardware_breakpoint
1598           || bpt->type == bp_dprintf);
1599 }
1600
1601 /* Return true if BPT is of any hardware watchpoint kind.  */
1602
1603 static int
1604 is_hardware_watchpoint (const struct breakpoint *bpt)
1605 {
1606   return (bpt->type == bp_hardware_watchpoint
1607           || bpt->type == bp_read_watchpoint
1608           || bpt->type == bp_access_watchpoint);
1609 }
1610
1611 /* Return true if BPT is of any watchpoint kind, hardware or
1612    software.  */
1613
1614 int
1615 is_watchpoint (const struct breakpoint *bpt)
1616 {
1617   return (is_hardware_watchpoint (bpt)
1618           || bpt->type == bp_watchpoint);
1619 }
1620
1621 /* Returns true if the current thread and its running state are safe
1622    to evaluate or update watchpoint B.  Watchpoints on local
1623    expressions need to be evaluated in the context of the thread that
1624    was current when the watchpoint was created, and, that thread needs
1625    to be stopped to be able to select the correct frame context.
1626    Watchpoints on global expressions can be evaluated on any thread,
1627    and in any state.  It is presently left to the target allowing
1628    memory accesses when threads are running.  */
1629
1630 static int
1631 watchpoint_in_thread_scope (struct watchpoint *b)
1632 {
1633   return (b->base.pspace == current_program_space
1634           && (ptid_equal (b->watchpoint_thread, null_ptid)
1635               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1636                   && !is_executing (inferior_ptid))));
1637 }
1638
1639 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1640    associated bp_watchpoint_scope breakpoint.  */
1641
1642 static void
1643 watchpoint_del_at_next_stop (struct watchpoint *w)
1644 {
1645   struct breakpoint *b = &w->base;
1646
1647   if (b->related_breakpoint != b)
1648     {
1649       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1650       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1651       b->related_breakpoint->disposition = disp_del_at_next_stop;
1652       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1653       b->related_breakpoint = b;
1654     }
1655   b->disposition = disp_del_at_next_stop;
1656 }
1657
1658 /* Assuming that B is a watchpoint:
1659    - Reparse watchpoint expression, if REPARSE is non-zero
1660    - Evaluate expression and store the result in B->val
1661    - Evaluate the condition if there is one, and store the result
1662      in b->loc->cond.
1663    - Update the list of values that must be watched in B->loc.
1664
1665    If the watchpoint disposition is disp_del_at_next_stop, then do
1666    nothing.  If this is local watchpoint that is out of scope, delete
1667    it.
1668
1669    Even with `set breakpoint always-inserted on' the watchpoints are
1670    removed + inserted on each stop here.  Normal breakpoints must
1671    never be removed because they might be missed by a running thread
1672    when debugging in non-stop mode.  On the other hand, hardware
1673    watchpoints (is_hardware_watchpoint; processed here) are specific
1674    to each LWP since they are stored in each LWP's hardware debug
1675    registers.  Therefore, such LWP must be stopped first in order to
1676    be able to modify its hardware watchpoints.
1677
1678    Hardware watchpoints must be reset exactly once after being
1679    presented to the user.  It cannot be done sooner, because it would
1680    reset the data used to present the watchpoint hit to the user.  And
1681    it must not be done later because it could display the same single
1682    watchpoint hit during multiple GDB stops.  Note that the latter is
1683    relevant only to the hardware watchpoint types bp_read_watchpoint
1684    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1685    not user-visible - its hit is suppressed if the memory content has
1686    not changed.
1687
1688    The following constraints influence the location where we can reset
1689    hardware watchpoints:
1690
1691    * target_stopped_by_watchpoint and target_stopped_data_address are
1692      called several times when GDB stops.
1693
1694    [linux] 
1695    * Multiple hardware watchpoints can be hit at the same time,
1696      causing GDB to stop.  GDB only presents one hardware watchpoint
1697      hit at a time as the reason for stopping, and all the other hits
1698      are presented later, one after the other, each time the user
1699      requests the execution to be resumed.  Execution is not resumed
1700      for the threads still having pending hit event stored in
1701      LWP_INFO->STATUS.  While the watchpoint is already removed from
1702      the inferior on the first stop the thread hit event is kept being
1703      reported from its cached value by linux_nat_stopped_data_address
1704      until the real thread resume happens after the watchpoint gets
1705      presented and thus its LWP_INFO->STATUS gets reset.
1706
1707    Therefore the hardware watchpoint hit can get safely reset on the
1708    watchpoint removal from inferior.  */
1709
1710 static void
1711 update_watchpoint (struct watchpoint *b, int reparse)
1712 {
1713   int within_current_scope;
1714   struct frame_id saved_frame_id;
1715   int frame_saved;
1716
1717   /* If this is a local watchpoint, we only want to check if the
1718      watchpoint frame is in scope if the current thread is the thread
1719      that was used to create the watchpoint.  */
1720   if (!watchpoint_in_thread_scope (b))
1721     return;
1722
1723   if (b->base.disposition == disp_del_at_next_stop)
1724     return;
1725  
1726   frame_saved = 0;
1727
1728   /* Determine if the watchpoint is within scope.  */
1729   if (b->exp_valid_block == NULL)
1730     within_current_scope = 1;
1731   else
1732     {
1733       struct frame_info *fi = get_current_frame ();
1734       struct gdbarch *frame_arch = get_frame_arch (fi);
1735       CORE_ADDR frame_pc = get_frame_pc (fi);
1736
1737       /* If we're in a function epilogue, unwinding may not work
1738          properly, so do not attempt to recreate locations at this
1739          point.  See similar comments in watchpoint_check.  */
1740       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1741         return;
1742
1743       /* Save the current frame's ID so we can restore it after
1744          evaluating the watchpoint expression on its own frame.  */
1745       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1746          took a frame parameter, so that we didn't have to change the
1747          selected frame.  */
1748       frame_saved = 1;
1749       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1750
1751       fi = frame_find_by_id (b->watchpoint_frame);
1752       within_current_scope = (fi != NULL);
1753       if (within_current_scope)
1754         select_frame (fi);
1755     }
1756
1757   /* We don't free locations.  They are stored in the bp_location array
1758      and update_global_location_list will eventually delete them and
1759      remove breakpoints if needed.  */
1760   b->base.loc = NULL;
1761
1762   if (within_current_scope && reparse)
1763     {
1764       const char *s;
1765
1766       if (b->exp)
1767         {
1768           xfree (b->exp);
1769           b->exp = NULL;
1770         }
1771       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1772       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1773       /* If the meaning of expression itself changed, the old value is
1774          no longer relevant.  We don't want to report a watchpoint hit
1775          to the user when the old value and the new value may actually
1776          be completely different objects.  */
1777       value_free (b->val);
1778       b->val = NULL;
1779       b->val_valid = 0;
1780
1781       /* Note that unlike with breakpoints, the watchpoint's condition
1782          expression is stored in the breakpoint object, not in the
1783          locations (re)created below.  */
1784       if (b->base.cond_string != NULL)
1785         {
1786           if (b->cond_exp != NULL)
1787             {
1788               xfree (b->cond_exp);
1789               b->cond_exp = NULL;
1790             }
1791
1792           s = b->base.cond_string;
1793           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1794         }
1795     }
1796
1797   /* If we failed to parse the expression, for example because
1798      it refers to a global variable in a not-yet-loaded shared library,
1799      don't try to insert watchpoint.  We don't automatically delete
1800      such watchpoint, though, since failure to parse expression
1801      is different from out-of-scope watchpoint.  */
1802   if ( !target_has_execution)
1803     {
1804       /* Without execution, memory can't change.  No use to try and
1805          set watchpoint locations.  The watchpoint will be reset when
1806          the target gains execution, through breakpoint_re_set.  */
1807     }
1808   else if (within_current_scope && b->exp)
1809     {
1810       int pc = 0;
1811       struct value *val_chain, *v, *result, *next;
1812       struct program_space *frame_pspace;
1813
1814       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1815
1816       /* Avoid setting b->val if it's already set.  The meaning of
1817          b->val is 'the last value' user saw, and we should update
1818          it only if we reported that last value to user.  As it
1819          happens, the code that reports it updates b->val directly.
1820          We don't keep track of the memory value for masked
1821          watchpoints.  */
1822       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1823         {
1824           b->val = v;
1825           b->val_valid = 1;
1826         }
1827
1828       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1829
1830       /* Look at each value on the value chain.  */
1831       for (v = val_chain; v; v = value_next (v))
1832         {
1833           /* If it's a memory location, and GDB actually needed
1834              its contents to evaluate the expression, then we
1835              must watch it.  If the first value returned is
1836              still lazy, that means an error occurred reading it;
1837              watch it anyway in case it becomes readable.  */
1838           if (VALUE_LVAL (v) == lval_memory
1839               && (v == val_chain || ! value_lazy (v)))
1840             {
1841               struct type *vtype = check_typedef (value_type (v));
1842
1843               /* We only watch structs and arrays if user asked
1844                  for it explicitly, never if they just happen to
1845                  appear in the middle of some value chain.  */
1846               if (v == result
1847                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1848                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1849                 {
1850                   CORE_ADDR addr;
1851                   int type;
1852                   struct bp_location *loc, **tmp;
1853
1854                   addr = value_address (v);
1855                   type = hw_write;
1856                   if (b->base.type == bp_read_watchpoint)
1857                     type = hw_read;
1858                   else if (b->base.type == bp_access_watchpoint)
1859                     type = hw_access;
1860
1861                   loc = allocate_bp_location (&b->base);
1862                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1863                     ;
1864                   *tmp = loc;
1865                   loc->gdbarch = get_type_arch (value_type (v));
1866
1867                   loc->pspace = frame_pspace;
1868                   loc->address = addr;
1869                   loc->length = TYPE_LENGTH (value_type (v));
1870                   loc->watchpoint_type = type;
1871                 }
1872             }
1873         }
1874
1875       /* Change the type of breakpoint between hardware assisted or
1876          an ordinary watchpoint depending on the hardware support
1877          and free hardware slots.  REPARSE is set when the inferior
1878          is started.  */
1879       if (reparse)
1880         {
1881           int reg_cnt;
1882           enum bp_loc_type loc_type;
1883           struct bp_location *bl;
1884
1885           reg_cnt = can_use_hardware_watchpoint (val_chain);
1886
1887           if (reg_cnt)
1888             {
1889               int i, target_resources_ok, other_type_used;
1890               enum bptype type;
1891
1892               /* Use an exact watchpoint when there's only one memory region to be
1893                  watched, and only one debug register is needed to watch it.  */
1894               b->exact = target_exact_watchpoints && reg_cnt == 1;
1895
1896               /* We need to determine how many resources are already
1897                  used for all other hardware watchpoints plus this one
1898                  to see if we still have enough resources to also fit
1899                  this watchpoint in as well.  */
1900
1901               /* If this is a software watchpoint, we try to turn it
1902                  to a hardware one -- count resources as if B was of
1903                  hardware watchpoint type.  */
1904               type = b->base.type;
1905               if (type == bp_watchpoint)
1906                 type = bp_hardware_watchpoint;
1907
1908               /* This watchpoint may or may not have been placed on
1909                  the list yet at this point (it won't be in the list
1910                  if we're trying to create it for the first time,
1911                  through watch_command), so always account for it
1912                  manually.  */
1913
1914               /* Count resources used by all watchpoints except B.  */
1915               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1916
1917               /* Add in the resources needed for B.  */
1918               i += hw_watchpoint_use_count (&b->base);
1919
1920               target_resources_ok
1921                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1922               if (target_resources_ok <= 0)
1923                 {
1924                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1925
1926                   if (target_resources_ok == 0 && !sw_mode)
1927                     error (_("Target does not support this type of "
1928                              "hardware watchpoint."));
1929                   else if (target_resources_ok < 0 && !sw_mode)
1930                     error (_("There are not enough available hardware "
1931                              "resources for this watchpoint."));
1932
1933                   /* Downgrade to software watchpoint.  */
1934                   b->base.type = bp_watchpoint;
1935                 }
1936               else
1937                 {
1938                   /* If this was a software watchpoint, we've just
1939                      found we have enough resources to turn it to a
1940                      hardware watchpoint.  Otherwise, this is a
1941                      nop.  */
1942                   b->base.type = type;
1943                 }
1944             }
1945           else if (!b->base.ops->works_in_software_mode (&b->base))
1946             error (_("Expression cannot be implemented with "
1947                      "read/access watchpoint."));
1948           else
1949             b->base.type = bp_watchpoint;
1950
1951           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1952                       : bp_loc_hardware_watchpoint);
1953           for (bl = b->base.loc; bl; bl = bl->next)
1954             bl->loc_type = loc_type;
1955         }
1956
1957       for (v = val_chain; v; v = next)
1958         {
1959           next = value_next (v);
1960           if (v != b->val)
1961             value_free (v);
1962         }
1963
1964       /* If a software watchpoint is not watching any memory, then the
1965          above left it without any location set up.  But,
1966          bpstat_stop_status requires a location to be able to report
1967          stops, so make sure there's at least a dummy one.  */
1968       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1969         {
1970           struct breakpoint *base = &b->base;
1971           base->loc = allocate_bp_location (base);
1972           base->loc->pspace = frame_pspace;
1973           base->loc->address = -1;
1974           base->loc->length = -1;
1975           base->loc->watchpoint_type = -1;
1976         }
1977     }
1978   else if (!within_current_scope)
1979     {
1980       printf_filtered (_("\
1981 Watchpoint %d deleted because the program has left the block\n\
1982 in which its expression is valid.\n"),
1983                        b->base.number);
1984       watchpoint_del_at_next_stop (b);
1985     }
1986
1987   /* Restore the selected frame.  */
1988   if (frame_saved)
1989     select_frame (frame_find_by_id (saved_frame_id));
1990 }
1991
1992
1993 /* Returns 1 iff breakpoint location should be
1994    inserted in the inferior.  We don't differentiate the type of BL's owner
1995    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1996    breakpoint_ops is not defined, because in insert_bp_location,
1997    tracepoint's insert_location will not be called.  */
1998 static int
1999 should_be_inserted (struct bp_location *bl)
2000 {
2001   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2002     return 0;
2003
2004   if (bl->owner->disposition == disp_del_at_next_stop)
2005     return 0;
2006
2007   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2008     return 0;
2009
2010   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2011     return 0;
2012
2013   /* This is set for example, when we're attached to the parent of a
2014      vfork, and have detached from the child.  The child is running
2015      free, and we expect it to do an exec or exit, at which point the
2016      OS makes the parent schedulable again (and the target reports
2017      that the vfork is done).  Until the child is done with the shared
2018      memory region, do not insert breakpoints in the parent, otherwise
2019      the child could still trip on the parent's breakpoints.  Since
2020      the parent is blocked anyway, it won't miss any breakpoint.  */
2021   if (bl->pspace->breakpoints_not_allowed)
2022     return 0;
2023
2024   return 1;
2025 }
2026
2027 /* Same as should_be_inserted but does the check assuming
2028    that the location is not duplicated.  */
2029
2030 static int
2031 unduplicated_should_be_inserted (struct bp_location *bl)
2032 {
2033   int result;
2034   const int save_duplicate = bl->duplicate;
2035
2036   bl->duplicate = 0;
2037   result = should_be_inserted (bl);
2038   bl->duplicate = save_duplicate;
2039   return result;
2040 }
2041
2042 /* Parses a conditional described by an expression COND into an
2043    agent expression bytecode suitable for evaluation
2044    by the bytecode interpreter.  Return NULL if there was
2045    any error during parsing.  */
2046
2047 static struct agent_expr *
2048 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2049 {
2050   struct agent_expr *aexpr = NULL;
2051   struct cleanup *old_chain = NULL;
2052   volatile struct gdb_exception ex;
2053
2054   if (!cond)
2055     return NULL;
2056
2057   /* We don't want to stop processing, so catch any errors
2058      that may show up.  */
2059   TRY_CATCH (ex, RETURN_MASK_ERROR)
2060     {
2061       aexpr = gen_eval_for_expr (scope, cond);
2062     }
2063
2064   if (ex.reason < 0)
2065     {
2066       /* If we got here, it means the condition could not be parsed to a valid
2067          bytecode expression and thus can't be evaluated on the target's side.
2068          It's no use iterating through the conditions.  */
2069       return NULL;
2070     }
2071
2072   /* We have a valid agent expression.  */
2073   return aexpr;
2074 }
2075
2076 /* Based on location BL, create a list of breakpoint conditions to be
2077    passed on to the target.  If we have duplicated locations with different
2078    conditions, we will add such conditions to the list.  The idea is that the
2079    target will evaluate the list of conditions and will only notify GDB when
2080    one of them is true.  */
2081
2082 static void
2083 build_target_condition_list (struct bp_location *bl)
2084 {
2085   struct bp_location **locp = NULL, **loc2p;
2086   int null_condition_or_parse_error = 0;
2087   int modified = bl->needs_update;
2088   struct bp_location *loc;
2089
2090   /* This is only meaningful if the target is
2091      evaluating conditions and if the user has
2092      opted for condition evaluation on the target's
2093      side.  */
2094   if (gdb_evaluates_breakpoint_condition_p ()
2095       || !target_supports_evaluation_of_breakpoint_conditions ())
2096     return;
2097
2098   /* Do a first pass to check for locations with no assigned
2099      conditions or conditions that fail to parse to a valid agent expression
2100      bytecode.  If any of these happen, then it's no use to send conditions
2101      to the target since this location will always trigger and generate a
2102      response back to GDB.  */
2103   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2104     {
2105       loc = (*loc2p);
2106       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2107         {
2108           if (modified)
2109             {
2110               struct agent_expr *aexpr;
2111
2112               /* Re-parse the conditions since something changed.  In that
2113                  case we already freed the condition bytecodes (see
2114                  force_breakpoint_reinsertion).  We just
2115                  need to parse the condition to bytecodes again.  */
2116               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2117               loc->cond_bytecode = aexpr;
2118
2119               /* Check if we managed to parse the conditional expression
2120                  correctly.  If not, we will not send this condition
2121                  to the target.  */
2122               if (aexpr)
2123                 continue;
2124             }
2125
2126           /* If we have a NULL bytecode expression, it means something
2127              went wrong or we have a null condition expression.  */
2128           if (!loc->cond_bytecode)
2129             {
2130               null_condition_or_parse_error = 1;
2131               break;
2132             }
2133         }
2134     }
2135
2136   /* If any of these happened, it means we will have to evaluate the conditions
2137      for the location's address on gdb's side.  It is no use keeping bytecodes
2138      for all the other duplicate locations, thus we free all of them here.
2139
2140      This is so we have a finer control over which locations' conditions are
2141      being evaluated by GDB or the remote stub.  */
2142   if (null_condition_or_parse_error)
2143     {
2144       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2145         {
2146           loc = (*loc2p);
2147           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2148             {
2149               /* Only go as far as the first NULL bytecode is
2150                  located.  */
2151               if (!loc->cond_bytecode)
2152                 return;
2153
2154               free_agent_expr (loc->cond_bytecode);
2155               loc->cond_bytecode = NULL;
2156             }
2157         }
2158     }
2159
2160   /* No NULL conditions or failed bytecode generation.  Build a condition list
2161      for this location's address.  */
2162   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2163     {
2164       loc = (*loc2p);
2165       if (loc->cond
2166           && is_breakpoint (loc->owner)
2167           && loc->pspace->num == bl->pspace->num
2168           && loc->owner->enable_state == bp_enabled
2169           && loc->enabled)
2170         /* Add the condition to the vector.  This will be used later to send the
2171            conditions to the target.  */
2172         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2173                        loc->cond_bytecode);
2174     }
2175
2176   return;
2177 }
2178
2179 /* Parses a command described by string CMD into an agent expression
2180    bytecode suitable for evaluation by the bytecode interpreter.
2181    Return NULL if there was any error during parsing.  */
2182
2183 static struct agent_expr *
2184 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2185 {
2186   struct cleanup *old_cleanups = 0;
2187   struct expression *expr, **argvec;
2188   struct agent_expr *aexpr = NULL;
2189   struct cleanup *old_chain = NULL;
2190   volatile struct gdb_exception ex;
2191   const char *cmdrest;
2192   const char *format_start, *format_end;
2193   struct format_piece *fpieces;
2194   int nargs;
2195   struct gdbarch *gdbarch = get_current_arch ();
2196
2197   if (!cmd)
2198     return NULL;
2199
2200   cmdrest = cmd;
2201
2202   if (*cmdrest == ',')
2203     ++cmdrest;
2204   cmdrest = skip_spaces_const (cmdrest);
2205
2206   if (*cmdrest++ != '"')
2207     error (_("No format string following the location"));
2208
2209   format_start = cmdrest;
2210
2211   fpieces = parse_format_string (&cmdrest);
2212
2213   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2214
2215   format_end = cmdrest;
2216
2217   if (*cmdrest++ != '"')
2218     error (_("Bad format string, non-terminated '\"'."));
2219   
2220   cmdrest = skip_spaces_const (cmdrest);
2221
2222   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2223     error (_("Invalid argument syntax"));
2224
2225   if (*cmdrest == ',')
2226     cmdrest++;
2227   cmdrest = skip_spaces_const (cmdrest);
2228
2229   /* For each argument, make an expression.  */
2230
2231   argvec = (struct expression **) alloca (strlen (cmd)
2232                                          * sizeof (struct expression *));
2233
2234   nargs = 0;
2235   while (*cmdrest != '\0')
2236     {
2237       const char *cmd1;
2238
2239       cmd1 = cmdrest;
2240       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2241       argvec[nargs++] = expr;
2242       cmdrest = cmd1;
2243       if (*cmdrest == ',')
2244         ++cmdrest;
2245     }
2246
2247   /* We don't want to stop processing, so catch any errors
2248      that may show up.  */
2249   TRY_CATCH (ex, RETURN_MASK_ERROR)
2250     {
2251       aexpr = gen_printf (scope, gdbarch, 0, 0,
2252                           format_start, format_end - format_start,
2253                           fpieces, nargs, argvec);
2254     }
2255
2256   if (ex.reason < 0)
2257     {
2258       /* If we got here, it means the command could not be parsed to a valid
2259          bytecode expression and thus can't be evaluated on the target's side.
2260          It's no use iterating through the other commands.  */
2261       return NULL;
2262     }
2263
2264   do_cleanups (old_cleanups);
2265
2266   /* We have a valid agent expression, return it.  */
2267   return aexpr;
2268 }
2269
2270 /* Based on location BL, create a list of breakpoint commands to be
2271    passed on to the target.  If we have duplicated locations with
2272    different commands, we will add any such to the list.  */
2273
2274 static void
2275 build_target_command_list (struct bp_location *bl)
2276 {
2277   struct bp_location **locp = NULL, **loc2p;
2278   int null_command_or_parse_error = 0;
2279   int modified = bl->needs_update;
2280   struct bp_location *loc;
2281
2282   /* For now, limit to agent-style dprintf breakpoints.  */
2283   if (bl->owner->type != bp_dprintf
2284       || strcmp (dprintf_style, dprintf_style_agent) != 0)
2285     return;
2286
2287   if (!target_can_run_breakpoint_commands ())
2288     return;
2289
2290   /* Do a first pass to check for locations with no assigned
2291      conditions or conditions that fail to parse to a valid agent expression
2292      bytecode.  If any of these happen, then it's no use to send conditions
2293      to the target since this location will always trigger and generate a
2294      response back to GDB.  */
2295   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2296     {
2297       loc = (*loc2p);
2298       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2299         {
2300           if (modified)
2301             {
2302               struct agent_expr *aexpr;
2303
2304               /* Re-parse the commands since something changed.  In that
2305                  case we already freed the command bytecodes (see
2306                  force_breakpoint_reinsertion).  We just
2307                  need to parse the command to bytecodes again.  */
2308               aexpr = parse_cmd_to_aexpr (bl->address,
2309                                           loc->owner->extra_string);
2310               loc->cmd_bytecode = aexpr;
2311
2312               if (!aexpr)
2313                 continue;
2314             }
2315
2316           /* If we have a NULL bytecode expression, it means something
2317              went wrong or we have a null command expression.  */
2318           if (!loc->cmd_bytecode)
2319             {
2320               null_command_or_parse_error = 1;
2321               break;
2322             }
2323         }
2324     }
2325
2326   /* If anything failed, then we're not doing target-side commands,
2327      and so clean up.  */
2328   if (null_command_or_parse_error)
2329     {
2330       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2331         {
2332           loc = (*loc2p);
2333           if (is_breakpoint (loc->owner)
2334               && loc->pspace->num == bl->pspace->num)
2335             {
2336               /* Only go as far as the first NULL bytecode is
2337                  located.  */
2338               if (loc->cmd_bytecode == NULL)
2339                 return;
2340
2341               free_agent_expr (loc->cmd_bytecode);
2342               loc->cmd_bytecode = NULL;
2343             }
2344         }
2345     }
2346
2347   /* No NULL commands or failed bytecode generation.  Build a command list
2348      for this location's address.  */
2349   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2350     {
2351       loc = (*loc2p);
2352       if (loc->owner->extra_string
2353           && is_breakpoint (loc->owner)
2354           && loc->pspace->num == bl->pspace->num
2355           && loc->owner->enable_state == bp_enabled
2356           && loc->enabled)
2357         /* Add the command to the vector.  This will be used later
2358            to send the commands to the target.  */
2359         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2360                        loc->cmd_bytecode);
2361     }
2362
2363   bl->target_info.persist = 0;
2364   /* Maybe flag this location as persistent.  */
2365   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2366     bl->target_info.persist = 1;
2367 }
2368
2369 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2370    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2371    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2372    Returns 0 for success, 1 if the bp_location type is not supported or
2373    -1 for failure.
2374
2375    NOTE drow/2003-09-09: This routine could be broken down to an
2376    object-style method for each breakpoint or catchpoint type.  */
2377 static int
2378 insert_bp_location (struct bp_location *bl,
2379                     struct ui_file *tmp_error_stream,
2380                     int *disabled_breaks,
2381                     int *hw_breakpoint_error,
2382                     int *hw_bp_error_explained_already)
2383 {
2384   int val = 0;
2385   char *hw_bp_err_string = NULL;
2386   struct gdb_exception e;
2387
2388   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2389     return 0;
2390
2391   /* Note we don't initialize bl->target_info, as that wipes out
2392      the breakpoint location's shadow_contents if the breakpoint
2393      is still inserted at that location.  This in turn breaks
2394      target_read_memory which depends on these buffers when
2395      a memory read is requested at the breakpoint location:
2396      Once the target_info has been wiped, we fail to see that
2397      we have a breakpoint inserted at that address and thus
2398      read the breakpoint instead of returning the data saved in
2399      the breakpoint location's shadow contents.  */
2400   bl->target_info.placed_address = bl->address;
2401   bl->target_info.placed_address_space = bl->pspace->aspace;
2402   bl->target_info.length = bl->length;
2403
2404   /* When working with target-side conditions, we must pass all the conditions
2405      for the same breakpoint address down to the target since GDB will not
2406      insert those locations.  With a list of breakpoint conditions, the target
2407      can decide when to stop and notify GDB.  */
2408
2409   if (is_breakpoint (bl->owner))
2410     {
2411       build_target_condition_list (bl);
2412       build_target_command_list (bl);
2413       /* Reset the modification marker.  */
2414       bl->needs_update = 0;
2415     }
2416
2417   if (bl->loc_type == bp_loc_software_breakpoint
2418       || bl->loc_type == bp_loc_hardware_breakpoint)
2419     {
2420       if (bl->owner->type != bp_hardware_breakpoint)
2421         {
2422           /* If the explicitly specified breakpoint type
2423              is not hardware breakpoint, check the memory map to see
2424              if the breakpoint address is in read only memory or not.
2425
2426              Two important cases are:
2427              - location type is not hardware breakpoint, memory
2428              is readonly.  We change the type of the location to
2429              hardware breakpoint.
2430              - location type is hardware breakpoint, memory is
2431              read-write.  This means we've previously made the
2432              location hardware one, but then the memory map changed,
2433              so we undo.
2434              
2435              When breakpoints are removed, remove_breakpoints will use
2436              location types we've just set here, the only possible
2437              problem is that memory map has changed during running
2438              program, but it's not going to work anyway with current
2439              gdb.  */
2440           struct mem_region *mr 
2441             = lookup_mem_region (bl->target_info.placed_address);
2442           
2443           if (mr)
2444             {
2445               if (automatic_hardware_breakpoints)
2446                 {
2447                   enum bp_loc_type new_type;
2448                   
2449                   if (mr->attrib.mode != MEM_RW)
2450                     new_type = bp_loc_hardware_breakpoint;
2451                   else 
2452                     new_type = bp_loc_software_breakpoint;
2453                   
2454                   if (new_type != bl->loc_type)
2455                     {
2456                       static int said = 0;
2457
2458                       bl->loc_type = new_type;
2459                       if (!said)
2460                         {
2461                           fprintf_filtered (gdb_stdout,
2462                                             _("Note: automatically using "
2463                                               "hardware breakpoints for "
2464                                               "read-only addresses.\n"));
2465                           said = 1;
2466                         }
2467                     }
2468                 }
2469               else if (bl->loc_type == bp_loc_software_breakpoint
2470                        && mr->attrib.mode != MEM_RW)        
2471                 warning (_("cannot set software breakpoint "
2472                            "at readonly address %s"),
2473                          paddress (bl->gdbarch, bl->address));
2474             }
2475         }
2476         
2477       /* First check to see if we have to handle an overlay.  */
2478       if (overlay_debugging == ovly_off
2479           || bl->section == NULL
2480           || !(section_is_overlay (bl->section)))
2481         {
2482           /* No overlay handling: just set the breakpoint.  */
2483           TRY_CATCH (e, RETURN_MASK_ALL)
2484             {
2485               val = bl->owner->ops->insert_location (bl);
2486             }
2487           if (e.reason < 0)
2488             {
2489               val = 1;
2490               hw_bp_err_string = (char *) e.message;
2491             }
2492         }
2493       else
2494         {
2495           /* This breakpoint is in an overlay section.
2496              Shall we set a breakpoint at the LMA?  */
2497           if (!overlay_events_enabled)
2498             {
2499               /* Yes -- overlay event support is not active, 
2500                  so we must try to set a breakpoint at the LMA.
2501                  This will not work for a hardware breakpoint.  */
2502               if (bl->loc_type == bp_loc_hardware_breakpoint)
2503                 warning (_("hardware breakpoint %d not supported in overlay!"),
2504                          bl->owner->number);
2505               else
2506                 {
2507                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2508                                                              bl->section);
2509                   /* Set a software (trap) breakpoint at the LMA.  */
2510                   bl->overlay_target_info = bl->target_info;
2511                   bl->overlay_target_info.placed_address = addr;
2512                   val = target_insert_breakpoint (bl->gdbarch,
2513                                                   &bl->overlay_target_info);
2514                   if (val != 0)
2515                     fprintf_unfiltered (tmp_error_stream,
2516                                         "Overlay breakpoint %d "
2517                                         "failed: in ROM?\n",
2518                                         bl->owner->number);
2519                 }
2520             }
2521           /* Shall we set a breakpoint at the VMA? */
2522           if (section_is_mapped (bl->section))
2523             {
2524               /* Yes.  This overlay section is mapped into memory.  */
2525               TRY_CATCH (e, RETURN_MASK_ALL)
2526                 {
2527                   val = bl->owner->ops->insert_location (bl);
2528                 }
2529               if (e.reason < 0)
2530                 {
2531                   val = 1;
2532                   hw_bp_err_string = (char *) e.message;
2533                 }
2534             }
2535           else
2536             {
2537               /* No.  This breakpoint will not be inserted.  
2538                  No error, but do not mark the bp as 'inserted'.  */
2539               return 0;
2540             }
2541         }
2542
2543       if (val)
2544         {
2545           /* Can't set the breakpoint.  */
2546           if (solib_name_from_address (bl->pspace, bl->address))
2547             {
2548               /* See also: disable_breakpoints_in_shlibs.  */
2549               val = 0;
2550               bl->shlib_disabled = 1;
2551               observer_notify_breakpoint_modified (bl->owner);
2552               if (!*disabled_breaks)
2553                 {
2554                   fprintf_unfiltered (tmp_error_stream, 
2555                                       "Cannot insert breakpoint %d.\n", 
2556                                       bl->owner->number);
2557                   fprintf_unfiltered (tmp_error_stream, 
2558                                       "Temporarily disabling shared "
2559                                       "library breakpoints:\n");
2560                 }
2561               *disabled_breaks = 1;
2562               fprintf_unfiltered (tmp_error_stream,
2563                                   "breakpoint #%d\n", bl->owner->number);
2564             }
2565           else
2566             {
2567               if (bl->loc_type == bp_loc_hardware_breakpoint)
2568                 {
2569                   *hw_breakpoint_error = 1;
2570                   *hw_bp_error_explained_already = hw_bp_err_string != NULL;
2571                   fprintf_unfiltered (tmp_error_stream,
2572                                       "Cannot insert hardware breakpoint %d%s",
2573                                       bl->owner->number, hw_bp_err_string ? ":" : ".\n");
2574                   if (hw_bp_err_string)
2575                     fprintf_unfiltered (tmp_error_stream, "%s.\n", hw_bp_err_string);
2576                 }
2577               else
2578                 {
2579                   fprintf_unfiltered (tmp_error_stream, 
2580                                       "Cannot insert breakpoint %d.\n", 
2581                                       bl->owner->number);
2582                   fprintf_filtered (tmp_error_stream, 
2583                                     "Error accessing memory address ");
2584                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2585                                   tmp_error_stream);
2586                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2587                                     safe_strerror (val));
2588                 }
2589
2590             }
2591         }
2592       else
2593         bl->inserted = 1;
2594
2595       return val;
2596     }
2597
2598   else if (bl->loc_type == bp_loc_hardware_watchpoint
2599            /* NOTE drow/2003-09-08: This state only exists for removing
2600               watchpoints.  It's not clear that it's necessary...  */
2601            && bl->owner->disposition != disp_del_at_next_stop)
2602     {
2603       gdb_assert (bl->owner->ops != NULL
2604                   && bl->owner->ops->insert_location != NULL);
2605
2606       val = bl->owner->ops->insert_location (bl);
2607
2608       /* If trying to set a read-watchpoint, and it turns out it's not
2609          supported, try emulating one with an access watchpoint.  */
2610       if (val == 1 && bl->watchpoint_type == hw_read)
2611         {
2612           struct bp_location *loc, **loc_temp;
2613
2614           /* But don't try to insert it, if there's already another
2615              hw_access location that would be considered a duplicate
2616              of this one.  */
2617           ALL_BP_LOCATIONS (loc, loc_temp)
2618             if (loc != bl
2619                 && loc->watchpoint_type == hw_access
2620                 && watchpoint_locations_match (bl, loc))
2621               {
2622                 bl->duplicate = 1;
2623                 bl->inserted = 1;
2624                 bl->target_info = loc->target_info;
2625                 bl->watchpoint_type = hw_access;
2626                 val = 0;
2627                 break;
2628               }
2629
2630           if (val == 1)
2631             {
2632               bl->watchpoint_type = hw_access;
2633               val = bl->owner->ops->insert_location (bl);
2634
2635               if (val)
2636                 /* Back to the original value.  */
2637                 bl->watchpoint_type = hw_read;
2638             }
2639         }
2640
2641       bl->inserted = (val == 0);
2642     }
2643
2644   else if (bl->owner->type == bp_catchpoint)
2645     {
2646       gdb_assert (bl->owner->ops != NULL
2647                   && bl->owner->ops->insert_location != NULL);
2648
2649       val = bl->owner->ops->insert_location (bl);
2650       if (val)
2651         {
2652           bl->owner->enable_state = bp_disabled;
2653
2654           if (val == 1)
2655             warning (_("\
2656 Error inserting catchpoint %d: Your system does not support this type\n\
2657 of catchpoint."), bl->owner->number);
2658           else
2659             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2660         }
2661
2662       bl->inserted = (val == 0);
2663
2664       /* We've already printed an error message if there was a problem
2665          inserting this catchpoint, and we've disabled the catchpoint,
2666          so just return success.  */
2667       return 0;
2668     }
2669
2670   return 0;
2671 }
2672
2673 /* This function is called when program space PSPACE is about to be
2674    deleted.  It takes care of updating breakpoints to not reference
2675    PSPACE anymore.  */
2676
2677 void
2678 breakpoint_program_space_exit (struct program_space *pspace)
2679 {
2680   struct breakpoint *b, *b_temp;
2681   struct bp_location *loc, **loc_temp;
2682
2683   /* Remove any breakpoint that was set through this program space.  */
2684   ALL_BREAKPOINTS_SAFE (b, b_temp)
2685     {
2686       if (b->pspace == pspace)
2687         delete_breakpoint (b);
2688     }
2689
2690   /* Breakpoints set through other program spaces could have locations
2691      bound to PSPACE as well.  Remove those.  */
2692   ALL_BP_LOCATIONS (loc, loc_temp)
2693     {
2694       struct bp_location *tmp;
2695
2696       if (loc->pspace == pspace)
2697         {
2698           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2699           if (loc->owner->loc == loc)
2700             loc->owner->loc = loc->next;
2701           else
2702             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2703               if (tmp->next == loc)
2704                 {
2705                   tmp->next = loc->next;
2706                   break;
2707                 }
2708         }
2709     }
2710
2711   /* Now update the global location list to permanently delete the
2712      removed locations above.  */
2713   update_global_location_list (0);
2714 }
2715
2716 /* Make sure all breakpoints are inserted in inferior.
2717    Throws exception on any error.
2718    A breakpoint that is already inserted won't be inserted
2719    again, so calling this function twice is safe.  */
2720 void
2721 insert_breakpoints (void)
2722 {
2723   struct breakpoint *bpt;
2724
2725   ALL_BREAKPOINTS (bpt)
2726     if (is_hardware_watchpoint (bpt))
2727       {
2728         struct watchpoint *w = (struct watchpoint *) bpt;
2729
2730         update_watchpoint (w, 0 /* don't reparse.  */);
2731       }
2732
2733   update_global_location_list (1);
2734
2735   /* update_global_location_list does not insert breakpoints when
2736      always_inserted_mode is not enabled.  Explicitly insert them
2737      now.  */
2738   if (!breakpoints_always_inserted_mode ())
2739     insert_breakpoint_locations ();
2740 }
2741
2742 /* Invoke CALLBACK for each of bp_location.  */
2743
2744 void
2745 iterate_over_bp_locations (walk_bp_location_callback callback)
2746 {
2747   struct bp_location *loc, **loc_tmp;
2748
2749   ALL_BP_LOCATIONS (loc, loc_tmp)
2750     {
2751       callback (loc, NULL);
2752     }
2753 }
2754
2755 /* This is used when we need to synch breakpoint conditions between GDB and the
2756    target.  It is the case with deleting and disabling of breakpoints when using
2757    always-inserted mode.  */
2758
2759 static void
2760 update_inserted_breakpoint_locations (void)
2761 {
2762   struct bp_location *bl, **blp_tmp;
2763   int error_flag = 0;
2764   int val = 0;
2765   int disabled_breaks = 0;
2766   int hw_breakpoint_error = 0;
2767   int hw_bp_details_reported = 0;
2768
2769   struct ui_file *tmp_error_stream = mem_fileopen ();
2770   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2771
2772   /* Explicitly mark the warning -- this will only be printed if
2773      there was an error.  */
2774   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2775
2776   save_current_space_and_thread ();
2777
2778   ALL_BP_LOCATIONS (bl, blp_tmp)
2779     {
2780       /* We only want to update software breakpoints and hardware
2781          breakpoints.  */
2782       if (!is_breakpoint (bl->owner))
2783         continue;
2784
2785       /* We only want to update locations that are already inserted
2786          and need updating.  This is to avoid unwanted insertion during
2787          deletion of breakpoints.  */
2788       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2789         continue;
2790
2791       switch_to_program_space_and_thread (bl->pspace);
2792
2793       /* For targets that support global breakpoints, there's no need
2794          to select an inferior to insert breakpoint to.  In fact, even
2795          if we aren't attached to any process yet, we should still
2796          insert breakpoints.  */
2797       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2798           && ptid_equal (inferior_ptid, null_ptid))
2799         continue;
2800
2801       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2802                                     &hw_breakpoint_error, &hw_bp_details_reported);
2803       if (val)
2804         error_flag = val;
2805     }
2806
2807   if (error_flag)
2808     {
2809       target_terminal_ours_for_output ();
2810       error_stream (tmp_error_stream);
2811     }
2812
2813   do_cleanups (cleanups);
2814 }
2815
2816 /* Used when starting or continuing the program.  */
2817
2818 static void
2819 insert_breakpoint_locations (void)
2820 {
2821   struct breakpoint *bpt;
2822   struct bp_location *bl, **blp_tmp;
2823   int error_flag = 0;
2824   int val = 0;
2825   int disabled_breaks = 0;
2826   int hw_breakpoint_error = 0;
2827   int hw_bp_error_explained_already = 0;
2828
2829   struct ui_file *tmp_error_stream = mem_fileopen ();
2830   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2831   
2832   /* Explicitly mark the warning -- this will only be printed if
2833      there was an error.  */
2834   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2835
2836   save_current_space_and_thread ();
2837
2838   ALL_BP_LOCATIONS (bl, blp_tmp)
2839     {
2840       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2841         continue;
2842
2843       /* There is no point inserting thread-specific breakpoints if
2844          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2845          has BL->OWNER always non-NULL.  */
2846       if (bl->owner->thread != -1
2847           && !valid_thread_id (bl->owner->thread))
2848         continue;
2849
2850       switch_to_program_space_and_thread (bl->pspace);
2851
2852       /* For targets that support global breakpoints, there's no need
2853          to select an inferior to insert breakpoint to.  In fact, even
2854          if we aren't attached to any process yet, we should still
2855          insert breakpoints.  */
2856       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2857           && ptid_equal (inferior_ptid, null_ptid))
2858         continue;
2859
2860       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2861                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2862       if (val)
2863         error_flag = val;
2864     }
2865
2866   /* If we failed to insert all locations of a watchpoint, remove
2867      them, as half-inserted watchpoint is of limited use.  */
2868   ALL_BREAKPOINTS (bpt)  
2869     {
2870       int some_failed = 0;
2871       struct bp_location *loc;
2872
2873       if (!is_hardware_watchpoint (bpt))
2874         continue;
2875
2876       if (!breakpoint_enabled (bpt))
2877         continue;
2878
2879       if (bpt->disposition == disp_del_at_next_stop)
2880         continue;
2881       
2882       for (loc = bpt->loc; loc; loc = loc->next)
2883         if (!loc->inserted && should_be_inserted (loc))
2884           {
2885             some_failed = 1;
2886             break;
2887           }
2888       if (some_failed)
2889         {
2890           for (loc = bpt->loc; loc; loc = loc->next)
2891             if (loc->inserted)
2892               remove_breakpoint (loc, mark_uninserted);
2893
2894           hw_breakpoint_error = 1;
2895           fprintf_unfiltered (tmp_error_stream,
2896                               "Could not insert hardware watchpoint %d.\n", 
2897                               bpt->number);
2898           error_flag = -1;
2899         }
2900     }
2901
2902   if (error_flag)
2903     {
2904       /* If a hardware breakpoint or watchpoint was inserted, add a
2905          message about possibly exhausted resources.  */
2906       if (hw_breakpoint_error && !hw_bp_error_explained_already)
2907         {
2908           fprintf_unfiltered (tmp_error_stream, 
2909                               "Could not insert hardware breakpoints:\n\
2910 You may have requested too many hardware breakpoints/watchpoints.\n");
2911         }
2912       target_terminal_ours_for_output ();
2913       error_stream (tmp_error_stream);
2914     }
2915
2916   do_cleanups (cleanups);
2917 }
2918
2919 /* Used when the program stops.
2920    Returns zero if successful, or non-zero if there was a problem
2921    removing a breakpoint location.  */
2922
2923 int
2924 remove_breakpoints (void)
2925 {
2926   struct bp_location *bl, **blp_tmp;
2927   int val = 0;
2928
2929   ALL_BP_LOCATIONS (bl, blp_tmp)
2930   {
2931     if (bl->inserted && !is_tracepoint (bl->owner))
2932       val |= remove_breakpoint (bl, mark_uninserted);
2933   }
2934   return val;
2935 }
2936
2937 /* Remove breakpoints of process PID.  */
2938
2939 int
2940 remove_breakpoints_pid (int pid)
2941 {
2942   struct bp_location *bl, **blp_tmp;
2943   int val;
2944   struct inferior *inf = find_inferior_pid (pid);
2945
2946   ALL_BP_LOCATIONS (bl, blp_tmp)
2947   {
2948     if (bl->pspace != inf->pspace)
2949       continue;
2950
2951     if (bl->owner->type == bp_dprintf)
2952       continue;
2953
2954     if (bl->inserted)
2955       {
2956         val = remove_breakpoint (bl, mark_uninserted);
2957         if (val != 0)
2958           return val;
2959       }
2960   }
2961   return 0;
2962 }
2963
2964 int
2965 reattach_breakpoints (int pid)
2966 {
2967   struct cleanup *old_chain;
2968   struct bp_location *bl, **blp_tmp;
2969   int val;
2970   struct ui_file *tmp_error_stream;
2971   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
2972   struct inferior *inf;
2973   struct thread_info *tp;
2974
2975   tp = any_live_thread_of_process (pid);
2976   if (tp == NULL)
2977     return 1;
2978
2979   inf = find_inferior_pid (pid);
2980   old_chain = save_inferior_ptid ();
2981
2982   inferior_ptid = tp->ptid;
2983
2984   tmp_error_stream = mem_fileopen ();
2985   make_cleanup_ui_file_delete (tmp_error_stream);
2986
2987   ALL_BP_LOCATIONS (bl, blp_tmp)
2988   {
2989     if (bl->pspace != inf->pspace)
2990       continue;
2991
2992     if (bl->inserted)
2993       {
2994         bl->inserted = 0;
2995         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
2996         if (val != 0)
2997           {
2998             do_cleanups (old_chain);
2999             return val;
3000           }
3001       }
3002   }
3003   do_cleanups (old_chain);
3004   return 0;
3005 }
3006
3007 static int internal_breakpoint_number = -1;
3008
3009 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3010    If INTERNAL is non-zero, the breakpoint number will be populated
3011    from internal_breakpoint_number and that variable decremented.
3012    Otherwise the breakpoint number will be populated from
3013    breakpoint_count and that value incremented.  Internal breakpoints
3014    do not set the internal var bpnum.  */
3015 static void
3016 set_breakpoint_number (int internal, struct breakpoint *b)
3017 {
3018   if (internal)
3019     b->number = internal_breakpoint_number--;
3020   else
3021     {
3022       set_breakpoint_count (breakpoint_count + 1);
3023       b->number = breakpoint_count;
3024     }
3025 }
3026
3027 static struct breakpoint *
3028 create_internal_breakpoint (struct gdbarch *gdbarch,
3029                             CORE_ADDR address, enum bptype type,
3030                             const struct breakpoint_ops *ops)
3031 {
3032   struct symtab_and_line sal;
3033   struct breakpoint *b;
3034
3035   init_sal (&sal);              /* Initialize to zeroes.  */
3036
3037   sal.pc = address;
3038   sal.section = find_pc_overlay (sal.pc);
3039   sal.pspace = current_program_space;
3040
3041   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3042   b->number = internal_breakpoint_number--;
3043   b->disposition = disp_donttouch;
3044
3045   return b;
3046 }
3047
3048 static const char *const longjmp_names[] =
3049   {
3050     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3051   };
3052 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3053
3054 /* Per-objfile data private to breakpoint.c.  */
3055 struct breakpoint_objfile_data
3056 {
3057   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3058   struct minimal_symbol *overlay_msym;
3059
3060   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3061   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
3062
3063   /* True if we have looked for longjmp probes.  */
3064   int longjmp_searched;
3065
3066   /* SystemTap probe points for longjmp (if any).  */
3067   VEC (probe_p) *longjmp_probes;
3068
3069   /* Minimal symbol for "std::terminate()" (if any).  */
3070   struct minimal_symbol *terminate_msym;
3071
3072   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3073   struct minimal_symbol *exception_msym;
3074
3075   /* True if we have looked for exception probes.  */
3076   int exception_searched;
3077
3078   /* SystemTap probe points for unwinding (if any).  */
3079   VEC (probe_p) *exception_probes;
3080 };
3081
3082 static const struct objfile_data *breakpoint_objfile_key;
3083
3084 /* Minimal symbol not found sentinel.  */
3085 static struct minimal_symbol msym_not_found;
3086
3087 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3088
3089 static int
3090 msym_not_found_p (const struct minimal_symbol *msym)
3091 {
3092   return msym == &msym_not_found;
3093 }
3094
3095 /* Return per-objfile data needed by breakpoint.c.
3096    Allocate the data if necessary.  */
3097
3098 static struct breakpoint_objfile_data *
3099 get_breakpoint_objfile_data (struct objfile *objfile)
3100 {
3101   struct breakpoint_objfile_data *bp_objfile_data;
3102
3103   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3104   if (bp_objfile_data == NULL)
3105     {
3106       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3107                                        sizeof (*bp_objfile_data));
3108
3109       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3110       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3111     }
3112   return bp_objfile_data;
3113 }
3114
3115 static void
3116 free_breakpoint_probes (struct objfile *obj, void *data)
3117 {
3118   struct breakpoint_objfile_data *bp_objfile_data = data;
3119
3120   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3121   VEC_free (probe_p, bp_objfile_data->exception_probes);
3122 }
3123
3124 static void
3125 create_overlay_event_breakpoint (void)
3126 {
3127   struct objfile *objfile;
3128   const char *const func_name = "_ovly_debug_event";
3129
3130   ALL_OBJFILES (objfile)
3131     {
3132       struct breakpoint *b;
3133       struct breakpoint_objfile_data *bp_objfile_data;
3134       CORE_ADDR addr;
3135
3136       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3137
3138       if (msym_not_found_p (bp_objfile_data->overlay_msym))
3139         continue;
3140
3141       if (bp_objfile_data->overlay_msym == NULL)
3142         {
3143           struct minimal_symbol *m;
3144
3145           m = lookup_minimal_symbol_text (func_name, objfile);
3146           if (m == NULL)
3147             {
3148               /* Avoid future lookups in this objfile.  */
3149               bp_objfile_data->overlay_msym = &msym_not_found;
3150               continue;
3151             }
3152           bp_objfile_data->overlay_msym = m;
3153         }
3154
3155       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3156       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3157                                       bp_overlay_event,
3158                                       &internal_breakpoint_ops);
3159       b->addr_string = xstrdup (func_name);
3160
3161       if (overlay_debugging == ovly_auto)
3162         {
3163           b->enable_state = bp_enabled;
3164           overlay_events_enabled = 1;
3165         }
3166       else
3167        {
3168          b->enable_state = bp_disabled;
3169          overlay_events_enabled = 0;
3170        }
3171     }
3172   update_global_location_list (1);
3173 }
3174
3175 static void
3176 create_longjmp_master_breakpoint (void)
3177 {
3178   struct program_space *pspace;
3179   struct cleanup *old_chain;
3180
3181   old_chain = save_current_program_space ();
3182
3183   ALL_PSPACES (pspace)
3184   {
3185     struct objfile *objfile;
3186
3187     set_current_program_space (pspace);
3188
3189     ALL_OBJFILES (objfile)
3190     {
3191       int i;
3192       struct gdbarch *gdbarch;
3193       struct breakpoint_objfile_data *bp_objfile_data;
3194
3195       gdbarch = get_objfile_arch (objfile);
3196       if (!gdbarch_get_longjmp_target_p (gdbarch))
3197         continue;
3198
3199       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3200
3201       if (!bp_objfile_data->longjmp_searched)
3202         {
3203           bp_objfile_data->longjmp_probes
3204             = find_probes_in_objfile (objfile, "libc", "longjmp");
3205           bp_objfile_data->longjmp_searched = 1;
3206         }
3207
3208       if (bp_objfile_data->longjmp_probes != NULL)
3209         {
3210           int i;
3211           struct probe *probe;
3212           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3213
3214           for (i = 0;
3215                VEC_iterate (probe_p,
3216                             bp_objfile_data->longjmp_probes,
3217                             i, probe);
3218                ++i)
3219             {
3220               struct breakpoint *b;
3221
3222               b = create_internal_breakpoint (gdbarch, probe->address,
3223                                               bp_longjmp_master,
3224                                               &internal_breakpoint_ops);
3225               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3226               b->enable_state = bp_disabled;
3227             }
3228
3229           continue;
3230         }
3231
3232       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3233         {
3234           struct breakpoint *b;
3235           const char *func_name;
3236           CORE_ADDR addr;
3237
3238           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
3239             continue;
3240
3241           func_name = longjmp_names[i];
3242           if (bp_objfile_data->longjmp_msym[i] == NULL)
3243             {
3244               struct minimal_symbol *m;
3245
3246               m = lookup_minimal_symbol_text (func_name, objfile);
3247               if (m == NULL)
3248                 {
3249                   /* Prevent future lookups in this objfile.  */
3250                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
3251                   continue;
3252                 }
3253               bp_objfile_data->longjmp_msym[i] = m;
3254             }
3255
3256           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3257           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3258                                           &internal_breakpoint_ops);
3259           b->addr_string = xstrdup (func_name);
3260           b->enable_state = bp_disabled;
3261         }
3262     }
3263   }
3264   update_global_location_list (1);
3265
3266   do_cleanups (old_chain);
3267 }
3268
3269 /* Create a master std::terminate breakpoint.  */
3270 static void
3271 create_std_terminate_master_breakpoint (void)
3272 {
3273   struct program_space *pspace;
3274   struct cleanup *old_chain;
3275   const char *const func_name = "std::terminate()";
3276
3277   old_chain = save_current_program_space ();
3278
3279   ALL_PSPACES (pspace)
3280   {
3281     struct objfile *objfile;
3282     CORE_ADDR addr;
3283
3284     set_current_program_space (pspace);
3285
3286     ALL_OBJFILES (objfile)
3287     {
3288       struct breakpoint *b;
3289       struct breakpoint_objfile_data *bp_objfile_data;
3290
3291       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3292
3293       if (msym_not_found_p (bp_objfile_data->terminate_msym))
3294         continue;
3295
3296       if (bp_objfile_data->terminate_msym == NULL)
3297         {
3298           struct minimal_symbol *m;
3299
3300           m = lookup_minimal_symbol (func_name, NULL, objfile);
3301           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
3302                             && MSYMBOL_TYPE (m) != mst_file_text))
3303             {
3304               /* Prevent future lookups in this objfile.  */
3305               bp_objfile_data->terminate_msym = &msym_not_found;
3306               continue;
3307             }
3308           bp_objfile_data->terminate_msym = m;
3309         }
3310
3311       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3312       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3313                                       bp_std_terminate_master,
3314                                       &internal_breakpoint_ops);
3315       b->addr_string = xstrdup (func_name);
3316       b->enable_state = bp_disabled;
3317     }
3318   }
3319
3320   update_global_location_list (1);
3321
3322   do_cleanups (old_chain);
3323 }
3324
3325 /* Install a master breakpoint on the unwinder's debug hook.  */
3326
3327 static void
3328 create_exception_master_breakpoint (void)
3329 {
3330   struct objfile *objfile;
3331   const char *const func_name = "_Unwind_DebugHook";
3332
3333   ALL_OBJFILES (objfile)
3334     {
3335       struct breakpoint *b;
3336       struct gdbarch *gdbarch;
3337       struct breakpoint_objfile_data *bp_objfile_data;
3338       CORE_ADDR addr;
3339
3340       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3341
3342       /* We prefer the SystemTap probe point if it exists.  */
3343       if (!bp_objfile_data->exception_searched)
3344         {
3345           bp_objfile_data->exception_probes
3346             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3347           bp_objfile_data->exception_searched = 1;
3348         }
3349
3350       if (bp_objfile_data->exception_probes != NULL)
3351         {
3352           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3353           int i;
3354           struct probe *probe;
3355
3356           for (i = 0;
3357                VEC_iterate (probe_p,
3358                             bp_objfile_data->exception_probes,
3359                             i, probe);
3360                ++i)
3361             {
3362               struct breakpoint *b;
3363
3364               b = create_internal_breakpoint (gdbarch, probe->address,
3365                                               bp_exception_master,
3366                                               &internal_breakpoint_ops);
3367               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3368               b->enable_state = bp_disabled;
3369             }
3370
3371           continue;
3372         }
3373
3374       /* Otherwise, try the hook function.  */
3375
3376       if (msym_not_found_p (bp_objfile_data->exception_msym))
3377         continue;
3378
3379       gdbarch = get_objfile_arch (objfile);
3380
3381       if (bp_objfile_data->exception_msym == NULL)
3382         {
3383           struct minimal_symbol *debug_hook;
3384
3385           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3386           if (debug_hook == NULL)
3387             {
3388               bp_objfile_data->exception_msym = &msym_not_found;
3389               continue;
3390             }
3391
3392           bp_objfile_data->exception_msym = debug_hook;
3393         }
3394
3395       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3396       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3397                                                  &current_target);
3398       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3399                                       &internal_breakpoint_ops);
3400       b->addr_string = xstrdup (func_name);
3401       b->enable_state = bp_disabled;
3402     }
3403
3404   update_global_location_list (1);
3405 }
3406
3407 void
3408 update_breakpoints_after_exec (void)
3409 {
3410   struct breakpoint *b, *b_tmp;
3411   struct bp_location *bploc, **bplocp_tmp;
3412
3413   /* We're about to delete breakpoints from GDB's lists.  If the
3414      INSERTED flag is true, GDB will try to lift the breakpoints by
3415      writing the breakpoints' "shadow contents" back into memory.  The
3416      "shadow contents" are NOT valid after an exec, so GDB should not
3417      do that.  Instead, the target is responsible from marking
3418      breakpoints out as soon as it detects an exec.  We don't do that
3419      here instead, because there may be other attempts to delete
3420      breakpoints after detecting an exec and before reaching here.  */
3421   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3422     if (bploc->pspace == current_program_space)
3423       gdb_assert (!bploc->inserted);
3424
3425   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3426   {
3427     if (b->pspace != current_program_space)
3428       continue;
3429
3430     /* Solib breakpoints must be explicitly reset after an exec().  */
3431     if (b->type == bp_shlib_event)
3432       {
3433         delete_breakpoint (b);
3434         continue;
3435       }
3436
3437     /* JIT breakpoints must be explicitly reset after an exec().  */
3438     if (b->type == bp_jit_event)
3439       {
3440         delete_breakpoint (b);
3441         continue;
3442       }
3443
3444     /* Thread event breakpoints must be set anew after an exec(),
3445        as must overlay event and longjmp master breakpoints.  */
3446     if (b->type == bp_thread_event || b->type == bp_overlay_event
3447         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3448         || b->type == bp_exception_master)
3449       {
3450         delete_breakpoint (b);
3451         continue;
3452       }
3453
3454     /* Step-resume breakpoints are meaningless after an exec().  */
3455     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3456       {
3457         delete_breakpoint (b);
3458         continue;
3459       }
3460
3461     /* Longjmp and longjmp-resume breakpoints are also meaningless
3462        after an exec.  */
3463     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3464         || b->type == bp_longjmp_call_dummy
3465         || b->type == bp_exception || b->type == bp_exception_resume)
3466       {
3467         delete_breakpoint (b);
3468         continue;
3469       }
3470
3471     if (b->type == bp_catchpoint)
3472       {
3473         /* For now, none of the bp_catchpoint breakpoints need to
3474            do anything at this point.  In the future, if some of
3475            the catchpoints need to something, we will need to add
3476            a new method, and call this method from here.  */
3477         continue;
3478       }
3479
3480     /* bp_finish is a special case.  The only way we ought to be able
3481        to see one of these when an exec() has happened, is if the user
3482        caught a vfork, and then said "finish".  Ordinarily a finish just
3483        carries them to the call-site of the current callee, by setting
3484        a temporary bp there and resuming.  But in this case, the finish
3485        will carry them entirely through the vfork & exec.
3486
3487        We don't want to allow a bp_finish to remain inserted now.  But
3488        we can't safely delete it, 'cause finish_command has a handle to
3489        the bp on a bpstat, and will later want to delete it.  There's a
3490        chance (and I've seen it happen) that if we delete the bp_finish
3491        here, that its storage will get reused by the time finish_command
3492        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3493        We really must allow finish_command to delete a bp_finish.
3494
3495        In the absence of a general solution for the "how do we know
3496        it's safe to delete something others may have handles to?"
3497        problem, what we'll do here is just uninsert the bp_finish, and
3498        let finish_command delete it.
3499
3500        (We know the bp_finish is "doomed" in the sense that it's
3501        momentary, and will be deleted as soon as finish_command sees
3502        the inferior stopped.  So it doesn't matter that the bp's
3503        address is probably bogus in the new a.out, unlike e.g., the
3504        solib breakpoints.)  */
3505
3506     if (b->type == bp_finish)
3507       {
3508         continue;
3509       }
3510
3511     /* Without a symbolic address, we have little hope of the
3512        pre-exec() address meaning the same thing in the post-exec()
3513        a.out.  */
3514     if (b->addr_string == NULL)
3515       {
3516         delete_breakpoint (b);
3517         continue;
3518       }
3519   }
3520   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3521   create_overlay_event_breakpoint ();
3522   create_longjmp_master_breakpoint ();
3523   create_std_terminate_master_breakpoint ();
3524   create_exception_master_breakpoint ();
3525 }
3526
3527 int
3528 detach_breakpoints (ptid_t ptid)
3529 {
3530   struct bp_location *bl, **blp_tmp;
3531   int val = 0;
3532   struct cleanup *old_chain = save_inferior_ptid ();
3533   struct inferior *inf = current_inferior ();
3534
3535   if (PIDGET (ptid) == PIDGET (inferior_ptid))
3536     error (_("Cannot detach breakpoints of inferior_ptid"));
3537
3538   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3539   inferior_ptid = ptid;
3540   ALL_BP_LOCATIONS (bl, blp_tmp)
3541   {
3542     if (bl->pspace != inf->pspace)
3543       continue;
3544
3545     if (bl->inserted)
3546       val |= remove_breakpoint_1 (bl, mark_inserted);
3547   }
3548
3549   /* Detach single-step breakpoints as well.  */
3550   detach_single_step_breakpoints ();
3551
3552   do_cleanups (old_chain);
3553   return val;
3554 }
3555
3556 /* Remove the breakpoint location BL from the current address space.
3557    Note that this is used to detach breakpoints from a child fork.
3558    When we get here, the child isn't in the inferior list, and neither
3559    do we have objects to represent its address space --- we should
3560    *not* look at bl->pspace->aspace here.  */
3561
3562 static int
3563 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3564 {
3565   int val;
3566
3567   /* BL is never in moribund_locations by our callers.  */
3568   gdb_assert (bl->owner != NULL);
3569
3570   if (bl->owner->enable_state == bp_permanent)
3571     /* Permanent breakpoints cannot be inserted or removed.  */
3572     return 0;
3573
3574   /* The type of none suggests that owner is actually deleted.
3575      This should not ever happen.  */
3576   gdb_assert (bl->owner->type != bp_none);
3577
3578   if (bl->loc_type == bp_loc_software_breakpoint
3579       || bl->loc_type == bp_loc_hardware_breakpoint)
3580     {
3581       /* "Normal" instruction breakpoint: either the standard
3582          trap-instruction bp (bp_breakpoint), or a
3583          bp_hardware_breakpoint.  */
3584
3585       /* First check to see if we have to handle an overlay.  */
3586       if (overlay_debugging == ovly_off
3587           || bl->section == NULL
3588           || !(section_is_overlay (bl->section)))
3589         {
3590           /* No overlay handling: just remove the breakpoint.  */
3591           val = bl->owner->ops->remove_location (bl);
3592         }
3593       else
3594         {
3595           /* This breakpoint is in an overlay section.
3596              Did we set a breakpoint at the LMA?  */
3597           if (!overlay_events_enabled)
3598               {
3599                 /* Yes -- overlay event support is not active, so we
3600                    should have set a breakpoint at the LMA.  Remove it.  
3601                 */
3602                 /* Ignore any failures: if the LMA is in ROM, we will
3603                    have already warned when we failed to insert it.  */
3604                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3605                   target_remove_hw_breakpoint (bl->gdbarch,
3606                                                &bl->overlay_target_info);
3607                 else
3608                   target_remove_breakpoint (bl->gdbarch,
3609                                             &bl->overlay_target_info);
3610               }
3611           /* Did we set a breakpoint at the VMA? 
3612              If so, we will have marked the breakpoint 'inserted'.  */
3613           if (bl->inserted)
3614             {
3615               /* Yes -- remove it.  Previously we did not bother to
3616                  remove the breakpoint if the section had been
3617                  unmapped, but let's not rely on that being safe.  We
3618                  don't know what the overlay manager might do.  */
3619
3620               /* However, we should remove *software* breakpoints only
3621                  if the section is still mapped, or else we overwrite
3622                  wrong code with the saved shadow contents.  */
3623               if (bl->loc_type == bp_loc_hardware_breakpoint
3624                   || section_is_mapped (bl->section))
3625                 val = bl->owner->ops->remove_location (bl);
3626               else
3627                 val = 0;
3628             }
3629           else
3630             {
3631               /* No -- not inserted, so no need to remove.  No error.  */
3632               val = 0;
3633             }
3634         }
3635
3636       /* In some cases, we might not be able to remove a breakpoint
3637          in a shared library that has already been removed, but we
3638          have not yet processed the shlib unload event.  */
3639       if (val && solib_name_from_address (bl->pspace, bl->address))
3640         val = 0;
3641
3642       if (val)
3643         return val;
3644       bl->inserted = (is == mark_inserted);
3645     }
3646   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3647     {
3648       gdb_assert (bl->owner->ops != NULL
3649                   && bl->owner->ops->remove_location != NULL);
3650
3651       bl->inserted = (is == mark_inserted);
3652       bl->owner->ops->remove_location (bl);
3653
3654       /* Failure to remove any of the hardware watchpoints comes here.  */
3655       if ((is == mark_uninserted) && (bl->inserted))
3656         warning (_("Could not remove hardware watchpoint %d."),
3657                  bl->owner->number);
3658     }
3659   else if (bl->owner->type == bp_catchpoint
3660            && breakpoint_enabled (bl->owner)
3661            && !bl->duplicate)
3662     {
3663       gdb_assert (bl->owner->ops != NULL
3664                   && bl->owner->ops->remove_location != NULL);
3665
3666       val = bl->owner->ops->remove_location (bl);
3667       if (val)
3668         return val;
3669
3670       bl->inserted = (is == mark_inserted);
3671     }
3672
3673   return 0;
3674 }
3675
3676 static int
3677 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3678 {
3679   int ret;
3680   struct cleanup *old_chain;
3681
3682   /* BL is never in moribund_locations by our callers.  */
3683   gdb_assert (bl->owner != NULL);
3684
3685   if (bl->owner->enable_state == bp_permanent)
3686     /* Permanent breakpoints cannot be inserted or removed.  */
3687     return 0;
3688
3689   /* The type of none suggests that owner is actually deleted.
3690      This should not ever happen.  */
3691   gdb_assert (bl->owner->type != bp_none);
3692
3693   old_chain = save_current_space_and_thread ();
3694
3695   switch_to_program_space_and_thread (bl->pspace);
3696
3697   ret = remove_breakpoint_1 (bl, is);
3698
3699   do_cleanups (old_chain);
3700   return ret;
3701 }
3702
3703 /* Clear the "inserted" flag in all breakpoints.  */
3704
3705 void
3706 mark_breakpoints_out (void)
3707 {
3708   struct bp_location *bl, **blp_tmp;
3709
3710   ALL_BP_LOCATIONS (bl, blp_tmp)
3711     if (bl->pspace == current_program_space)
3712       bl->inserted = 0;
3713 }
3714
3715 /* Clear the "inserted" flag in all breakpoints and delete any
3716    breakpoints which should go away between runs of the program.
3717
3718    Plus other such housekeeping that has to be done for breakpoints
3719    between runs.
3720
3721    Note: this function gets called at the end of a run (by
3722    generic_mourn_inferior) and when a run begins (by
3723    init_wait_for_inferior).  */
3724
3725
3726
3727 void
3728 breakpoint_init_inferior (enum inf_context context)
3729 {
3730   struct breakpoint *b, *b_tmp;
3731   struct bp_location *bl, **blp_tmp;
3732   int ix;
3733   struct program_space *pspace = current_program_space;
3734
3735   /* If breakpoint locations are shared across processes, then there's
3736      nothing to do.  */
3737   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3738     return;
3739
3740   ALL_BP_LOCATIONS (bl, blp_tmp)
3741   {
3742     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3743     if (bl->pspace == pspace
3744         && bl->owner->enable_state != bp_permanent)
3745       bl->inserted = 0;
3746   }
3747
3748   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3749   {
3750     if (b->loc && b->loc->pspace != pspace)
3751       continue;
3752
3753     switch (b->type)
3754       {
3755       case bp_call_dummy:
3756       case bp_longjmp_call_dummy:
3757
3758         /* If the call dummy breakpoint is at the entry point it will
3759            cause problems when the inferior is rerun, so we better get
3760            rid of it.  */
3761
3762       case bp_watchpoint_scope:
3763
3764         /* Also get rid of scope breakpoints.  */
3765
3766       case bp_shlib_event:
3767
3768         /* Also remove solib event breakpoints.  Their addresses may
3769            have changed since the last time we ran the program.
3770            Actually we may now be debugging against different target;
3771            and so the solib backend that installed this breakpoint may
3772            not be used in by the target.  E.g.,
3773
3774            (gdb) file prog-linux
3775            (gdb) run               # native linux target
3776            ...
3777            (gdb) kill
3778            (gdb) file prog-win.exe
3779            (gdb) tar rem :9999     # remote Windows gdbserver.
3780         */
3781
3782       case bp_step_resume:
3783
3784         /* Also remove step-resume breakpoints.  */
3785
3786         delete_breakpoint (b);
3787         break;
3788
3789       case bp_watchpoint:
3790       case bp_hardware_watchpoint:
3791       case bp_read_watchpoint:
3792       case bp_access_watchpoint:
3793         {
3794           struct watchpoint *w = (struct watchpoint *) b;
3795
3796           /* Likewise for watchpoints on local expressions.  */
3797           if (w->exp_valid_block != NULL)
3798             delete_breakpoint (b);
3799           else if (context == inf_starting)
3800             {
3801               /* Reset val field to force reread of starting value in
3802                  insert_breakpoints.  */
3803               if (w->val)
3804                 value_free (w->val);
3805               w->val = NULL;
3806               w->val_valid = 0;
3807           }
3808         }
3809         break;
3810       default:
3811         break;
3812       }
3813   }
3814
3815   /* Get rid of the moribund locations.  */
3816   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3817     decref_bp_location (&bl);
3818   VEC_free (bp_location_p, moribund_locations);
3819 }
3820
3821 /* These functions concern about actual breakpoints inserted in the
3822    target --- to e.g. check if we need to do decr_pc adjustment or if
3823    we need to hop over the bkpt --- so we check for address space
3824    match, not program space.  */
3825
3826 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3827    exists at PC.  It returns ordinary_breakpoint_here if it's an
3828    ordinary breakpoint, or permanent_breakpoint_here if it's a
3829    permanent breakpoint.
3830    - When continuing from a location with an ordinary breakpoint, we
3831      actually single step once before calling insert_breakpoints.
3832    - When continuing from a location with a permanent breakpoint, we
3833      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3834      the target, to advance the PC past the breakpoint.  */
3835
3836 enum breakpoint_here
3837 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3838 {
3839   struct bp_location *bl, **blp_tmp;
3840   int any_breakpoint_here = 0;
3841
3842   ALL_BP_LOCATIONS (bl, blp_tmp)
3843     {
3844       if (bl->loc_type != bp_loc_software_breakpoint
3845           && bl->loc_type != bp_loc_hardware_breakpoint)
3846         continue;
3847
3848       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3849       if ((breakpoint_enabled (bl->owner)
3850            || bl->owner->enable_state == bp_permanent)
3851           && breakpoint_location_address_match (bl, aspace, pc))
3852         {
3853           if (overlay_debugging 
3854               && section_is_overlay (bl->section)
3855               && !section_is_mapped (bl->section))
3856             continue;           /* unmapped overlay -- can't be a match */
3857           else if (bl->owner->enable_state == bp_permanent)
3858             return permanent_breakpoint_here;
3859           else
3860             any_breakpoint_here = 1;
3861         }
3862     }
3863
3864   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3865 }
3866
3867 /* Return true if there's a moribund breakpoint at PC.  */
3868
3869 int
3870 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3871 {
3872   struct bp_location *loc;
3873   int ix;
3874
3875   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3876     if (breakpoint_location_address_match (loc, aspace, pc))
3877       return 1;
3878
3879   return 0;
3880 }
3881
3882 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3883    inserted using regular breakpoint_chain / bp_location array
3884    mechanism.  This does not check for single-step breakpoints, which
3885    are inserted and removed using direct target manipulation.  */
3886
3887 int
3888 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3889                                     CORE_ADDR pc)
3890 {
3891   struct bp_location *bl, **blp_tmp;
3892
3893   ALL_BP_LOCATIONS (bl, blp_tmp)
3894     {
3895       if (bl->loc_type != bp_loc_software_breakpoint
3896           && bl->loc_type != bp_loc_hardware_breakpoint)
3897         continue;
3898
3899       if (bl->inserted
3900           && breakpoint_location_address_match (bl, aspace, pc))
3901         {
3902           if (overlay_debugging 
3903               && section_is_overlay (bl->section)
3904               && !section_is_mapped (bl->section))
3905             continue;           /* unmapped overlay -- can't be a match */
3906           else
3907             return 1;
3908         }
3909     }
3910   return 0;
3911 }
3912
3913 /* Returns non-zero iff there's either regular breakpoint
3914    or a single step breakpoint inserted at PC.  */
3915
3916 int
3917 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3918 {
3919   if (regular_breakpoint_inserted_here_p (aspace, pc))
3920     return 1;
3921
3922   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3923     return 1;
3924
3925   return 0;
3926 }
3927
3928 /* This function returns non-zero iff there is a software breakpoint
3929    inserted at PC.  */
3930
3931 int
3932 software_breakpoint_inserted_here_p (struct address_space *aspace,
3933                                      CORE_ADDR pc)
3934 {
3935   struct bp_location *bl, **blp_tmp;
3936
3937   ALL_BP_LOCATIONS (bl, blp_tmp)
3938     {
3939       if (bl->loc_type != bp_loc_software_breakpoint)
3940         continue;
3941
3942       if (bl->inserted
3943           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3944                                        aspace, pc))
3945         {
3946           if (overlay_debugging 
3947               && section_is_overlay (bl->section)
3948               && !section_is_mapped (bl->section))
3949             continue;           /* unmapped overlay -- can't be a match */
3950           else
3951             return 1;
3952         }
3953     }
3954
3955   /* Also check for software single-step breakpoints.  */
3956   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3957     return 1;
3958
3959   return 0;
3960 }
3961
3962 int
3963 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3964                                        CORE_ADDR addr, ULONGEST len)
3965 {
3966   struct breakpoint *bpt;
3967
3968   ALL_BREAKPOINTS (bpt)
3969     {
3970       struct bp_location *loc;
3971
3972       if (bpt->type != bp_hardware_watchpoint
3973           && bpt->type != bp_access_watchpoint)
3974         continue;
3975
3976       if (!breakpoint_enabled (bpt))
3977         continue;
3978
3979       for (loc = bpt->loc; loc; loc = loc->next)
3980         if (loc->pspace->aspace == aspace && loc->inserted)
3981           {
3982             CORE_ADDR l, h;
3983
3984             /* Check for intersection.  */
3985             l = max (loc->address, addr);
3986             h = min (loc->address + loc->length, addr + len);
3987             if (l < h)
3988               return 1;
3989           }
3990     }
3991   return 0;
3992 }
3993
3994 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3995    PC is valid for process/thread PTID.  */
3996
3997 int
3998 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3999                          ptid_t ptid)
4000 {
4001   struct bp_location *bl, **blp_tmp;
4002   /* The thread and task IDs associated to PTID, computed lazily.  */
4003   int thread = -1;
4004   int task = 0;
4005   
4006   ALL_BP_LOCATIONS (bl, blp_tmp)
4007     {
4008       if (bl->loc_type != bp_loc_software_breakpoint
4009           && bl->loc_type != bp_loc_hardware_breakpoint)
4010         continue;
4011
4012       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4013       if (!breakpoint_enabled (bl->owner)
4014           && bl->owner->enable_state != bp_permanent)
4015         continue;
4016
4017       if (!breakpoint_location_address_match (bl, aspace, pc))
4018         continue;
4019
4020       if (bl->owner->thread != -1)
4021         {
4022           /* This is a thread-specific breakpoint.  Check that ptid
4023              matches that thread.  If thread hasn't been computed yet,
4024              it is now time to do so.  */
4025           if (thread == -1)
4026             thread = pid_to_thread_id (ptid);
4027           if (bl->owner->thread != thread)
4028             continue;
4029         }
4030
4031       if (bl->owner->task != 0)
4032         {
4033           /* This is a task-specific breakpoint.  Check that ptid
4034              matches that task.  If task hasn't been computed yet,
4035              it is now time to do so.  */
4036           if (task == 0)
4037             task = ada_get_task_number (ptid);
4038           if (bl->owner->task != task)
4039             continue;
4040         }
4041
4042       if (overlay_debugging 
4043           && section_is_overlay (bl->section)
4044           && !section_is_mapped (bl->section))
4045         continue;           /* unmapped overlay -- can't be a match */
4046
4047       return 1;
4048     }
4049
4050   return 0;
4051 }
4052 \f
4053
4054 /* bpstat stuff.  External routines' interfaces are documented
4055    in breakpoint.h.  */
4056
4057 int
4058 is_catchpoint (struct breakpoint *ep)
4059 {
4060   return (ep->type == bp_catchpoint);
4061 }
4062
4063 /* Frees any storage that is part of a bpstat.  Does not walk the
4064    'next' chain.  */
4065
4066 static void
4067 bpstat_free (bpstat bs)
4068 {
4069   if (bs->old_val != NULL)
4070     value_free (bs->old_val);
4071   decref_counted_command_line (&bs->commands);
4072   decref_bp_location (&bs->bp_location_at);
4073   xfree (bs);
4074 }
4075
4076 /* Clear a bpstat so that it says we are not at any breakpoint.
4077    Also free any storage that is part of a bpstat.  */
4078
4079 void
4080 bpstat_clear (bpstat *bsp)
4081 {
4082   bpstat p;
4083   bpstat q;
4084
4085   if (bsp == 0)
4086     return;
4087   p = *bsp;
4088   while (p != NULL)
4089     {
4090       q = p->next;
4091       bpstat_free (p);
4092       p = q;
4093     }
4094   *bsp = NULL;
4095 }
4096
4097 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4098    is part of the bpstat is copied as well.  */
4099
4100 bpstat
4101 bpstat_copy (bpstat bs)
4102 {
4103   bpstat p = NULL;
4104   bpstat tmp;
4105   bpstat retval = NULL;
4106
4107   if (bs == NULL)
4108     return bs;
4109
4110   for (; bs != NULL; bs = bs->next)
4111     {
4112       tmp = (bpstat) xmalloc (sizeof (*tmp));
4113       memcpy (tmp, bs, sizeof (*tmp));
4114       incref_counted_command_line (tmp->commands);
4115       incref_bp_location (tmp->bp_location_at);
4116       if (bs->old_val != NULL)
4117         {
4118           tmp->old_val = value_copy (bs->old_val);
4119           release_value (tmp->old_val);
4120         }
4121
4122       if (p == NULL)
4123         /* This is the first thing in the chain.  */
4124         retval = tmp;
4125       else
4126         p->next = tmp;
4127       p = tmp;
4128     }
4129   p->next = NULL;
4130   return retval;
4131 }
4132
4133 /* Find the bpstat associated with this breakpoint.  */
4134
4135 bpstat
4136 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4137 {
4138   if (bsp == NULL)
4139     return NULL;
4140
4141   for (; bsp != NULL; bsp = bsp->next)
4142     {
4143       if (bsp->breakpoint_at == breakpoint)
4144         return bsp;
4145     }
4146   return NULL;
4147 }
4148
4149 /* See breakpoint.h.  */
4150
4151 enum bpstat_signal_value
4152 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4153 {
4154   enum bpstat_signal_value result = BPSTAT_SIGNAL_NO;
4155
4156   for (; bsp != NULL; bsp = bsp->next)
4157     {
4158       /* Ensure that, if we ever entered this loop, then we at least
4159          return BPSTAT_SIGNAL_HIDE.  */
4160       enum bpstat_signal_value newval;
4161
4162       if (bsp->breakpoint_at == NULL)
4163         {
4164           /* A moribund location can never explain a signal other than
4165              GDB_SIGNAL_TRAP.  */
4166           if (sig == GDB_SIGNAL_TRAP)
4167             newval = BPSTAT_SIGNAL_HIDE;
4168           else
4169             newval = BPSTAT_SIGNAL_NO;
4170         }
4171       else
4172         newval = bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4173                                                            sig);
4174
4175       if (newval > result)
4176         result = newval;
4177     }
4178
4179   return result;
4180 }
4181
4182 /* Put in *NUM the breakpoint number of the first breakpoint we are
4183    stopped at.  *BSP upon return is a bpstat which points to the
4184    remaining breakpoints stopped at (but which is not guaranteed to be
4185    good for anything but further calls to bpstat_num).
4186
4187    Return 0 if passed a bpstat which does not indicate any breakpoints.
4188    Return -1 if stopped at a breakpoint that has been deleted since
4189    we set it.
4190    Return 1 otherwise.  */
4191
4192 int
4193 bpstat_num (bpstat *bsp, int *num)
4194 {
4195   struct breakpoint *b;
4196
4197   if ((*bsp) == NULL)
4198     return 0;                   /* No more breakpoint values */
4199
4200   /* We assume we'll never have several bpstats that correspond to a
4201      single breakpoint -- otherwise, this function might return the
4202      same number more than once and this will look ugly.  */
4203   b = (*bsp)->breakpoint_at;
4204   *bsp = (*bsp)->next;
4205   if (b == NULL)
4206     return -1;                  /* breakpoint that's been deleted since */
4207
4208   *num = b->number;             /* We have its number */
4209   return 1;
4210 }
4211
4212 /* See breakpoint.h.  */
4213
4214 void
4215 bpstat_clear_actions (void)
4216 {
4217   struct thread_info *tp;
4218   bpstat bs;
4219
4220   if (ptid_equal (inferior_ptid, null_ptid))
4221     return;
4222
4223   tp = find_thread_ptid (inferior_ptid);
4224   if (tp == NULL)
4225     return;
4226
4227   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4228     {
4229       decref_counted_command_line (&bs->commands);
4230
4231       if (bs->old_val != NULL)
4232         {
4233           value_free (bs->old_val);
4234           bs->old_val = NULL;
4235         }
4236     }
4237 }
4238
4239 /* Called when a command is about to proceed the inferior.  */
4240
4241 static void
4242 breakpoint_about_to_proceed (void)
4243 {
4244   if (!ptid_equal (inferior_ptid, null_ptid))
4245     {
4246       struct thread_info *tp = inferior_thread ();
4247
4248       /* Allow inferior function calls in breakpoint commands to not
4249          interrupt the command list.  When the call finishes
4250          successfully, the inferior will be standing at the same
4251          breakpoint as if nothing happened.  */
4252       if (tp->control.in_infcall)
4253         return;
4254     }
4255
4256   breakpoint_proceeded = 1;
4257 }
4258
4259 /* Stub for cleaning up our state if we error-out of a breakpoint
4260    command.  */
4261 static void
4262 cleanup_executing_breakpoints (void *ignore)
4263 {
4264   executing_breakpoint_commands = 0;
4265 }
4266
4267 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4268    or its equivalent.  */
4269
4270 static int
4271 command_line_is_silent (struct command_line *cmd)
4272 {
4273   return cmd && (strcmp ("silent", cmd->line) == 0
4274                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4275 }
4276
4277 /* Execute all the commands associated with all the breakpoints at
4278    this location.  Any of these commands could cause the process to
4279    proceed beyond this point, etc.  We look out for such changes by
4280    checking the global "breakpoint_proceeded" after each command.
4281
4282    Returns true if a breakpoint command resumed the inferior.  In that
4283    case, it is the caller's responsibility to recall it again with the
4284    bpstat of the current thread.  */
4285
4286 static int
4287 bpstat_do_actions_1 (bpstat *bsp)
4288 {
4289   bpstat bs;
4290   struct cleanup *old_chain;
4291   int again = 0;
4292
4293   /* Avoid endless recursion if a `source' command is contained
4294      in bs->commands.  */
4295   if (executing_breakpoint_commands)
4296     return 0;
4297
4298   executing_breakpoint_commands = 1;
4299   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4300
4301   prevent_dont_repeat ();
4302
4303   /* This pointer will iterate over the list of bpstat's.  */
4304   bs = *bsp;
4305
4306   breakpoint_proceeded = 0;
4307   for (; bs != NULL; bs = bs->next)
4308     {
4309       struct counted_command_line *ccmd;
4310       struct command_line *cmd;
4311       struct cleanup *this_cmd_tree_chain;
4312
4313       /* Take ownership of the BSP's command tree, if it has one.
4314
4315          The command tree could legitimately contain commands like
4316          'step' and 'next', which call clear_proceed_status, which
4317          frees stop_bpstat's command tree.  To make sure this doesn't
4318          free the tree we're executing out from under us, we need to
4319          take ownership of the tree ourselves.  Since a given bpstat's
4320          commands are only executed once, we don't need to copy it; we
4321          can clear the pointer in the bpstat, and make sure we free
4322          the tree when we're done.  */
4323       ccmd = bs->commands;
4324       bs->commands = NULL;
4325       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4326       cmd = ccmd ? ccmd->commands : NULL;
4327       if (command_line_is_silent (cmd))
4328         {
4329           /* The action has been already done by bpstat_stop_status.  */
4330           cmd = cmd->next;
4331         }
4332
4333       while (cmd != NULL)
4334         {
4335           execute_control_command (cmd);
4336
4337           if (breakpoint_proceeded)
4338             break;
4339           else
4340             cmd = cmd->next;
4341         }
4342
4343       /* We can free this command tree now.  */
4344       do_cleanups (this_cmd_tree_chain);
4345
4346       if (breakpoint_proceeded)
4347         {
4348           if (target_can_async_p ())
4349             /* If we are in async mode, then the target might be still
4350                running, not stopped at any breakpoint, so nothing for
4351                us to do here -- just return to the event loop.  */
4352             ;
4353           else
4354             /* In sync mode, when execute_control_command returns
4355                we're already standing on the next breakpoint.
4356                Breakpoint commands for that stop were not run, since
4357                execute_command does not run breakpoint commands --
4358                only command_line_handler does, but that one is not
4359                involved in execution of breakpoint commands.  So, we
4360                can now execute breakpoint commands.  It should be
4361                noted that making execute_command do bpstat actions is
4362                not an option -- in this case we'll have recursive
4363                invocation of bpstat for each breakpoint with a
4364                command, and can easily blow up GDB stack.  Instead, we
4365                return true, which will trigger the caller to recall us
4366                with the new stop_bpstat.  */
4367             again = 1;
4368           break;
4369         }
4370     }
4371   do_cleanups (old_chain);
4372   return again;
4373 }
4374
4375 void
4376 bpstat_do_actions (void)
4377 {
4378   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4379
4380   /* Do any commands attached to breakpoint we are stopped at.  */
4381   while (!ptid_equal (inferior_ptid, null_ptid)
4382          && target_has_execution
4383          && !is_exited (inferior_ptid)
4384          && !is_executing (inferior_ptid))
4385     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4386        and only return when it is stopped at the next breakpoint, we
4387        keep doing breakpoint actions until it returns false to
4388        indicate the inferior was not resumed.  */
4389     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4390       break;
4391
4392   discard_cleanups (cleanup_if_error);
4393 }
4394
4395 /* Print out the (old or new) value associated with a watchpoint.  */
4396
4397 static void
4398 watchpoint_value_print (struct value *val, struct ui_file *stream)
4399 {
4400   if (val == NULL)
4401     fprintf_unfiltered (stream, _("<unreadable>"));
4402   else
4403     {
4404       struct value_print_options opts;
4405       get_user_print_options (&opts);
4406       value_print (val, stream, &opts);
4407     }
4408 }
4409
4410 /* Generic routine for printing messages indicating why we
4411    stopped.  The behavior of this function depends on the value
4412    'print_it' in the bpstat structure.  Under some circumstances we
4413    may decide not to print anything here and delegate the task to
4414    normal_stop().  */
4415
4416 static enum print_stop_action
4417 print_bp_stop_message (bpstat bs)
4418 {
4419   switch (bs->print_it)
4420     {
4421     case print_it_noop:
4422       /* Nothing should be printed for this bpstat entry.  */
4423       return PRINT_UNKNOWN;
4424       break;
4425
4426     case print_it_done:
4427       /* We still want to print the frame, but we already printed the
4428          relevant messages.  */
4429       return PRINT_SRC_AND_LOC;
4430       break;
4431
4432     case print_it_normal:
4433       {
4434         struct breakpoint *b = bs->breakpoint_at;
4435
4436         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4437            which has since been deleted.  */
4438         if (b == NULL)
4439           return PRINT_UNKNOWN;
4440
4441         /* Normal case.  Call the breakpoint's print_it method.  */
4442         return b->ops->print_it (bs);
4443       }
4444       break;
4445
4446     default:
4447       internal_error (__FILE__, __LINE__,
4448                       _("print_bp_stop_message: unrecognized enum value"));
4449       break;
4450     }
4451 }
4452
4453 /* A helper function that prints a shared library stopped event.  */
4454
4455 static void
4456 print_solib_event (int is_catchpoint)
4457 {
4458   int any_deleted
4459     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4460   int any_added
4461     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4462
4463   if (!is_catchpoint)
4464     {
4465       if (any_added || any_deleted)
4466         ui_out_text (current_uiout,
4467                      _("Stopped due to shared library event:\n"));
4468       else
4469         ui_out_text (current_uiout,
4470                      _("Stopped due to shared library event (no "
4471                        "libraries added or removed)\n"));
4472     }
4473
4474   if (ui_out_is_mi_like_p (current_uiout))
4475     ui_out_field_string (current_uiout, "reason",
4476                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4477
4478   if (any_deleted)
4479     {
4480       struct cleanup *cleanup;
4481       char *name;
4482       int ix;
4483
4484       ui_out_text (current_uiout, _("  Inferior unloaded "));
4485       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4486                                                     "removed");
4487       for (ix = 0;
4488            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4489                         ix, name);
4490            ++ix)
4491         {
4492           if (ix > 0)
4493             ui_out_text (current_uiout, "    ");
4494           ui_out_field_string (current_uiout, "library", name);
4495           ui_out_text (current_uiout, "\n");
4496         }
4497
4498       do_cleanups (cleanup);
4499     }
4500
4501   if (any_added)
4502     {
4503       struct so_list *iter;
4504       int ix;
4505       struct cleanup *cleanup;
4506
4507       ui_out_text (current_uiout, _("  Inferior loaded "));
4508       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4509                                                     "added");
4510       for (ix = 0;
4511            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4512                         ix, iter);
4513            ++ix)
4514         {
4515           if (ix > 0)
4516             ui_out_text (current_uiout, "    ");
4517           ui_out_field_string (current_uiout, "library", iter->so_name);
4518           ui_out_text (current_uiout, "\n");
4519         }
4520
4521       do_cleanups (cleanup);
4522     }
4523 }
4524
4525 /* Print a message indicating what happened.  This is called from
4526    normal_stop().  The input to this routine is the head of the bpstat
4527    list - a list of the eventpoints that caused this stop.  KIND is
4528    the target_waitkind for the stopping event.  This
4529    routine calls the generic print routine for printing a message
4530    about reasons for stopping.  This will print (for example) the
4531    "Breakpoint n," part of the output.  The return value of this
4532    routine is one of:
4533
4534    PRINT_UNKNOWN: Means we printed nothing.
4535    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4536    code to print the location.  An example is 
4537    "Breakpoint 1, " which should be followed by
4538    the location.
4539    PRINT_SRC_ONLY: Means we printed something, but there is no need
4540    to also print the location part of the message.
4541    An example is the catch/throw messages, which
4542    don't require a location appended to the end.
4543    PRINT_NOTHING: We have done some printing and we don't need any 
4544    further info to be printed.  */
4545
4546 enum print_stop_action
4547 bpstat_print (bpstat bs, int kind)
4548 {
4549   int val;
4550
4551   /* Maybe another breakpoint in the chain caused us to stop.
4552      (Currently all watchpoints go on the bpstat whether hit or not.
4553      That probably could (should) be changed, provided care is taken
4554      with respect to bpstat_explains_signal).  */
4555   for (; bs; bs = bs->next)
4556     {
4557       val = print_bp_stop_message (bs);
4558       if (val == PRINT_SRC_ONLY 
4559           || val == PRINT_SRC_AND_LOC 
4560           || val == PRINT_NOTHING)
4561         return val;
4562     }
4563
4564   /* If we had hit a shared library event breakpoint,
4565      print_bp_stop_message would print out this message.  If we hit an
4566      OS-level shared library event, do the same thing.  */
4567   if (kind == TARGET_WAITKIND_LOADED)
4568     {
4569       print_solib_event (0);
4570       return PRINT_NOTHING;
4571     }
4572
4573   /* We reached the end of the chain, or we got a null BS to start
4574      with and nothing was printed.  */
4575   return PRINT_UNKNOWN;
4576 }
4577
4578 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4579    used inside a catch_errors to evaluate the breakpoint condition.
4580    The argument is a "struct expression *" that has been cast to a
4581    "char *" to make it pass through catch_errors.  */
4582
4583 static int
4584 breakpoint_cond_eval (void *exp)
4585 {
4586   struct value *mark = value_mark ();
4587   int i = !value_true (evaluate_expression ((struct expression *) exp));
4588
4589   value_free_to_mark (mark);
4590   return i;
4591 }
4592
4593 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4594
4595 static bpstat
4596 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4597 {
4598   bpstat bs;
4599
4600   bs = (bpstat) xmalloc (sizeof (*bs));
4601   bs->next = NULL;
4602   **bs_link_pointer = bs;
4603   *bs_link_pointer = &bs->next;
4604   bs->breakpoint_at = bl->owner;
4605   bs->bp_location_at = bl;
4606   incref_bp_location (bl);
4607   /* If the condition is false, etc., don't do the commands.  */
4608   bs->commands = NULL;
4609   bs->old_val = NULL;
4610   bs->print_it = print_it_normal;
4611   return bs;
4612 }
4613 \f
4614 /* The target has stopped with waitstatus WS.  Check if any hardware
4615    watchpoints have triggered, according to the target.  */
4616
4617 int
4618 watchpoints_triggered (struct target_waitstatus *ws)
4619 {
4620   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4621   CORE_ADDR addr;
4622   struct breakpoint *b;
4623
4624   if (!stopped_by_watchpoint)
4625     {
4626       /* We were not stopped by a watchpoint.  Mark all watchpoints
4627          as not triggered.  */
4628       ALL_BREAKPOINTS (b)
4629         if (is_hardware_watchpoint (b))
4630           {
4631             struct watchpoint *w = (struct watchpoint *) b;
4632
4633             w->watchpoint_triggered = watch_triggered_no;
4634           }
4635
4636       return 0;
4637     }
4638
4639   if (!target_stopped_data_address (&current_target, &addr))
4640     {
4641       /* We were stopped by a watchpoint, but we don't know where.
4642          Mark all watchpoints as unknown.  */
4643       ALL_BREAKPOINTS (b)
4644         if (is_hardware_watchpoint (b))
4645           {
4646             struct watchpoint *w = (struct watchpoint *) b;
4647
4648             w->watchpoint_triggered = watch_triggered_unknown;
4649           }
4650
4651       return stopped_by_watchpoint;
4652     }
4653
4654   /* The target could report the data address.  Mark watchpoints
4655      affected by this data address as triggered, and all others as not
4656      triggered.  */
4657
4658   ALL_BREAKPOINTS (b)
4659     if (is_hardware_watchpoint (b))
4660       {
4661         struct watchpoint *w = (struct watchpoint *) b;
4662         struct bp_location *loc;
4663
4664         w->watchpoint_triggered = watch_triggered_no;
4665         for (loc = b->loc; loc; loc = loc->next)
4666           {
4667             if (is_masked_watchpoint (b))
4668               {
4669                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4670                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4671
4672                 if (newaddr == start)
4673                   {
4674                     w->watchpoint_triggered = watch_triggered_yes;
4675                     break;
4676                   }
4677               }
4678             /* Exact match not required.  Within range is sufficient.  */
4679             else if (target_watchpoint_addr_within_range (&current_target,
4680                                                          addr, loc->address,
4681                                                          loc->length))
4682               {
4683                 w->watchpoint_triggered = watch_triggered_yes;
4684                 break;
4685               }
4686           }
4687       }
4688
4689   return 1;
4690 }
4691
4692 /* Possible return values for watchpoint_check (this can't be an enum
4693    because of check_errors).  */
4694 /* The watchpoint has been deleted.  */
4695 #define WP_DELETED 1
4696 /* The value has changed.  */
4697 #define WP_VALUE_CHANGED 2
4698 /* The value has not changed.  */
4699 #define WP_VALUE_NOT_CHANGED 3
4700 /* Ignore this watchpoint, no matter if the value changed or not.  */
4701 #define WP_IGNORE 4
4702
4703 #define BP_TEMPFLAG 1
4704 #define BP_HARDWAREFLAG 2
4705
4706 /* Evaluate watchpoint condition expression and check if its value
4707    changed.
4708
4709    P should be a pointer to struct bpstat, but is defined as a void *
4710    in order for this function to be usable with catch_errors.  */
4711
4712 static int
4713 watchpoint_check (void *p)
4714 {
4715   bpstat bs = (bpstat) p;
4716   struct watchpoint *b;
4717   struct frame_info *fr;
4718   int within_current_scope;
4719
4720   /* BS is built from an existing struct breakpoint.  */
4721   gdb_assert (bs->breakpoint_at != NULL);
4722   b = (struct watchpoint *) bs->breakpoint_at;
4723
4724   /* If this is a local watchpoint, we only want to check if the
4725      watchpoint frame is in scope if the current thread is the thread
4726      that was used to create the watchpoint.  */
4727   if (!watchpoint_in_thread_scope (b))
4728     return WP_IGNORE;
4729
4730   if (b->exp_valid_block == NULL)
4731     within_current_scope = 1;
4732   else
4733     {
4734       struct frame_info *frame = get_current_frame ();
4735       struct gdbarch *frame_arch = get_frame_arch (frame);
4736       CORE_ADDR frame_pc = get_frame_pc (frame);
4737
4738       /* in_function_epilogue_p() returns a non-zero value if we're
4739          still in the function but the stack frame has already been
4740          invalidated.  Since we can't rely on the values of local
4741          variables after the stack has been destroyed, we are treating
4742          the watchpoint in that state as `not changed' without further
4743          checking.  Don't mark watchpoints as changed if the current
4744          frame is in an epilogue - even if they are in some other
4745          frame, our view of the stack is likely to be wrong and
4746          frame_find_by_id could error out.  */
4747       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4748         return WP_IGNORE;
4749
4750       fr = frame_find_by_id (b->watchpoint_frame);
4751       within_current_scope = (fr != NULL);
4752
4753       /* If we've gotten confused in the unwinder, we might have
4754          returned a frame that can't describe this variable.  */
4755       if (within_current_scope)
4756         {
4757           struct symbol *function;
4758
4759           function = get_frame_function (fr);
4760           if (function == NULL
4761               || !contained_in (b->exp_valid_block,
4762                                 SYMBOL_BLOCK_VALUE (function)))
4763             within_current_scope = 0;
4764         }
4765
4766       if (within_current_scope)
4767         /* If we end up stopping, the current frame will get selected
4768            in normal_stop.  So this call to select_frame won't affect
4769            the user.  */
4770         select_frame (fr);
4771     }
4772
4773   if (within_current_scope)
4774     {
4775       /* We use value_{,free_to_}mark because it could be a *long*
4776          time before we return to the command level and call
4777          free_all_values.  We can't call free_all_values because we
4778          might be in the middle of evaluating a function call.  */
4779
4780       int pc = 0;
4781       struct value *mark;
4782       struct value *new_val;
4783
4784       if (is_masked_watchpoint (&b->base))
4785         /* Since we don't know the exact trigger address (from
4786            stopped_data_address), just tell the user we've triggered
4787            a mask watchpoint.  */
4788         return WP_VALUE_CHANGED;
4789
4790       mark = value_mark ();
4791       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4792
4793       /* We use value_equal_contents instead of value_equal because
4794          the latter coerces an array to a pointer, thus comparing just
4795          the address of the array instead of its contents.  This is
4796          not what we want.  */
4797       if ((b->val != NULL) != (new_val != NULL)
4798           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4799         {
4800           if (new_val != NULL)
4801             {
4802               release_value (new_val);
4803               value_free_to_mark (mark);
4804             }
4805           bs->old_val = b->val;
4806           b->val = new_val;
4807           b->val_valid = 1;
4808           return WP_VALUE_CHANGED;
4809         }
4810       else
4811         {
4812           /* Nothing changed.  */
4813           value_free_to_mark (mark);
4814           return WP_VALUE_NOT_CHANGED;
4815         }
4816     }
4817   else
4818     {
4819       struct ui_out *uiout = current_uiout;
4820
4821       /* This seems like the only logical thing to do because
4822          if we temporarily ignored the watchpoint, then when
4823          we reenter the block in which it is valid it contains
4824          garbage (in the case of a function, it may have two
4825          garbage values, one before and one after the prologue).
4826          So we can't even detect the first assignment to it and
4827          watch after that (since the garbage may or may not equal
4828          the first value assigned).  */
4829       /* We print all the stop information in
4830          breakpoint_ops->print_it, but in this case, by the time we
4831          call breakpoint_ops->print_it this bp will be deleted
4832          already.  So we have no choice but print the information
4833          here.  */
4834       if (ui_out_is_mi_like_p (uiout))
4835         ui_out_field_string
4836           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4837       ui_out_text (uiout, "\nWatchpoint ");
4838       ui_out_field_int (uiout, "wpnum", b->base.number);
4839       ui_out_text (uiout,
4840                    " deleted because the program has left the block in\n\
4841 which its expression is valid.\n");     
4842
4843       /* Make sure the watchpoint's commands aren't executed.  */
4844       decref_counted_command_line (&b->base.commands);
4845       watchpoint_del_at_next_stop (b);
4846
4847       return WP_DELETED;
4848     }
4849 }
4850
4851 /* Return true if it looks like target has stopped due to hitting
4852    breakpoint location BL.  This function does not check if we should
4853    stop, only if BL explains the stop.  */
4854
4855 static int
4856 bpstat_check_location (const struct bp_location *bl,
4857                        struct address_space *aspace, CORE_ADDR bp_addr,
4858                        const struct target_waitstatus *ws)
4859 {
4860   struct breakpoint *b = bl->owner;
4861
4862   /* BL is from an existing breakpoint.  */
4863   gdb_assert (b != NULL);
4864
4865   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4866 }
4867
4868 /* Determine if the watched values have actually changed, and we
4869    should stop.  If not, set BS->stop to 0.  */
4870
4871 static void
4872 bpstat_check_watchpoint (bpstat bs)
4873 {
4874   const struct bp_location *bl;
4875   struct watchpoint *b;
4876
4877   /* BS is built for existing struct breakpoint.  */
4878   bl = bs->bp_location_at;
4879   gdb_assert (bl != NULL);
4880   b = (struct watchpoint *) bs->breakpoint_at;
4881   gdb_assert (b != NULL);
4882
4883     {
4884       int must_check_value = 0;
4885       
4886       if (b->base.type == bp_watchpoint)
4887         /* For a software watchpoint, we must always check the
4888            watched value.  */
4889         must_check_value = 1;
4890       else if (b->watchpoint_triggered == watch_triggered_yes)
4891         /* We have a hardware watchpoint (read, write, or access)
4892            and the target earlier reported an address watched by
4893            this watchpoint.  */
4894         must_check_value = 1;
4895       else if (b->watchpoint_triggered == watch_triggered_unknown
4896                && b->base.type == bp_hardware_watchpoint)
4897         /* We were stopped by a hardware watchpoint, but the target could
4898            not report the data address.  We must check the watchpoint's
4899            value.  Access and read watchpoints are out of luck; without
4900            a data address, we can't figure it out.  */
4901         must_check_value = 1;
4902
4903       if (must_check_value)
4904         {
4905           char *message
4906             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4907                           b->base.number);
4908           struct cleanup *cleanups = make_cleanup (xfree, message);
4909           int e = catch_errors (watchpoint_check, bs, message,
4910                                 RETURN_MASK_ALL);
4911           do_cleanups (cleanups);
4912           switch (e)
4913             {
4914             case WP_DELETED:
4915               /* We've already printed what needs to be printed.  */
4916               bs->print_it = print_it_done;
4917               /* Stop.  */
4918               break;
4919             case WP_IGNORE:
4920               bs->print_it = print_it_noop;
4921               bs->stop = 0;
4922               break;
4923             case WP_VALUE_CHANGED:
4924               if (b->base.type == bp_read_watchpoint)
4925                 {
4926                   /* There are two cases to consider here:
4927
4928                      1. We're watching the triggered memory for reads.
4929                      In that case, trust the target, and always report
4930                      the watchpoint hit to the user.  Even though
4931                      reads don't cause value changes, the value may
4932                      have changed since the last time it was read, and
4933                      since we're not trapping writes, we will not see
4934                      those, and as such we should ignore our notion of
4935                      old value.
4936
4937                      2. We're watching the triggered memory for both
4938                      reads and writes.  There are two ways this may
4939                      happen:
4940
4941                      2.1. This is a target that can't break on data
4942                      reads only, but can break on accesses (reads or
4943                      writes), such as e.g., x86.  We detect this case
4944                      at the time we try to insert read watchpoints.
4945
4946                      2.2. Otherwise, the target supports read
4947                      watchpoints, but, the user set an access or write
4948                      watchpoint watching the same memory as this read
4949                      watchpoint.
4950
4951                      If we're watching memory writes as well as reads,
4952                      ignore watchpoint hits when we find that the
4953                      value hasn't changed, as reads don't cause
4954                      changes.  This still gives false positives when
4955                      the program writes the same value to memory as
4956                      what there was already in memory (we will confuse
4957                      it for a read), but it's much better than
4958                      nothing.  */
4959
4960                   int other_write_watchpoint = 0;
4961
4962                   if (bl->watchpoint_type == hw_read)
4963                     {
4964                       struct breakpoint *other_b;
4965
4966                       ALL_BREAKPOINTS (other_b)
4967                         if (other_b->type == bp_hardware_watchpoint
4968                             || other_b->type == bp_access_watchpoint)
4969                           {
4970                             struct watchpoint *other_w =
4971                               (struct watchpoint *) other_b;
4972
4973                             if (other_w->watchpoint_triggered
4974                                 == watch_triggered_yes)
4975                               {
4976                                 other_write_watchpoint = 1;
4977                                 break;
4978                               }
4979                           }
4980                     }
4981
4982                   if (other_write_watchpoint
4983                       || bl->watchpoint_type == hw_access)
4984                     {
4985                       /* We're watching the same memory for writes,
4986                          and the value changed since the last time we
4987                          updated it, so this trap must be for a write.
4988                          Ignore it.  */
4989                       bs->print_it = print_it_noop;
4990                       bs->stop = 0;
4991                     }
4992                 }
4993               break;
4994             case WP_VALUE_NOT_CHANGED:
4995               if (b->base.type == bp_hardware_watchpoint
4996                   || b->base.type == bp_watchpoint)
4997                 {
4998                   /* Don't stop: write watchpoints shouldn't fire if
4999                      the value hasn't changed.  */
5000                   bs->print_it = print_it_noop;
5001                   bs->stop = 0;
5002                 }
5003               /* Stop.  */
5004               break;
5005             default:
5006               /* Can't happen.  */
5007             case 0:
5008               /* Error from catch_errors.  */
5009               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5010               watchpoint_del_at_next_stop (b);
5011               /* We've already printed what needs to be printed.  */
5012               bs->print_it = print_it_done;
5013               break;
5014             }
5015         }
5016       else      /* must_check_value == 0 */
5017         {
5018           /* This is a case where some watchpoint(s) triggered, but
5019              not at the address of this watchpoint, or else no
5020              watchpoint triggered after all.  So don't print
5021              anything for this watchpoint.  */
5022           bs->print_it = print_it_noop;
5023           bs->stop = 0;
5024         }
5025     }
5026 }
5027
5028
5029 /* Check conditions (condition proper, frame, thread and ignore count)
5030    of breakpoint referred to by BS.  If we should not stop for this
5031    breakpoint, set BS->stop to 0.  */
5032
5033 static void
5034 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5035 {
5036   int thread_id = pid_to_thread_id (ptid);
5037   const struct bp_location *bl;
5038   struct breakpoint *b;
5039
5040   /* BS is built for existing struct breakpoint.  */
5041   bl = bs->bp_location_at;
5042   gdb_assert (bl != NULL);
5043   b = bs->breakpoint_at;
5044   gdb_assert (b != NULL);
5045
5046   /* Even if the target evaluated the condition on its end and notified GDB, we
5047      need to do so again since GDB does not know if we stopped due to a
5048      breakpoint or a single step breakpoint.  */
5049
5050   if (frame_id_p (b->frame_id)
5051       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5052     bs->stop = 0;
5053   else if (bs->stop)
5054     {
5055       int value_is_zero = 0;
5056       struct expression *cond;
5057
5058       /* Evaluate Python breakpoints that have a "stop"
5059          method implemented.  */
5060       if (b->py_bp_object)
5061         bs->stop = gdbpy_should_stop (b->py_bp_object);
5062
5063       if (is_watchpoint (b))
5064         {
5065           struct watchpoint *w = (struct watchpoint *) b;
5066
5067           cond = w->cond_exp;
5068         }
5069       else
5070         cond = bl->cond;
5071
5072       if (cond && b->disposition != disp_del_at_next_stop)
5073         {
5074           int within_current_scope = 1;
5075           struct watchpoint * w;
5076
5077           /* We use value_mark and value_free_to_mark because it could
5078              be a long time before we return to the command level and
5079              call free_all_values.  We can't call free_all_values
5080              because we might be in the middle of evaluating a
5081              function call.  */
5082           struct value *mark = value_mark ();
5083
5084           if (is_watchpoint (b))
5085             w = (struct watchpoint *) b;
5086           else
5087             w = NULL;
5088
5089           /* Need to select the frame, with all that implies so that
5090              the conditions will have the right context.  Because we
5091              use the frame, we will not see an inlined function's
5092              variables when we arrive at a breakpoint at the start
5093              of the inlined function; the current frame will be the
5094              call site.  */
5095           if (w == NULL || w->cond_exp_valid_block == NULL)
5096             select_frame (get_current_frame ());
5097           else
5098             {
5099               struct frame_info *frame;
5100
5101               /* For local watchpoint expressions, which particular
5102                  instance of a local is being watched matters, so we
5103                  keep track of the frame to evaluate the expression
5104                  in.  To evaluate the condition however, it doesn't
5105                  really matter which instantiation of the function
5106                  where the condition makes sense triggers the
5107                  watchpoint.  This allows an expression like "watch
5108                  global if q > 10" set in `func', catch writes to
5109                  global on all threads that call `func', or catch
5110                  writes on all recursive calls of `func' by a single
5111                  thread.  We simply always evaluate the condition in
5112                  the innermost frame that's executing where it makes
5113                  sense to evaluate the condition.  It seems
5114                  intuitive.  */
5115               frame = block_innermost_frame (w->cond_exp_valid_block);
5116               if (frame != NULL)
5117                 select_frame (frame);
5118               else
5119                 within_current_scope = 0;
5120             }
5121           if (within_current_scope)
5122             value_is_zero
5123               = catch_errors (breakpoint_cond_eval, cond,
5124                               "Error in testing breakpoint condition:\n",
5125                               RETURN_MASK_ALL);
5126           else
5127             {
5128               warning (_("Watchpoint condition cannot be tested "
5129                          "in the current scope"));
5130               /* If we failed to set the right context for this
5131                  watchpoint, unconditionally report it.  */
5132               value_is_zero = 0;
5133             }
5134           /* FIXME-someday, should give breakpoint #.  */
5135           value_free_to_mark (mark);
5136         }
5137
5138       if (cond && value_is_zero)
5139         {
5140           bs->stop = 0;
5141         }
5142       else if (b->thread != -1 && b->thread != thread_id)
5143         {
5144           bs->stop = 0;
5145         }
5146       else if (b->ignore_count > 0)
5147         {
5148           b->ignore_count--;
5149           bs->stop = 0;
5150           /* Increase the hit count even though we don't stop.  */
5151           ++(b->hit_count);
5152           observer_notify_breakpoint_modified (b);
5153         }       
5154     }
5155 }
5156
5157
5158 /* Get a bpstat associated with having just stopped at address
5159    BP_ADDR in thread PTID.
5160
5161    Determine whether we stopped at a breakpoint, etc, or whether we
5162    don't understand this stop.  Result is a chain of bpstat's such
5163    that:
5164
5165    if we don't understand the stop, the result is a null pointer.
5166
5167    if we understand why we stopped, the result is not null.
5168
5169    Each element of the chain refers to a particular breakpoint or
5170    watchpoint at which we have stopped.  (We may have stopped for
5171    several reasons concurrently.)
5172
5173    Each element of the chain has valid next, breakpoint_at,
5174    commands, FIXME??? fields.  */
5175
5176 bpstat
5177 bpstat_stop_status (struct address_space *aspace,
5178                     CORE_ADDR bp_addr, ptid_t ptid,
5179                     const struct target_waitstatus *ws)
5180 {
5181   struct breakpoint *b = NULL;
5182   struct bp_location *bl;
5183   struct bp_location *loc;
5184   /* First item of allocated bpstat's.  */
5185   bpstat bs_head = NULL, *bs_link = &bs_head;
5186   /* Pointer to the last thing in the chain currently.  */
5187   bpstat bs;
5188   int ix;
5189   int need_remove_insert;
5190   int removed_any;
5191
5192   /* First, build the bpstat chain with locations that explain a
5193      target stop, while being careful to not set the target running,
5194      as that may invalidate locations (in particular watchpoint
5195      locations are recreated).  Resuming will happen here with
5196      breakpoint conditions or watchpoint expressions that include
5197      inferior function calls.  */
5198
5199   ALL_BREAKPOINTS (b)
5200     {
5201       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5202         continue;
5203
5204       for (bl = b->loc; bl != NULL; bl = bl->next)
5205         {
5206           /* For hardware watchpoints, we look only at the first
5207              location.  The watchpoint_check function will work on the
5208              entire expression, not the individual locations.  For
5209              read watchpoints, the watchpoints_triggered function has
5210              checked all locations already.  */
5211           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5212             break;
5213
5214           if (!bl->enabled || bl->shlib_disabled)
5215             continue;
5216
5217           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5218             continue;
5219
5220           /* Come here if it's a watchpoint, or if the break address
5221              matches.  */
5222
5223           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5224                                                    explain stop.  */
5225
5226           /* Assume we stop.  Should we find a watchpoint that is not
5227              actually triggered, or if the condition of the breakpoint
5228              evaluates as false, we'll reset 'stop' to 0.  */
5229           bs->stop = 1;
5230           bs->print = 1;
5231
5232           /* If this is a scope breakpoint, mark the associated
5233              watchpoint as triggered so that we will handle the
5234              out-of-scope event.  We'll get to the watchpoint next
5235              iteration.  */
5236           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5237             {
5238               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5239
5240               w->watchpoint_triggered = watch_triggered_yes;
5241             }
5242         }
5243     }
5244
5245   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5246     {
5247       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5248         {
5249           bs = bpstat_alloc (loc, &bs_link);
5250           /* For hits of moribund locations, we should just proceed.  */
5251           bs->stop = 0;
5252           bs->print = 0;
5253           bs->print_it = print_it_noop;
5254         }
5255     }
5256
5257   /* A bit of special processing for shlib breakpoints.  We need to
5258      process solib loading here, so that the lists of loaded and
5259      unloaded libraries are correct before we handle "catch load" and
5260      "catch unload".  */
5261   for (bs = bs_head; bs != NULL; bs = bs->next)
5262     {
5263       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5264         {
5265           handle_solib_event ();
5266           break;
5267         }
5268     }
5269
5270   /* Now go through the locations that caused the target to stop, and
5271      check whether we're interested in reporting this stop to higher
5272      layers, or whether we should resume the target transparently.  */
5273
5274   removed_any = 0;
5275
5276   for (bs = bs_head; bs != NULL; bs = bs->next)
5277     {
5278       if (!bs->stop)
5279         continue;
5280
5281       b = bs->breakpoint_at;
5282       b->ops->check_status (bs);
5283       if (bs->stop)
5284         {
5285           bpstat_check_breakpoint_conditions (bs, ptid);
5286
5287           if (bs->stop)
5288             {
5289               ++(b->hit_count);
5290               observer_notify_breakpoint_modified (b);
5291
5292               /* We will stop here.  */
5293               if (b->disposition == disp_disable)
5294                 {
5295                   --(b->enable_count);
5296                   if (b->enable_count <= 0
5297                       && b->enable_state != bp_permanent)
5298                     b->enable_state = bp_disabled;
5299                   removed_any = 1;
5300                 }
5301               if (b->silent)
5302                 bs->print = 0;
5303               bs->commands = b->commands;
5304               incref_counted_command_line (bs->commands);
5305               if (command_line_is_silent (bs->commands
5306                                           ? bs->commands->commands : NULL))
5307                 bs->print = 0;
5308
5309               b->ops->after_condition_true (bs);
5310             }
5311
5312         }
5313
5314       /* Print nothing for this entry if we don't stop or don't
5315          print.  */
5316       if (!bs->stop || !bs->print)
5317         bs->print_it = print_it_noop;
5318     }
5319
5320   /* If we aren't stopping, the value of some hardware watchpoint may
5321      not have changed, but the intermediate memory locations we are
5322      watching may have.  Don't bother if we're stopping; this will get
5323      done later.  */
5324   need_remove_insert = 0;
5325   if (! bpstat_causes_stop (bs_head))
5326     for (bs = bs_head; bs != NULL; bs = bs->next)
5327       if (!bs->stop
5328           && bs->breakpoint_at
5329           && is_hardware_watchpoint (bs->breakpoint_at))
5330         {
5331           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5332
5333           update_watchpoint (w, 0 /* don't reparse.  */);
5334           need_remove_insert = 1;
5335         }
5336
5337   if (need_remove_insert)
5338     update_global_location_list (1);
5339   else if (removed_any)
5340     update_global_location_list (0);
5341
5342   return bs_head;
5343 }
5344
5345 static void
5346 handle_jit_event (void)
5347 {
5348   struct frame_info *frame;
5349   struct gdbarch *gdbarch;
5350
5351   /* Switch terminal for any messages produced by
5352      breakpoint_re_set.  */
5353   target_terminal_ours_for_output ();
5354
5355   frame = get_current_frame ();
5356   gdbarch = get_frame_arch (frame);
5357
5358   jit_event_handler (gdbarch);
5359
5360   target_terminal_inferior ();
5361 }
5362
5363 /* Handle an solib event by calling solib_add.  */
5364
5365 void
5366 handle_solib_event (void)
5367 {
5368   clear_program_space_solib_cache (current_inferior ()->pspace);
5369
5370   /* Check for any newly added shared libraries if we're supposed to
5371      be adding them automatically.  Switch terminal for any messages
5372      produced by breakpoint_re_set.  */
5373   target_terminal_ours_for_output ();
5374 #ifdef SOLIB_ADD
5375   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
5376 #else
5377   solib_add (NULL, 0, &current_target, auto_solib_add);
5378 #endif
5379   target_terminal_inferior ();
5380 }
5381
5382 /* Prepare WHAT final decision for infrun.  */
5383
5384 /* Decide what infrun needs to do with this bpstat.  */
5385
5386 struct bpstat_what
5387 bpstat_what (bpstat bs_head)
5388 {
5389   struct bpstat_what retval;
5390   int jit_event = 0;
5391   bpstat bs;
5392
5393   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5394   retval.call_dummy = STOP_NONE;
5395   retval.is_longjmp = 0;
5396
5397   for (bs = bs_head; bs != NULL; bs = bs->next)
5398     {
5399       /* Extract this BS's action.  After processing each BS, we check
5400          if its action overrides all we've seem so far.  */
5401       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5402       enum bptype bptype;
5403
5404       if (bs->breakpoint_at == NULL)
5405         {
5406           /* I suspect this can happen if it was a momentary
5407              breakpoint which has since been deleted.  */
5408           bptype = bp_none;
5409         }
5410       else
5411         bptype = bs->breakpoint_at->type;
5412
5413       switch (bptype)
5414         {
5415         case bp_none:
5416           break;
5417         case bp_breakpoint:
5418         case bp_hardware_breakpoint:
5419         case bp_until:
5420         case bp_finish:
5421         case bp_shlib_event:
5422           if (bs->stop)
5423             {
5424               if (bs->print)
5425                 this_action = BPSTAT_WHAT_STOP_NOISY;
5426               else
5427                 this_action = BPSTAT_WHAT_STOP_SILENT;
5428             }
5429           else
5430             this_action = BPSTAT_WHAT_SINGLE;
5431           break;
5432         case bp_watchpoint:
5433         case bp_hardware_watchpoint:
5434         case bp_read_watchpoint:
5435         case bp_access_watchpoint:
5436           if (bs->stop)
5437             {
5438               if (bs->print)
5439                 this_action = BPSTAT_WHAT_STOP_NOISY;
5440               else
5441                 this_action = BPSTAT_WHAT_STOP_SILENT;
5442             }
5443           else
5444             {
5445               /* There was a watchpoint, but we're not stopping.
5446                  This requires no further action.  */
5447             }
5448           break;
5449         case bp_longjmp:
5450         case bp_longjmp_call_dummy:
5451         case bp_exception:
5452           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5453           retval.is_longjmp = bptype != bp_exception;
5454           break;
5455         case bp_longjmp_resume:
5456         case bp_exception_resume:
5457           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5458           retval.is_longjmp = bptype == bp_longjmp_resume;
5459           break;
5460         case bp_step_resume:
5461           if (bs->stop)
5462             this_action = BPSTAT_WHAT_STEP_RESUME;
5463           else
5464             {
5465               /* It is for the wrong frame.  */
5466               this_action = BPSTAT_WHAT_SINGLE;
5467             }
5468           break;
5469         case bp_hp_step_resume:
5470           if (bs->stop)
5471             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5472           else
5473             {
5474               /* It is for the wrong frame.  */
5475               this_action = BPSTAT_WHAT_SINGLE;
5476             }
5477           break;
5478         case bp_watchpoint_scope:
5479         case bp_thread_event:
5480         case bp_overlay_event:
5481         case bp_longjmp_master:
5482         case bp_std_terminate_master:
5483         case bp_exception_master:
5484           this_action = BPSTAT_WHAT_SINGLE;
5485           break;
5486         case bp_catchpoint:
5487           if (bs->stop)
5488             {
5489               if (bs->print)
5490                 this_action = BPSTAT_WHAT_STOP_NOISY;
5491               else
5492                 this_action = BPSTAT_WHAT_STOP_SILENT;
5493             }
5494           else
5495             {
5496               /* There was a catchpoint, but we're not stopping.
5497                  This requires no further action.  */
5498             }
5499           break;
5500         case bp_jit_event:
5501           jit_event = 1;
5502           this_action = BPSTAT_WHAT_SINGLE;
5503           break;
5504         case bp_call_dummy:
5505           /* Make sure the action is stop (silent or noisy),
5506              so infrun.c pops the dummy frame.  */
5507           retval.call_dummy = STOP_STACK_DUMMY;
5508           this_action = BPSTAT_WHAT_STOP_SILENT;
5509           break;
5510         case bp_std_terminate:
5511           /* Make sure the action is stop (silent or noisy),
5512              so infrun.c pops the dummy frame.  */
5513           retval.call_dummy = STOP_STD_TERMINATE;
5514           this_action = BPSTAT_WHAT_STOP_SILENT;
5515           break;
5516         case bp_tracepoint:
5517         case bp_fast_tracepoint:
5518         case bp_static_tracepoint:
5519           /* Tracepoint hits should not be reported back to GDB, and
5520              if one got through somehow, it should have been filtered
5521              out already.  */
5522           internal_error (__FILE__, __LINE__,
5523                           _("bpstat_what: tracepoint encountered"));
5524           break;
5525         case bp_gnu_ifunc_resolver:
5526           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5527           this_action = BPSTAT_WHAT_SINGLE;
5528           break;
5529         case bp_gnu_ifunc_resolver_return:
5530           /* The breakpoint will be removed, execution will restart from the
5531              PC of the former breakpoint.  */
5532           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5533           break;
5534
5535         case bp_dprintf:
5536           if (bs->stop)
5537             this_action = BPSTAT_WHAT_STOP_SILENT;
5538           else
5539             this_action = BPSTAT_WHAT_SINGLE;
5540           break;
5541
5542         default:
5543           internal_error (__FILE__, __LINE__,
5544                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5545         }
5546
5547       retval.main_action = max (retval.main_action, this_action);
5548     }
5549
5550   /* These operations may affect the bs->breakpoint_at state so they are
5551      delayed after MAIN_ACTION is decided above.  */
5552
5553   if (jit_event)
5554     {
5555       if (debug_infrun)
5556         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5557
5558       handle_jit_event ();
5559     }
5560
5561   for (bs = bs_head; bs != NULL; bs = bs->next)
5562     {
5563       struct breakpoint *b = bs->breakpoint_at;
5564
5565       if (b == NULL)
5566         continue;
5567       switch (b->type)
5568         {
5569         case bp_gnu_ifunc_resolver:
5570           gnu_ifunc_resolver_stop (b);
5571           break;
5572         case bp_gnu_ifunc_resolver_return:
5573           gnu_ifunc_resolver_return_stop (b);
5574           break;
5575         }
5576     }
5577
5578   return retval;
5579 }
5580
5581 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5582    without hardware support).  This isn't related to a specific bpstat,
5583    just to things like whether watchpoints are set.  */
5584
5585 int
5586 bpstat_should_step (void)
5587 {
5588   struct breakpoint *b;
5589
5590   ALL_BREAKPOINTS (b)
5591     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5592       return 1;
5593   return 0;
5594 }
5595
5596 int
5597 bpstat_causes_stop (bpstat bs)
5598 {
5599   for (; bs != NULL; bs = bs->next)
5600     if (bs->stop)
5601       return 1;
5602
5603   return 0;
5604 }
5605
5606 \f
5607
5608 /* Compute a string of spaces suitable to indent the next line
5609    so it starts at the position corresponding to the table column
5610    named COL_NAME in the currently active table of UIOUT.  */
5611
5612 static char *
5613 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5614 {
5615   static char wrap_indent[80];
5616   int i, total_width, width, align;
5617   char *text;
5618
5619   total_width = 0;
5620   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5621     {
5622       if (strcmp (text, col_name) == 0)
5623         {
5624           gdb_assert (total_width < sizeof wrap_indent);
5625           memset (wrap_indent, ' ', total_width);
5626           wrap_indent[total_width] = 0;
5627
5628           return wrap_indent;
5629         }
5630
5631       total_width += width + 1;
5632     }
5633
5634   return NULL;
5635 }
5636
5637 /* Determine if the locations of this breakpoint will have their conditions
5638    evaluated by the target, host or a mix of both.  Returns the following:
5639
5640     "host": Host evals condition.
5641     "host or target": Host or Target evals condition.
5642     "target": Target evals condition.
5643 */
5644
5645 static const char *
5646 bp_condition_evaluator (struct breakpoint *b)
5647 {
5648   struct bp_location *bl;
5649   char host_evals = 0;
5650   char target_evals = 0;
5651
5652   if (!b)
5653     return NULL;
5654
5655   if (!is_breakpoint (b))
5656     return NULL;
5657
5658   if (gdb_evaluates_breakpoint_condition_p ()
5659       || !target_supports_evaluation_of_breakpoint_conditions ())
5660     return condition_evaluation_host;
5661
5662   for (bl = b->loc; bl; bl = bl->next)
5663     {
5664       if (bl->cond_bytecode)
5665         target_evals++;
5666       else
5667         host_evals++;
5668     }
5669
5670   if (host_evals && target_evals)
5671     return condition_evaluation_both;
5672   else if (target_evals)
5673     return condition_evaluation_target;
5674   else
5675     return condition_evaluation_host;
5676 }
5677
5678 /* Determine the breakpoint location's condition evaluator.  This is
5679    similar to bp_condition_evaluator, but for locations.  */
5680
5681 static const char *
5682 bp_location_condition_evaluator (struct bp_location *bl)
5683 {
5684   if (bl && !is_breakpoint (bl->owner))
5685     return NULL;
5686
5687   if (gdb_evaluates_breakpoint_condition_p ()
5688       || !target_supports_evaluation_of_breakpoint_conditions ())
5689     return condition_evaluation_host;
5690
5691   if (bl && bl->cond_bytecode)
5692     return condition_evaluation_target;
5693   else
5694     return condition_evaluation_host;
5695 }
5696
5697 /* Print the LOC location out of the list of B->LOC locations.  */
5698
5699 static void
5700 print_breakpoint_location (struct breakpoint *b,
5701                            struct bp_location *loc)
5702 {
5703   struct ui_out *uiout = current_uiout;
5704   struct cleanup *old_chain = save_current_program_space ();
5705
5706   if (loc != NULL && loc->shlib_disabled)
5707     loc = NULL;
5708
5709   if (loc != NULL)
5710     set_current_program_space (loc->pspace);
5711
5712   if (b->display_canonical)
5713     ui_out_field_string (uiout, "what", b->addr_string);
5714   else if (loc && loc->symtab)
5715     {
5716       struct symbol *sym 
5717         = find_pc_sect_function (loc->address, loc->section);
5718       if (sym)
5719         {
5720           ui_out_text (uiout, "in ");
5721           ui_out_field_string (uiout, "func",
5722                                SYMBOL_PRINT_NAME (sym));
5723           ui_out_text (uiout, " ");
5724           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5725           ui_out_text (uiout, "at ");
5726         }
5727       ui_out_field_string (uiout, "file",
5728                            symtab_to_filename_for_display (loc->symtab));
5729       ui_out_text (uiout, ":");
5730
5731       if (ui_out_is_mi_like_p (uiout))
5732         ui_out_field_string (uiout, "fullname",
5733                              symtab_to_fullname (loc->symtab));
5734       
5735       ui_out_field_int (uiout, "line", loc->line_number);
5736     }
5737   else if (loc)
5738     {
5739       struct ui_file *stb = mem_fileopen ();
5740       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5741
5742       print_address_symbolic (loc->gdbarch, loc->address, stb,
5743                               demangle, "");
5744       ui_out_field_stream (uiout, "at", stb);
5745
5746       do_cleanups (stb_chain);
5747     }
5748   else
5749     ui_out_field_string (uiout, "pending", b->addr_string);
5750
5751   if (loc && is_breakpoint (b)
5752       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5753       && bp_condition_evaluator (b) == condition_evaluation_both)
5754     {
5755       ui_out_text (uiout, " (");
5756       ui_out_field_string (uiout, "evaluated-by",
5757                            bp_location_condition_evaluator (loc));
5758       ui_out_text (uiout, ")");
5759     }
5760
5761   do_cleanups (old_chain);
5762 }
5763
5764 static const char *
5765 bptype_string (enum bptype type)
5766 {
5767   struct ep_type_description
5768     {
5769       enum bptype type;
5770       char *description;
5771     };
5772   static struct ep_type_description bptypes[] =
5773   {
5774     {bp_none, "?deleted?"},
5775     {bp_breakpoint, "breakpoint"},
5776     {bp_hardware_breakpoint, "hw breakpoint"},
5777     {bp_until, "until"},
5778     {bp_finish, "finish"},
5779     {bp_watchpoint, "watchpoint"},
5780     {bp_hardware_watchpoint, "hw watchpoint"},
5781     {bp_read_watchpoint, "read watchpoint"},
5782     {bp_access_watchpoint, "acc watchpoint"},
5783     {bp_longjmp, "longjmp"},
5784     {bp_longjmp_resume, "longjmp resume"},
5785     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5786     {bp_exception, "exception"},
5787     {bp_exception_resume, "exception resume"},
5788     {bp_step_resume, "step resume"},
5789     {bp_hp_step_resume, "high-priority step resume"},
5790     {bp_watchpoint_scope, "watchpoint scope"},
5791     {bp_call_dummy, "call dummy"},
5792     {bp_std_terminate, "std::terminate"},
5793     {bp_shlib_event, "shlib events"},
5794     {bp_thread_event, "thread events"},
5795     {bp_overlay_event, "overlay events"},
5796     {bp_longjmp_master, "longjmp master"},
5797     {bp_std_terminate_master, "std::terminate master"},
5798     {bp_exception_master, "exception master"},
5799     {bp_catchpoint, "catchpoint"},
5800     {bp_tracepoint, "tracepoint"},
5801     {bp_fast_tracepoint, "fast tracepoint"},
5802     {bp_static_tracepoint, "static tracepoint"},
5803     {bp_dprintf, "dprintf"},
5804     {bp_jit_event, "jit events"},
5805     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5806     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5807   };
5808
5809   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5810       || ((int) type != bptypes[(int) type].type))
5811     internal_error (__FILE__, __LINE__,
5812                     _("bptypes table does not describe type #%d."),
5813                     (int) type);
5814
5815   return bptypes[(int) type].description;
5816 }
5817
5818 DEF_VEC_I(int);
5819
5820 /* For MI, output a field named 'thread-groups' with a list as the value.
5821    For CLI, prefix the list with the string 'inf'. */
5822
5823 static void
5824 output_thread_groups (struct ui_out *uiout,
5825                       const char *field_name,
5826                       VEC(int) *inf_num,
5827                       int mi_only)
5828 {
5829   struct cleanup *back_to = make_cleanup_ui_out_list_begin_end (uiout,
5830                                                                 field_name);
5831   int is_mi = ui_out_is_mi_like_p (uiout);
5832   int inf;
5833   int i;
5834
5835   /* For backward compatibility, don't display inferiors in CLI unless
5836      there are several.  Always display them for MI. */
5837   if (!is_mi && mi_only)
5838     return;
5839
5840   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
5841     {
5842       if (is_mi)
5843         {
5844           char mi_group[10];
5845
5846           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
5847           ui_out_field_string (uiout, NULL, mi_group);
5848         }
5849       else
5850         {
5851           if (i == 0)
5852             ui_out_text (uiout, " inf ");
5853           else
5854             ui_out_text (uiout, ", ");
5855         
5856           ui_out_text (uiout, plongest (inf));
5857         }
5858     }
5859
5860   do_cleanups (back_to);
5861 }
5862
5863 /* Print B to gdb_stdout.  */
5864
5865 static void
5866 print_one_breakpoint_location (struct breakpoint *b,
5867                                struct bp_location *loc,
5868                                int loc_number,
5869                                struct bp_location **last_loc,
5870                                int allflag)
5871 {
5872   struct command_line *l;
5873   static char bpenables[] = "nynny";
5874
5875   struct ui_out *uiout = current_uiout;
5876   int header_of_multiple = 0;
5877   int part_of_multiple = (loc != NULL);
5878   struct value_print_options opts;
5879
5880   get_user_print_options (&opts);
5881
5882   gdb_assert (!loc || loc_number != 0);
5883   /* See comment in print_one_breakpoint concerning treatment of
5884      breakpoints with single disabled location.  */
5885   if (loc == NULL 
5886       && (b->loc != NULL 
5887           && (b->loc->next != NULL || !b->loc->enabled)))
5888     header_of_multiple = 1;
5889   if (loc == NULL)
5890     loc = b->loc;
5891
5892   annotate_record ();
5893
5894   /* 1 */
5895   annotate_field (0);
5896   if (part_of_multiple)
5897     {
5898       char *formatted;
5899       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5900       ui_out_field_string (uiout, "number", formatted);
5901       xfree (formatted);
5902     }
5903   else
5904     {
5905       ui_out_field_int (uiout, "number", b->number);
5906     }
5907
5908   /* 2 */
5909   annotate_field (1);
5910   if (part_of_multiple)
5911     ui_out_field_skip (uiout, "type");
5912   else
5913     ui_out_field_string (uiout, "type", bptype_string (b->type));
5914
5915   /* 3 */
5916   annotate_field (2);
5917   if (part_of_multiple)
5918     ui_out_field_skip (uiout, "disp");
5919   else
5920     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5921
5922
5923   /* 4 */
5924   annotate_field (3);
5925   if (part_of_multiple)
5926     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5927   else
5928     ui_out_field_fmt (uiout, "enabled", "%c", 
5929                       bpenables[(int) b->enable_state]);
5930   ui_out_spaces (uiout, 2);
5931
5932   
5933   /* 5 and 6 */
5934   if (b->ops != NULL && b->ops->print_one != NULL)
5935     {
5936       /* Although the print_one can possibly print all locations,
5937          calling it here is not likely to get any nice result.  So,
5938          make sure there's just one location.  */
5939       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5940       b->ops->print_one (b, last_loc);
5941     }
5942   else
5943     switch (b->type)
5944       {
5945       case bp_none:
5946         internal_error (__FILE__, __LINE__,
5947                         _("print_one_breakpoint: bp_none encountered\n"));
5948         break;
5949
5950       case bp_watchpoint:
5951       case bp_hardware_watchpoint:
5952       case bp_read_watchpoint:
5953       case bp_access_watchpoint:
5954         {
5955           struct watchpoint *w = (struct watchpoint *) b;
5956
5957           /* Field 4, the address, is omitted (which makes the columns
5958              not line up too nicely with the headers, but the effect
5959              is relatively readable).  */
5960           if (opts.addressprint)
5961             ui_out_field_skip (uiout, "addr");
5962           annotate_field (5);
5963           ui_out_field_string (uiout, "what", w->exp_string);
5964         }
5965         break;
5966
5967       case bp_breakpoint:
5968       case bp_hardware_breakpoint:
5969       case bp_until:
5970       case bp_finish:
5971       case bp_longjmp:
5972       case bp_longjmp_resume:
5973       case bp_longjmp_call_dummy:
5974       case bp_exception:
5975       case bp_exception_resume:
5976       case bp_step_resume:
5977       case bp_hp_step_resume:
5978       case bp_watchpoint_scope:
5979       case bp_call_dummy:
5980       case bp_std_terminate:
5981       case bp_shlib_event:
5982       case bp_thread_event:
5983       case bp_overlay_event:
5984       case bp_longjmp_master:
5985       case bp_std_terminate_master:
5986       case bp_exception_master:
5987       case bp_tracepoint:
5988       case bp_fast_tracepoint:
5989       case bp_static_tracepoint:
5990       case bp_dprintf:
5991       case bp_jit_event:
5992       case bp_gnu_ifunc_resolver:
5993       case bp_gnu_ifunc_resolver_return:
5994         if (opts.addressprint)
5995           {
5996             annotate_field (4);
5997             if (header_of_multiple)
5998               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5999             else if (b->loc == NULL || loc->shlib_disabled)
6000               ui_out_field_string (uiout, "addr", "<PENDING>");
6001             else
6002               ui_out_field_core_addr (uiout, "addr",
6003                                       loc->gdbarch, loc->address);
6004           }
6005         annotate_field (5);
6006         if (!header_of_multiple)
6007           print_breakpoint_location (b, loc);
6008         if (b->loc)
6009           *last_loc = b->loc;
6010         break;
6011       }
6012
6013
6014   if (loc != NULL && !header_of_multiple)
6015     {
6016       struct inferior *inf;
6017       VEC(int) *inf_num = NULL;
6018       int mi_only = 1;
6019
6020       ALL_INFERIORS (inf)
6021         {
6022           if (inf->pspace == loc->pspace)
6023             VEC_safe_push (int, inf_num, inf->num);
6024         }
6025
6026         /* For backward compatibility, don't display inferiors in CLI unless
6027            there are several.  Always display for MI. */
6028         if (allflag
6029             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6030                 && (number_of_program_spaces () > 1
6031                     || number_of_inferiors () > 1)
6032                 /* LOC is for existing B, it cannot be in
6033                    moribund_locations and thus having NULL OWNER.  */
6034                 && loc->owner->type != bp_catchpoint))
6035         mi_only = 0;
6036       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6037       VEC_free (int, inf_num);
6038     }
6039
6040   if (!part_of_multiple)
6041     {
6042       if (b->thread != -1)
6043         {
6044           /* FIXME: This seems to be redundant and lost here; see the
6045              "stop only in" line a little further down.  */
6046           ui_out_text (uiout, " thread ");
6047           ui_out_field_int (uiout, "thread", b->thread);
6048         }
6049       else if (b->task != 0)
6050         {
6051           ui_out_text (uiout, " task ");
6052           ui_out_field_int (uiout, "task", b->task);
6053         }
6054     }
6055
6056   ui_out_text (uiout, "\n");
6057
6058   if (!part_of_multiple)
6059     b->ops->print_one_detail (b, uiout);
6060
6061   if (part_of_multiple && frame_id_p (b->frame_id))
6062     {
6063       annotate_field (6);
6064       ui_out_text (uiout, "\tstop only in stack frame at ");
6065       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6066          the frame ID.  */
6067       ui_out_field_core_addr (uiout, "frame",
6068                               b->gdbarch, b->frame_id.stack_addr);
6069       ui_out_text (uiout, "\n");
6070     }
6071   
6072   if (!part_of_multiple && b->cond_string)
6073     {
6074       annotate_field (7);
6075       if (is_tracepoint (b))
6076         ui_out_text (uiout, "\ttrace only if ");
6077       else
6078         ui_out_text (uiout, "\tstop only if ");
6079       ui_out_field_string (uiout, "cond", b->cond_string);
6080
6081       /* Print whether the target is doing the breakpoint's condition
6082          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6083       if (is_breakpoint (b)
6084           && breakpoint_condition_evaluation_mode ()
6085           == condition_evaluation_target)
6086         {
6087           ui_out_text (uiout, " (");
6088           ui_out_field_string (uiout, "evaluated-by",
6089                                bp_condition_evaluator (b));
6090           ui_out_text (uiout, " evals)");
6091         }
6092       ui_out_text (uiout, "\n");
6093     }
6094
6095   if (!part_of_multiple && b->thread != -1)
6096     {
6097       /* FIXME should make an annotation for this.  */
6098       ui_out_text (uiout, "\tstop only in thread ");
6099       ui_out_field_int (uiout, "thread", b->thread);
6100       ui_out_text (uiout, "\n");
6101     }
6102   
6103   if (!part_of_multiple)
6104     {
6105       if (b->hit_count)
6106         {
6107           /* FIXME should make an annotation for this.  */
6108           if (is_catchpoint (b))
6109             ui_out_text (uiout, "\tcatchpoint");
6110           else if (is_tracepoint (b))
6111             ui_out_text (uiout, "\ttracepoint");
6112           else
6113             ui_out_text (uiout, "\tbreakpoint");
6114           ui_out_text (uiout, " already hit ");
6115           ui_out_field_int (uiout, "times", b->hit_count);
6116           if (b->hit_count == 1)
6117             ui_out_text (uiout, " time\n");
6118           else
6119             ui_out_text (uiout, " times\n");
6120         }
6121       else
6122         {
6123           /* Output the count also if it is zero, but only if this is mi.  */
6124           if (ui_out_is_mi_like_p (uiout))
6125             ui_out_field_int (uiout, "times", b->hit_count);
6126         }
6127     }
6128
6129   if (!part_of_multiple && b->ignore_count)
6130     {
6131       annotate_field (8);
6132       ui_out_text (uiout, "\tignore next ");
6133       ui_out_field_int (uiout, "ignore", b->ignore_count);
6134       ui_out_text (uiout, " hits\n");
6135     }
6136
6137   /* Note that an enable count of 1 corresponds to "enable once"
6138      behavior, which is reported by the combination of enablement and
6139      disposition, so we don't need to mention it here.  */
6140   if (!part_of_multiple && b->enable_count > 1)
6141     {
6142       annotate_field (8);
6143       ui_out_text (uiout, "\tdisable after ");
6144       /* Tweak the wording to clarify that ignore and enable counts
6145          are distinct, and have additive effect.  */
6146       if (b->ignore_count)
6147         ui_out_text (uiout, "additional ");
6148       else
6149         ui_out_text (uiout, "next ");
6150       ui_out_field_int (uiout, "enable", b->enable_count);
6151       ui_out_text (uiout, " hits\n");
6152     }
6153
6154   if (!part_of_multiple && is_tracepoint (b))
6155     {
6156       struct tracepoint *tp = (struct tracepoint *) b;
6157
6158       if (tp->traceframe_usage)
6159         {
6160           ui_out_text (uiout, "\ttrace buffer usage ");
6161           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6162           ui_out_text (uiout, " bytes\n");
6163         }
6164     }
6165
6166   l = b->commands ? b->commands->commands : NULL;
6167   if (!part_of_multiple && l)
6168     {
6169       struct cleanup *script_chain;
6170
6171       annotate_field (9);
6172       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6173       print_command_lines (uiout, l, 4);
6174       do_cleanups (script_chain);
6175     }
6176
6177   if (is_tracepoint (b))
6178     {
6179       struct tracepoint *t = (struct tracepoint *) b;
6180
6181       if (!part_of_multiple && t->pass_count)
6182         {
6183           annotate_field (10);
6184           ui_out_text (uiout, "\tpass count ");
6185           ui_out_field_int (uiout, "pass", t->pass_count);
6186           ui_out_text (uiout, " \n");
6187         }
6188
6189       /* Don't display it when tracepoint or tracepoint location is
6190          pending.   */
6191       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6192         {
6193           annotate_field (11);
6194
6195           if (ui_out_is_mi_like_p (uiout))
6196             ui_out_field_string (uiout, "installed",
6197                                  loc->inserted ? "y" : "n");
6198           else
6199             {
6200               if (loc->inserted)
6201                 ui_out_text (uiout, "\t");
6202               else
6203                 ui_out_text (uiout, "\tnot ");
6204               ui_out_text (uiout, "installed on target\n");
6205             }
6206         }
6207     }
6208
6209   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6210     {
6211       if (is_watchpoint (b))
6212         {
6213           struct watchpoint *w = (struct watchpoint *) b;
6214
6215           ui_out_field_string (uiout, "original-location", w->exp_string);
6216         }
6217       else if (b->addr_string)
6218         ui_out_field_string (uiout, "original-location", b->addr_string);
6219     }
6220 }
6221
6222 static void
6223 print_one_breakpoint (struct breakpoint *b,
6224                       struct bp_location **last_loc, 
6225                       int allflag)
6226 {
6227   struct cleanup *bkpt_chain;
6228   struct ui_out *uiout = current_uiout;
6229
6230   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6231
6232   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6233   do_cleanups (bkpt_chain);
6234
6235   /* If this breakpoint has custom print function,
6236      it's already printed.  Otherwise, print individual
6237      locations, if any.  */
6238   if (b->ops == NULL || b->ops->print_one == NULL)
6239     {
6240       /* If breakpoint has a single location that is disabled, we
6241          print it as if it had several locations, since otherwise it's
6242          hard to represent "breakpoint enabled, location disabled"
6243          situation.
6244
6245          Note that while hardware watchpoints have several locations
6246          internally, that's not a property exposed to user.  */
6247       if (b->loc 
6248           && !is_hardware_watchpoint (b)
6249           && (b->loc->next || !b->loc->enabled))
6250         {
6251           struct bp_location *loc;
6252           int n = 1;
6253
6254           for (loc = b->loc; loc; loc = loc->next, ++n)
6255             {
6256               struct cleanup *inner2 =
6257                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6258               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6259               do_cleanups (inner2);
6260             }
6261         }
6262     }
6263 }
6264
6265 static int
6266 breakpoint_address_bits (struct breakpoint *b)
6267 {
6268   int print_address_bits = 0;
6269   struct bp_location *loc;
6270
6271   for (loc = b->loc; loc; loc = loc->next)
6272     {
6273       int addr_bit;
6274
6275       /* Software watchpoints that aren't watching memory don't have
6276          an address to print.  */
6277       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6278         continue;
6279
6280       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6281       if (addr_bit > print_address_bits)
6282         print_address_bits = addr_bit;
6283     }
6284
6285   return print_address_bits;
6286 }
6287
6288 struct captured_breakpoint_query_args
6289   {
6290     int bnum;
6291   };
6292
6293 static int
6294 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6295 {
6296   struct captured_breakpoint_query_args *args = data;
6297   struct breakpoint *b;
6298   struct bp_location *dummy_loc = NULL;
6299
6300   ALL_BREAKPOINTS (b)
6301     {
6302       if (args->bnum == b->number)
6303         {
6304           print_one_breakpoint (b, &dummy_loc, 0);
6305           return GDB_RC_OK;
6306         }
6307     }
6308   return GDB_RC_NONE;
6309 }
6310
6311 enum gdb_rc
6312 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6313                       char **error_message)
6314 {
6315   struct captured_breakpoint_query_args args;
6316
6317   args.bnum = bnum;
6318   /* For the moment we don't trust print_one_breakpoint() to not throw
6319      an error.  */
6320   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6321                                  error_message, RETURN_MASK_ALL) < 0)
6322     return GDB_RC_FAIL;
6323   else
6324     return GDB_RC_OK;
6325 }
6326
6327 /* Return true if this breakpoint was set by the user, false if it is
6328    internal or momentary.  */
6329
6330 int
6331 user_breakpoint_p (struct breakpoint *b)
6332 {
6333   return b->number > 0;
6334 }
6335
6336 /* Print information on user settable breakpoint (watchpoint, etc)
6337    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6338    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6339    FILTER is non-NULL, call it on each breakpoint and only include the
6340    ones for which it returns non-zero.  Return the total number of
6341    breakpoints listed.  */
6342
6343 static int
6344 breakpoint_1 (char *args, int allflag, 
6345               int (*filter) (const struct breakpoint *))
6346 {
6347   struct breakpoint *b;
6348   struct bp_location *last_loc = NULL;
6349   int nr_printable_breakpoints;
6350   struct cleanup *bkpttbl_chain;
6351   struct value_print_options opts;
6352   int print_address_bits = 0;
6353   int print_type_col_width = 14;
6354   struct ui_out *uiout = current_uiout;
6355
6356   get_user_print_options (&opts);
6357
6358   /* Compute the number of rows in the table, as well as the size
6359      required for address fields.  */
6360   nr_printable_breakpoints = 0;
6361   ALL_BREAKPOINTS (b)
6362     {
6363       /* If we have a filter, only list the breakpoints it accepts.  */
6364       if (filter && !filter (b))
6365         continue;
6366
6367       /* If we have an "args" string, it is a list of breakpoints to 
6368          accept.  Skip the others.  */
6369       if (args != NULL && *args != '\0')
6370         {
6371           if (allflag && parse_and_eval_long (args) != b->number)
6372             continue;
6373           if (!allflag && !number_is_in_list (args, b->number))
6374             continue;
6375         }
6376
6377       if (allflag || user_breakpoint_p (b))
6378         {
6379           int addr_bit, type_len;
6380
6381           addr_bit = breakpoint_address_bits (b);
6382           if (addr_bit > print_address_bits)
6383             print_address_bits = addr_bit;
6384
6385           type_len = strlen (bptype_string (b->type));
6386           if (type_len > print_type_col_width)
6387             print_type_col_width = type_len;
6388
6389           nr_printable_breakpoints++;
6390         }
6391     }
6392
6393   if (opts.addressprint)
6394     bkpttbl_chain 
6395       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6396                                              nr_printable_breakpoints,
6397                                              "BreakpointTable");
6398   else
6399     bkpttbl_chain 
6400       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6401                                              nr_printable_breakpoints,
6402                                              "BreakpointTable");
6403
6404   if (nr_printable_breakpoints > 0)
6405     annotate_breakpoints_headers ();
6406   if (nr_printable_breakpoints > 0)
6407     annotate_field (0);
6408   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6409   if (nr_printable_breakpoints > 0)
6410     annotate_field (1);
6411   ui_out_table_header (uiout, print_type_col_width, ui_left,
6412                        "type", "Type");                         /* 2 */
6413   if (nr_printable_breakpoints > 0)
6414     annotate_field (2);
6415   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6416   if (nr_printable_breakpoints > 0)
6417     annotate_field (3);
6418   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6419   if (opts.addressprint)
6420     {
6421       if (nr_printable_breakpoints > 0)
6422         annotate_field (4);
6423       if (print_address_bits <= 32)
6424         ui_out_table_header (uiout, 10, ui_left, 
6425                              "addr", "Address");                /* 5 */
6426       else
6427         ui_out_table_header (uiout, 18, ui_left, 
6428                              "addr", "Address");                /* 5 */
6429     }
6430   if (nr_printable_breakpoints > 0)
6431     annotate_field (5);
6432   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6433   ui_out_table_body (uiout);
6434   if (nr_printable_breakpoints > 0)
6435     annotate_breakpoints_table ();
6436
6437   ALL_BREAKPOINTS (b)
6438     {
6439       QUIT;
6440       /* If we have a filter, only list the breakpoints it accepts.  */
6441       if (filter && !filter (b))
6442         continue;
6443
6444       /* If we have an "args" string, it is a list of breakpoints to 
6445          accept.  Skip the others.  */
6446
6447       if (args != NULL && *args != '\0')
6448         {
6449           if (allflag)  /* maintenance info breakpoint */
6450             {
6451               if (parse_and_eval_long (args) != b->number)
6452                 continue;
6453             }
6454           else          /* all others */
6455             {
6456               if (!number_is_in_list (args, b->number))
6457                 continue;
6458             }
6459         }
6460       /* We only print out user settable breakpoints unless the
6461          allflag is set.  */
6462       if (allflag || user_breakpoint_p (b))
6463         print_one_breakpoint (b, &last_loc, allflag);
6464     }
6465
6466   do_cleanups (bkpttbl_chain);
6467
6468   if (nr_printable_breakpoints == 0)
6469     {
6470       /* If there's a filter, let the caller decide how to report
6471          empty list.  */
6472       if (!filter)
6473         {
6474           if (args == NULL || *args == '\0')
6475             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6476           else
6477             ui_out_message (uiout, 0, 
6478                             "No breakpoint or watchpoint matching '%s'.\n",
6479                             args);
6480         }
6481     }
6482   else
6483     {
6484       if (last_loc && !server_command)
6485         set_next_address (last_loc->gdbarch, last_loc->address);
6486     }
6487
6488   /* FIXME?  Should this be moved up so that it is only called when
6489      there have been breakpoints? */
6490   annotate_breakpoints_table_end ();
6491
6492   return nr_printable_breakpoints;
6493 }
6494
6495 /* Display the value of default-collect in a way that is generally
6496    compatible with the breakpoint list.  */
6497
6498 static void
6499 default_collect_info (void)
6500 {
6501   struct ui_out *uiout = current_uiout;
6502
6503   /* If it has no value (which is frequently the case), say nothing; a
6504      message like "No default-collect." gets in user's face when it's
6505      not wanted.  */
6506   if (!*default_collect)
6507     return;
6508
6509   /* The following phrase lines up nicely with per-tracepoint collect
6510      actions.  */
6511   ui_out_text (uiout, "default collect ");
6512   ui_out_field_string (uiout, "default-collect", default_collect);
6513   ui_out_text (uiout, " \n");
6514 }
6515   
6516 static void
6517 breakpoints_info (char *args, int from_tty)
6518 {
6519   breakpoint_1 (args, 0, NULL);
6520
6521   default_collect_info ();
6522 }
6523
6524 static void
6525 watchpoints_info (char *args, int from_tty)
6526 {
6527   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6528   struct ui_out *uiout = current_uiout;
6529
6530   if (num_printed == 0)
6531     {
6532       if (args == NULL || *args == '\0')
6533         ui_out_message (uiout, 0, "No watchpoints.\n");
6534       else
6535         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6536     }
6537 }
6538
6539 static void
6540 maintenance_info_breakpoints (char *args, int from_tty)
6541 {
6542   breakpoint_1 (args, 1, NULL);
6543
6544   default_collect_info ();
6545 }
6546
6547 static int
6548 breakpoint_has_pc (struct breakpoint *b,
6549                    struct program_space *pspace,
6550                    CORE_ADDR pc, struct obj_section *section)
6551 {
6552   struct bp_location *bl = b->loc;
6553
6554   for (; bl; bl = bl->next)
6555     {
6556       if (bl->pspace == pspace
6557           && bl->address == pc
6558           && (!overlay_debugging || bl->section == section))
6559         return 1;         
6560     }
6561   return 0;
6562 }
6563
6564 /* Print a message describing any user-breakpoints set at PC.  This
6565    concerns with logical breakpoints, so we match program spaces, not
6566    address spaces.  */
6567
6568 static void
6569 describe_other_breakpoints (struct gdbarch *gdbarch,
6570                             struct program_space *pspace, CORE_ADDR pc,
6571                             struct obj_section *section, int thread)
6572 {
6573   int others = 0;
6574   struct breakpoint *b;
6575
6576   ALL_BREAKPOINTS (b)
6577     others += (user_breakpoint_p (b)
6578                && breakpoint_has_pc (b, pspace, pc, section));
6579   if (others > 0)
6580     {
6581       if (others == 1)
6582         printf_filtered (_("Note: breakpoint "));
6583       else /* if (others == ???) */
6584         printf_filtered (_("Note: breakpoints "));
6585       ALL_BREAKPOINTS (b)
6586         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6587           {
6588             others--;
6589             printf_filtered ("%d", b->number);
6590             if (b->thread == -1 && thread != -1)
6591               printf_filtered (" (all threads)");
6592             else if (b->thread != -1)
6593               printf_filtered (" (thread %d)", b->thread);
6594             printf_filtered ("%s%s ",
6595                              ((b->enable_state == bp_disabled
6596                                || b->enable_state == bp_call_disabled)
6597                               ? " (disabled)"
6598                               : b->enable_state == bp_permanent 
6599                               ? " (permanent)"
6600                               : ""),
6601                              (others > 1) ? "," 
6602                              : ((others == 1) ? " and" : ""));
6603           }
6604       printf_filtered (_("also set at pc "));
6605       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6606       printf_filtered (".\n");
6607     }
6608 }
6609 \f
6610
6611 /* Return true iff it is meaningful to use the address member of
6612    BPT.  For some breakpoint types, the address member is irrelevant
6613    and it makes no sense to attempt to compare it to other addresses
6614    (or use it for any other purpose either).
6615
6616    More specifically, each of the following breakpoint types will
6617    always have a zero valued address and we don't want to mark
6618    breakpoints of any of these types to be a duplicate of an actual
6619    breakpoint at address zero:
6620
6621       bp_watchpoint
6622       bp_catchpoint
6623
6624 */
6625
6626 static int
6627 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6628 {
6629   enum bptype type = bpt->type;
6630
6631   return (type != bp_watchpoint && type != bp_catchpoint);
6632 }
6633
6634 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6635    true if LOC1 and LOC2 represent the same watchpoint location.  */
6636
6637 static int
6638 watchpoint_locations_match (struct bp_location *loc1, 
6639                             struct bp_location *loc2)
6640 {
6641   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6642   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6643
6644   /* Both of them must exist.  */
6645   gdb_assert (w1 != NULL);
6646   gdb_assert (w2 != NULL);
6647
6648   /* If the target can evaluate the condition expression in hardware,
6649      then we we need to insert both watchpoints even if they are at
6650      the same place.  Otherwise the watchpoint will only trigger when
6651      the condition of whichever watchpoint was inserted evaluates to
6652      true, not giving a chance for GDB to check the condition of the
6653      other watchpoint.  */
6654   if ((w1->cond_exp
6655        && target_can_accel_watchpoint_condition (loc1->address, 
6656                                                  loc1->length,
6657                                                  loc1->watchpoint_type,
6658                                                  w1->cond_exp))
6659       || (w2->cond_exp
6660           && target_can_accel_watchpoint_condition (loc2->address, 
6661                                                     loc2->length,
6662                                                     loc2->watchpoint_type,
6663                                                     w2->cond_exp)))
6664     return 0;
6665
6666   /* Note that this checks the owner's type, not the location's.  In
6667      case the target does not support read watchpoints, but does
6668      support access watchpoints, we'll have bp_read_watchpoint
6669      watchpoints with hw_access locations.  Those should be considered
6670      duplicates of hw_read locations.  The hw_read locations will
6671      become hw_access locations later.  */
6672   return (loc1->owner->type == loc2->owner->type
6673           && loc1->pspace->aspace == loc2->pspace->aspace
6674           && loc1->address == loc2->address
6675           && loc1->length == loc2->length);
6676 }
6677
6678 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6679    same breakpoint location.  In most targets, this can only be true
6680    if ASPACE1 matches ASPACE2.  On targets that have global
6681    breakpoints, the address space doesn't really matter.  */
6682
6683 static int
6684 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6685                           struct address_space *aspace2, CORE_ADDR addr2)
6686 {
6687   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6688            || aspace1 == aspace2)
6689           && addr1 == addr2);
6690 }
6691
6692 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6693    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6694    matches ASPACE2.  On targets that have global breakpoints, the address
6695    space doesn't really matter.  */
6696
6697 static int
6698 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6699                                 int len1, struct address_space *aspace2,
6700                                 CORE_ADDR addr2)
6701 {
6702   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6703            || aspace1 == aspace2)
6704           && addr2 >= addr1 && addr2 < addr1 + len1);
6705 }
6706
6707 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6708    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6709    matches the breakpoint's address space.  On targets that have global
6710    breakpoints, the address space doesn't really matter.  */
6711
6712 static int
6713 breakpoint_location_address_match (struct bp_location *bl,
6714                                    struct address_space *aspace,
6715                                    CORE_ADDR addr)
6716 {
6717   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6718                                     aspace, addr)
6719           || (bl->length
6720               && breakpoint_address_match_range (bl->pspace->aspace,
6721                                                  bl->address, bl->length,
6722                                                  aspace, addr)));
6723 }
6724
6725 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6726    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6727    true, otherwise returns false.  */
6728
6729 static int
6730 tracepoint_locations_match (struct bp_location *loc1,
6731                             struct bp_location *loc2)
6732 {
6733   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6734     /* Since tracepoint locations are never duplicated with others', tracepoint
6735        locations at the same address of different tracepoints are regarded as
6736        different locations.  */
6737     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6738   else
6739     return 0;
6740 }
6741
6742 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6743    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6744    represent the same location.  */
6745
6746 static int
6747 breakpoint_locations_match (struct bp_location *loc1, 
6748                             struct bp_location *loc2)
6749 {
6750   int hw_point1, hw_point2;
6751
6752   /* Both of them must not be in moribund_locations.  */
6753   gdb_assert (loc1->owner != NULL);
6754   gdb_assert (loc2->owner != NULL);
6755
6756   hw_point1 = is_hardware_watchpoint (loc1->owner);
6757   hw_point2 = is_hardware_watchpoint (loc2->owner);
6758
6759   if (hw_point1 != hw_point2)
6760     return 0;
6761   else if (hw_point1)
6762     return watchpoint_locations_match (loc1, loc2);
6763   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6764     return tracepoint_locations_match (loc1, loc2);
6765   else
6766     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6767     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6768                                      loc2->pspace->aspace, loc2->address)
6769             && loc1->length == loc2->length);
6770 }
6771
6772 static void
6773 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6774                                int bnum, int have_bnum)
6775 {
6776   /* The longest string possibly returned by hex_string_custom
6777      is 50 chars.  These must be at least that big for safety.  */
6778   char astr1[64];
6779   char astr2[64];
6780
6781   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6782   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6783   if (have_bnum)
6784     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6785              bnum, astr1, astr2);
6786   else
6787     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6788 }
6789
6790 /* Adjust a breakpoint's address to account for architectural
6791    constraints on breakpoint placement.  Return the adjusted address.
6792    Note: Very few targets require this kind of adjustment.  For most
6793    targets, this function is simply the identity function.  */
6794
6795 static CORE_ADDR
6796 adjust_breakpoint_address (struct gdbarch *gdbarch,
6797                            CORE_ADDR bpaddr, enum bptype bptype)
6798 {
6799   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6800     {
6801       /* Very few targets need any kind of breakpoint adjustment.  */
6802       return bpaddr;
6803     }
6804   else if (bptype == bp_watchpoint
6805            || bptype == bp_hardware_watchpoint
6806            || bptype == bp_read_watchpoint
6807            || bptype == bp_access_watchpoint
6808            || bptype == bp_catchpoint)
6809     {
6810       /* Watchpoints and the various bp_catch_* eventpoints should not
6811          have their addresses modified.  */
6812       return bpaddr;
6813     }
6814   else
6815     {
6816       CORE_ADDR adjusted_bpaddr;
6817
6818       /* Some targets have architectural constraints on the placement
6819          of breakpoint instructions.  Obtain the adjusted address.  */
6820       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6821
6822       /* An adjusted breakpoint address can significantly alter
6823          a user's expectations.  Print a warning if an adjustment
6824          is required.  */
6825       if (adjusted_bpaddr != bpaddr)
6826         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6827
6828       return adjusted_bpaddr;
6829     }
6830 }
6831
6832 void
6833 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6834                   struct breakpoint *owner)
6835 {
6836   memset (loc, 0, sizeof (*loc));
6837
6838   gdb_assert (ops != NULL);
6839
6840   loc->ops = ops;
6841   loc->owner = owner;
6842   loc->cond = NULL;
6843   loc->cond_bytecode = NULL;
6844   loc->shlib_disabled = 0;
6845   loc->enabled = 1;
6846
6847   switch (owner->type)
6848     {
6849     case bp_breakpoint:
6850     case bp_until:
6851     case bp_finish:
6852     case bp_longjmp:
6853     case bp_longjmp_resume:
6854     case bp_longjmp_call_dummy:
6855     case bp_exception:
6856     case bp_exception_resume:
6857     case bp_step_resume:
6858     case bp_hp_step_resume:
6859     case bp_watchpoint_scope:
6860     case bp_call_dummy:
6861     case bp_std_terminate:
6862     case bp_shlib_event:
6863     case bp_thread_event:
6864     case bp_overlay_event:
6865     case bp_jit_event:
6866     case bp_longjmp_master:
6867     case bp_std_terminate_master:
6868     case bp_exception_master:
6869     case bp_gnu_ifunc_resolver:
6870     case bp_gnu_ifunc_resolver_return:
6871     case bp_dprintf:
6872       loc->loc_type = bp_loc_software_breakpoint;
6873       mark_breakpoint_location_modified (loc);
6874       break;
6875     case bp_hardware_breakpoint:
6876       loc->loc_type = bp_loc_hardware_breakpoint;
6877       mark_breakpoint_location_modified (loc);
6878       break;
6879     case bp_hardware_watchpoint:
6880     case bp_read_watchpoint:
6881     case bp_access_watchpoint:
6882       loc->loc_type = bp_loc_hardware_watchpoint;
6883       break;
6884     case bp_watchpoint:
6885     case bp_catchpoint:
6886     case bp_tracepoint:
6887     case bp_fast_tracepoint:
6888     case bp_static_tracepoint:
6889       loc->loc_type = bp_loc_other;
6890       break;
6891     default:
6892       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6893     }
6894
6895   loc->refc = 1;
6896 }
6897
6898 /* Allocate a struct bp_location.  */
6899
6900 static struct bp_location *
6901 allocate_bp_location (struct breakpoint *bpt)
6902 {
6903   return bpt->ops->allocate_location (bpt);
6904 }
6905
6906 static void
6907 free_bp_location (struct bp_location *loc)
6908 {
6909   loc->ops->dtor (loc);
6910   xfree (loc);
6911 }
6912
6913 /* Increment reference count.  */
6914
6915 static void
6916 incref_bp_location (struct bp_location *bl)
6917 {
6918   ++bl->refc;
6919 }
6920
6921 /* Decrement reference count.  If the reference count reaches 0,
6922    destroy the bp_location.  Sets *BLP to NULL.  */
6923
6924 static void
6925 decref_bp_location (struct bp_location **blp)
6926 {
6927   gdb_assert ((*blp)->refc > 0);
6928
6929   if (--(*blp)->refc == 0)
6930     free_bp_location (*blp);
6931   *blp = NULL;
6932 }
6933
6934 /* Add breakpoint B at the end of the global breakpoint chain.  */
6935
6936 static void
6937 add_to_breakpoint_chain (struct breakpoint *b)
6938 {
6939   struct breakpoint *b1;
6940
6941   /* Add this breakpoint to the end of the chain so that a list of
6942      breakpoints will come out in order of increasing numbers.  */
6943
6944   b1 = breakpoint_chain;
6945   if (b1 == 0)
6946     breakpoint_chain = b;
6947   else
6948     {
6949       while (b1->next)
6950         b1 = b1->next;
6951       b1->next = b;
6952     }
6953 }
6954
6955 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6956
6957 static void
6958 init_raw_breakpoint_without_location (struct breakpoint *b,
6959                                       struct gdbarch *gdbarch,
6960                                       enum bptype bptype,
6961                                       const struct breakpoint_ops *ops)
6962 {
6963   memset (b, 0, sizeof (*b));
6964
6965   gdb_assert (ops != NULL);
6966
6967   b->ops = ops;
6968   b->type = bptype;
6969   b->gdbarch = gdbarch;
6970   b->language = current_language->la_language;
6971   b->input_radix = input_radix;
6972   b->thread = -1;
6973   b->enable_state = bp_enabled;
6974   b->next = 0;
6975   b->silent = 0;
6976   b->ignore_count = 0;
6977   b->commands = NULL;
6978   b->frame_id = null_frame_id;
6979   b->condition_not_parsed = 0;
6980   b->py_bp_object = NULL;
6981   b->related_breakpoint = b;
6982 }
6983
6984 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6985    that has type BPTYPE and has no locations as yet.  */
6986
6987 static struct breakpoint *
6988 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6989                                      enum bptype bptype,
6990                                      const struct breakpoint_ops *ops)
6991 {
6992   struct breakpoint *b = XNEW (struct breakpoint);
6993
6994   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6995   add_to_breakpoint_chain (b);
6996   return b;
6997 }
6998
6999 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7000    resolutions should be made as the user specified the location explicitly
7001    enough.  */
7002
7003 static void
7004 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7005 {
7006   gdb_assert (loc->owner != NULL);
7007
7008   if (loc->owner->type == bp_breakpoint
7009       || loc->owner->type == bp_hardware_breakpoint
7010       || is_tracepoint (loc->owner))
7011     {
7012       int is_gnu_ifunc;
7013       const char *function_name;
7014       CORE_ADDR func_addr;
7015
7016       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7017                                           &func_addr, NULL, &is_gnu_ifunc);
7018
7019       if (is_gnu_ifunc && !explicit_loc)
7020         {
7021           struct breakpoint *b = loc->owner;
7022
7023           gdb_assert (loc->pspace == current_program_space);
7024           if (gnu_ifunc_resolve_name (function_name,
7025                                       &loc->requested_address))
7026             {
7027               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7028               loc->address = adjust_breakpoint_address (loc->gdbarch,
7029                                                         loc->requested_address,
7030                                                         b->type);
7031             }
7032           else if (b->type == bp_breakpoint && b->loc == loc
7033                    && loc->next == NULL && b->related_breakpoint == b)
7034             {
7035               /* Create only the whole new breakpoint of this type but do not
7036                  mess more complicated breakpoints with multiple locations.  */
7037               b->type = bp_gnu_ifunc_resolver;
7038               /* Remember the resolver's address for use by the return
7039                  breakpoint.  */
7040               loc->related_address = func_addr;
7041             }
7042         }
7043
7044       if (function_name)
7045         loc->function_name = xstrdup (function_name);
7046     }
7047 }
7048
7049 /* Attempt to determine architecture of location identified by SAL.  */
7050 struct gdbarch *
7051 get_sal_arch (struct symtab_and_line sal)
7052 {
7053   if (sal.section)
7054     return get_objfile_arch (sal.section->objfile);
7055   if (sal.symtab)
7056     return get_objfile_arch (sal.symtab->objfile);
7057
7058   return NULL;
7059 }
7060
7061 /* Low level routine for partially initializing a breakpoint of type
7062    BPTYPE.  The newly created breakpoint's address, section, source
7063    file name, and line number are provided by SAL.
7064
7065    It is expected that the caller will complete the initialization of
7066    the newly created breakpoint struct as well as output any status
7067    information regarding the creation of a new breakpoint.  */
7068
7069 static void
7070 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7071                      struct symtab_and_line sal, enum bptype bptype,
7072                      const struct breakpoint_ops *ops)
7073 {
7074   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7075
7076   add_location_to_breakpoint (b, &sal);
7077
7078   if (bptype != bp_catchpoint)
7079     gdb_assert (sal.pspace != NULL);
7080
7081   /* Store the program space that was used to set the breakpoint,
7082      except for ordinary breakpoints, which are independent of the
7083      program space.  */
7084   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7085     b->pspace = sal.pspace;
7086 }
7087
7088 /* set_raw_breakpoint is a low level routine for allocating and
7089    partially initializing a breakpoint of type BPTYPE.  The newly
7090    created breakpoint's address, section, source file name, and line
7091    number are provided by SAL.  The newly created and partially
7092    initialized breakpoint is added to the breakpoint chain and
7093    is also returned as the value of this function.
7094
7095    It is expected that the caller will complete the initialization of
7096    the newly created breakpoint struct as well as output any status
7097    information regarding the creation of a new breakpoint.  In
7098    particular, set_raw_breakpoint does NOT set the breakpoint
7099    number!  Care should be taken to not allow an error to occur
7100    prior to completing the initialization of the breakpoint.  If this
7101    should happen, a bogus breakpoint will be left on the chain.  */
7102
7103 struct breakpoint *
7104 set_raw_breakpoint (struct gdbarch *gdbarch,
7105                     struct symtab_and_line sal, enum bptype bptype,
7106                     const struct breakpoint_ops *ops)
7107 {
7108   struct breakpoint *b = XNEW (struct breakpoint);
7109
7110   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7111   add_to_breakpoint_chain (b);
7112   return b;
7113 }
7114
7115
7116 /* Note that the breakpoint object B describes a permanent breakpoint
7117    instruction, hard-wired into the inferior's code.  */
7118 void
7119 make_breakpoint_permanent (struct breakpoint *b)
7120 {
7121   struct bp_location *bl;
7122
7123   b->enable_state = bp_permanent;
7124
7125   /* By definition, permanent breakpoints are already present in the
7126      code.  Mark all locations as inserted.  For now,
7127      make_breakpoint_permanent is called in just one place, so it's
7128      hard to say if it's reasonable to have permanent breakpoint with
7129      multiple locations or not, but it's easy to implement.  */
7130   for (bl = b->loc; bl; bl = bl->next)
7131     bl->inserted = 1;
7132 }
7133
7134 /* Call this routine when stepping and nexting to enable a breakpoint
7135    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7136    initiated the operation.  */
7137
7138 void
7139 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7140 {
7141   struct breakpoint *b, *b_tmp;
7142   int thread = tp->num;
7143
7144   /* To avoid having to rescan all objfile symbols at every step,
7145      we maintain a list of continually-inserted but always disabled
7146      longjmp "master" breakpoints.  Here, we simply create momentary
7147      clones of those and enable them for the requested thread.  */
7148   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7149     if (b->pspace == current_program_space
7150         && (b->type == bp_longjmp_master
7151             || b->type == bp_exception_master))
7152       {
7153         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7154         struct breakpoint *clone;
7155
7156         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7157            after their removal.  */
7158         clone = momentary_breakpoint_from_master (b, type,
7159                                                   &longjmp_breakpoint_ops);
7160         clone->thread = thread;
7161       }
7162
7163   tp->initiating_frame = frame;
7164 }
7165
7166 /* Delete all longjmp breakpoints from THREAD.  */
7167 void
7168 delete_longjmp_breakpoint (int thread)
7169 {
7170   struct breakpoint *b, *b_tmp;
7171
7172   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7173     if (b->type == bp_longjmp || b->type == bp_exception)
7174       {
7175         if (b->thread == thread)
7176           delete_breakpoint (b);
7177       }
7178 }
7179
7180 void
7181 delete_longjmp_breakpoint_at_next_stop (int thread)
7182 {
7183   struct breakpoint *b, *b_tmp;
7184
7185   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7186     if (b->type == bp_longjmp || b->type == bp_exception)
7187       {
7188         if (b->thread == thread)
7189           b->disposition = disp_del_at_next_stop;
7190       }
7191 }
7192
7193 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7194    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7195    pointer to any of them.  Return NULL if this system cannot place longjmp
7196    breakpoints.  */
7197
7198 struct breakpoint *
7199 set_longjmp_breakpoint_for_call_dummy (void)
7200 {
7201   struct breakpoint *b, *retval = NULL;
7202
7203   ALL_BREAKPOINTS (b)
7204     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7205       {
7206         struct breakpoint *new_b;
7207
7208         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7209                                                   &momentary_breakpoint_ops);
7210         new_b->thread = pid_to_thread_id (inferior_ptid);
7211
7212         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7213
7214         gdb_assert (new_b->related_breakpoint == new_b);
7215         if (retval == NULL)
7216           retval = new_b;
7217         new_b->related_breakpoint = retval;
7218         while (retval->related_breakpoint != new_b->related_breakpoint)
7219           retval = retval->related_breakpoint;
7220         retval->related_breakpoint = new_b;
7221       }
7222
7223   return retval;
7224 }
7225
7226 /* Verify all existing dummy frames and their associated breakpoints for
7227    THREAD.  Remove those which can no longer be found in the current frame
7228    stack.
7229
7230    You should call this function only at places where it is safe to currently
7231    unwind the whole stack.  Failed stack unwind would discard live dummy
7232    frames.  */
7233
7234 void
7235 check_longjmp_breakpoint_for_call_dummy (int thread)
7236 {
7237   struct breakpoint *b, *b_tmp;
7238
7239   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7240     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7241       {
7242         struct breakpoint *dummy_b = b->related_breakpoint;
7243
7244         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7245           dummy_b = dummy_b->related_breakpoint;
7246         if (dummy_b->type != bp_call_dummy
7247             || frame_find_by_id (dummy_b->frame_id) != NULL)
7248           continue;
7249         
7250         dummy_frame_discard (dummy_b->frame_id);
7251
7252         while (b->related_breakpoint != b)
7253           {
7254             if (b_tmp == b->related_breakpoint)
7255               b_tmp = b->related_breakpoint->next;
7256             delete_breakpoint (b->related_breakpoint);
7257           }
7258         delete_breakpoint (b);
7259       }
7260 }
7261
7262 void
7263 enable_overlay_breakpoints (void)
7264 {
7265   struct breakpoint *b;
7266
7267   ALL_BREAKPOINTS (b)
7268     if (b->type == bp_overlay_event)
7269     {
7270       b->enable_state = bp_enabled;
7271       update_global_location_list (1);
7272       overlay_events_enabled = 1;
7273     }
7274 }
7275
7276 void
7277 disable_overlay_breakpoints (void)
7278 {
7279   struct breakpoint *b;
7280
7281   ALL_BREAKPOINTS (b)
7282     if (b->type == bp_overlay_event)
7283     {
7284       b->enable_state = bp_disabled;
7285       update_global_location_list (0);
7286       overlay_events_enabled = 0;
7287     }
7288 }
7289
7290 /* Set an active std::terminate breakpoint for each std::terminate
7291    master breakpoint.  */
7292 void
7293 set_std_terminate_breakpoint (void)
7294 {
7295   struct breakpoint *b, *b_tmp;
7296
7297   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7298     if (b->pspace == current_program_space
7299         && b->type == bp_std_terminate_master)
7300       {
7301         momentary_breakpoint_from_master (b, bp_std_terminate,
7302                                           &momentary_breakpoint_ops);
7303       }
7304 }
7305
7306 /* Delete all the std::terminate breakpoints.  */
7307 void
7308 delete_std_terminate_breakpoint (void)
7309 {
7310   struct breakpoint *b, *b_tmp;
7311
7312   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7313     if (b->type == bp_std_terminate)
7314       delete_breakpoint (b);
7315 }
7316
7317 struct breakpoint *
7318 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7319 {
7320   struct breakpoint *b;
7321
7322   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7323                                   &internal_breakpoint_ops);
7324
7325   b->enable_state = bp_enabled;
7326   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7327   b->addr_string
7328     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7329
7330   update_global_location_list_nothrow (1);
7331
7332   return b;
7333 }
7334
7335 void
7336 remove_thread_event_breakpoints (void)
7337 {
7338   struct breakpoint *b, *b_tmp;
7339
7340   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7341     if (b->type == bp_thread_event
7342         && b->loc->pspace == current_program_space)
7343       delete_breakpoint (b);
7344 }
7345
7346 struct lang_and_radix
7347   {
7348     enum language lang;
7349     int radix;
7350   };
7351
7352 /* Create a breakpoint for JIT code registration and unregistration.  */
7353
7354 struct breakpoint *
7355 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7356 {
7357   struct breakpoint *b;
7358
7359   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7360                                   &internal_breakpoint_ops);
7361   update_global_location_list_nothrow (1);
7362   return b;
7363 }
7364
7365 /* Remove JIT code registration and unregistration breakpoint(s).  */
7366
7367 void
7368 remove_jit_event_breakpoints (void)
7369 {
7370   struct breakpoint *b, *b_tmp;
7371
7372   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7373     if (b->type == bp_jit_event
7374         && b->loc->pspace == current_program_space)
7375       delete_breakpoint (b);
7376 }
7377
7378 void
7379 remove_solib_event_breakpoints (void)
7380 {
7381   struct breakpoint *b, *b_tmp;
7382
7383   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7384     if (b->type == bp_shlib_event
7385         && b->loc->pspace == current_program_space)
7386       delete_breakpoint (b);
7387 }
7388
7389 struct breakpoint *
7390 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7391 {
7392   struct breakpoint *b;
7393
7394   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7395                                   &internal_breakpoint_ops);
7396   update_global_location_list_nothrow (1);
7397   return b;
7398 }
7399
7400 /* Disable any breakpoints that are on code in shared libraries.  Only
7401    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7402
7403 void
7404 disable_breakpoints_in_shlibs (void)
7405 {
7406   struct bp_location *loc, **locp_tmp;
7407
7408   ALL_BP_LOCATIONS (loc, locp_tmp)
7409   {
7410     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7411     struct breakpoint *b = loc->owner;
7412
7413     /* We apply the check to all breakpoints, including disabled for
7414        those with loc->duplicate set.  This is so that when breakpoint
7415        becomes enabled, or the duplicate is removed, gdb will try to
7416        insert all breakpoints.  If we don't set shlib_disabled here,
7417        we'll try to insert those breakpoints and fail.  */
7418     if (((b->type == bp_breakpoint)
7419          || (b->type == bp_jit_event)
7420          || (b->type == bp_hardware_breakpoint)
7421          || (is_tracepoint (b)))
7422         && loc->pspace == current_program_space
7423         && !loc->shlib_disabled
7424 #ifdef PC_SOLIB
7425         && PC_SOLIB (loc->address)
7426 #else
7427         && solib_name_from_address (loc->pspace, loc->address)
7428 #endif
7429         )
7430       {
7431         loc->shlib_disabled = 1;
7432       }
7433   }
7434 }
7435
7436 /* Disable any breakpoints and tracepoints that are in an unloaded shared
7437    library.  Only apply to enabled breakpoints, disabled ones can just stay
7438    disabled.  */
7439
7440 static void
7441 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7442 {
7443   struct bp_location *loc, **locp_tmp;
7444   int disabled_shlib_breaks = 0;
7445
7446   /* SunOS a.out shared libraries are always mapped, so do not
7447      disable breakpoints; they will only be reported as unloaded
7448      through clear_solib when GDB discards its shared library
7449      list.  See clear_solib for more information.  */
7450   if (exec_bfd != NULL
7451       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7452     return;
7453
7454   ALL_BP_LOCATIONS (loc, locp_tmp)
7455   {
7456     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7457     struct breakpoint *b = loc->owner;
7458
7459     if (solib->pspace == loc->pspace
7460         && !loc->shlib_disabled
7461         && (((b->type == bp_breakpoint
7462               || b->type == bp_jit_event
7463               || b->type == bp_hardware_breakpoint)
7464              && (loc->loc_type == bp_loc_hardware_breakpoint
7465                  || loc->loc_type == bp_loc_software_breakpoint))
7466             || is_tracepoint (b))
7467         && solib_contains_address_p (solib, loc->address))
7468       {
7469         loc->shlib_disabled = 1;
7470         /* At this point, we cannot rely on remove_breakpoint
7471            succeeding so we must mark the breakpoint as not inserted
7472            to prevent future errors occurring in remove_breakpoints.  */
7473         loc->inserted = 0;
7474
7475         /* This may cause duplicate notifications for the same breakpoint.  */
7476         observer_notify_breakpoint_modified (b);
7477
7478         if (!disabled_shlib_breaks)
7479           {
7480             target_terminal_ours_for_output ();
7481             warning (_("Temporarily disabling breakpoints "
7482                        "for unloaded shared library \"%s\""),
7483                      solib->so_name);
7484           }
7485         disabled_shlib_breaks = 1;
7486       }
7487   }
7488 }
7489
7490 /* FORK & VFORK catchpoints.  */
7491
7492 /* An instance of this type is used to represent a fork or vfork
7493    catchpoint.  It includes a "struct breakpoint" as a kind of base
7494    class; users downcast to "struct breakpoint *" when needed.  A
7495    breakpoint is really of this type iff its ops pointer points to
7496    CATCH_FORK_BREAKPOINT_OPS.  */
7497
7498 struct fork_catchpoint
7499 {
7500   /* The base class.  */
7501   struct breakpoint base;
7502
7503   /* Process id of a child process whose forking triggered this
7504      catchpoint.  This field is only valid immediately after this
7505      catchpoint has triggered.  */
7506   ptid_t forked_inferior_pid;
7507 };
7508
7509 /* Implement the "insert" breakpoint_ops method for fork
7510    catchpoints.  */
7511
7512 static int
7513 insert_catch_fork (struct bp_location *bl)
7514 {
7515   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
7516 }
7517
7518 /* Implement the "remove" breakpoint_ops method for fork
7519    catchpoints.  */
7520
7521 static int
7522 remove_catch_fork (struct bp_location *bl)
7523 {
7524   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
7525 }
7526
7527 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7528    catchpoints.  */
7529
7530 static int
7531 breakpoint_hit_catch_fork (const struct bp_location *bl,
7532                            struct address_space *aspace, CORE_ADDR bp_addr,
7533                            const struct target_waitstatus *ws)
7534 {
7535   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7536
7537   if (ws->kind != TARGET_WAITKIND_FORKED)
7538     return 0;
7539
7540   c->forked_inferior_pid = ws->value.related_pid;
7541   return 1;
7542 }
7543
7544 /* Implement the "print_it" breakpoint_ops method for fork
7545    catchpoints.  */
7546
7547 static enum print_stop_action
7548 print_it_catch_fork (bpstat bs)
7549 {
7550   struct ui_out *uiout = current_uiout;
7551   struct breakpoint *b = bs->breakpoint_at;
7552   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7553
7554   annotate_catchpoint (b->number);
7555   if (b->disposition == disp_del)
7556     ui_out_text (uiout, "\nTemporary catchpoint ");
7557   else
7558     ui_out_text (uiout, "\nCatchpoint ");
7559   if (ui_out_is_mi_like_p (uiout))
7560     {
7561       ui_out_field_string (uiout, "reason",
7562                            async_reason_lookup (EXEC_ASYNC_FORK));
7563       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7564     }
7565   ui_out_field_int (uiout, "bkptno", b->number);
7566   ui_out_text (uiout, " (forked process ");
7567   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7568   ui_out_text (uiout, "), ");
7569   return PRINT_SRC_AND_LOC;
7570 }
7571
7572 /* Implement the "print_one" breakpoint_ops method for fork
7573    catchpoints.  */
7574
7575 static void
7576 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7577 {
7578   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7579   struct value_print_options opts;
7580   struct ui_out *uiout = current_uiout;
7581
7582   get_user_print_options (&opts);
7583
7584   /* Field 4, the address, is omitted (which makes the columns not
7585      line up too nicely with the headers, but the effect is relatively
7586      readable).  */
7587   if (opts.addressprint)
7588     ui_out_field_skip (uiout, "addr");
7589   annotate_field (5);
7590   ui_out_text (uiout, "fork");
7591   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7592     {
7593       ui_out_text (uiout, ", process ");
7594       ui_out_field_int (uiout, "what",
7595                         ptid_get_pid (c->forked_inferior_pid));
7596       ui_out_spaces (uiout, 1);
7597     }
7598
7599   if (ui_out_is_mi_like_p (uiout))
7600     ui_out_field_string (uiout, "catch-type", "fork");
7601 }
7602
7603 /* Implement the "print_mention" breakpoint_ops method for fork
7604    catchpoints.  */
7605
7606 static void
7607 print_mention_catch_fork (struct breakpoint *b)
7608 {
7609   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7610 }
7611
7612 /* Implement the "print_recreate" breakpoint_ops method for fork
7613    catchpoints.  */
7614
7615 static void
7616 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7617 {
7618   fprintf_unfiltered (fp, "catch fork");
7619   print_recreate_thread (b, fp);
7620 }
7621
7622 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7623
7624 static struct breakpoint_ops catch_fork_breakpoint_ops;
7625
7626 /* Implement the "insert" breakpoint_ops method for vfork
7627    catchpoints.  */
7628
7629 static int
7630 insert_catch_vfork (struct bp_location *bl)
7631 {
7632   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7633 }
7634
7635 /* Implement the "remove" breakpoint_ops method for vfork
7636    catchpoints.  */
7637
7638 static int
7639 remove_catch_vfork (struct bp_location *bl)
7640 {
7641   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7642 }
7643
7644 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7645    catchpoints.  */
7646
7647 static int
7648 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7649                             struct address_space *aspace, CORE_ADDR bp_addr,
7650                             const struct target_waitstatus *ws)
7651 {
7652   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7653
7654   if (ws->kind != TARGET_WAITKIND_VFORKED)
7655     return 0;
7656
7657   c->forked_inferior_pid = ws->value.related_pid;
7658   return 1;
7659 }
7660
7661 /* Implement the "print_it" breakpoint_ops method for vfork
7662    catchpoints.  */
7663
7664 static enum print_stop_action
7665 print_it_catch_vfork (bpstat bs)
7666 {
7667   struct ui_out *uiout = current_uiout;
7668   struct breakpoint *b = bs->breakpoint_at;
7669   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7670
7671   annotate_catchpoint (b->number);
7672   if (b->disposition == disp_del)
7673     ui_out_text (uiout, "\nTemporary catchpoint ");
7674   else
7675     ui_out_text (uiout, "\nCatchpoint ");
7676   if (ui_out_is_mi_like_p (uiout))
7677     {
7678       ui_out_field_string (uiout, "reason",
7679                            async_reason_lookup (EXEC_ASYNC_VFORK));
7680       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7681     }
7682   ui_out_field_int (uiout, "bkptno", b->number);
7683   ui_out_text (uiout, " (vforked process ");
7684   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7685   ui_out_text (uiout, "), ");
7686   return PRINT_SRC_AND_LOC;
7687 }
7688
7689 /* Implement the "print_one" breakpoint_ops method for vfork
7690    catchpoints.  */
7691
7692 static void
7693 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7694 {
7695   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7696   struct value_print_options opts;
7697   struct ui_out *uiout = current_uiout;
7698
7699   get_user_print_options (&opts);
7700   /* Field 4, the address, is omitted (which makes the columns not
7701      line up too nicely with the headers, but the effect is relatively
7702      readable).  */
7703   if (opts.addressprint)
7704     ui_out_field_skip (uiout, "addr");
7705   annotate_field (5);
7706   ui_out_text (uiout, "vfork");
7707   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7708     {
7709       ui_out_text (uiout, ", process ");
7710       ui_out_field_int (uiout, "what",
7711                         ptid_get_pid (c->forked_inferior_pid));
7712       ui_out_spaces (uiout, 1);
7713     }
7714
7715   if (ui_out_is_mi_like_p (uiout))
7716     ui_out_field_string (uiout, "catch-type", "vfork");
7717 }
7718
7719 /* Implement the "print_mention" breakpoint_ops method for vfork
7720    catchpoints.  */
7721
7722 static void
7723 print_mention_catch_vfork (struct breakpoint *b)
7724 {
7725   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7726 }
7727
7728 /* Implement the "print_recreate" breakpoint_ops method for vfork
7729    catchpoints.  */
7730
7731 static void
7732 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7733 {
7734   fprintf_unfiltered (fp, "catch vfork");
7735   print_recreate_thread (b, fp);
7736 }
7737
7738 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7739
7740 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7741
7742 /* An instance of this type is used to represent an solib catchpoint.
7743    It includes a "struct breakpoint" as a kind of base class; users
7744    downcast to "struct breakpoint *" when needed.  A breakpoint is
7745    really of this type iff its ops pointer points to
7746    CATCH_SOLIB_BREAKPOINT_OPS.  */
7747
7748 struct solib_catchpoint
7749 {
7750   /* The base class.  */
7751   struct breakpoint base;
7752
7753   /* True for "catch load", false for "catch unload".  */
7754   unsigned char is_load;
7755
7756   /* Regular expression to match, if any.  COMPILED is only valid when
7757      REGEX is non-NULL.  */
7758   char *regex;
7759   regex_t compiled;
7760 };
7761
7762 static void
7763 dtor_catch_solib (struct breakpoint *b)
7764 {
7765   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7766
7767   if (self->regex)
7768     regfree (&self->compiled);
7769   xfree (self->regex);
7770
7771   base_breakpoint_ops.dtor (b);
7772 }
7773
7774 static int
7775 insert_catch_solib (struct bp_location *ignore)
7776 {
7777   return 0;
7778 }
7779
7780 static int
7781 remove_catch_solib (struct bp_location *ignore)
7782 {
7783   return 0;
7784 }
7785
7786 static int
7787 breakpoint_hit_catch_solib (const struct bp_location *bl,
7788                             struct address_space *aspace,
7789                             CORE_ADDR bp_addr,
7790                             const struct target_waitstatus *ws)
7791 {
7792   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7793   struct breakpoint *other;
7794
7795   if (ws->kind == TARGET_WAITKIND_LOADED)
7796     return 1;
7797
7798   ALL_BREAKPOINTS (other)
7799   {
7800     struct bp_location *other_bl;
7801
7802     if (other == bl->owner)
7803       continue;
7804
7805     if (other->type != bp_shlib_event)
7806       continue;
7807
7808     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7809       continue;
7810
7811     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7812       {
7813         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7814           return 1;
7815       }
7816   }
7817
7818   return 0;
7819 }
7820
7821 static void
7822 check_status_catch_solib (struct bpstats *bs)
7823 {
7824   struct solib_catchpoint *self
7825     = (struct solib_catchpoint *) bs->breakpoint_at;
7826   int ix;
7827
7828   if (self->is_load)
7829     {
7830       struct so_list *iter;
7831
7832       for (ix = 0;
7833            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7834                         ix, iter);
7835            ++ix)
7836         {
7837           if (!self->regex
7838               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7839             return;
7840         }
7841     }
7842   else
7843     {
7844       char *iter;
7845
7846       for (ix = 0;
7847            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7848                         ix, iter);
7849            ++ix)
7850         {
7851           if (!self->regex
7852               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7853             return;
7854         }
7855     }
7856
7857   bs->stop = 0;
7858   bs->print_it = print_it_noop;
7859 }
7860
7861 static enum print_stop_action
7862 print_it_catch_solib (bpstat bs)
7863 {
7864   struct breakpoint *b = bs->breakpoint_at;
7865   struct ui_out *uiout = current_uiout;
7866
7867   annotate_catchpoint (b->number);
7868   if (b->disposition == disp_del)
7869     ui_out_text (uiout, "\nTemporary catchpoint ");
7870   else
7871     ui_out_text (uiout, "\nCatchpoint ");
7872   ui_out_field_int (uiout, "bkptno", b->number);
7873   ui_out_text (uiout, "\n");
7874   if (ui_out_is_mi_like_p (uiout))
7875     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7876   print_solib_event (1);
7877   return PRINT_SRC_AND_LOC;
7878 }
7879
7880 static void
7881 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7882 {
7883   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7884   struct value_print_options opts;
7885   struct ui_out *uiout = current_uiout;
7886   char *msg;
7887
7888   get_user_print_options (&opts);
7889   /* Field 4, the address, is omitted (which makes the columns not
7890      line up too nicely with the headers, but the effect is relatively
7891      readable).  */
7892   if (opts.addressprint)
7893     {
7894       annotate_field (4);
7895       ui_out_field_skip (uiout, "addr");
7896     }
7897
7898   annotate_field (5);
7899   if (self->is_load)
7900     {
7901       if (self->regex)
7902         msg = xstrprintf (_("load of library matching %s"), self->regex);
7903       else
7904         msg = xstrdup (_("load of library"));
7905     }
7906   else
7907     {
7908       if (self->regex)
7909         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7910       else
7911         msg = xstrdup (_("unload of library"));
7912     }
7913   ui_out_field_string (uiout, "what", msg);
7914   xfree (msg);
7915
7916   if (ui_out_is_mi_like_p (uiout))
7917     ui_out_field_string (uiout, "catch-type",
7918                          self->is_load ? "load" : "unload");
7919 }
7920
7921 static void
7922 print_mention_catch_solib (struct breakpoint *b)
7923 {
7924   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7925
7926   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7927                    self->is_load ? "load" : "unload");
7928 }
7929
7930 static void
7931 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7932 {
7933   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7934
7935   fprintf_unfiltered (fp, "%s %s",
7936                       b->disposition == disp_del ? "tcatch" : "catch",
7937                       self->is_load ? "load" : "unload");
7938   if (self->regex)
7939     fprintf_unfiltered (fp, " %s", self->regex);
7940   fprintf_unfiltered (fp, "\n");
7941 }
7942
7943 static struct breakpoint_ops catch_solib_breakpoint_ops;
7944
7945 /* Shared helper function (MI and CLI) for creating and installing
7946    a shared object event catchpoint.  If IS_LOAD is non-zero then
7947    the events to be caught are load events, otherwise they are
7948    unload events.  If IS_TEMP is non-zero the catchpoint is a
7949    temporary one.  If ENABLED is non-zero the catchpoint is
7950    created in an enabled state.  */
7951
7952 void
7953 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
7954 {
7955   struct solib_catchpoint *c;
7956   struct gdbarch *gdbarch = get_current_arch ();
7957   struct cleanup *cleanup;
7958
7959   if (!arg)
7960     arg = "";
7961   arg = skip_spaces (arg);
7962
7963   c = XCNEW (struct solib_catchpoint);
7964   cleanup = make_cleanup (xfree, c);
7965
7966   if (*arg != '\0')
7967     {
7968       int errcode;
7969
7970       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7971       if (errcode != 0)
7972         {
7973           char *err = get_regcomp_error (errcode, &c->compiled);
7974
7975           make_cleanup (xfree, err);
7976           error (_("Invalid regexp (%s): %s"), err, arg);
7977         }
7978       c->regex = xstrdup (arg);
7979     }
7980
7981   c->is_load = is_load;
7982   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
7983                    &catch_solib_breakpoint_ops);
7984
7985   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
7986
7987   discard_cleanups (cleanup);
7988   install_breakpoint (0, &c->base, 1);
7989 }
7990
7991 /* A helper function that does all the work for "catch load" and
7992    "catch unload".  */
7993
7994 static void
7995 catch_load_or_unload (char *arg, int from_tty, int is_load,
7996                       struct cmd_list_element *command)
7997 {
7998   int tempflag;
7999   const int enabled = 1;
8000
8001   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8002
8003   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8004 }
8005
8006 static void
8007 catch_load_command_1 (char *arg, int from_tty,
8008                       struct cmd_list_element *command)
8009 {
8010   catch_load_or_unload (arg, from_tty, 1, command);
8011 }
8012
8013 static void
8014 catch_unload_command_1 (char *arg, int from_tty,
8015                         struct cmd_list_element *command)
8016 {
8017   catch_load_or_unload (arg, from_tty, 0, command);
8018 }
8019
8020 /* An instance of this type is used to represent a syscall catchpoint.
8021    It includes a "struct breakpoint" as a kind of base class; users
8022    downcast to "struct breakpoint *" when needed.  A breakpoint is
8023    really of this type iff its ops pointer points to
8024    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8025
8026 struct syscall_catchpoint
8027 {
8028   /* The base class.  */
8029   struct breakpoint base;
8030
8031   /* Syscall numbers used for the 'catch syscall' feature.  If no
8032      syscall has been specified for filtering, its value is NULL.
8033      Otherwise, it holds a list of all syscalls to be caught.  The
8034      list elements are allocated with xmalloc.  */
8035   VEC(int) *syscalls_to_be_caught;
8036 };
8037
8038 /* Implement the "dtor" breakpoint_ops method for syscall
8039    catchpoints.  */
8040
8041 static void
8042 dtor_catch_syscall (struct breakpoint *b)
8043 {
8044   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8045
8046   VEC_free (int, c->syscalls_to_be_caught);
8047
8048   base_breakpoint_ops.dtor (b);
8049 }
8050
8051 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8052
8053 struct catch_syscall_inferior_data
8054 {
8055   /* We keep a count of the number of times the user has requested a
8056      particular syscall to be tracked, and pass this information to the
8057      target.  This lets capable targets implement filtering directly.  */
8058
8059   /* Number of times that "any" syscall is requested.  */
8060   int any_syscall_count;
8061
8062   /* Count of each system call.  */
8063   VEC(int) *syscalls_counts;
8064
8065   /* This counts all syscall catch requests, so we can readily determine
8066      if any catching is necessary.  */
8067   int total_syscalls_count;
8068 };
8069
8070 static struct catch_syscall_inferior_data*
8071 get_catch_syscall_inferior_data (struct inferior *inf)
8072 {
8073   struct catch_syscall_inferior_data *inf_data;
8074
8075   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8076   if (inf_data == NULL)
8077     {
8078       inf_data = XZALLOC (struct catch_syscall_inferior_data);
8079       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8080     }
8081
8082   return inf_data;
8083 }
8084
8085 static void
8086 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8087 {
8088   xfree (arg);
8089 }
8090
8091
8092 /* Implement the "insert" breakpoint_ops method for syscall
8093    catchpoints.  */
8094
8095 static int
8096 insert_catch_syscall (struct bp_location *bl)
8097 {
8098   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8099   struct inferior *inf = current_inferior ();
8100   struct catch_syscall_inferior_data *inf_data
8101     = get_catch_syscall_inferior_data (inf);
8102
8103   ++inf_data->total_syscalls_count;
8104   if (!c->syscalls_to_be_caught)
8105     ++inf_data->any_syscall_count;
8106   else
8107     {
8108       int i, iter;
8109
8110       for (i = 0;
8111            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8112            i++)
8113         {
8114           int elem;
8115
8116           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8117             {
8118               int old_size = VEC_length (int, inf_data->syscalls_counts);
8119               uintptr_t vec_addr_offset
8120                 = old_size * ((uintptr_t) sizeof (int));
8121               uintptr_t vec_addr;
8122               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8123               vec_addr = ((uintptr_t) VEC_address (int,
8124                                                   inf_data->syscalls_counts)
8125                           + vec_addr_offset);
8126               memset ((void *) vec_addr, 0,
8127                       (iter + 1 - old_size) * sizeof (int));
8128             }
8129           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8130           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8131         }
8132     }
8133
8134   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
8135                                         inf_data->total_syscalls_count != 0,
8136                                         inf_data->any_syscall_count,
8137                                         VEC_length (int,
8138                                                     inf_data->syscalls_counts),
8139                                         VEC_address (int,
8140                                                      inf_data->syscalls_counts));
8141 }
8142
8143 /* Implement the "remove" breakpoint_ops method for syscall
8144    catchpoints.  */
8145
8146 static int
8147 remove_catch_syscall (struct bp_location *bl)
8148 {
8149   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8150   struct inferior *inf = current_inferior ();
8151   struct catch_syscall_inferior_data *inf_data
8152     = get_catch_syscall_inferior_data (inf);
8153
8154   --inf_data->total_syscalls_count;
8155   if (!c->syscalls_to_be_caught)
8156     --inf_data->any_syscall_count;
8157   else
8158     {
8159       int i, iter;
8160
8161       for (i = 0;
8162            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8163            i++)
8164         {
8165           int elem;
8166           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8167             /* Shouldn't happen.  */
8168             continue;
8169           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8170           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8171         }
8172     }
8173
8174   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
8175                                         inf_data->total_syscalls_count != 0,
8176                                         inf_data->any_syscall_count,
8177                                         VEC_length (int,
8178                                                     inf_data->syscalls_counts),
8179                                         VEC_address (int,
8180                                                      inf_data->syscalls_counts));
8181 }
8182
8183 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8184    catchpoints.  */
8185
8186 static int
8187 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8188                               struct address_space *aspace, CORE_ADDR bp_addr,
8189                               const struct target_waitstatus *ws)
8190 {
8191   /* We must check if we are catching specific syscalls in this
8192      breakpoint.  If we are, then we must guarantee that the called
8193      syscall is the same syscall we are catching.  */
8194   int syscall_number = 0;
8195   const struct syscall_catchpoint *c
8196     = (const struct syscall_catchpoint *) bl->owner;
8197
8198   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8199       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8200     return 0;
8201
8202   syscall_number = ws->value.syscall_number;
8203
8204   /* Now, checking if the syscall is the same.  */
8205   if (c->syscalls_to_be_caught)
8206     {
8207       int i, iter;
8208
8209       for (i = 0;
8210            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8211            i++)
8212         if (syscall_number == iter)
8213           break;
8214       /* Not the same.  */
8215       if (!iter)
8216         return 0;
8217     }
8218
8219   return 1;
8220 }
8221
8222 /* Implement the "print_it" breakpoint_ops method for syscall
8223    catchpoints.  */
8224
8225 static enum print_stop_action
8226 print_it_catch_syscall (bpstat bs)
8227 {
8228   struct ui_out *uiout = current_uiout;
8229   struct breakpoint *b = bs->breakpoint_at;
8230   /* These are needed because we want to know in which state a
8231      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8232      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8233      must print "called syscall" or "returned from syscall".  */
8234   ptid_t ptid;
8235   struct target_waitstatus last;
8236   struct syscall s;
8237
8238   get_last_target_status (&ptid, &last);
8239
8240   get_syscall_by_number (last.value.syscall_number, &s);
8241
8242   annotate_catchpoint (b->number);
8243
8244   if (b->disposition == disp_del)
8245     ui_out_text (uiout, "\nTemporary catchpoint ");
8246   else
8247     ui_out_text (uiout, "\nCatchpoint ");
8248   if (ui_out_is_mi_like_p (uiout))
8249     {
8250       ui_out_field_string (uiout, "reason",
8251                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8252                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8253                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8254       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8255     }
8256   ui_out_field_int (uiout, "bkptno", b->number);
8257
8258   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8259     ui_out_text (uiout, " (call to syscall ");
8260   else
8261     ui_out_text (uiout, " (returned from syscall ");
8262
8263   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8264     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8265   if (s.name != NULL)
8266     ui_out_field_string (uiout, "syscall-name", s.name);
8267
8268   ui_out_text (uiout, "), ");
8269
8270   return PRINT_SRC_AND_LOC;
8271 }
8272
8273 /* Implement the "print_one" breakpoint_ops method for syscall
8274    catchpoints.  */
8275
8276 static void
8277 print_one_catch_syscall (struct breakpoint *b,
8278                          struct bp_location **last_loc)
8279 {
8280   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8281   struct value_print_options opts;
8282   struct ui_out *uiout = current_uiout;
8283
8284   get_user_print_options (&opts);
8285   /* Field 4, the address, is omitted (which makes the columns not
8286      line up too nicely with the headers, but the effect is relatively
8287      readable).  */
8288   if (opts.addressprint)
8289     ui_out_field_skip (uiout, "addr");
8290   annotate_field (5);
8291
8292   if (c->syscalls_to_be_caught
8293       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8294     ui_out_text (uiout, "syscalls \"");
8295   else
8296     ui_out_text (uiout, "syscall \"");
8297
8298   if (c->syscalls_to_be_caught)
8299     {
8300       int i, iter;
8301       char *text = xstrprintf ("%s", "");
8302
8303       for (i = 0;
8304            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8305            i++)
8306         {
8307           char *x = text;
8308           struct syscall s;
8309           get_syscall_by_number (iter, &s);
8310
8311           if (s.name != NULL)
8312             text = xstrprintf ("%s%s, ", text, s.name);
8313           else
8314             text = xstrprintf ("%s%d, ", text, iter);
8315
8316           /* We have to xfree the last 'text' (now stored at 'x')
8317              because xstrprintf dynamically allocates new space for it
8318              on every call.  */
8319           xfree (x);
8320         }
8321       /* Remove the last comma.  */
8322       text[strlen (text) - 2] = '\0';
8323       ui_out_field_string (uiout, "what", text);
8324     }
8325   else
8326     ui_out_field_string (uiout, "what", "<any syscall>");
8327   ui_out_text (uiout, "\" ");
8328
8329   if (ui_out_is_mi_like_p (uiout))
8330     ui_out_field_string (uiout, "catch-type", "syscall");
8331 }
8332
8333 /* Implement the "print_mention" breakpoint_ops method for syscall
8334    catchpoints.  */
8335
8336 static void
8337 print_mention_catch_syscall (struct breakpoint *b)
8338 {
8339   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8340
8341   if (c->syscalls_to_be_caught)
8342     {
8343       int i, iter;
8344
8345       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8346         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8347       else
8348         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8349
8350       for (i = 0;
8351            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8352            i++)
8353         {
8354           struct syscall s;
8355           get_syscall_by_number (iter, &s);
8356
8357           if (s.name)
8358             printf_filtered (" '%s' [%d]", s.name, s.number);
8359           else
8360             printf_filtered (" %d", s.number);
8361         }
8362       printf_filtered (")");
8363     }
8364   else
8365     printf_filtered (_("Catchpoint %d (any syscall)"),
8366                      b->number);
8367 }
8368
8369 /* Implement the "print_recreate" breakpoint_ops method for syscall
8370    catchpoints.  */
8371
8372 static void
8373 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8374 {
8375   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8376
8377   fprintf_unfiltered (fp, "catch syscall");
8378
8379   if (c->syscalls_to_be_caught)
8380     {
8381       int i, iter;
8382
8383       for (i = 0;
8384            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8385            i++)
8386         {
8387           struct syscall s;
8388
8389           get_syscall_by_number (iter, &s);
8390           if (s.name)
8391             fprintf_unfiltered (fp, " %s", s.name);
8392           else
8393             fprintf_unfiltered (fp, " %d", s.number);
8394         }
8395     }
8396   print_recreate_thread (b, fp);
8397 }
8398
8399 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8400
8401 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8402
8403 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8404
8405 static int
8406 syscall_catchpoint_p (struct breakpoint *b)
8407 {
8408   return (b->ops == &catch_syscall_breakpoint_ops);
8409 }
8410
8411 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8412    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8413    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8414    the breakpoint_ops structure associated to the catchpoint.  */
8415
8416 void
8417 init_catchpoint (struct breakpoint *b,
8418                  struct gdbarch *gdbarch, int tempflag,
8419                  char *cond_string,
8420                  const struct breakpoint_ops *ops)
8421 {
8422   struct symtab_and_line sal;
8423
8424   init_sal (&sal);
8425   sal.pspace = current_program_space;
8426
8427   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8428
8429   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8430   b->disposition = tempflag ? disp_del : disp_donttouch;
8431 }
8432
8433 void
8434 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8435 {
8436   add_to_breakpoint_chain (b);
8437   set_breakpoint_number (internal, b);
8438   if (is_tracepoint (b))
8439     set_tracepoint_count (breakpoint_count);
8440   if (!internal)
8441     mention (b);
8442   observer_notify_breakpoint_created (b);
8443
8444   if (update_gll)
8445     update_global_location_list (1);
8446 }
8447
8448 static void
8449 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8450                                     int tempflag, char *cond_string,
8451                                     const struct breakpoint_ops *ops)
8452 {
8453   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8454
8455   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8456
8457   c->forked_inferior_pid = null_ptid;
8458
8459   install_breakpoint (0, &c->base, 1);
8460 }
8461
8462 /* Exec catchpoints.  */
8463
8464 /* An instance of this type is used to represent an exec catchpoint.
8465    It includes a "struct breakpoint" as a kind of base class; users
8466    downcast to "struct breakpoint *" when needed.  A breakpoint is
8467    really of this type iff its ops pointer points to
8468    CATCH_EXEC_BREAKPOINT_OPS.  */
8469
8470 struct exec_catchpoint
8471 {
8472   /* The base class.  */
8473   struct breakpoint base;
8474
8475   /* Filename of a program whose exec triggered this catchpoint.
8476      This field is only valid immediately after this catchpoint has
8477      triggered.  */
8478   char *exec_pathname;
8479 };
8480
8481 /* Implement the "dtor" breakpoint_ops method for exec
8482    catchpoints.  */
8483
8484 static void
8485 dtor_catch_exec (struct breakpoint *b)
8486 {
8487   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8488
8489   xfree (c->exec_pathname);
8490
8491   base_breakpoint_ops.dtor (b);
8492 }
8493
8494 static int
8495 insert_catch_exec (struct bp_location *bl)
8496 {
8497   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
8498 }
8499
8500 static int
8501 remove_catch_exec (struct bp_location *bl)
8502 {
8503   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
8504 }
8505
8506 static int
8507 breakpoint_hit_catch_exec (const struct bp_location *bl,
8508                            struct address_space *aspace, CORE_ADDR bp_addr,
8509                            const struct target_waitstatus *ws)
8510 {
8511   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8512
8513   if (ws->kind != TARGET_WAITKIND_EXECD)
8514     return 0;
8515
8516   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8517   return 1;
8518 }
8519
8520 static enum print_stop_action
8521 print_it_catch_exec (bpstat bs)
8522 {
8523   struct ui_out *uiout = current_uiout;
8524   struct breakpoint *b = bs->breakpoint_at;
8525   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8526
8527   annotate_catchpoint (b->number);
8528   if (b->disposition == disp_del)
8529     ui_out_text (uiout, "\nTemporary catchpoint ");
8530   else
8531     ui_out_text (uiout, "\nCatchpoint ");
8532   if (ui_out_is_mi_like_p (uiout))
8533     {
8534       ui_out_field_string (uiout, "reason",
8535                            async_reason_lookup (EXEC_ASYNC_EXEC));
8536       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8537     }
8538   ui_out_field_int (uiout, "bkptno", b->number);
8539   ui_out_text (uiout, " (exec'd ");
8540   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8541   ui_out_text (uiout, "), ");
8542
8543   return PRINT_SRC_AND_LOC;
8544 }
8545
8546 static void
8547 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8548 {
8549   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8550   struct value_print_options opts;
8551   struct ui_out *uiout = current_uiout;
8552
8553   get_user_print_options (&opts);
8554
8555   /* Field 4, the address, is omitted (which makes the columns
8556      not line up too nicely with the headers, but the effect
8557      is relatively readable).  */
8558   if (opts.addressprint)
8559     ui_out_field_skip (uiout, "addr");
8560   annotate_field (5);
8561   ui_out_text (uiout, "exec");
8562   if (c->exec_pathname != NULL)
8563     {
8564       ui_out_text (uiout, ", program \"");
8565       ui_out_field_string (uiout, "what", c->exec_pathname);
8566       ui_out_text (uiout, "\" ");
8567     }
8568
8569   if (ui_out_is_mi_like_p (uiout))
8570     ui_out_field_string (uiout, "catch-type", "exec");
8571 }
8572
8573 static void
8574 print_mention_catch_exec (struct breakpoint *b)
8575 {
8576   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8577 }
8578
8579 /* Implement the "print_recreate" breakpoint_ops method for exec
8580    catchpoints.  */
8581
8582 static void
8583 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8584 {
8585   fprintf_unfiltered (fp, "catch exec");
8586   print_recreate_thread (b, fp);
8587 }
8588
8589 static struct breakpoint_ops catch_exec_breakpoint_ops;
8590
8591 static void
8592 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8593                                  const struct breakpoint_ops *ops)
8594 {
8595   struct syscall_catchpoint *c;
8596   struct gdbarch *gdbarch = get_current_arch ();
8597
8598   c = XNEW (struct syscall_catchpoint);
8599   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8600   c->syscalls_to_be_caught = filter;
8601
8602   install_breakpoint (0, &c->base, 1);
8603 }
8604
8605 static int
8606 hw_breakpoint_used_count (void)
8607 {
8608   int i = 0;
8609   struct breakpoint *b;
8610   struct bp_location *bl;
8611
8612   ALL_BREAKPOINTS (b)
8613   {
8614     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8615       for (bl = b->loc; bl; bl = bl->next)
8616         {
8617           /* Special types of hardware breakpoints may use more than
8618              one register.  */
8619           i += b->ops->resources_needed (bl);
8620         }
8621   }
8622
8623   return i;
8624 }
8625
8626 /* Returns the resources B would use if it were a hardware
8627    watchpoint.  */
8628
8629 static int
8630 hw_watchpoint_use_count (struct breakpoint *b)
8631 {
8632   int i = 0;
8633   struct bp_location *bl;
8634
8635   if (!breakpoint_enabled (b))
8636     return 0;
8637
8638   for (bl = b->loc; bl; bl = bl->next)
8639     {
8640       /* Special types of hardware watchpoints may use more than
8641          one register.  */
8642       i += b->ops->resources_needed (bl);
8643     }
8644
8645   return i;
8646 }
8647
8648 /* Returns the sum the used resources of all hardware watchpoints of
8649    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8650    the sum of the used resources of all hardware watchpoints of other
8651    types _not_ TYPE.  */
8652
8653 static int
8654 hw_watchpoint_used_count_others (struct breakpoint *except,
8655                                  enum bptype type, int *other_type_used)
8656 {
8657   int i = 0;
8658   struct breakpoint *b;
8659
8660   *other_type_used = 0;
8661   ALL_BREAKPOINTS (b)
8662     {
8663       if (b == except)
8664         continue;
8665       if (!breakpoint_enabled (b))
8666         continue;
8667
8668       if (b->type == type)
8669         i += hw_watchpoint_use_count (b);
8670       else if (is_hardware_watchpoint (b))
8671         *other_type_used = 1;
8672     }
8673
8674   return i;
8675 }
8676
8677 void
8678 disable_watchpoints_before_interactive_call_start (void)
8679 {
8680   struct breakpoint *b;
8681
8682   ALL_BREAKPOINTS (b)
8683   {
8684     if (is_watchpoint (b) && breakpoint_enabled (b))
8685       {
8686         b->enable_state = bp_call_disabled;
8687         update_global_location_list (0);
8688       }
8689   }
8690 }
8691
8692 void
8693 enable_watchpoints_after_interactive_call_stop (void)
8694 {
8695   struct breakpoint *b;
8696
8697   ALL_BREAKPOINTS (b)
8698   {
8699     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8700       {
8701         b->enable_state = bp_enabled;
8702         update_global_location_list (1);
8703       }
8704   }
8705 }
8706
8707 void
8708 disable_breakpoints_before_startup (void)
8709 {
8710   current_program_space->executing_startup = 1;
8711   update_global_location_list (0);
8712 }
8713
8714 void
8715 enable_breakpoints_after_startup (void)
8716 {
8717   current_program_space->executing_startup = 0;
8718   breakpoint_re_set ();
8719 }
8720
8721
8722 /* Set a breakpoint that will evaporate an end of command
8723    at address specified by SAL.
8724    Restrict it to frame FRAME if FRAME is nonzero.  */
8725
8726 struct breakpoint *
8727 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8728                           struct frame_id frame_id, enum bptype type)
8729 {
8730   struct breakpoint *b;
8731
8732   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8733      tail-called one.  */
8734   gdb_assert (!frame_id_artificial_p (frame_id));
8735
8736   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8737   b->enable_state = bp_enabled;
8738   b->disposition = disp_donttouch;
8739   b->frame_id = frame_id;
8740
8741   /* If we're debugging a multi-threaded program, then we want
8742      momentary breakpoints to be active in only a single thread of
8743      control.  */
8744   if (in_thread_list (inferior_ptid))
8745     b->thread = pid_to_thread_id (inferior_ptid);
8746
8747   update_global_location_list_nothrow (1);
8748
8749   return b;
8750 }
8751
8752 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8753    The new breakpoint will have type TYPE, and use OPS as it
8754    breakpoint_ops.  */
8755
8756 static struct breakpoint *
8757 momentary_breakpoint_from_master (struct breakpoint *orig,
8758                                   enum bptype type,
8759                                   const struct breakpoint_ops *ops)
8760 {
8761   struct breakpoint *copy;
8762
8763   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8764   copy->loc = allocate_bp_location (copy);
8765   set_breakpoint_location_function (copy->loc, 1);
8766
8767   copy->loc->gdbarch = orig->loc->gdbarch;
8768   copy->loc->requested_address = orig->loc->requested_address;
8769   copy->loc->address = orig->loc->address;
8770   copy->loc->section = orig->loc->section;
8771   copy->loc->pspace = orig->loc->pspace;
8772   copy->loc->probe = orig->loc->probe;
8773   copy->loc->line_number = orig->loc->line_number;
8774   copy->loc->symtab = orig->loc->symtab;
8775   copy->frame_id = orig->frame_id;
8776   copy->thread = orig->thread;
8777   copy->pspace = orig->pspace;
8778
8779   copy->enable_state = bp_enabled;
8780   copy->disposition = disp_donttouch;
8781   copy->number = internal_breakpoint_number--;
8782
8783   update_global_location_list_nothrow (0);
8784   return copy;
8785 }
8786
8787 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8788    ORIG is NULL.  */
8789
8790 struct breakpoint *
8791 clone_momentary_breakpoint (struct breakpoint *orig)
8792 {
8793   /* If there's nothing to clone, then return nothing.  */
8794   if (orig == NULL)
8795     return NULL;
8796
8797   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8798 }
8799
8800 struct breakpoint *
8801 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8802                                 enum bptype type)
8803 {
8804   struct symtab_and_line sal;
8805
8806   sal = find_pc_line (pc, 0);
8807   sal.pc = pc;
8808   sal.section = find_pc_overlay (pc);
8809   sal.explicit_pc = 1;
8810
8811   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8812 }
8813 \f
8814
8815 /* Tell the user we have just set a breakpoint B.  */
8816
8817 static void
8818 mention (struct breakpoint *b)
8819 {
8820   b->ops->print_mention (b);
8821   if (ui_out_is_mi_like_p (current_uiout))
8822     return;
8823   printf_filtered ("\n");
8824 }
8825 \f
8826
8827 static struct bp_location *
8828 add_location_to_breakpoint (struct breakpoint *b,
8829                             const struct symtab_and_line *sal)
8830 {
8831   struct bp_location *loc, **tmp;
8832   CORE_ADDR adjusted_address;
8833   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8834
8835   if (loc_gdbarch == NULL)
8836     loc_gdbarch = b->gdbarch;
8837
8838   /* Adjust the breakpoint's address prior to allocating a location.
8839      Once we call allocate_bp_location(), that mostly uninitialized
8840      location will be placed on the location chain.  Adjustment of the
8841      breakpoint may cause target_read_memory() to be called and we do
8842      not want its scan of the location chain to find a breakpoint and
8843      location that's only been partially initialized.  */
8844   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8845                                                 sal->pc, b->type);
8846
8847   /* Sort the locations by their ADDRESS.  */
8848   loc = allocate_bp_location (b);
8849   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
8850        tmp = &((*tmp)->next))
8851     ;
8852   loc->next = *tmp;
8853   *tmp = loc;
8854
8855   loc->requested_address = sal->pc;
8856   loc->address = adjusted_address;
8857   loc->pspace = sal->pspace;
8858   loc->probe = sal->probe;
8859   gdb_assert (loc->pspace != NULL);
8860   loc->section = sal->section;
8861   loc->gdbarch = loc_gdbarch;
8862   loc->line_number = sal->line;
8863   loc->symtab = sal->symtab;
8864
8865   set_breakpoint_location_function (loc,
8866                                     sal->explicit_pc || sal->explicit_line);
8867   return loc;
8868 }
8869 \f
8870
8871 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8872    return 0 otherwise.  */
8873
8874 static int
8875 bp_loc_is_permanent (struct bp_location *loc)
8876 {
8877   int len;
8878   CORE_ADDR addr;
8879   const gdb_byte *bpoint;
8880   gdb_byte *target_mem;
8881   struct cleanup *cleanup;
8882   int retval = 0;
8883
8884   gdb_assert (loc != NULL);
8885
8886   addr = loc->address;
8887   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8888
8889   /* Software breakpoints unsupported?  */
8890   if (bpoint == NULL)
8891     return 0;
8892
8893   target_mem = alloca (len);
8894
8895   /* Enable the automatic memory restoration from breakpoints while
8896      we read the memory.  Otherwise we could say about our temporary
8897      breakpoints they are permanent.  */
8898   cleanup = save_current_space_and_thread ();
8899
8900   switch_to_program_space_and_thread (loc->pspace);
8901   make_show_memory_breakpoints_cleanup (0);
8902
8903   if (target_read_memory (loc->address, target_mem, len) == 0
8904       && memcmp (target_mem, bpoint, len) == 0)
8905     retval = 1;
8906
8907   do_cleanups (cleanup);
8908
8909   return retval;
8910 }
8911
8912 /* Build a command list for the dprintf corresponding to the current
8913    settings of the dprintf style options.  */
8914
8915 static void
8916 update_dprintf_command_list (struct breakpoint *b)
8917 {
8918   char *dprintf_args = b->extra_string;
8919   char *printf_line = NULL;
8920
8921   if (!dprintf_args)
8922     return;
8923
8924   dprintf_args = skip_spaces (dprintf_args);
8925
8926   /* Allow a comma, as it may have terminated a location, but don't
8927      insist on it.  */
8928   if (*dprintf_args == ',')
8929     ++dprintf_args;
8930   dprintf_args = skip_spaces (dprintf_args);
8931
8932   if (*dprintf_args != '"')
8933     error (_("Bad format string, missing '\"'."));
8934
8935   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
8936     printf_line = xstrprintf ("printf %s", dprintf_args);
8937   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
8938     {
8939       if (!dprintf_function)
8940         error (_("No function supplied for dprintf call"));
8941
8942       if (dprintf_channel && strlen (dprintf_channel) > 0)
8943         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8944                                   dprintf_function,
8945                                   dprintf_channel,
8946                                   dprintf_args);
8947       else
8948         printf_line = xstrprintf ("call (void) %s (%s)",
8949                                   dprintf_function,
8950                                   dprintf_args);
8951     }
8952   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
8953     {
8954       if (target_can_run_breakpoint_commands ())
8955         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
8956       else
8957         {
8958           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
8959           printf_line = xstrprintf ("printf %s", dprintf_args);
8960         }
8961     }
8962   else
8963     internal_error (__FILE__, __LINE__,
8964                     _("Invalid dprintf style."));
8965
8966   gdb_assert (printf_line != NULL);
8967   /* Manufacture a printf sequence.  */
8968   {
8969     struct command_line *printf_cmd_line
8970       = xmalloc (sizeof (struct command_line));
8971
8972     printf_cmd_line = xmalloc (sizeof (struct command_line));
8973     printf_cmd_line->control_type = simple_control;
8974     printf_cmd_line->body_count = 0;
8975     printf_cmd_line->body_list = NULL;
8976     printf_cmd_line->next = NULL;
8977     printf_cmd_line->line = printf_line;
8978
8979     breakpoint_set_commands (b, printf_cmd_line);
8980   }
8981 }
8982
8983 /* Update all dprintf commands, making their command lists reflect
8984    current style settings.  */
8985
8986 static void
8987 update_dprintf_commands (char *args, int from_tty,
8988                          struct cmd_list_element *c)
8989 {
8990   struct breakpoint *b;
8991
8992   ALL_BREAKPOINTS (b)
8993     {
8994       if (b->type == bp_dprintf)
8995         update_dprintf_command_list (b);
8996     }
8997 }
8998
8999 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9000    as textual description of the location, and COND_STRING
9001    as condition expression.  */
9002
9003 static void
9004 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9005                      struct symtabs_and_lines sals, char *addr_string,
9006                      char *filter, char *cond_string,
9007                      char *extra_string,
9008                      enum bptype type, enum bpdisp disposition,
9009                      int thread, int task, int ignore_count,
9010                      const struct breakpoint_ops *ops, int from_tty,
9011                      int enabled, int internal, unsigned flags,
9012                      int display_canonical)
9013 {
9014   int i;
9015
9016   if (type == bp_hardware_breakpoint)
9017     {
9018       int target_resources_ok;
9019
9020       i = hw_breakpoint_used_count ();
9021       target_resources_ok =
9022         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9023                                             i + 1, 0);
9024       if (target_resources_ok == 0)
9025         error (_("No hardware breakpoint support in the target."));
9026       else if (target_resources_ok < 0)
9027         error (_("Hardware breakpoints used exceeds limit."));
9028     }
9029
9030   gdb_assert (sals.nelts > 0);
9031
9032   for (i = 0; i < sals.nelts; ++i)
9033     {
9034       struct symtab_and_line sal = sals.sals[i];
9035       struct bp_location *loc;
9036
9037       if (from_tty)
9038         {
9039           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9040           if (!loc_gdbarch)
9041             loc_gdbarch = gdbarch;
9042
9043           describe_other_breakpoints (loc_gdbarch,
9044                                       sal.pspace, sal.pc, sal.section, thread);
9045         }
9046
9047       if (i == 0)
9048         {
9049           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9050           b->thread = thread;
9051           b->task = task;
9052
9053           b->cond_string = cond_string;
9054           b->extra_string = extra_string;
9055           b->ignore_count = ignore_count;
9056           b->enable_state = enabled ? bp_enabled : bp_disabled;
9057           b->disposition = disposition;
9058
9059           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9060             b->loc->inserted = 1;
9061
9062           if (type == bp_static_tracepoint)
9063             {
9064               struct tracepoint *t = (struct tracepoint *) b;
9065               struct static_tracepoint_marker marker;
9066
9067               if (strace_marker_p (b))
9068                 {
9069                   /* We already know the marker exists, otherwise, we
9070                      wouldn't see a sal for it.  */
9071                   char *p = &addr_string[3];
9072                   char *endp;
9073                   char *marker_str;
9074
9075                   p = skip_spaces (p);
9076
9077                   endp = skip_to_space (p);
9078
9079                   marker_str = savestring (p, endp - p);
9080                   t->static_trace_marker_id = marker_str;
9081
9082                   printf_filtered (_("Probed static tracepoint "
9083                                      "marker \"%s\"\n"),
9084                                    t->static_trace_marker_id);
9085                 }
9086               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9087                 {
9088                   t->static_trace_marker_id = xstrdup (marker.str_id);
9089                   release_static_tracepoint_marker (&marker);
9090
9091                   printf_filtered (_("Probed static tracepoint "
9092                                      "marker \"%s\"\n"),
9093                                    t->static_trace_marker_id);
9094                 }
9095               else
9096                 warning (_("Couldn't determine the static "
9097                            "tracepoint marker to probe"));
9098             }
9099
9100           loc = b->loc;
9101         }
9102       else
9103         {
9104           loc = add_location_to_breakpoint (b, &sal);
9105           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9106             loc->inserted = 1;
9107         }
9108
9109       if (bp_loc_is_permanent (loc))
9110         make_breakpoint_permanent (b);
9111
9112       if (b->cond_string)
9113         {
9114           const char *arg = b->cond_string;
9115
9116           loc->cond = parse_exp_1 (&arg, loc->address,
9117                                    block_for_pc (loc->address), 0);
9118           if (*arg)
9119               error (_("Garbage '%s' follows condition"), arg);
9120         }
9121
9122       /* Dynamic printf requires and uses additional arguments on the
9123          command line, otherwise it's an error.  */
9124       if (type == bp_dprintf)
9125         {
9126           if (b->extra_string)
9127             update_dprintf_command_list (b);
9128           else
9129             error (_("Format string required"));
9130         }
9131       else if (b->extra_string)
9132         error (_("Garbage '%s' at end of command"), b->extra_string);
9133     }
9134
9135   b->display_canonical = display_canonical;
9136   if (addr_string)
9137     b->addr_string = addr_string;
9138   else
9139     /* addr_string has to be used or breakpoint_re_set will delete
9140        me.  */
9141     b->addr_string
9142       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9143   b->filter = filter;
9144 }
9145
9146 static void
9147 create_breakpoint_sal (struct gdbarch *gdbarch,
9148                        struct symtabs_and_lines sals, char *addr_string,
9149                        char *filter, char *cond_string,
9150                        char *extra_string,
9151                        enum bptype type, enum bpdisp disposition,
9152                        int thread, int task, int ignore_count,
9153                        const struct breakpoint_ops *ops, int from_tty,
9154                        int enabled, int internal, unsigned flags,
9155                        int display_canonical)
9156 {
9157   struct breakpoint *b;
9158   struct cleanup *old_chain;
9159
9160   if (is_tracepoint_type (type))
9161     {
9162       struct tracepoint *t;
9163
9164       t = XCNEW (struct tracepoint);
9165       b = &t->base;
9166     }
9167   else
9168     b = XNEW (struct breakpoint);
9169
9170   old_chain = make_cleanup (xfree, b);
9171
9172   init_breakpoint_sal (b, gdbarch,
9173                        sals, addr_string,
9174                        filter, cond_string, extra_string,
9175                        type, disposition,
9176                        thread, task, ignore_count,
9177                        ops, from_tty,
9178                        enabled, internal, flags,
9179                        display_canonical);
9180   discard_cleanups (old_chain);
9181
9182   install_breakpoint (internal, b, 0);
9183 }
9184
9185 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9186    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9187    value.  COND_STRING, if not NULL, specified the condition to be
9188    used for all breakpoints.  Essentially the only case where
9189    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9190    function.  In that case, it's still not possible to specify
9191    separate conditions for different overloaded functions, so
9192    we take just a single condition string.
9193    
9194    NOTE: If the function succeeds, the caller is expected to cleanup
9195    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9196    array contents).  If the function fails (error() is called), the
9197    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9198    COND and SALS arrays and each of those arrays contents.  */
9199
9200 static void
9201 create_breakpoints_sal (struct gdbarch *gdbarch,
9202                         struct linespec_result *canonical,
9203                         char *cond_string, char *extra_string,
9204                         enum bptype type, enum bpdisp disposition,
9205                         int thread, int task, int ignore_count,
9206                         const struct breakpoint_ops *ops, int from_tty,
9207                         int enabled, int internal, unsigned flags)
9208 {
9209   int i;
9210   struct linespec_sals *lsal;
9211
9212   if (canonical->pre_expanded)
9213     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9214
9215   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9216     {
9217       /* Note that 'addr_string' can be NULL in the case of a plain
9218          'break', without arguments.  */
9219       char *addr_string = (canonical->addr_string
9220                            ? xstrdup (canonical->addr_string)
9221                            : NULL);
9222       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9223       struct cleanup *inner = make_cleanup (xfree, addr_string);
9224
9225       make_cleanup (xfree, filter_string);
9226       create_breakpoint_sal (gdbarch, lsal->sals,
9227                              addr_string,
9228                              filter_string,
9229                              cond_string, extra_string,
9230                              type, disposition,
9231                              thread, task, ignore_count, ops,
9232                              from_tty, enabled, internal, flags,
9233                              canonical->special_display);
9234       discard_cleanups (inner);
9235     }
9236 }
9237
9238 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9239    followed by conditionals.  On return, SALS contains an array of SAL
9240    addresses found.  ADDR_STRING contains a vector of (canonical)
9241    address strings.  ADDRESS points to the end of the SAL.
9242
9243    The array and the line spec strings are allocated on the heap, it is
9244    the caller's responsibility to free them.  */
9245
9246 static void
9247 parse_breakpoint_sals (char **address,
9248                        struct linespec_result *canonical)
9249 {
9250   /* If no arg given, or if first arg is 'if ', use the default
9251      breakpoint.  */
9252   if ((*address) == NULL
9253       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9254     {
9255       /* The last displayed codepoint, if it's valid, is our default breakpoint
9256          address.  */
9257       if (last_displayed_sal_is_valid ())
9258         {
9259           struct linespec_sals lsal;
9260           struct symtab_and_line sal;
9261           CORE_ADDR pc;
9262
9263           init_sal (&sal);              /* Initialize to zeroes.  */
9264           lsal.sals.sals = (struct symtab_and_line *)
9265             xmalloc (sizeof (struct symtab_and_line));
9266
9267           /* Set sal's pspace, pc, symtab, and line to the values
9268              corresponding to the last call to print_frame_info.
9269              Be sure to reinitialize LINE with NOTCURRENT == 0
9270              as the breakpoint line number is inappropriate otherwise.
9271              find_pc_line would adjust PC, re-set it back.  */
9272           get_last_displayed_sal (&sal);
9273           pc = sal.pc;
9274           sal = find_pc_line (pc, 0);
9275
9276           /* "break" without arguments is equivalent to "break *PC"
9277              where PC is the last displayed codepoint's address.  So
9278              make sure to set sal.explicit_pc to prevent GDB from
9279              trying to expand the list of sals to include all other
9280              instances with the same symtab and line.  */
9281           sal.pc = pc;
9282           sal.explicit_pc = 1;
9283
9284           lsal.sals.sals[0] = sal;
9285           lsal.sals.nelts = 1;
9286           lsal.canonical = NULL;
9287
9288           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9289         }
9290       else
9291         error (_("No default breakpoint address now."));
9292     }
9293   else
9294     {
9295       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9296
9297       /* Force almost all breakpoints to be in terms of the
9298          current_source_symtab (which is decode_line_1's default).
9299          This should produce the results we want almost all of the
9300          time while leaving default_breakpoint_* alone.
9301
9302          ObjC: However, don't match an Objective-C method name which
9303          may have a '+' or '-' succeeded by a '['.  */
9304       if (last_displayed_sal_is_valid ()
9305           && (!cursal.symtab
9306               || ((strchr ("+-", (*address)[0]) != NULL)
9307                   && ((*address)[1] != '['))))
9308         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9309                           get_last_displayed_symtab (),
9310                           get_last_displayed_line (),
9311                           canonical, NULL, NULL);
9312       else
9313         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9314                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9315     }
9316 }
9317
9318
9319 /* Convert each SAL into a real PC.  Verify that the PC can be
9320    inserted as a breakpoint.  If it can't throw an error.  */
9321
9322 static void
9323 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9324 {    
9325   int i;
9326
9327   for (i = 0; i < sals->nelts; i++)
9328     resolve_sal_pc (&sals->sals[i]);
9329 }
9330
9331 /* Fast tracepoints may have restrictions on valid locations.  For
9332    instance, a fast tracepoint using a jump instead of a trap will
9333    likely have to overwrite more bytes than a trap would, and so can
9334    only be placed where the instruction is longer than the jump, or a
9335    multi-instruction sequence does not have a jump into the middle of
9336    it, etc.  */
9337
9338 static void
9339 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9340                             struct symtabs_and_lines *sals)
9341 {
9342   int i, rslt;
9343   struct symtab_and_line *sal;
9344   char *msg;
9345   struct cleanup *old_chain;
9346
9347   for (i = 0; i < sals->nelts; i++)
9348     {
9349       struct gdbarch *sarch;
9350
9351       sal = &sals->sals[i];
9352
9353       sarch = get_sal_arch (*sal);
9354       /* We fall back to GDBARCH if there is no architecture
9355          associated with SAL.  */
9356       if (sarch == NULL)
9357         sarch = gdbarch;
9358       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9359                                                NULL, &msg);
9360       old_chain = make_cleanup (xfree, msg);
9361
9362       if (!rslt)
9363         error (_("May not have a fast tracepoint at 0x%s%s"),
9364                paddress (sarch, sal->pc), (msg ? msg : ""));
9365
9366       do_cleanups (old_chain);
9367     }
9368 }
9369
9370 /* Issue an invalid thread ID error.  */
9371
9372 static void ATTRIBUTE_NORETURN
9373 invalid_thread_id_error (int id)
9374 {
9375   error (_("Unknown thread %d."), id);
9376 }
9377
9378 /* Given TOK, a string specification of condition and thread, as
9379    accepted by the 'break' command, extract the condition
9380    string and thread number and set *COND_STRING and *THREAD.
9381    PC identifies the context at which the condition should be parsed.
9382    If no condition is found, *COND_STRING is set to NULL.
9383    If no thread is found, *THREAD is set to -1.  */
9384
9385 static void
9386 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9387                            char **cond_string, int *thread, int *task,
9388                            char **rest)
9389 {
9390   *cond_string = NULL;
9391   *thread = -1;
9392   *task = 0;
9393   *rest = NULL;
9394
9395   while (tok && *tok)
9396     {
9397       const char *end_tok;
9398       int toklen;
9399       const char *cond_start = NULL;
9400       const char *cond_end = NULL;
9401
9402       tok = skip_spaces_const (tok);
9403
9404       if ((*tok == '"' || *tok == ',') && rest)
9405         {
9406           *rest = savestring (tok, strlen (tok));
9407           return;
9408         }
9409
9410       end_tok = skip_to_space_const (tok);
9411
9412       toklen = end_tok - tok;
9413
9414       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9415         {
9416           struct expression *expr;
9417
9418           tok = cond_start = end_tok + 1;
9419           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9420           xfree (expr);
9421           cond_end = tok;
9422           *cond_string = savestring (cond_start, cond_end - cond_start);
9423         }
9424       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9425         {
9426           char *tmptok;
9427
9428           tok = end_tok + 1;
9429           *thread = strtol (tok, &tmptok, 0);
9430           if (tok == tmptok)
9431             error (_("Junk after thread keyword."));
9432           if (!valid_thread_id (*thread))
9433             invalid_thread_id_error (*thread);
9434           tok = tmptok;
9435         }
9436       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9437         {
9438           char *tmptok;
9439
9440           tok = end_tok + 1;
9441           *task = strtol (tok, &tmptok, 0);
9442           if (tok == tmptok)
9443             error (_("Junk after task keyword."));
9444           if (!valid_task_id (*task))
9445             error (_("Unknown task %d."), *task);
9446           tok = tmptok;
9447         }
9448       else if (rest)
9449         {
9450           *rest = savestring (tok, strlen (tok));
9451           return;
9452         }
9453       else
9454         error (_("Junk at end of arguments."));
9455     }
9456 }
9457
9458 /* Decode a static tracepoint marker spec.  */
9459
9460 static struct symtabs_and_lines
9461 decode_static_tracepoint_spec (char **arg_p)
9462 {
9463   VEC(static_tracepoint_marker_p) *markers = NULL;
9464   struct symtabs_and_lines sals;
9465   struct cleanup *old_chain;
9466   char *p = &(*arg_p)[3];
9467   char *endp;
9468   char *marker_str;
9469   int i;
9470
9471   p = skip_spaces (p);
9472
9473   endp = skip_to_space (p);
9474
9475   marker_str = savestring (p, endp - p);
9476   old_chain = make_cleanup (xfree, marker_str);
9477
9478   markers = target_static_tracepoint_markers_by_strid (marker_str);
9479   if (VEC_empty(static_tracepoint_marker_p, markers))
9480     error (_("No known static tracepoint marker named %s"), marker_str);
9481
9482   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9483   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9484
9485   for (i = 0; i < sals.nelts; i++)
9486     {
9487       struct static_tracepoint_marker *marker;
9488
9489       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9490
9491       init_sal (&sals.sals[i]);
9492
9493       sals.sals[i] = find_pc_line (marker->address, 0);
9494       sals.sals[i].pc = marker->address;
9495
9496       release_static_tracepoint_marker (marker);
9497     }
9498
9499   do_cleanups (old_chain);
9500
9501   *arg_p = endp;
9502   return sals;
9503 }
9504
9505 /* Set a breakpoint.  This function is shared between CLI and MI
9506    functions for setting a breakpoint.  This function has two major
9507    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
9508    parameter.  If non-zero, the function will parse arg, extracting
9509    breakpoint location, address and thread.  Otherwise, ARG is just
9510    the location of breakpoint, with condition and thread specified by
9511    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
9512    the breakpoint number will be allocated from the internal
9513    breakpoint count.  Returns true if any breakpoint was created;
9514    false otherwise.  */
9515
9516 int
9517 create_breakpoint (struct gdbarch *gdbarch,
9518                    char *arg, char *cond_string,
9519                    int thread, char *extra_string,
9520                    int parse_condition_and_thread,
9521                    int tempflag, enum bptype type_wanted,
9522                    int ignore_count,
9523                    enum auto_boolean pending_break_support,
9524                    const struct breakpoint_ops *ops,
9525                    int from_tty, int enabled, int internal,
9526                    unsigned flags)
9527 {
9528   volatile struct gdb_exception e;
9529   char *copy_arg = NULL;
9530   char *addr_start = arg;
9531   struct linespec_result canonical;
9532   struct cleanup *old_chain;
9533   struct cleanup *bkpt_chain = NULL;
9534   int pending = 0;
9535   int task = 0;
9536   int prev_bkpt_count = breakpoint_count;
9537
9538   gdb_assert (ops != NULL);
9539
9540   init_linespec_result (&canonical);
9541
9542   TRY_CATCH (e, RETURN_MASK_ALL)
9543     {
9544       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9545                                      addr_start, &copy_arg);
9546     }
9547
9548   /* If caller is interested in rc value from parse, set value.  */
9549   switch (e.reason)
9550     {
9551     case GDB_NO_ERROR:
9552       if (VEC_empty (linespec_sals, canonical.sals))
9553         return 0;
9554       break;
9555     case RETURN_ERROR:
9556       switch (e.error)
9557         {
9558         case NOT_FOUND_ERROR:
9559
9560           /* If pending breakpoint support is turned off, throw
9561              error.  */
9562
9563           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9564             throw_exception (e);
9565
9566           exception_print (gdb_stderr, e);
9567
9568           /* If pending breakpoint support is auto query and the user
9569              selects no, then simply return the error code.  */
9570           if (pending_break_support == AUTO_BOOLEAN_AUTO
9571               && !nquery (_("Make %s pending on future shared library load? "),
9572                           bptype_string (type_wanted)))
9573             return 0;
9574
9575           /* At this point, either the user was queried about setting
9576              a pending breakpoint and selected yes, or pending
9577              breakpoint behavior is on and thus a pending breakpoint
9578              is defaulted on behalf of the user.  */
9579           {
9580             struct linespec_sals lsal;
9581
9582             copy_arg = xstrdup (addr_start);
9583             lsal.canonical = xstrdup (copy_arg);
9584             lsal.sals.nelts = 1;
9585             lsal.sals.sals = XNEW (struct symtab_and_line);
9586             init_sal (&lsal.sals.sals[0]);
9587             pending = 1;
9588             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9589           }
9590           break;
9591         default:
9592           throw_exception (e);
9593         }
9594       break;
9595     default:
9596       throw_exception (e);
9597     }
9598
9599   /* Create a chain of things that always need to be cleaned up.  */
9600   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9601
9602   /* ----------------------------- SNIP -----------------------------
9603      Anything added to the cleanup chain beyond this point is assumed
9604      to be part of a breakpoint.  If the breakpoint create succeeds
9605      then the memory is not reclaimed.  */
9606   bkpt_chain = make_cleanup (null_cleanup, 0);
9607
9608   /* Resolve all line numbers to PC's and verify that the addresses
9609      are ok for the target.  */
9610   if (!pending)
9611     {
9612       int ix;
9613       struct linespec_sals *iter;
9614
9615       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9616         breakpoint_sals_to_pc (&iter->sals);
9617     }
9618
9619   /* Fast tracepoints may have additional restrictions on location.  */
9620   if (!pending && type_wanted == bp_fast_tracepoint)
9621     {
9622       int ix;
9623       struct linespec_sals *iter;
9624
9625       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9626         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9627     }
9628
9629   /* Verify that condition can be parsed, before setting any
9630      breakpoints.  Allocate a separate condition expression for each
9631      breakpoint.  */
9632   if (!pending)
9633     {
9634       struct linespec_sals *lsal;
9635
9636       lsal = VEC_index (linespec_sals, canonical.sals, 0);
9637
9638       if (parse_condition_and_thread)
9639         {
9640             char *rest;
9641             /* Here we only parse 'arg' to separate condition
9642                from thread number, so parsing in context of first
9643                sal is OK.  When setting the breakpoint we'll 
9644                re-parse it in context of each sal.  */
9645
9646             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9647                                        &thread, &task, &rest);
9648             if (cond_string)
9649                 make_cleanup (xfree, cond_string);
9650             if (rest)
9651               make_cleanup (xfree, rest);
9652             if (rest)
9653               extra_string = rest;
9654         }
9655       else
9656         {
9657             /* Create a private copy of condition string.  */
9658             if (cond_string)
9659             {
9660                 cond_string = xstrdup (cond_string);
9661                 make_cleanup (xfree, cond_string);
9662             }
9663             /* Create a private copy of any extra string.  */
9664             if (extra_string)
9665               {
9666                 extra_string = xstrdup (extra_string);
9667                 make_cleanup (xfree, extra_string);
9668               }
9669         }
9670
9671       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
9672                                    cond_string, extra_string, type_wanted,
9673                                    tempflag ? disp_del : disp_donttouch,
9674                                    thread, task, ignore_count, ops,
9675                                    from_tty, enabled, internal, flags);
9676     }
9677   else
9678     {
9679       struct breakpoint *b;
9680
9681       make_cleanup (xfree, copy_arg);
9682
9683       if (is_tracepoint_type (type_wanted))
9684         {
9685           struct tracepoint *t;
9686
9687           t = XCNEW (struct tracepoint);
9688           b = &t->base;
9689         }
9690       else
9691         b = XNEW (struct breakpoint);
9692
9693       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9694
9695       b->addr_string = copy_arg;
9696       if (parse_condition_and_thread)
9697         b->cond_string = NULL;
9698       else
9699         {
9700           /* Create a private copy of condition string.  */
9701           if (cond_string)
9702             {
9703               cond_string = xstrdup (cond_string);
9704               make_cleanup (xfree, cond_string);
9705             }
9706           b->cond_string = cond_string;
9707         }
9708       b->extra_string = NULL;
9709       b->ignore_count = ignore_count;
9710       b->disposition = tempflag ? disp_del : disp_donttouch;
9711       b->condition_not_parsed = 1;
9712       b->enable_state = enabled ? bp_enabled : bp_disabled;
9713       if ((type_wanted != bp_breakpoint
9714            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9715         b->pspace = current_program_space;
9716
9717       install_breakpoint (internal, b, 0);
9718     }
9719   
9720   if (VEC_length (linespec_sals, canonical.sals) > 1)
9721     {
9722       warning (_("Multiple breakpoints were set.\nUse the "
9723                  "\"delete\" command to delete unwanted breakpoints."));
9724       prev_breakpoint_count = prev_bkpt_count;
9725     }
9726
9727   /* That's it.  Discard the cleanups for data inserted into the
9728      breakpoint.  */
9729   discard_cleanups (bkpt_chain);
9730   /* But cleanup everything else.  */
9731   do_cleanups (old_chain);
9732
9733   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9734   update_global_location_list (1);
9735
9736   return 1;
9737 }
9738
9739 /* Set a breakpoint.
9740    ARG is a string describing breakpoint address,
9741    condition, and thread.
9742    FLAG specifies if a breakpoint is hardware on,
9743    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9744    and BP_TEMPFLAG.  */
9745
9746 static void
9747 break_command_1 (char *arg, int flag, int from_tty)
9748 {
9749   int tempflag = flag & BP_TEMPFLAG;
9750   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9751                              ? bp_hardware_breakpoint
9752                              : bp_breakpoint);
9753   struct breakpoint_ops *ops;
9754   const char *arg_cp = arg;
9755
9756   /* Matching breakpoints on probes.  */
9757   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9758     ops = &bkpt_probe_breakpoint_ops;
9759   else
9760     ops = &bkpt_breakpoint_ops;
9761
9762   create_breakpoint (get_current_arch (),
9763                      arg,
9764                      NULL, 0, NULL, 1 /* parse arg */,
9765                      tempflag, type_wanted,
9766                      0 /* Ignore count */,
9767                      pending_break_support,
9768                      ops,
9769                      from_tty,
9770                      1 /* enabled */,
9771                      0 /* internal */,
9772                      0);
9773 }
9774
9775 /* Helper function for break_command_1 and disassemble_command.  */
9776
9777 void
9778 resolve_sal_pc (struct symtab_and_line *sal)
9779 {
9780   CORE_ADDR pc;
9781
9782   if (sal->pc == 0 && sal->symtab != NULL)
9783     {
9784       if (!find_line_pc (sal->symtab, sal->line, &pc))
9785         error (_("No line %d in file \"%s\"."),
9786                sal->line, symtab_to_filename_for_display (sal->symtab));
9787       sal->pc = pc;
9788
9789       /* If this SAL corresponds to a breakpoint inserted using a line
9790          number, then skip the function prologue if necessary.  */
9791       if (sal->explicit_line)
9792         skip_prologue_sal (sal);
9793     }
9794
9795   if (sal->section == 0 && sal->symtab != NULL)
9796     {
9797       struct blockvector *bv;
9798       struct block *b;
9799       struct symbol *sym;
9800
9801       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9802       if (bv != NULL)
9803         {
9804           sym = block_linkage_function (b);
9805           if (sym != NULL)
9806             {
9807               fixup_symbol_section (sym, sal->symtab->objfile);
9808               sal->section = SYMBOL_OBJ_SECTION (sym);
9809             }
9810           else
9811             {
9812               /* It really is worthwhile to have the section, so we'll
9813                  just have to look harder. This case can be executed
9814                  if we have line numbers but no functions (as can
9815                  happen in assembly source).  */
9816
9817               struct minimal_symbol *msym;
9818               struct cleanup *old_chain = save_current_space_and_thread ();
9819
9820               switch_to_program_space_and_thread (sal->pspace);
9821
9822               msym = lookup_minimal_symbol_by_pc (sal->pc);
9823               if (msym)
9824                 sal->section = SYMBOL_OBJ_SECTION (msym);
9825
9826               do_cleanups (old_chain);
9827             }
9828         }
9829     }
9830 }
9831
9832 void
9833 break_command (char *arg, int from_tty)
9834 {
9835   break_command_1 (arg, 0, from_tty);
9836 }
9837
9838 void
9839 tbreak_command (char *arg, int from_tty)
9840 {
9841   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9842 }
9843
9844 static void
9845 hbreak_command (char *arg, int from_tty)
9846 {
9847   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9848 }
9849
9850 static void
9851 thbreak_command (char *arg, int from_tty)
9852 {
9853   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9854 }
9855
9856 static void
9857 stop_command (char *arg, int from_tty)
9858 {
9859   printf_filtered (_("Specify the type of breakpoint to set.\n\
9860 Usage: stop in <function | address>\n\
9861        stop at <line>\n"));
9862 }
9863
9864 static void
9865 stopin_command (char *arg, int from_tty)
9866 {
9867   int badInput = 0;
9868
9869   if (arg == (char *) NULL)
9870     badInput = 1;
9871   else if (*arg != '*')
9872     {
9873       char *argptr = arg;
9874       int hasColon = 0;
9875
9876       /* Look for a ':'.  If this is a line number specification, then
9877          say it is bad, otherwise, it should be an address or
9878          function/method name.  */
9879       while (*argptr && !hasColon)
9880         {
9881           hasColon = (*argptr == ':');
9882           argptr++;
9883         }
9884
9885       if (hasColon)
9886         badInput = (*argptr != ':');    /* Not a class::method */
9887       else
9888         badInput = isdigit (*arg);      /* a simple line number */
9889     }
9890
9891   if (badInput)
9892     printf_filtered (_("Usage: stop in <function | address>\n"));
9893   else
9894     break_command_1 (arg, 0, from_tty);
9895 }
9896
9897 static void
9898 stopat_command (char *arg, int from_tty)
9899 {
9900   int badInput = 0;
9901
9902   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9903     badInput = 1;
9904   else
9905     {
9906       char *argptr = arg;
9907       int hasColon = 0;
9908
9909       /* Look for a ':'.  If there is a '::' then get out, otherwise
9910          it is probably a line number.  */
9911       while (*argptr && !hasColon)
9912         {
9913           hasColon = (*argptr == ':');
9914           argptr++;
9915         }
9916
9917       if (hasColon)
9918         badInput = (*argptr == ':');    /* we have class::method */
9919       else
9920         badInput = !isdigit (*arg);     /* not a line number */
9921     }
9922
9923   if (badInput)
9924     printf_filtered (_("Usage: stop at <line>\n"));
9925   else
9926     break_command_1 (arg, 0, from_tty);
9927 }
9928
9929 /* The dynamic printf command is mostly like a regular breakpoint, but
9930    with a prewired command list consisting of a single output command,
9931    built from extra arguments supplied on the dprintf command
9932    line.  */
9933
9934 static void
9935 dprintf_command (char *arg, int from_tty)
9936 {
9937   create_breakpoint (get_current_arch (),
9938                      arg,
9939                      NULL, 0, NULL, 1 /* parse arg */,
9940                      0, bp_dprintf,
9941                      0 /* Ignore count */,
9942                      pending_break_support,
9943                      &dprintf_breakpoint_ops,
9944                      from_tty,
9945                      1 /* enabled */,
9946                      0 /* internal */,
9947                      0);
9948 }
9949
9950 static void
9951 agent_printf_command (char *arg, int from_tty)
9952 {
9953   error (_("May only run agent-printf on the target"));
9954 }
9955
9956 /* Implement the "breakpoint_hit" breakpoint_ops method for
9957    ranged breakpoints.  */
9958
9959 static int
9960 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9961                                   struct address_space *aspace,
9962                                   CORE_ADDR bp_addr,
9963                                   const struct target_waitstatus *ws)
9964 {
9965   if (ws->kind != TARGET_WAITKIND_STOPPED
9966       || ws->value.sig != GDB_SIGNAL_TRAP)
9967     return 0;
9968
9969   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9970                                          bl->length, aspace, bp_addr);
9971 }
9972
9973 /* Implement the "resources_needed" breakpoint_ops method for
9974    ranged breakpoints.  */
9975
9976 static int
9977 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9978 {
9979   return target_ranged_break_num_registers ();
9980 }
9981
9982 /* Implement the "print_it" breakpoint_ops method for
9983    ranged breakpoints.  */
9984
9985 static enum print_stop_action
9986 print_it_ranged_breakpoint (bpstat bs)
9987 {
9988   struct breakpoint *b = bs->breakpoint_at;
9989   struct bp_location *bl = b->loc;
9990   struct ui_out *uiout = current_uiout;
9991
9992   gdb_assert (b->type == bp_hardware_breakpoint);
9993
9994   /* Ranged breakpoints have only one location.  */
9995   gdb_assert (bl && bl->next == NULL);
9996
9997   annotate_breakpoint (b->number);
9998   if (b->disposition == disp_del)
9999     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10000   else
10001     ui_out_text (uiout, "\nRanged breakpoint ");
10002   if (ui_out_is_mi_like_p (uiout))
10003     {
10004       ui_out_field_string (uiout, "reason",
10005                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10006       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10007     }
10008   ui_out_field_int (uiout, "bkptno", b->number);
10009   ui_out_text (uiout, ", ");
10010
10011   return PRINT_SRC_AND_LOC;
10012 }
10013
10014 /* Implement the "print_one" breakpoint_ops method for
10015    ranged breakpoints.  */
10016
10017 static void
10018 print_one_ranged_breakpoint (struct breakpoint *b,
10019                              struct bp_location **last_loc)
10020 {
10021   struct bp_location *bl = b->loc;
10022   struct value_print_options opts;
10023   struct ui_out *uiout = current_uiout;
10024
10025   /* Ranged breakpoints have only one location.  */
10026   gdb_assert (bl && bl->next == NULL);
10027
10028   get_user_print_options (&opts);
10029
10030   if (opts.addressprint)
10031     /* We don't print the address range here, it will be printed later
10032        by print_one_detail_ranged_breakpoint.  */
10033     ui_out_field_skip (uiout, "addr");
10034   annotate_field (5);
10035   print_breakpoint_location (b, bl);
10036   *last_loc = bl;
10037 }
10038
10039 /* Implement the "print_one_detail" breakpoint_ops method for
10040    ranged breakpoints.  */
10041
10042 static void
10043 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10044                                     struct ui_out *uiout)
10045 {
10046   CORE_ADDR address_start, address_end;
10047   struct bp_location *bl = b->loc;
10048   struct ui_file *stb = mem_fileopen ();
10049   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10050
10051   gdb_assert (bl);
10052
10053   address_start = bl->address;
10054   address_end = address_start + bl->length - 1;
10055
10056   ui_out_text (uiout, "\taddress range: ");
10057   fprintf_unfiltered (stb, "[%s, %s]",
10058                       print_core_address (bl->gdbarch, address_start),
10059                       print_core_address (bl->gdbarch, address_end));
10060   ui_out_field_stream (uiout, "addr", stb);
10061   ui_out_text (uiout, "\n");
10062
10063   do_cleanups (cleanup);
10064 }
10065
10066 /* Implement the "print_mention" breakpoint_ops method for
10067    ranged breakpoints.  */
10068
10069 static void
10070 print_mention_ranged_breakpoint (struct breakpoint *b)
10071 {
10072   struct bp_location *bl = b->loc;
10073   struct ui_out *uiout = current_uiout;
10074
10075   gdb_assert (bl);
10076   gdb_assert (b->type == bp_hardware_breakpoint);
10077
10078   if (ui_out_is_mi_like_p (uiout))
10079     return;
10080
10081   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10082                    b->number, paddress (bl->gdbarch, bl->address),
10083                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10084 }
10085
10086 /* Implement the "print_recreate" breakpoint_ops method for
10087    ranged breakpoints.  */
10088
10089 static void
10090 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10091 {
10092   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10093                       b->addr_string_range_end);
10094   print_recreate_thread (b, fp);
10095 }
10096
10097 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10098
10099 static struct breakpoint_ops ranged_breakpoint_ops;
10100
10101 /* Find the address where the end of the breakpoint range should be
10102    placed, given the SAL of the end of the range.  This is so that if
10103    the user provides a line number, the end of the range is set to the
10104    last instruction of the given line.  */
10105
10106 static CORE_ADDR
10107 find_breakpoint_range_end (struct symtab_and_line sal)
10108 {
10109   CORE_ADDR end;
10110
10111   /* If the user provided a PC value, use it.  Otherwise,
10112      find the address of the end of the given location.  */
10113   if (sal.explicit_pc)
10114     end = sal.pc;
10115   else
10116     {
10117       int ret;
10118       CORE_ADDR start;
10119
10120       ret = find_line_pc_range (sal, &start, &end);
10121       if (!ret)
10122         error (_("Could not find location of the end of the range."));
10123
10124       /* find_line_pc_range returns the start of the next line.  */
10125       end--;
10126     }
10127
10128   return end;
10129 }
10130
10131 /* Implement the "break-range" CLI command.  */
10132
10133 static void
10134 break_range_command (char *arg, int from_tty)
10135 {
10136   char *arg_start, *addr_string_start, *addr_string_end;
10137   struct linespec_result canonical_start, canonical_end;
10138   int bp_count, can_use_bp, length;
10139   CORE_ADDR end;
10140   struct breakpoint *b;
10141   struct symtab_and_line sal_start, sal_end;
10142   struct cleanup *cleanup_bkpt;
10143   struct linespec_sals *lsal_start, *lsal_end;
10144
10145   /* We don't support software ranged breakpoints.  */
10146   if (target_ranged_break_num_registers () < 0)
10147     error (_("This target does not support hardware ranged breakpoints."));
10148
10149   bp_count = hw_breakpoint_used_count ();
10150   bp_count += target_ranged_break_num_registers ();
10151   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10152                                                    bp_count, 0);
10153   if (can_use_bp < 0)
10154     error (_("Hardware breakpoints used exceeds limit."));
10155
10156   arg = skip_spaces (arg);
10157   if (arg == NULL || arg[0] == '\0')
10158     error(_("No address range specified."));
10159
10160   init_linespec_result (&canonical_start);
10161
10162   arg_start = arg;
10163   parse_breakpoint_sals (&arg, &canonical_start);
10164
10165   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10166
10167   if (arg[0] != ',')
10168     error (_("Too few arguments."));
10169   else if (VEC_empty (linespec_sals, canonical_start.sals))
10170     error (_("Could not find location of the beginning of the range."));
10171
10172   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10173
10174   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10175       || lsal_start->sals.nelts != 1)
10176     error (_("Cannot create a ranged breakpoint with multiple locations."));
10177
10178   sal_start = lsal_start->sals.sals[0];
10179   addr_string_start = savestring (arg_start, arg - arg_start);
10180   make_cleanup (xfree, addr_string_start);
10181
10182   arg++;        /* Skip the comma.  */
10183   arg = skip_spaces (arg);
10184
10185   /* Parse the end location.  */
10186
10187   init_linespec_result (&canonical_end);
10188   arg_start = arg;
10189
10190   /* We call decode_line_full directly here instead of using
10191      parse_breakpoint_sals because we need to specify the start location's
10192      symtab and line as the default symtab and line for the end of the
10193      range.  This makes it possible to have ranges like "foo.c:27, +14",
10194      where +14 means 14 lines from the start location.  */
10195   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10196                     sal_start.symtab, sal_start.line,
10197                     &canonical_end, NULL, NULL);
10198
10199   make_cleanup_destroy_linespec_result (&canonical_end);
10200
10201   if (VEC_empty (linespec_sals, canonical_end.sals))
10202     error (_("Could not find location of the end of the range."));
10203
10204   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10205   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10206       || lsal_end->sals.nelts != 1)
10207     error (_("Cannot create a ranged breakpoint with multiple locations."));
10208
10209   sal_end = lsal_end->sals.sals[0];
10210   addr_string_end = savestring (arg_start, arg - arg_start);
10211   make_cleanup (xfree, addr_string_end);
10212
10213   end = find_breakpoint_range_end (sal_end);
10214   if (sal_start.pc > end)
10215     error (_("Invalid address range, end precedes start."));
10216
10217   length = end - sal_start.pc + 1;
10218   if (length < 0)
10219     /* Length overflowed.  */
10220     error (_("Address range too large."));
10221   else if (length == 1)
10222     {
10223       /* This range is simple enough to be handled by
10224          the `hbreak' command.  */
10225       hbreak_command (addr_string_start, 1);
10226
10227       do_cleanups (cleanup_bkpt);
10228
10229       return;
10230     }
10231
10232   /* Now set up the breakpoint.  */
10233   b = set_raw_breakpoint (get_current_arch (), sal_start,
10234                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10235   set_breakpoint_count (breakpoint_count + 1);
10236   b->number = breakpoint_count;
10237   b->disposition = disp_donttouch;
10238   b->addr_string = xstrdup (addr_string_start);
10239   b->addr_string_range_end = xstrdup (addr_string_end);
10240   b->loc->length = length;
10241
10242   do_cleanups (cleanup_bkpt);
10243
10244   mention (b);
10245   observer_notify_breakpoint_created (b);
10246   update_global_location_list (1);
10247 }
10248
10249 /*  Return non-zero if EXP is verified as constant.  Returned zero
10250     means EXP is variable.  Also the constant detection may fail for
10251     some constant expressions and in such case still falsely return
10252     zero.  */
10253
10254 static int
10255 watchpoint_exp_is_const (const struct expression *exp)
10256 {
10257   int i = exp->nelts;
10258
10259   while (i > 0)
10260     {
10261       int oplenp, argsp;
10262
10263       /* We are only interested in the descriptor of each element.  */
10264       operator_length (exp, i, &oplenp, &argsp);
10265       i -= oplenp;
10266
10267       switch (exp->elts[i].opcode)
10268         {
10269         case BINOP_ADD:
10270         case BINOP_SUB:
10271         case BINOP_MUL:
10272         case BINOP_DIV:
10273         case BINOP_REM:
10274         case BINOP_MOD:
10275         case BINOP_LSH:
10276         case BINOP_RSH:
10277         case BINOP_LOGICAL_AND:
10278         case BINOP_LOGICAL_OR:
10279         case BINOP_BITWISE_AND:
10280         case BINOP_BITWISE_IOR:
10281         case BINOP_BITWISE_XOR:
10282         case BINOP_EQUAL:
10283         case BINOP_NOTEQUAL:
10284         case BINOP_LESS:
10285         case BINOP_GTR:
10286         case BINOP_LEQ:
10287         case BINOP_GEQ:
10288         case BINOP_REPEAT:
10289         case BINOP_COMMA:
10290         case BINOP_EXP:
10291         case BINOP_MIN:
10292         case BINOP_MAX:
10293         case BINOP_INTDIV:
10294         case BINOP_CONCAT:
10295         case BINOP_IN:
10296         case BINOP_RANGE:
10297         case TERNOP_COND:
10298         case TERNOP_SLICE:
10299
10300         case OP_LONG:
10301         case OP_DOUBLE:
10302         case OP_DECFLOAT:
10303         case OP_LAST:
10304         case OP_COMPLEX:
10305         case OP_STRING:
10306         case OP_ARRAY:
10307         case OP_TYPE:
10308         case OP_TYPEOF:
10309         case OP_DECLTYPE:
10310         case OP_NAME:
10311         case OP_OBJC_NSSTRING:
10312
10313         case UNOP_NEG:
10314         case UNOP_LOGICAL_NOT:
10315         case UNOP_COMPLEMENT:
10316         case UNOP_ADDR:
10317         case UNOP_HIGH:
10318         case UNOP_CAST:
10319
10320         case UNOP_CAST_TYPE:
10321         case UNOP_REINTERPRET_CAST:
10322         case UNOP_DYNAMIC_CAST:
10323           /* Unary, binary and ternary operators: We have to check
10324              their operands.  If they are constant, then so is the
10325              result of that operation.  For instance, if A and B are
10326              determined to be constants, then so is "A + B".
10327
10328              UNOP_IND is one exception to the rule above, because the
10329              value of *ADDR is not necessarily a constant, even when
10330              ADDR is.  */
10331           break;
10332
10333         case OP_VAR_VALUE:
10334           /* Check whether the associated symbol is a constant.
10335
10336              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10337              possible that a buggy compiler could mark a variable as
10338              constant even when it is not, and TYPE_CONST would return
10339              true in this case, while SYMBOL_CLASS wouldn't.
10340
10341              We also have to check for function symbols because they
10342              are always constant.  */
10343           {
10344             struct symbol *s = exp->elts[i + 2].symbol;
10345
10346             if (SYMBOL_CLASS (s) != LOC_BLOCK
10347                 && SYMBOL_CLASS (s) != LOC_CONST
10348                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10349               return 0;
10350             break;
10351           }
10352
10353         /* The default action is to return 0 because we are using
10354            the optimistic approach here: If we don't know something,
10355            then it is not a constant.  */
10356         default:
10357           return 0;
10358         }
10359     }
10360
10361   return 1;
10362 }
10363
10364 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10365
10366 static void
10367 dtor_watchpoint (struct breakpoint *self)
10368 {
10369   struct watchpoint *w = (struct watchpoint *) self;
10370
10371   xfree (w->cond_exp);
10372   xfree (w->exp);
10373   xfree (w->exp_string);
10374   xfree (w->exp_string_reparse);
10375   value_free (w->val);
10376
10377   base_breakpoint_ops.dtor (self);
10378 }
10379
10380 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10381
10382 static void
10383 re_set_watchpoint (struct breakpoint *b)
10384 {
10385   struct watchpoint *w = (struct watchpoint *) b;
10386
10387   /* Watchpoint can be either on expression using entirely global
10388      variables, or it can be on local variables.
10389
10390      Watchpoints of the first kind are never auto-deleted, and even
10391      persist across program restarts.  Since they can use variables
10392      from shared libraries, we need to reparse expression as libraries
10393      are loaded and unloaded.
10394
10395      Watchpoints on local variables can also change meaning as result
10396      of solib event.  For example, if a watchpoint uses both a local
10397      and a global variables in expression, it's a local watchpoint,
10398      but unloading of a shared library will make the expression
10399      invalid.  This is not a very common use case, but we still
10400      re-evaluate expression, to avoid surprises to the user.
10401
10402      Note that for local watchpoints, we re-evaluate it only if
10403      watchpoints frame id is still valid.  If it's not, it means the
10404      watchpoint is out of scope and will be deleted soon.  In fact,
10405      I'm not sure we'll ever be called in this case.
10406
10407      If a local watchpoint's frame id is still valid, then
10408      w->exp_valid_block is likewise valid, and we can safely use it.
10409
10410      Don't do anything about disabled watchpoints, since they will be
10411      reevaluated again when enabled.  */
10412   update_watchpoint (w, 1 /* reparse */);
10413 }
10414
10415 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10416
10417 static int
10418 insert_watchpoint (struct bp_location *bl)
10419 {
10420   struct watchpoint *w = (struct watchpoint *) bl->owner;
10421   int length = w->exact ? 1 : bl->length;
10422
10423   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10424                                    w->cond_exp);
10425 }
10426
10427 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10428
10429 static int
10430 remove_watchpoint (struct bp_location *bl)
10431 {
10432   struct watchpoint *w = (struct watchpoint *) bl->owner;
10433   int length = w->exact ? 1 : bl->length;
10434
10435   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10436                                    w->cond_exp);
10437 }
10438
10439 static int
10440 breakpoint_hit_watchpoint (const struct bp_location *bl,
10441                            struct address_space *aspace, CORE_ADDR bp_addr,
10442                            const struct target_waitstatus *ws)
10443 {
10444   struct breakpoint *b = bl->owner;
10445   struct watchpoint *w = (struct watchpoint *) b;
10446
10447   /* Continuable hardware watchpoints are treated as non-existent if the
10448      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10449      some data address).  Otherwise gdb won't stop on a break instruction
10450      in the code (not from a breakpoint) when a hardware watchpoint has
10451      been defined.  Also skip watchpoints which we know did not trigger
10452      (did not match the data address).  */
10453   if (is_hardware_watchpoint (b)
10454       && w->watchpoint_triggered == watch_triggered_no)
10455     return 0;
10456
10457   return 1;
10458 }
10459
10460 static void
10461 check_status_watchpoint (bpstat bs)
10462 {
10463   gdb_assert (is_watchpoint (bs->breakpoint_at));
10464
10465   bpstat_check_watchpoint (bs);
10466 }
10467
10468 /* Implement the "resources_needed" breakpoint_ops method for
10469    hardware watchpoints.  */
10470
10471 static int
10472 resources_needed_watchpoint (const struct bp_location *bl)
10473 {
10474   struct watchpoint *w = (struct watchpoint *) bl->owner;
10475   int length = w->exact? 1 : bl->length;
10476
10477   return target_region_ok_for_hw_watchpoint (bl->address, length);
10478 }
10479
10480 /* Implement the "works_in_software_mode" breakpoint_ops method for
10481    hardware watchpoints.  */
10482
10483 static int
10484 works_in_software_mode_watchpoint (const struct breakpoint *b)
10485 {
10486   /* Read and access watchpoints only work with hardware support.  */
10487   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10488 }
10489
10490 static enum print_stop_action
10491 print_it_watchpoint (bpstat bs)
10492 {
10493   struct cleanup *old_chain;
10494   struct breakpoint *b;
10495   const struct bp_location *bl;
10496   struct ui_file *stb;
10497   enum print_stop_action result;
10498   struct watchpoint *w;
10499   struct ui_out *uiout = current_uiout;
10500
10501   gdb_assert (bs->bp_location_at != NULL);
10502
10503   bl = bs->bp_location_at;
10504   b = bs->breakpoint_at;
10505   w = (struct watchpoint *) b;
10506
10507   stb = mem_fileopen ();
10508   old_chain = make_cleanup_ui_file_delete (stb);
10509
10510   switch (b->type)
10511     {
10512     case bp_watchpoint:
10513     case bp_hardware_watchpoint:
10514       annotate_watchpoint (b->number);
10515       if (ui_out_is_mi_like_p (uiout))
10516         ui_out_field_string
10517           (uiout, "reason",
10518            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10519       mention (b);
10520       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10521       ui_out_text (uiout, "\nOld value = ");
10522       watchpoint_value_print (bs->old_val, stb);
10523       ui_out_field_stream (uiout, "old", stb);
10524       ui_out_text (uiout, "\nNew value = ");
10525       watchpoint_value_print (w->val, stb);
10526       ui_out_field_stream (uiout, "new", stb);
10527       ui_out_text (uiout, "\n");
10528       /* More than one watchpoint may have been triggered.  */
10529       result = PRINT_UNKNOWN;
10530       break;
10531
10532     case bp_read_watchpoint:
10533       if (ui_out_is_mi_like_p (uiout))
10534         ui_out_field_string
10535           (uiout, "reason",
10536            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10537       mention (b);
10538       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10539       ui_out_text (uiout, "\nValue = ");
10540       watchpoint_value_print (w->val, stb);
10541       ui_out_field_stream (uiout, "value", stb);
10542       ui_out_text (uiout, "\n");
10543       result = PRINT_UNKNOWN;
10544       break;
10545
10546     case bp_access_watchpoint:
10547       if (bs->old_val != NULL)
10548         {
10549           annotate_watchpoint (b->number);
10550           if (ui_out_is_mi_like_p (uiout))
10551             ui_out_field_string
10552               (uiout, "reason",
10553                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10554           mention (b);
10555           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10556           ui_out_text (uiout, "\nOld value = ");
10557           watchpoint_value_print (bs->old_val, stb);
10558           ui_out_field_stream (uiout, "old", stb);
10559           ui_out_text (uiout, "\nNew value = ");
10560         }
10561       else
10562         {
10563           mention (b);
10564           if (ui_out_is_mi_like_p (uiout))
10565             ui_out_field_string
10566               (uiout, "reason",
10567                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10568           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10569           ui_out_text (uiout, "\nValue = ");
10570         }
10571       watchpoint_value_print (w->val, stb);
10572       ui_out_field_stream (uiout, "new", stb);
10573       ui_out_text (uiout, "\n");
10574       result = PRINT_UNKNOWN;
10575       break;
10576     default:
10577       result = PRINT_UNKNOWN;
10578     }
10579
10580   do_cleanups (old_chain);
10581   return result;
10582 }
10583
10584 /* Implement the "print_mention" breakpoint_ops method for hardware
10585    watchpoints.  */
10586
10587 static void
10588 print_mention_watchpoint (struct breakpoint *b)
10589 {
10590   struct cleanup *ui_out_chain;
10591   struct watchpoint *w = (struct watchpoint *) b;
10592   struct ui_out *uiout = current_uiout;
10593
10594   switch (b->type)
10595     {
10596     case bp_watchpoint:
10597       ui_out_text (uiout, "Watchpoint ");
10598       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10599       break;
10600     case bp_hardware_watchpoint:
10601       ui_out_text (uiout, "Hardware watchpoint ");
10602       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10603       break;
10604     case bp_read_watchpoint:
10605       ui_out_text (uiout, "Hardware read watchpoint ");
10606       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10607       break;
10608     case bp_access_watchpoint:
10609       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10610       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10611       break;
10612     default:
10613       internal_error (__FILE__, __LINE__,
10614                       _("Invalid hardware watchpoint type."));
10615     }
10616
10617   ui_out_field_int (uiout, "number", b->number);
10618   ui_out_text (uiout, ": ");
10619   ui_out_field_string (uiout, "exp", w->exp_string);
10620   do_cleanups (ui_out_chain);
10621 }
10622
10623 /* Implement the "print_recreate" breakpoint_ops method for
10624    watchpoints.  */
10625
10626 static void
10627 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10628 {
10629   struct watchpoint *w = (struct watchpoint *) b;
10630
10631   switch (b->type)
10632     {
10633     case bp_watchpoint:
10634     case bp_hardware_watchpoint:
10635       fprintf_unfiltered (fp, "watch");
10636       break;
10637     case bp_read_watchpoint:
10638       fprintf_unfiltered (fp, "rwatch");
10639       break;
10640     case bp_access_watchpoint:
10641       fprintf_unfiltered (fp, "awatch");
10642       break;
10643     default:
10644       internal_error (__FILE__, __LINE__,
10645                       _("Invalid watchpoint type."));
10646     }
10647
10648   fprintf_unfiltered (fp, " %s", w->exp_string);
10649   print_recreate_thread (b, fp);
10650 }
10651
10652 /* Implement the "explains_signal" breakpoint_ops method for
10653    watchpoints.  */
10654
10655 static enum bpstat_signal_value
10656 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10657 {
10658   /* A software watchpoint cannot cause a signal other than
10659      GDB_SIGNAL_TRAP.  */
10660   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10661     return BPSTAT_SIGNAL_NO;
10662
10663   return BPSTAT_SIGNAL_HIDE;
10664 }
10665
10666 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10667
10668 static struct breakpoint_ops watchpoint_breakpoint_ops;
10669
10670 /* Implement the "insert" breakpoint_ops method for
10671    masked hardware watchpoints.  */
10672
10673 static int
10674 insert_masked_watchpoint (struct bp_location *bl)
10675 {
10676   struct watchpoint *w = (struct watchpoint *) bl->owner;
10677
10678   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10679                                         bl->watchpoint_type);
10680 }
10681
10682 /* Implement the "remove" breakpoint_ops method for
10683    masked hardware watchpoints.  */
10684
10685 static int
10686 remove_masked_watchpoint (struct bp_location *bl)
10687 {
10688   struct watchpoint *w = (struct watchpoint *) bl->owner;
10689
10690   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10691                                         bl->watchpoint_type);
10692 }
10693
10694 /* Implement the "resources_needed" breakpoint_ops method for
10695    masked hardware watchpoints.  */
10696
10697 static int
10698 resources_needed_masked_watchpoint (const struct bp_location *bl)
10699 {
10700   struct watchpoint *w = (struct watchpoint *) bl->owner;
10701
10702   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10703 }
10704
10705 /* Implement the "works_in_software_mode" breakpoint_ops method for
10706    masked hardware watchpoints.  */
10707
10708 static int
10709 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10710 {
10711   return 0;
10712 }
10713
10714 /* Implement the "print_it" breakpoint_ops method for
10715    masked hardware watchpoints.  */
10716
10717 static enum print_stop_action
10718 print_it_masked_watchpoint (bpstat bs)
10719 {
10720   struct breakpoint *b = bs->breakpoint_at;
10721   struct ui_out *uiout = current_uiout;
10722
10723   /* Masked watchpoints have only one location.  */
10724   gdb_assert (b->loc && b->loc->next == NULL);
10725
10726   switch (b->type)
10727     {
10728     case bp_hardware_watchpoint:
10729       annotate_watchpoint (b->number);
10730       if (ui_out_is_mi_like_p (uiout))
10731         ui_out_field_string
10732           (uiout, "reason",
10733            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10734       break;
10735
10736     case bp_read_watchpoint:
10737       if (ui_out_is_mi_like_p (uiout))
10738         ui_out_field_string
10739           (uiout, "reason",
10740            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10741       break;
10742
10743     case bp_access_watchpoint:
10744       if (ui_out_is_mi_like_p (uiout))
10745         ui_out_field_string
10746           (uiout, "reason",
10747            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10748       break;
10749     default:
10750       internal_error (__FILE__, __LINE__,
10751                       _("Invalid hardware watchpoint type."));
10752     }
10753
10754   mention (b);
10755   ui_out_text (uiout, _("\n\
10756 Check the underlying instruction at PC for the memory\n\
10757 address and value which triggered this watchpoint.\n"));
10758   ui_out_text (uiout, "\n");
10759
10760   /* More than one watchpoint may have been triggered.  */
10761   return PRINT_UNKNOWN;
10762 }
10763
10764 /* Implement the "print_one_detail" breakpoint_ops method for
10765    masked hardware watchpoints.  */
10766
10767 static void
10768 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10769                                     struct ui_out *uiout)
10770 {
10771   struct watchpoint *w = (struct watchpoint *) b;
10772
10773   /* Masked watchpoints have only one location.  */
10774   gdb_assert (b->loc && b->loc->next == NULL);
10775
10776   ui_out_text (uiout, "\tmask ");
10777   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10778   ui_out_text (uiout, "\n");
10779 }
10780
10781 /* Implement the "print_mention" breakpoint_ops method for
10782    masked hardware watchpoints.  */
10783
10784 static void
10785 print_mention_masked_watchpoint (struct breakpoint *b)
10786 {
10787   struct watchpoint *w = (struct watchpoint *) b;
10788   struct ui_out *uiout = current_uiout;
10789   struct cleanup *ui_out_chain;
10790
10791   switch (b->type)
10792     {
10793     case bp_hardware_watchpoint:
10794       ui_out_text (uiout, "Masked hardware watchpoint ");
10795       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10796       break;
10797     case bp_read_watchpoint:
10798       ui_out_text (uiout, "Masked hardware read watchpoint ");
10799       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10800       break;
10801     case bp_access_watchpoint:
10802       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10803       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10804       break;
10805     default:
10806       internal_error (__FILE__, __LINE__,
10807                       _("Invalid hardware watchpoint type."));
10808     }
10809
10810   ui_out_field_int (uiout, "number", b->number);
10811   ui_out_text (uiout, ": ");
10812   ui_out_field_string (uiout, "exp", w->exp_string);
10813   do_cleanups (ui_out_chain);
10814 }
10815
10816 /* Implement the "print_recreate" breakpoint_ops method for
10817    masked hardware watchpoints.  */
10818
10819 static void
10820 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10821 {
10822   struct watchpoint *w = (struct watchpoint *) b;
10823   char tmp[40];
10824
10825   switch (b->type)
10826     {
10827     case bp_hardware_watchpoint:
10828       fprintf_unfiltered (fp, "watch");
10829       break;
10830     case bp_read_watchpoint:
10831       fprintf_unfiltered (fp, "rwatch");
10832       break;
10833     case bp_access_watchpoint:
10834       fprintf_unfiltered (fp, "awatch");
10835       break;
10836     default:
10837       internal_error (__FILE__, __LINE__,
10838                       _("Invalid hardware watchpoint type."));
10839     }
10840
10841   sprintf_vma (tmp, w->hw_wp_mask);
10842   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10843   print_recreate_thread (b, fp);
10844 }
10845
10846 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10847
10848 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10849
10850 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10851
10852 static int
10853 is_masked_watchpoint (const struct breakpoint *b)
10854 {
10855   return b->ops == &masked_watchpoint_breakpoint_ops;
10856 }
10857
10858 /* accessflag:  hw_write:  watch write, 
10859                 hw_read:   watch read, 
10860                 hw_access: watch access (read or write) */
10861 static void
10862 watch_command_1 (const char *arg, int accessflag, int from_tty,
10863                  int just_location, int internal)
10864 {
10865   volatile struct gdb_exception e;
10866   struct breakpoint *b, *scope_breakpoint = NULL;
10867   struct expression *exp;
10868   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10869   struct value *val, *mark, *result;
10870   struct frame_info *frame;
10871   const char *exp_start = NULL;
10872   const char *exp_end = NULL;
10873   const char *tok, *end_tok;
10874   int toklen = -1;
10875   const char *cond_start = NULL;
10876   const char *cond_end = NULL;
10877   enum bptype bp_type;
10878   int thread = -1;
10879   int pc = 0;
10880   /* Flag to indicate whether we are going to use masks for
10881      the hardware watchpoint.  */
10882   int use_mask = 0;
10883   CORE_ADDR mask = 0;
10884   struct watchpoint *w;
10885   char *expression;
10886   struct cleanup *back_to;
10887
10888   /* Make sure that we actually have parameters to parse.  */
10889   if (arg != NULL && arg[0] != '\0')
10890     {
10891       const char *value_start;
10892
10893       exp_end = arg + strlen (arg);
10894
10895       /* Look for "parameter value" pairs at the end
10896          of the arguments string.  */
10897       for (tok = exp_end - 1; tok > arg; tok--)
10898         {
10899           /* Skip whitespace at the end of the argument list.  */
10900           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10901             tok--;
10902
10903           /* Find the beginning of the last token.
10904              This is the value of the parameter.  */
10905           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10906             tok--;
10907           value_start = tok + 1;
10908
10909           /* Skip whitespace.  */
10910           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10911             tok--;
10912
10913           end_tok = tok;
10914
10915           /* Find the beginning of the second to last token.
10916              This is the parameter itself.  */
10917           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10918             tok--;
10919           tok++;
10920           toklen = end_tok - tok + 1;
10921
10922           if (toklen == 6 && !strncmp (tok, "thread", 6))
10923             {
10924               /* At this point we've found a "thread" token, which means
10925                  the user is trying to set a watchpoint that triggers
10926                  only in a specific thread.  */
10927               char *endp;
10928
10929               if (thread != -1)
10930                 error(_("You can specify only one thread."));
10931
10932               /* Extract the thread ID from the next token.  */
10933               thread = strtol (value_start, &endp, 0);
10934
10935               /* Check if the user provided a valid numeric value for the
10936                  thread ID.  */
10937               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10938                 error (_("Invalid thread ID specification %s."), value_start);
10939
10940               /* Check if the thread actually exists.  */
10941               if (!valid_thread_id (thread))
10942                 invalid_thread_id_error (thread);
10943             }
10944           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10945             {
10946               /* We've found a "mask" token, which means the user wants to
10947                  create a hardware watchpoint that is going to have the mask
10948                  facility.  */
10949               struct value *mask_value, *mark;
10950
10951               if (use_mask)
10952                 error(_("You can specify only one mask."));
10953
10954               use_mask = just_location = 1;
10955
10956               mark = value_mark ();
10957               mask_value = parse_to_comma_and_eval (&value_start);
10958               mask = value_as_address (mask_value);
10959               value_free_to_mark (mark);
10960             }
10961           else
10962             /* We didn't recognize what we found.  We should stop here.  */
10963             break;
10964
10965           /* Truncate the string and get rid of the "parameter value" pair before
10966              the arguments string is parsed by the parse_exp_1 function.  */
10967           exp_end = tok;
10968         }
10969     }
10970   else
10971     exp_end = arg;
10972
10973   /* Parse the rest of the arguments.  From here on out, everything
10974      is in terms of a newly allocated string instead of the original
10975      ARG.  */
10976   innermost_block = NULL;
10977   expression = savestring (arg, exp_end - arg);
10978   back_to = make_cleanup (xfree, expression);
10979   exp_start = arg = expression;
10980   exp = parse_exp_1 (&arg, 0, 0, 0);
10981   exp_end = arg;
10982   /* Remove trailing whitespace from the expression before saving it.
10983      This makes the eventual display of the expression string a bit
10984      prettier.  */
10985   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10986     --exp_end;
10987
10988   /* Checking if the expression is not constant.  */
10989   if (watchpoint_exp_is_const (exp))
10990     {
10991       int len;
10992
10993       len = exp_end - exp_start;
10994       while (len > 0 && isspace (exp_start[len - 1]))
10995         len--;
10996       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10997     }
10998
10999   exp_valid_block = innermost_block;
11000   mark = value_mark ();
11001   fetch_subexp_value (exp, &pc, &val, &result, NULL);
11002
11003   if (just_location)
11004     {
11005       int ret;
11006
11007       exp_valid_block = NULL;
11008       val = value_addr (result);
11009       release_value (val);
11010       value_free_to_mark (mark);
11011
11012       if (use_mask)
11013         {
11014           ret = target_masked_watch_num_registers (value_as_address (val),
11015                                                    mask);
11016           if (ret == -1)
11017             error (_("This target does not support masked watchpoints."));
11018           else if (ret == -2)
11019             error (_("Invalid mask or memory region."));
11020         }
11021     }
11022   else if (val != NULL)
11023     release_value (val);
11024
11025   tok = skip_spaces_const (arg);
11026   end_tok = skip_to_space_const (tok);
11027
11028   toklen = end_tok - tok;
11029   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11030     {
11031       struct expression *cond;
11032
11033       innermost_block = NULL;
11034       tok = cond_start = end_tok + 1;
11035       cond = parse_exp_1 (&tok, 0, 0, 0);
11036
11037       /* The watchpoint expression may not be local, but the condition
11038          may still be.  E.g.: `watch global if local > 0'.  */
11039       cond_exp_valid_block = innermost_block;
11040
11041       xfree (cond);
11042       cond_end = tok;
11043     }
11044   if (*tok)
11045     error (_("Junk at end of command."));
11046
11047   if (accessflag == hw_read)
11048     bp_type = bp_read_watchpoint;
11049   else if (accessflag == hw_access)
11050     bp_type = bp_access_watchpoint;
11051   else
11052     bp_type = bp_hardware_watchpoint;
11053
11054   frame = block_innermost_frame (exp_valid_block);
11055
11056   /* If the expression is "local", then set up a "watchpoint scope"
11057      breakpoint at the point where we've left the scope of the watchpoint
11058      expression.  Create the scope breakpoint before the watchpoint, so
11059      that we will encounter it first in bpstat_stop_status.  */
11060   if (exp_valid_block && frame)
11061     {
11062       if (frame_id_p (frame_unwind_caller_id (frame)))
11063         {
11064           scope_breakpoint
11065             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11066                                           frame_unwind_caller_pc (frame),
11067                                           bp_watchpoint_scope,
11068                                           &momentary_breakpoint_ops);
11069
11070           scope_breakpoint->enable_state = bp_enabled;
11071
11072           /* Automatically delete the breakpoint when it hits.  */
11073           scope_breakpoint->disposition = disp_del;
11074
11075           /* Only break in the proper frame (help with recursion).  */
11076           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11077
11078           /* Set the address at which we will stop.  */
11079           scope_breakpoint->loc->gdbarch
11080             = frame_unwind_caller_arch (frame);
11081           scope_breakpoint->loc->requested_address
11082             = frame_unwind_caller_pc (frame);
11083           scope_breakpoint->loc->address
11084             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11085                                          scope_breakpoint->loc->requested_address,
11086                                          scope_breakpoint->type);
11087         }
11088     }
11089
11090   /* Now set up the breakpoint.  */
11091
11092   w = XCNEW (struct watchpoint);
11093   b = &w->base;
11094   if (use_mask)
11095     init_raw_breakpoint_without_location (b, NULL, bp_type,
11096                                           &masked_watchpoint_breakpoint_ops);
11097   else
11098     init_raw_breakpoint_without_location (b, NULL, bp_type,
11099                                           &watchpoint_breakpoint_ops);
11100   b->thread = thread;
11101   b->disposition = disp_donttouch;
11102   b->pspace = current_program_space;
11103   w->exp = exp;
11104   w->exp_valid_block = exp_valid_block;
11105   w->cond_exp_valid_block = cond_exp_valid_block;
11106   if (just_location)
11107     {
11108       struct type *t = value_type (val);
11109       CORE_ADDR addr = value_as_address (val);
11110       char *name;
11111
11112       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11113       name = type_to_string (t);
11114
11115       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11116                                           core_addr_to_string (addr));
11117       xfree (name);
11118
11119       w->exp_string = xstrprintf ("-location %.*s",
11120                                   (int) (exp_end - exp_start), exp_start);
11121
11122       /* The above expression is in C.  */
11123       b->language = language_c;
11124     }
11125   else
11126     w->exp_string = savestring (exp_start, exp_end - exp_start);
11127
11128   if (use_mask)
11129     {
11130       w->hw_wp_mask = mask;
11131     }
11132   else
11133     {
11134       w->val = val;
11135       w->val_valid = 1;
11136     }
11137
11138   if (cond_start)
11139     b->cond_string = savestring (cond_start, cond_end - cond_start);
11140   else
11141     b->cond_string = 0;
11142
11143   if (frame)
11144     {
11145       w->watchpoint_frame = get_frame_id (frame);
11146       w->watchpoint_thread = inferior_ptid;
11147     }
11148   else
11149     {
11150       w->watchpoint_frame = null_frame_id;
11151       w->watchpoint_thread = null_ptid;
11152     }
11153
11154   if (scope_breakpoint != NULL)
11155     {
11156       /* The scope breakpoint is related to the watchpoint.  We will
11157          need to act on them together.  */
11158       b->related_breakpoint = scope_breakpoint;
11159       scope_breakpoint->related_breakpoint = b;
11160     }
11161
11162   if (!just_location)
11163     value_free_to_mark (mark);
11164
11165   TRY_CATCH (e, RETURN_MASK_ALL)
11166     {
11167       /* Finally update the new watchpoint.  This creates the locations
11168          that should be inserted.  */
11169       update_watchpoint (w, 1);
11170     }
11171   if (e.reason < 0)
11172     {
11173       delete_breakpoint (b);
11174       throw_exception (e);
11175     }
11176
11177   install_breakpoint (internal, b, 1);
11178   do_cleanups (back_to);
11179 }
11180
11181 /* Return count of debug registers needed to watch the given expression.
11182    If the watchpoint cannot be handled in hardware return zero.  */
11183
11184 static int
11185 can_use_hardware_watchpoint (struct value *v)
11186 {
11187   int found_memory_cnt = 0;
11188   struct value *head = v;
11189
11190   /* Did the user specifically forbid us to use hardware watchpoints? */
11191   if (!can_use_hw_watchpoints)
11192     return 0;
11193
11194   /* Make sure that the value of the expression depends only upon
11195      memory contents, and values computed from them within GDB.  If we
11196      find any register references or function calls, we can't use a
11197      hardware watchpoint.
11198
11199      The idea here is that evaluating an expression generates a series
11200      of values, one holding the value of every subexpression.  (The
11201      expression a*b+c has five subexpressions: a, b, a*b, c, and
11202      a*b+c.)  GDB's values hold almost enough information to establish
11203      the criteria given above --- they identify memory lvalues,
11204      register lvalues, computed values, etcetera.  So we can evaluate
11205      the expression, and then scan the chain of values that leaves
11206      behind to decide whether we can detect any possible change to the
11207      expression's final value using only hardware watchpoints.
11208
11209      However, I don't think that the values returned by inferior
11210      function calls are special in any way.  So this function may not
11211      notice that an expression involving an inferior function call
11212      can't be watched with hardware watchpoints.  FIXME.  */
11213   for (; v; v = value_next (v))
11214     {
11215       if (VALUE_LVAL (v) == lval_memory)
11216         {
11217           if (v != head && value_lazy (v))
11218             /* A lazy memory lvalue in the chain is one that GDB never
11219                needed to fetch; we either just used its address (e.g.,
11220                `a' in `a.b') or we never needed it at all (e.g., `a'
11221                in `a,b').  This doesn't apply to HEAD; if that is
11222                lazy then it was not readable, but watch it anyway.  */
11223             ;
11224           else
11225             {
11226               /* Ahh, memory we actually used!  Check if we can cover
11227                  it with hardware watchpoints.  */
11228               struct type *vtype = check_typedef (value_type (v));
11229
11230               /* We only watch structs and arrays if user asked for it
11231                  explicitly, never if they just happen to appear in a
11232                  middle of some value chain.  */
11233               if (v == head
11234                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11235                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11236                 {
11237                   CORE_ADDR vaddr = value_address (v);
11238                   int len;
11239                   int num_regs;
11240
11241                   len = (target_exact_watchpoints
11242                          && is_scalar_type_recursive (vtype))?
11243                     1 : TYPE_LENGTH (value_type (v));
11244
11245                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11246                   if (!num_regs)
11247                     return 0;
11248                   else
11249                     found_memory_cnt += num_regs;
11250                 }
11251             }
11252         }
11253       else if (VALUE_LVAL (v) != not_lval
11254                && deprecated_value_modifiable (v) == 0)
11255         return 0;       /* These are values from the history (e.g., $1).  */
11256       else if (VALUE_LVAL (v) == lval_register)
11257         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11258     }
11259
11260   /* The expression itself looks suitable for using a hardware
11261      watchpoint, but give the target machine a chance to reject it.  */
11262   return found_memory_cnt;
11263 }
11264
11265 void
11266 watch_command_wrapper (char *arg, int from_tty, int internal)
11267 {
11268   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11269 }
11270
11271 /* A helper function that looks for the "-location" argument and then
11272    calls watch_command_1.  */
11273
11274 static void
11275 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11276 {
11277   int just_location = 0;
11278
11279   if (arg
11280       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11281           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11282     {
11283       arg = skip_spaces (arg);
11284       just_location = 1;
11285     }
11286
11287   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11288 }
11289
11290 static void
11291 watch_command (char *arg, int from_tty)
11292 {
11293   watch_maybe_just_location (arg, hw_write, from_tty);
11294 }
11295
11296 void
11297 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11298 {
11299   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11300 }
11301
11302 static void
11303 rwatch_command (char *arg, int from_tty)
11304 {
11305   watch_maybe_just_location (arg, hw_read, from_tty);
11306 }
11307
11308 void
11309 awatch_command_wrapper (char *arg, int from_tty, int internal)
11310 {
11311   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11312 }
11313
11314 static void
11315 awatch_command (char *arg, int from_tty)
11316 {
11317   watch_maybe_just_location (arg, hw_access, from_tty);
11318 }
11319 \f
11320
11321 /* Helper routines for the until_command routine in infcmd.c.  Here
11322    because it uses the mechanisms of breakpoints.  */
11323
11324 struct until_break_command_continuation_args
11325 {
11326   struct breakpoint *breakpoint;
11327   struct breakpoint *breakpoint2;
11328   int thread_num;
11329 };
11330
11331 /* This function is called by fetch_inferior_event via the
11332    cmd_continuation pointer, to complete the until command.  It takes
11333    care of cleaning up the temporary breakpoints set up by the until
11334    command.  */
11335 static void
11336 until_break_command_continuation (void *arg, int err)
11337 {
11338   struct until_break_command_continuation_args *a = arg;
11339
11340   delete_breakpoint (a->breakpoint);
11341   if (a->breakpoint2)
11342     delete_breakpoint (a->breakpoint2);
11343   delete_longjmp_breakpoint (a->thread_num);
11344 }
11345
11346 void
11347 until_break_command (char *arg, int from_tty, int anywhere)
11348 {
11349   struct symtabs_and_lines sals;
11350   struct symtab_and_line sal;
11351   struct frame_info *frame;
11352   struct gdbarch *frame_gdbarch;
11353   struct frame_id stack_frame_id;
11354   struct frame_id caller_frame_id;
11355   struct breakpoint *breakpoint;
11356   struct breakpoint *breakpoint2 = NULL;
11357   struct cleanup *old_chain;
11358   int thread;
11359   struct thread_info *tp;
11360
11361   clear_proceed_status ();
11362
11363   /* Set a breakpoint where the user wants it and at return from
11364      this function.  */
11365
11366   if (last_displayed_sal_is_valid ())
11367     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11368                           get_last_displayed_symtab (),
11369                           get_last_displayed_line ());
11370   else
11371     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11372                           (struct symtab *) NULL, 0);
11373
11374   if (sals.nelts != 1)
11375     error (_("Couldn't get information on specified line."));
11376
11377   sal = sals.sals[0];
11378   xfree (sals.sals);    /* malloc'd, so freed.  */
11379
11380   if (*arg)
11381     error (_("Junk at end of arguments."));
11382
11383   resolve_sal_pc (&sal);
11384
11385   tp = inferior_thread ();
11386   thread = tp->num;
11387
11388   old_chain = make_cleanup (null_cleanup, NULL);
11389
11390   /* Note linespec handling above invalidates the frame chain.
11391      Installing a breakpoint also invalidates the frame chain (as it
11392      may need to switch threads), so do any frame handling before
11393      that.  */
11394
11395   frame = get_selected_frame (NULL);
11396   frame_gdbarch = get_frame_arch (frame);
11397   stack_frame_id = get_stack_frame_id (frame);
11398   caller_frame_id = frame_unwind_caller_id (frame);
11399
11400   /* Keep within the current frame, or in frames called by the current
11401      one.  */
11402
11403   if (frame_id_p (caller_frame_id))
11404     {
11405       struct symtab_and_line sal2;
11406
11407       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11408       sal2.pc = frame_unwind_caller_pc (frame);
11409       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11410                                               sal2,
11411                                               caller_frame_id,
11412                                               bp_until);
11413       make_cleanup_delete_breakpoint (breakpoint2);
11414
11415       set_longjmp_breakpoint (tp, caller_frame_id);
11416       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11417     }
11418
11419   /* set_momentary_breakpoint could invalidate FRAME.  */
11420   frame = NULL;
11421
11422   if (anywhere)
11423     /* If the user told us to continue until a specified location,
11424        we don't specify a frame at which we need to stop.  */
11425     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11426                                            null_frame_id, bp_until);
11427   else
11428     /* Otherwise, specify the selected frame, because we want to stop
11429        only at the very same frame.  */
11430     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11431                                            stack_frame_id, bp_until);
11432   make_cleanup_delete_breakpoint (breakpoint);
11433
11434   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11435
11436   /* If we are running asynchronously, and proceed call above has
11437      actually managed to start the target, arrange for breakpoints to
11438      be deleted when the target stops.  Otherwise, we're already
11439      stopped and delete breakpoints via cleanup chain.  */
11440
11441   if (target_can_async_p () && is_running (inferior_ptid))
11442     {
11443       struct until_break_command_continuation_args *args;
11444       args = xmalloc (sizeof (*args));
11445
11446       args->breakpoint = breakpoint;
11447       args->breakpoint2 = breakpoint2;
11448       args->thread_num = thread;
11449
11450       discard_cleanups (old_chain);
11451       add_continuation (inferior_thread (),
11452                         until_break_command_continuation, args,
11453                         xfree);
11454     }
11455   else
11456     do_cleanups (old_chain);
11457 }
11458
11459 /* This function attempts to parse an optional "if <cond>" clause
11460    from the arg string.  If one is not found, it returns NULL.
11461
11462    Else, it returns a pointer to the condition string.  (It does not
11463    attempt to evaluate the string against a particular block.)  And,
11464    it updates arg to point to the first character following the parsed
11465    if clause in the arg string.  */
11466
11467 static char *
11468 ep_parse_optional_if_clause (char **arg)
11469 {
11470   char *cond_string;
11471
11472   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11473     return NULL;
11474
11475   /* Skip the "if" keyword.  */
11476   (*arg) += 2;
11477
11478   /* Skip any extra leading whitespace, and record the start of the
11479      condition string.  */
11480   *arg = skip_spaces (*arg);
11481   cond_string = *arg;
11482
11483   /* Assume that the condition occupies the remainder of the arg
11484      string.  */
11485   (*arg) += strlen (cond_string);
11486
11487   return cond_string;
11488 }
11489
11490 /* Commands to deal with catching events, such as signals, exceptions,
11491    process start/exit, etc.  */
11492
11493 typedef enum
11494 {
11495   catch_fork_temporary, catch_vfork_temporary,
11496   catch_fork_permanent, catch_vfork_permanent
11497 }
11498 catch_fork_kind;
11499
11500 static void
11501 catch_fork_command_1 (char *arg, int from_tty, 
11502                       struct cmd_list_element *command)
11503 {
11504   struct gdbarch *gdbarch = get_current_arch ();
11505   char *cond_string = NULL;
11506   catch_fork_kind fork_kind;
11507   int tempflag;
11508
11509   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11510   tempflag = (fork_kind == catch_fork_temporary
11511               || fork_kind == catch_vfork_temporary);
11512
11513   if (!arg)
11514     arg = "";
11515   arg = skip_spaces (arg);
11516
11517   /* The allowed syntax is:
11518      catch [v]fork
11519      catch [v]fork if <cond>
11520
11521      First, check if there's an if clause.  */
11522   cond_string = ep_parse_optional_if_clause (&arg);
11523
11524   if ((*arg != '\0') && !isspace (*arg))
11525     error (_("Junk at end of arguments."));
11526
11527   /* If this target supports it, create a fork or vfork catchpoint
11528      and enable reporting of such events.  */
11529   switch (fork_kind)
11530     {
11531     case catch_fork_temporary:
11532     case catch_fork_permanent:
11533       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11534                                           &catch_fork_breakpoint_ops);
11535       break;
11536     case catch_vfork_temporary:
11537     case catch_vfork_permanent:
11538       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11539                                           &catch_vfork_breakpoint_ops);
11540       break;
11541     default:
11542       error (_("unsupported or unknown fork kind; cannot catch it"));
11543       break;
11544     }
11545 }
11546
11547 static void
11548 catch_exec_command_1 (char *arg, int from_tty, 
11549                       struct cmd_list_element *command)
11550 {
11551   struct exec_catchpoint *c;
11552   struct gdbarch *gdbarch = get_current_arch ();
11553   int tempflag;
11554   char *cond_string = NULL;
11555
11556   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11557
11558   if (!arg)
11559     arg = "";
11560   arg = skip_spaces (arg);
11561
11562   /* The allowed syntax is:
11563      catch exec
11564      catch exec if <cond>
11565
11566      First, check if there's an if clause.  */
11567   cond_string = ep_parse_optional_if_clause (&arg);
11568
11569   if ((*arg != '\0') && !isspace (*arg))
11570     error (_("Junk at end of arguments."));
11571
11572   c = XNEW (struct exec_catchpoint);
11573   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11574                    &catch_exec_breakpoint_ops);
11575   c->exec_pathname = NULL;
11576
11577   install_breakpoint (0, &c->base, 1);
11578 }
11579
11580 static enum print_stop_action
11581 print_it_exception_catchpoint (bpstat bs)
11582 {
11583   struct ui_out *uiout = current_uiout;
11584   struct breakpoint *b = bs->breakpoint_at;
11585   int bp_temp, bp_throw;
11586
11587   annotate_catchpoint (b->number);
11588
11589   bp_throw = strstr (b->addr_string, "throw") != NULL;
11590   if (b->loc->address != b->loc->requested_address)
11591     breakpoint_adjustment_warning (b->loc->requested_address,
11592                                    b->loc->address,
11593                                    b->number, 1);
11594   bp_temp = b->disposition == disp_del;
11595   ui_out_text (uiout, 
11596                bp_temp ? "Temporary catchpoint "
11597                        : "Catchpoint ");
11598   if (!ui_out_is_mi_like_p (uiout))
11599     ui_out_field_int (uiout, "bkptno", b->number);
11600   ui_out_text (uiout,
11601                bp_throw ? " (exception thrown), "
11602                         : " (exception caught), ");
11603   if (ui_out_is_mi_like_p (uiout))
11604     {
11605       ui_out_field_string (uiout, "reason", 
11606                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11607       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11608       ui_out_field_int (uiout, "bkptno", b->number);
11609     }
11610   return PRINT_SRC_AND_LOC;
11611 }
11612
11613 static void
11614 print_one_exception_catchpoint (struct breakpoint *b, 
11615                                 struct bp_location **last_loc)
11616 {
11617   struct value_print_options opts;
11618   struct ui_out *uiout = current_uiout;
11619
11620   get_user_print_options (&opts);
11621   if (opts.addressprint)
11622     {
11623       annotate_field (4);
11624       if (b->loc == NULL || b->loc->shlib_disabled)
11625         ui_out_field_string (uiout, "addr", "<PENDING>");
11626       else
11627         ui_out_field_core_addr (uiout, "addr",
11628                                 b->loc->gdbarch, b->loc->address);
11629     }
11630   annotate_field (5);
11631   if (b->loc)
11632     *last_loc = b->loc;
11633   if (strstr (b->addr_string, "throw") != NULL)
11634     {
11635       ui_out_field_string (uiout, "what", "exception throw");
11636       if (ui_out_is_mi_like_p (uiout))
11637         ui_out_field_string (uiout, "catch-type", "throw");
11638     }
11639   else
11640     {
11641       ui_out_field_string (uiout, "what", "exception catch");
11642       if (ui_out_is_mi_like_p (uiout))
11643         ui_out_field_string (uiout, "catch-type", "catch");
11644     }
11645 }
11646
11647 static void
11648 print_mention_exception_catchpoint (struct breakpoint *b)
11649 {
11650   struct ui_out *uiout = current_uiout;
11651   int bp_temp;
11652   int bp_throw;
11653
11654   bp_temp = b->disposition == disp_del;
11655   bp_throw = strstr (b->addr_string, "throw") != NULL;
11656   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
11657                               : _("Catchpoint "));
11658   ui_out_field_int (uiout, "bkptno", b->number);
11659   ui_out_text (uiout, bp_throw ? _(" (throw)")
11660                                : _(" (catch)"));
11661 }
11662
11663 /* Implement the "print_recreate" breakpoint_ops method for throw and
11664    catch catchpoints.  */
11665
11666 static void
11667 print_recreate_exception_catchpoint (struct breakpoint *b, 
11668                                      struct ui_file *fp)
11669 {
11670   int bp_temp;
11671   int bp_throw;
11672
11673   bp_temp = b->disposition == disp_del;
11674   bp_throw = strstr (b->addr_string, "throw") != NULL;
11675   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
11676   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
11677   print_recreate_thread (b, fp);
11678 }
11679
11680 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
11681
11682 static int
11683 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
11684                           enum exception_event_kind ex_event, int from_tty)
11685 {
11686   char *trigger_func_name;
11687  
11688   if (ex_event == EX_EVENT_CATCH)
11689     trigger_func_name = "__cxa_begin_catch";
11690   else
11691     trigger_func_name = "__cxa_throw";
11692
11693   create_breakpoint (get_current_arch (),
11694                      trigger_func_name, cond_string, -1, NULL,
11695                      0 /* condition and thread are valid.  */,
11696                      tempflag, bp_breakpoint,
11697                      0,
11698                      AUTO_BOOLEAN_TRUE /* pending */,
11699                      &gnu_v3_exception_catchpoint_ops, from_tty,
11700                      1 /* enabled */,
11701                      0 /* internal */,
11702                      0);
11703
11704   return 1;
11705 }
11706
11707 /* Deal with "catch catch" and "catch throw" commands.  */
11708
11709 static void
11710 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
11711                            int tempflag, int from_tty)
11712 {
11713   char *cond_string = NULL;
11714
11715   if (!arg)
11716     arg = "";
11717   arg = skip_spaces (arg);
11718
11719   cond_string = ep_parse_optional_if_clause (&arg);
11720
11721   if ((*arg != '\0') && !isspace (*arg))
11722     error (_("Junk at end of arguments."));
11723
11724   if (ex_event != EX_EVENT_THROW
11725       && ex_event != EX_EVENT_CATCH)
11726     error (_("Unsupported or unknown exception event; cannot catch it"));
11727
11728   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
11729     return;
11730
11731   warning (_("Unsupported with this platform/compiler combination."));
11732 }
11733
11734 /* Implementation of "catch catch" command.  */
11735
11736 static void
11737 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
11738 {
11739   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11740
11741   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
11742 }
11743
11744 /* Implementation of "catch throw" command.  */
11745
11746 static void
11747 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
11748 {
11749   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11750
11751   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
11752 }
11753
11754 void
11755 init_ada_exception_breakpoint (struct breakpoint *b,
11756                                struct gdbarch *gdbarch,
11757                                struct symtab_and_line sal,
11758                                char *addr_string,
11759                                const struct breakpoint_ops *ops,
11760                                int tempflag,
11761                                int from_tty)
11762 {
11763   if (from_tty)
11764     {
11765       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11766       if (!loc_gdbarch)
11767         loc_gdbarch = gdbarch;
11768
11769       describe_other_breakpoints (loc_gdbarch,
11770                                   sal.pspace, sal.pc, sal.section, -1);
11771       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11772          version for exception catchpoints, because two catchpoints
11773          used for different exception names will use the same address.
11774          In this case, a "breakpoint ... also set at..." warning is
11775          unproductive.  Besides, the warning phrasing is also a bit
11776          inappropriate, we should use the word catchpoint, and tell
11777          the user what type of catchpoint it is.  The above is good
11778          enough for now, though.  */
11779     }
11780
11781   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11782
11783   b->enable_state = bp_enabled;
11784   b->disposition = tempflag ? disp_del : disp_donttouch;
11785   b->addr_string = addr_string;
11786   b->language = language_ada;
11787 }
11788
11789 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11790    filter list, or NULL if no filtering is required.  */
11791 static VEC(int) *
11792 catch_syscall_split_args (char *arg)
11793 {
11794   VEC(int) *result = NULL;
11795   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11796
11797   while (*arg != '\0')
11798     {
11799       int i, syscall_number;
11800       char *endptr;
11801       char cur_name[128];
11802       struct syscall s;
11803
11804       /* Skip whitespace.  */
11805       arg = skip_spaces (arg);
11806
11807       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11808         cur_name[i] = arg[i];
11809       cur_name[i] = '\0';
11810       arg += i;
11811
11812       /* Check if the user provided a syscall name or a number.  */
11813       syscall_number = (int) strtol (cur_name, &endptr, 0);
11814       if (*endptr == '\0')
11815         get_syscall_by_number (syscall_number, &s);
11816       else
11817         {
11818           /* We have a name.  Let's check if it's valid and convert it
11819              to a number.  */
11820           get_syscall_by_name (cur_name, &s);
11821
11822           if (s.number == UNKNOWN_SYSCALL)
11823             /* Here we have to issue an error instead of a warning,
11824                because GDB cannot do anything useful if there's no
11825                syscall number to be caught.  */
11826             error (_("Unknown syscall name '%s'."), cur_name);
11827         }
11828
11829       /* Ok, it's valid.  */
11830       VEC_safe_push (int, result, s.number);
11831     }
11832
11833   discard_cleanups (cleanup);
11834   return result;
11835 }
11836
11837 /* Implement the "catch syscall" command.  */
11838
11839 static void
11840 catch_syscall_command_1 (char *arg, int from_tty, 
11841                          struct cmd_list_element *command)
11842 {
11843   int tempflag;
11844   VEC(int) *filter;
11845   struct syscall s;
11846   struct gdbarch *gdbarch = get_current_arch ();
11847
11848   /* Checking if the feature if supported.  */
11849   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11850     error (_("The feature 'catch syscall' is not supported on \
11851 this architecture yet."));
11852
11853   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11854
11855   arg = skip_spaces (arg);
11856
11857   /* We need to do this first "dummy" translation in order
11858      to get the syscall XML file loaded or, most important,
11859      to display a warning to the user if there's no XML file
11860      for his/her architecture.  */
11861   get_syscall_by_number (0, &s);
11862
11863   /* The allowed syntax is:
11864      catch syscall
11865      catch syscall <name | number> [<name | number> ... <name | number>]
11866
11867      Let's check if there's a syscall name.  */
11868
11869   if (arg != NULL)
11870     filter = catch_syscall_split_args (arg);
11871   else
11872     filter = NULL;
11873
11874   create_syscall_event_catchpoint (tempflag, filter,
11875                                    &catch_syscall_breakpoint_ops);
11876 }
11877
11878 static void
11879 catch_command (char *arg, int from_tty)
11880 {
11881   error (_("Catch requires an event name."));
11882 }
11883 \f
11884
11885 static void
11886 tcatch_command (char *arg, int from_tty)
11887 {
11888   error (_("Catch requires an event name."));
11889 }
11890
11891 /* A qsort comparison function that sorts breakpoints in order.  */
11892
11893 static int
11894 compare_breakpoints (const void *a, const void *b)
11895 {
11896   const breakpoint_p *ba = a;
11897   uintptr_t ua = (uintptr_t) *ba;
11898   const breakpoint_p *bb = b;
11899   uintptr_t ub = (uintptr_t) *bb;
11900
11901   if ((*ba)->number < (*bb)->number)
11902     return -1;
11903   else if ((*ba)->number > (*bb)->number)
11904     return 1;
11905
11906   /* Now sort by address, in case we see, e..g, two breakpoints with
11907      the number 0.  */
11908   if (ua < ub)
11909     return -1;
11910   return ua > ub ? 1 : 0;
11911 }
11912
11913 /* Delete breakpoints by address or line.  */
11914
11915 static void
11916 clear_command (char *arg, int from_tty)
11917 {
11918   struct breakpoint *b, *prev;
11919   VEC(breakpoint_p) *found = 0;
11920   int ix;
11921   int default_match;
11922   struct symtabs_and_lines sals;
11923   struct symtab_and_line sal;
11924   int i;
11925   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11926
11927   if (arg)
11928     {
11929       sals = decode_line_with_current_source (arg,
11930                                               (DECODE_LINE_FUNFIRSTLINE
11931                                                | DECODE_LINE_LIST_MODE));
11932       make_cleanup (xfree, sals.sals);
11933       default_match = 0;
11934     }
11935   else
11936     {
11937       sals.sals = (struct symtab_and_line *)
11938         xmalloc (sizeof (struct symtab_and_line));
11939       make_cleanup (xfree, sals.sals);
11940       init_sal (&sal);          /* Initialize to zeroes.  */
11941
11942       /* Set sal's line, symtab, pc, and pspace to the values
11943          corresponding to the last call to print_frame_info.  If the
11944          codepoint is not valid, this will set all the fields to 0.  */
11945       get_last_displayed_sal (&sal);
11946       if (sal.symtab == 0)
11947         error (_("No source file specified."));
11948
11949       sals.sals[0] = sal;
11950       sals.nelts = 1;
11951
11952       default_match = 1;
11953     }
11954
11955   /* We don't call resolve_sal_pc here.  That's not as bad as it
11956      seems, because all existing breakpoints typically have both
11957      file/line and pc set.  So, if clear is given file/line, we can
11958      match this to existing breakpoint without obtaining pc at all.
11959
11960      We only support clearing given the address explicitly 
11961      present in breakpoint table.  Say, we've set breakpoint 
11962      at file:line.  There were several PC values for that file:line,
11963      due to optimization, all in one block.
11964
11965      We've picked one PC value.  If "clear" is issued with another
11966      PC corresponding to the same file:line, the breakpoint won't
11967      be cleared.  We probably can still clear the breakpoint, but 
11968      since the other PC value is never presented to user, user
11969      can only find it by guessing, and it does not seem important
11970      to support that.  */
11971
11972   /* For each line spec given, delete bps which correspond to it.  Do
11973      it in two passes, solely to preserve the current behavior that
11974      from_tty is forced true if we delete more than one
11975      breakpoint.  */
11976
11977   found = NULL;
11978   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11979   for (i = 0; i < sals.nelts; i++)
11980     {
11981       const char *sal_fullname;
11982
11983       /* If exact pc given, clear bpts at that pc.
11984          If line given (pc == 0), clear all bpts on specified line.
11985          If defaulting, clear all bpts on default line
11986          or at default pc.
11987
11988          defaulting    sal.pc != 0    tests to do
11989
11990          0              1             pc
11991          1              1             pc _and_ line
11992          0              0             line
11993          1              0             <can't happen> */
11994
11995       sal = sals.sals[i];
11996       sal_fullname = (sal.symtab == NULL
11997                       ? NULL : symtab_to_fullname (sal.symtab));
11998
11999       /* Find all matching breakpoints and add them to 'found'.  */
12000       ALL_BREAKPOINTS (b)
12001         {
12002           int match = 0;
12003           /* Are we going to delete b?  */
12004           if (b->type != bp_none && !is_watchpoint (b))
12005             {
12006               struct bp_location *loc = b->loc;
12007               for (; loc; loc = loc->next)
12008                 {
12009                   /* If the user specified file:line, don't allow a PC
12010                      match.  This matches historical gdb behavior.  */
12011                   int pc_match = (!sal.explicit_line
12012                                   && sal.pc
12013                                   && (loc->pspace == sal.pspace)
12014                                   && (loc->address == sal.pc)
12015                                   && (!section_is_overlay (loc->section)
12016                                       || loc->section == sal.section));
12017                   int line_match = 0;
12018
12019                   if ((default_match || sal.explicit_line)
12020                       && loc->symtab != NULL
12021                       && sal_fullname != NULL
12022                       && sal.pspace == loc->pspace
12023                       && loc->line_number == sal.line
12024                       && filename_cmp (symtab_to_fullname (loc->symtab),
12025                                        sal_fullname) == 0)
12026                     line_match = 1;
12027
12028                   if (pc_match || line_match)
12029                     {
12030                       match = 1;
12031                       break;
12032                     }
12033                 }
12034             }
12035
12036           if (match)
12037             VEC_safe_push(breakpoint_p, found, b);
12038         }
12039     }
12040
12041   /* Now go thru the 'found' chain and delete them.  */
12042   if (VEC_empty(breakpoint_p, found))
12043     {
12044       if (arg)
12045         error (_("No breakpoint at %s."), arg);
12046       else
12047         error (_("No breakpoint at this line."));
12048     }
12049
12050   /* Remove duplicates from the vec.  */
12051   qsort (VEC_address (breakpoint_p, found),
12052          VEC_length (breakpoint_p, found),
12053          sizeof (breakpoint_p),
12054          compare_breakpoints);
12055   prev = VEC_index (breakpoint_p, found, 0);
12056   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12057     {
12058       if (b == prev)
12059         {
12060           VEC_ordered_remove (breakpoint_p, found, ix);
12061           --ix;
12062         }
12063     }
12064
12065   if (VEC_length(breakpoint_p, found) > 1)
12066     from_tty = 1;       /* Always report if deleted more than one.  */
12067   if (from_tty)
12068     {
12069       if (VEC_length(breakpoint_p, found) == 1)
12070         printf_unfiltered (_("Deleted breakpoint "));
12071       else
12072         printf_unfiltered (_("Deleted breakpoints "));
12073     }
12074
12075   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12076     {
12077       if (from_tty)
12078         printf_unfiltered ("%d ", b->number);
12079       delete_breakpoint (b);
12080     }
12081   if (from_tty)
12082     putchar_unfiltered ('\n');
12083
12084   do_cleanups (cleanups);
12085 }
12086 \f
12087 /* Delete breakpoint in BS if they are `delete' breakpoints and
12088    all breakpoints that are marked for deletion, whether hit or not.
12089    This is called after any breakpoint is hit, or after errors.  */
12090
12091 void
12092 breakpoint_auto_delete (bpstat bs)
12093 {
12094   struct breakpoint *b, *b_tmp;
12095
12096   for (; bs; bs = bs->next)
12097     if (bs->breakpoint_at
12098         && bs->breakpoint_at->disposition == disp_del
12099         && bs->stop)
12100       delete_breakpoint (bs->breakpoint_at);
12101
12102   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12103   {
12104     if (b->disposition == disp_del_at_next_stop)
12105       delete_breakpoint (b);
12106   }
12107 }
12108
12109 /* A comparison function for bp_location AP and BP being interfaced to
12110    qsort.  Sort elements primarily by their ADDRESS (no matter what
12111    does breakpoint_address_is_meaningful say for its OWNER),
12112    secondarily by ordering first bp_permanent OWNERed elements and
12113    terciarily just ensuring the array is sorted stable way despite
12114    qsort being an unstable algorithm.  */
12115
12116 static int
12117 bp_location_compare (const void *ap, const void *bp)
12118 {
12119   struct bp_location *a = *(void **) ap;
12120   struct bp_location *b = *(void **) bp;
12121   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12122   int a_perm = a->owner->enable_state == bp_permanent;
12123   int b_perm = b->owner->enable_state == bp_permanent;
12124
12125   if (a->address != b->address)
12126     return (a->address > b->address) - (a->address < b->address);
12127
12128   /* Sort locations at the same address by their pspace number, keeping
12129      locations of the same inferior (in a multi-inferior environment)
12130      grouped.  */
12131
12132   if (a->pspace->num != b->pspace->num)
12133     return ((a->pspace->num > b->pspace->num)
12134             - (a->pspace->num < b->pspace->num));
12135
12136   /* Sort permanent breakpoints first.  */
12137   if (a_perm != b_perm)
12138     return (a_perm < b_perm) - (a_perm > b_perm);
12139
12140   /* Make the internal GDB representation stable across GDB runs
12141      where A and B memory inside GDB can differ.  Breakpoint locations of
12142      the same type at the same address can be sorted in arbitrary order.  */
12143
12144   if (a->owner->number != b->owner->number)
12145     return ((a->owner->number > b->owner->number)
12146             - (a->owner->number < b->owner->number));
12147
12148   return (a > b) - (a < b);
12149 }
12150
12151 /* Set bp_location_placed_address_before_address_max and
12152    bp_location_shadow_len_after_address_max according to the current
12153    content of the bp_location array.  */
12154
12155 static void
12156 bp_location_target_extensions_update (void)
12157 {
12158   struct bp_location *bl, **blp_tmp;
12159
12160   bp_location_placed_address_before_address_max = 0;
12161   bp_location_shadow_len_after_address_max = 0;
12162
12163   ALL_BP_LOCATIONS (bl, blp_tmp)
12164     {
12165       CORE_ADDR start, end, addr;
12166
12167       if (!bp_location_has_shadow (bl))
12168         continue;
12169
12170       start = bl->target_info.placed_address;
12171       end = start + bl->target_info.shadow_len;
12172
12173       gdb_assert (bl->address >= start);
12174       addr = bl->address - start;
12175       if (addr > bp_location_placed_address_before_address_max)
12176         bp_location_placed_address_before_address_max = addr;
12177
12178       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12179
12180       gdb_assert (bl->address < end);
12181       addr = end - bl->address;
12182       if (addr > bp_location_shadow_len_after_address_max)
12183         bp_location_shadow_len_after_address_max = addr;
12184     }
12185 }
12186
12187 /* Download tracepoint locations if they haven't been.  */
12188
12189 static void
12190 download_tracepoint_locations (void)
12191 {
12192   struct breakpoint *b;
12193   struct cleanup *old_chain;
12194
12195   if (!target_can_download_tracepoint ())
12196     return;
12197
12198   old_chain = save_current_space_and_thread ();
12199
12200   ALL_TRACEPOINTS (b)
12201     {
12202       struct bp_location *bl;
12203       struct tracepoint *t;
12204       int bp_location_downloaded = 0;
12205
12206       if ((b->type == bp_fast_tracepoint
12207            ? !may_insert_fast_tracepoints
12208            : !may_insert_tracepoints))
12209         continue;
12210
12211       for (bl = b->loc; bl; bl = bl->next)
12212         {
12213           /* In tracepoint, locations are _never_ duplicated, so
12214              should_be_inserted is equivalent to
12215              unduplicated_should_be_inserted.  */
12216           if (!should_be_inserted (bl) || bl->inserted)
12217             continue;
12218
12219           switch_to_program_space_and_thread (bl->pspace);
12220
12221           target_download_tracepoint (bl);
12222
12223           bl->inserted = 1;
12224           bp_location_downloaded = 1;
12225         }
12226       t = (struct tracepoint *) b;
12227       t->number_on_target = b->number;
12228       if (bp_location_downloaded)
12229         observer_notify_breakpoint_modified (b);
12230     }
12231
12232   do_cleanups (old_chain);
12233 }
12234
12235 /* Swap the insertion/duplication state between two locations.  */
12236
12237 static void
12238 swap_insertion (struct bp_location *left, struct bp_location *right)
12239 {
12240   const int left_inserted = left->inserted;
12241   const int left_duplicate = left->duplicate;
12242   const int left_needs_update = left->needs_update;
12243   const struct bp_target_info left_target_info = left->target_info;
12244
12245   /* Locations of tracepoints can never be duplicated.  */
12246   if (is_tracepoint (left->owner))
12247     gdb_assert (!left->duplicate);
12248   if (is_tracepoint (right->owner))
12249     gdb_assert (!right->duplicate);
12250
12251   left->inserted = right->inserted;
12252   left->duplicate = right->duplicate;
12253   left->needs_update = right->needs_update;
12254   left->target_info = right->target_info;
12255   right->inserted = left_inserted;
12256   right->duplicate = left_duplicate;
12257   right->needs_update = left_needs_update;
12258   right->target_info = left_target_info;
12259 }
12260
12261 /* Force the re-insertion of the locations at ADDRESS.  This is called
12262    once a new/deleted/modified duplicate location is found and we are evaluating
12263    conditions on the target's side.  Such conditions need to be updated on
12264    the target.  */
12265
12266 static void
12267 force_breakpoint_reinsertion (struct bp_location *bl)
12268 {
12269   struct bp_location **locp = NULL, **loc2p;
12270   struct bp_location *loc;
12271   CORE_ADDR address = 0;
12272   int pspace_num;
12273
12274   address = bl->address;
12275   pspace_num = bl->pspace->num;
12276
12277   /* This is only meaningful if the target is
12278      evaluating conditions and if the user has
12279      opted for condition evaluation on the target's
12280      side.  */
12281   if (gdb_evaluates_breakpoint_condition_p ()
12282       || !target_supports_evaluation_of_breakpoint_conditions ())
12283     return;
12284
12285   /* Flag all breakpoint locations with this address and
12286      the same program space as the location
12287      as "its condition has changed".  We need to
12288      update the conditions on the target's side.  */
12289   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12290     {
12291       loc = *loc2p;
12292
12293       if (!is_breakpoint (loc->owner)
12294           || pspace_num != loc->pspace->num)
12295         continue;
12296
12297       /* Flag the location appropriately.  We use a different state to
12298          let everyone know that we already updated the set of locations
12299          with addr bl->address and program space bl->pspace.  This is so
12300          we don't have to keep calling these functions just to mark locations
12301          that have already been marked.  */
12302       loc->condition_changed = condition_updated;
12303
12304       /* Free the agent expression bytecode as well.  We will compute
12305          it later on.  */
12306       if (loc->cond_bytecode)
12307         {
12308           free_agent_expr (loc->cond_bytecode);
12309           loc->cond_bytecode = NULL;
12310         }
12311     }
12312 }
12313
12314 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12315    into the inferior, only remove already-inserted locations that no
12316    longer should be inserted.  Functions that delete a breakpoint or
12317    breakpoints should pass false, so that deleting a breakpoint
12318    doesn't have the side effect of inserting the locations of other
12319    breakpoints that are marked not-inserted, but should_be_inserted
12320    returns true on them.
12321
12322    This behaviour is useful is situations close to tear-down -- e.g.,
12323    after an exec, while the target still has execution, but breakpoint
12324    shadows of the previous executable image should *NOT* be restored
12325    to the new image; or before detaching, where the target still has
12326    execution and wants to delete breakpoints from GDB's lists, and all
12327    breakpoints had already been removed from the inferior.  */
12328
12329 static void
12330 update_global_location_list (int should_insert)
12331 {
12332   struct breakpoint *b;
12333   struct bp_location **locp, *loc;
12334   struct cleanup *cleanups;
12335   /* Last breakpoint location address that was marked for update.  */
12336   CORE_ADDR last_addr = 0;
12337   /* Last breakpoint location program space that was marked for update.  */
12338   int last_pspace_num = -1;
12339
12340   /* Used in the duplicates detection below.  When iterating over all
12341      bp_locations, points to the first bp_location of a given address.
12342      Breakpoints and watchpoints of different types are never
12343      duplicates of each other.  Keep one pointer for each type of
12344      breakpoint/watchpoint, so we only need to loop over all locations
12345      once.  */
12346   struct bp_location *bp_loc_first;  /* breakpoint */
12347   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12348   struct bp_location *awp_loc_first; /* access watchpoint */
12349   struct bp_location *rwp_loc_first; /* read watchpoint */
12350
12351   /* Saved former bp_location array which we compare against the newly
12352      built bp_location from the current state of ALL_BREAKPOINTS.  */
12353   struct bp_location **old_location, **old_locp;
12354   unsigned old_location_count;
12355
12356   old_location = bp_location;
12357   old_location_count = bp_location_count;
12358   bp_location = NULL;
12359   bp_location_count = 0;
12360   cleanups = make_cleanup (xfree, old_location);
12361
12362   ALL_BREAKPOINTS (b)
12363     for (loc = b->loc; loc; loc = loc->next)
12364       bp_location_count++;
12365
12366   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12367   locp = bp_location;
12368   ALL_BREAKPOINTS (b)
12369     for (loc = b->loc; loc; loc = loc->next)
12370       *locp++ = loc;
12371   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12372          bp_location_compare);
12373
12374   bp_location_target_extensions_update ();
12375
12376   /* Identify bp_location instances that are no longer present in the
12377      new list, and therefore should be freed.  Note that it's not
12378      necessary that those locations should be removed from inferior --
12379      if there's another location at the same address (previously
12380      marked as duplicate), we don't need to remove/insert the
12381      location.
12382      
12383      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12384      and former bp_location array state respectively.  */
12385
12386   locp = bp_location;
12387   for (old_locp = old_location; old_locp < old_location + old_location_count;
12388        old_locp++)
12389     {
12390       struct bp_location *old_loc = *old_locp;
12391       struct bp_location **loc2p;
12392
12393       /* Tells if 'old_loc' is found among the new locations.  If
12394          not, we have to free it.  */
12395       int found_object = 0;
12396       /* Tells if the location should remain inserted in the target.  */
12397       int keep_in_target = 0;
12398       int removed = 0;
12399
12400       /* Skip LOCP entries which will definitely never be needed.
12401          Stop either at or being the one matching OLD_LOC.  */
12402       while (locp < bp_location + bp_location_count
12403              && (*locp)->address < old_loc->address)
12404         locp++;
12405
12406       for (loc2p = locp;
12407            (loc2p < bp_location + bp_location_count
12408             && (*loc2p)->address == old_loc->address);
12409            loc2p++)
12410         {
12411           /* Check if this is a new/duplicated location or a duplicated
12412              location that had its condition modified.  If so, we want to send
12413              its condition to the target if evaluation of conditions is taking
12414              place there.  */
12415           if ((*loc2p)->condition_changed == condition_modified
12416               && (last_addr != old_loc->address
12417                   || last_pspace_num != old_loc->pspace->num))
12418             {
12419               force_breakpoint_reinsertion (*loc2p);
12420               last_pspace_num = old_loc->pspace->num;
12421             }
12422
12423           if (*loc2p == old_loc)
12424             found_object = 1;
12425         }
12426
12427       /* We have already handled this address, update it so that we don't
12428          have to go through updates again.  */
12429       last_addr = old_loc->address;
12430
12431       /* Target-side condition evaluation: Handle deleted locations.  */
12432       if (!found_object)
12433         force_breakpoint_reinsertion (old_loc);
12434
12435       /* If this location is no longer present, and inserted, look if
12436          there's maybe a new location at the same address.  If so,
12437          mark that one inserted, and don't remove this one.  This is
12438          needed so that we don't have a time window where a breakpoint
12439          at certain location is not inserted.  */
12440
12441       if (old_loc->inserted)
12442         {
12443           /* If the location is inserted now, we might have to remove
12444              it.  */
12445
12446           if (found_object && should_be_inserted (old_loc))
12447             {
12448               /* The location is still present in the location list,
12449                  and still should be inserted.  Don't do anything.  */
12450               keep_in_target = 1;
12451             }
12452           else
12453             {
12454               /* This location still exists, but it won't be kept in the
12455                  target since it may have been disabled.  We proceed to
12456                  remove its target-side condition.  */
12457
12458               /* The location is either no longer present, or got
12459                  disabled.  See if there's another location at the
12460                  same address, in which case we don't need to remove
12461                  this one from the target.  */
12462
12463               /* OLD_LOC comes from existing struct breakpoint.  */
12464               if (breakpoint_address_is_meaningful (old_loc->owner))
12465                 {
12466                   for (loc2p = locp;
12467                        (loc2p < bp_location + bp_location_count
12468                         && (*loc2p)->address == old_loc->address);
12469                        loc2p++)
12470                     {
12471                       struct bp_location *loc2 = *loc2p;
12472
12473                       if (breakpoint_locations_match (loc2, old_loc))
12474                         {
12475                           /* Read watchpoint locations are switched to
12476                              access watchpoints, if the former are not
12477                              supported, but the latter are.  */
12478                           if (is_hardware_watchpoint (old_loc->owner))
12479                             {
12480                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12481                               loc2->watchpoint_type = old_loc->watchpoint_type;
12482                             }
12483
12484                           /* loc2 is a duplicated location. We need to check
12485                              if it should be inserted in case it will be
12486                              unduplicated.  */
12487                           if (loc2 != old_loc
12488                               && unduplicated_should_be_inserted (loc2))
12489                             {
12490                               swap_insertion (old_loc, loc2);
12491                               keep_in_target = 1;
12492                               break;
12493                             }
12494                         }
12495                     }
12496                 }
12497             }
12498
12499           if (!keep_in_target)
12500             {
12501               if (remove_breakpoint (old_loc, mark_uninserted))
12502                 {
12503                   /* This is just about all we can do.  We could keep
12504                      this location on the global list, and try to
12505                      remove it next time, but there's no particular
12506                      reason why we will succeed next time.
12507                      
12508                      Note that at this point, old_loc->owner is still
12509                      valid, as delete_breakpoint frees the breakpoint
12510                      only after calling us.  */
12511                   printf_filtered (_("warning: Error removing "
12512                                      "breakpoint %d\n"), 
12513                                    old_loc->owner->number);
12514                 }
12515               removed = 1;
12516             }
12517         }
12518
12519       if (!found_object)
12520         {
12521           if (removed && non_stop
12522               && breakpoint_address_is_meaningful (old_loc->owner)
12523               && !is_hardware_watchpoint (old_loc->owner))
12524             {
12525               /* This location was removed from the target.  In
12526                  non-stop mode, a race condition is possible where
12527                  we've removed a breakpoint, but stop events for that
12528                  breakpoint are already queued and will arrive later.
12529                  We apply an heuristic to be able to distinguish such
12530                  SIGTRAPs from other random SIGTRAPs: we keep this
12531                  breakpoint location for a bit, and will retire it
12532                  after we see some number of events.  The theory here
12533                  is that reporting of events should, "on the average",
12534                  be fair, so after a while we'll see events from all
12535                  threads that have anything of interest, and no longer
12536                  need to keep this breakpoint location around.  We
12537                  don't hold locations forever so to reduce chances of
12538                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12539                  SIGTRAP.
12540
12541                  The heuristic failing can be disastrous on
12542                  decr_pc_after_break targets.
12543
12544                  On decr_pc_after_break targets, like e.g., x86-linux,
12545                  if we fail to recognize a late breakpoint SIGTRAP,
12546                  because events_till_retirement has reached 0 too
12547                  soon, we'll fail to do the PC adjustment, and report
12548                  a random SIGTRAP to the user.  When the user resumes
12549                  the inferior, it will most likely immediately crash
12550                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12551                  corrupted, because of being resumed e.g., in the
12552                  middle of a multi-byte instruction, or skipped a
12553                  one-byte instruction.  This was actually seen happen
12554                  on native x86-linux, and should be less rare on
12555                  targets that do not support new thread events, like
12556                  remote, due to the heuristic depending on
12557                  thread_count.
12558
12559                  Mistaking a random SIGTRAP for a breakpoint trap
12560                  causes similar symptoms (PC adjustment applied when
12561                  it shouldn't), but then again, playing with SIGTRAPs
12562                  behind the debugger's back is asking for trouble.
12563
12564                  Since hardware watchpoint traps are always
12565                  distinguishable from other traps, so we don't need to
12566                  apply keep hardware watchpoint moribund locations
12567                  around.  We simply always ignore hardware watchpoint
12568                  traps we can no longer explain.  */
12569
12570               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12571               old_loc->owner = NULL;
12572
12573               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12574             }
12575           else
12576             {
12577               old_loc->owner = NULL;
12578               decref_bp_location (&old_loc);
12579             }
12580         }
12581     }
12582
12583   /* Rescan breakpoints at the same address and section, marking the
12584      first one as "first" and any others as "duplicates".  This is so
12585      that the bpt instruction is only inserted once.  If we have a
12586      permanent breakpoint at the same place as BPT, make that one the
12587      official one, and the rest as duplicates.  Permanent breakpoints
12588      are sorted first for the same address.
12589
12590      Do the same for hardware watchpoints, but also considering the
12591      watchpoint's type (regular/access/read) and length.  */
12592
12593   bp_loc_first = NULL;
12594   wp_loc_first = NULL;
12595   awp_loc_first = NULL;
12596   rwp_loc_first = NULL;
12597   ALL_BP_LOCATIONS (loc, locp)
12598     {
12599       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12600          non-NULL.  */
12601       struct bp_location **loc_first_p;
12602       b = loc->owner;
12603
12604       if (!unduplicated_should_be_inserted (loc)
12605           || !breakpoint_address_is_meaningful (b)
12606           /* Don't detect duplicate for tracepoint locations because they are
12607            never duplicated.  See the comments in field `duplicate' of
12608            `struct bp_location'.  */
12609           || is_tracepoint (b))
12610         {
12611           /* Clear the condition modification flag.  */
12612           loc->condition_changed = condition_unchanged;
12613           continue;
12614         }
12615
12616       /* Permanent breakpoint should always be inserted.  */
12617       if (b->enable_state == bp_permanent && ! loc->inserted)
12618         internal_error (__FILE__, __LINE__,
12619                         _("allegedly permanent breakpoint is not "
12620                         "actually inserted"));
12621
12622       if (b->type == bp_hardware_watchpoint)
12623         loc_first_p = &wp_loc_first;
12624       else if (b->type == bp_read_watchpoint)
12625         loc_first_p = &rwp_loc_first;
12626       else if (b->type == bp_access_watchpoint)
12627         loc_first_p = &awp_loc_first;
12628       else
12629         loc_first_p = &bp_loc_first;
12630
12631       if (*loc_first_p == NULL
12632           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12633           || !breakpoint_locations_match (loc, *loc_first_p))
12634         {
12635           *loc_first_p = loc;
12636           loc->duplicate = 0;
12637
12638           if (is_breakpoint (loc->owner) && loc->condition_changed)
12639             {
12640               loc->needs_update = 1;
12641               /* Clear the condition modification flag.  */
12642               loc->condition_changed = condition_unchanged;
12643             }
12644           continue;
12645         }
12646
12647
12648       /* This and the above ensure the invariant that the first location
12649          is not duplicated, and is the inserted one.
12650          All following are marked as duplicated, and are not inserted.  */
12651       if (loc->inserted)
12652         swap_insertion (loc, *loc_first_p);
12653       loc->duplicate = 1;
12654
12655       /* Clear the condition modification flag.  */
12656       loc->condition_changed = condition_unchanged;
12657
12658       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12659           && b->enable_state != bp_permanent)
12660         internal_error (__FILE__, __LINE__,
12661                         _("another breakpoint was inserted on top of "
12662                         "a permanent breakpoint"));
12663     }
12664
12665   if (breakpoints_always_inserted_mode ()
12666       && (have_live_inferiors ()
12667           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12668     {
12669       if (should_insert)
12670         insert_breakpoint_locations ();
12671       else
12672         {
12673           /* Though should_insert is false, we may need to update conditions
12674              on the target's side if it is evaluating such conditions.  We
12675              only update conditions for locations that are marked
12676              "needs_update".  */
12677           update_inserted_breakpoint_locations ();
12678         }
12679     }
12680
12681   if (should_insert)
12682     download_tracepoint_locations ();
12683
12684   do_cleanups (cleanups);
12685 }
12686
12687 void
12688 breakpoint_retire_moribund (void)
12689 {
12690   struct bp_location *loc;
12691   int ix;
12692
12693   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12694     if (--(loc->events_till_retirement) == 0)
12695       {
12696         decref_bp_location (&loc);
12697         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12698         --ix;
12699       }
12700 }
12701
12702 static void
12703 update_global_location_list_nothrow (int inserting)
12704 {
12705   volatile struct gdb_exception e;
12706
12707   TRY_CATCH (e, RETURN_MASK_ERROR)
12708     update_global_location_list (inserting);
12709 }
12710
12711 /* Clear BKP from a BPS.  */
12712
12713 static void
12714 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12715 {
12716   bpstat bs;
12717
12718   for (bs = bps; bs; bs = bs->next)
12719     if (bs->breakpoint_at == bpt)
12720       {
12721         bs->breakpoint_at = NULL;
12722         bs->old_val = NULL;
12723         /* bs->commands will be freed later.  */
12724       }
12725 }
12726
12727 /* Callback for iterate_over_threads.  */
12728 static int
12729 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12730 {
12731   struct breakpoint *bpt = data;
12732
12733   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12734   return 0;
12735 }
12736
12737 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12738    callbacks.  */
12739
12740 static void
12741 say_where (struct breakpoint *b)
12742 {
12743   struct ui_out *uiout = current_uiout;
12744   struct value_print_options opts;
12745
12746   get_user_print_options (&opts);
12747
12748   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12749      single string.  */
12750   if (b->loc == NULL)
12751     {
12752       printf_filtered (_(" (%s) pending."), b->addr_string);
12753     }
12754   else
12755     {
12756       if (opts.addressprint || b->loc->symtab == NULL)
12757         {
12758           printf_filtered (" at ");
12759           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12760                           gdb_stdout);
12761         }
12762       if (b->loc->symtab != NULL)
12763         {
12764           /* If there is a single location, we can print the location
12765              more nicely.  */
12766           if (b->loc->next == NULL)
12767             printf_filtered (": file %s, line %d.",
12768                              symtab_to_filename_for_display (b->loc->symtab),
12769                              b->loc->line_number);
12770           else
12771             /* This is not ideal, but each location may have a
12772                different file name, and this at least reflects the
12773                real situation somewhat.  */
12774             printf_filtered (": %s.", b->addr_string);
12775         }
12776
12777       if (b->loc->next)
12778         {
12779           struct bp_location *loc = b->loc;
12780           int n = 0;
12781           for (; loc; loc = loc->next)
12782             ++n;
12783           printf_filtered (" (%d locations)", n);
12784         }
12785     }
12786 }
12787
12788 /* Default bp_location_ops methods.  */
12789
12790 static void
12791 bp_location_dtor (struct bp_location *self)
12792 {
12793   xfree (self->cond);
12794   if (self->cond_bytecode)
12795     free_agent_expr (self->cond_bytecode);
12796   xfree (self->function_name);
12797 }
12798
12799 static const struct bp_location_ops bp_location_ops =
12800 {
12801   bp_location_dtor
12802 };
12803
12804 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12805    inherit from.  */
12806
12807 static void
12808 base_breakpoint_dtor (struct breakpoint *self)
12809 {
12810   decref_counted_command_line (&self->commands);
12811   xfree (self->cond_string);
12812   xfree (self->addr_string);
12813   xfree (self->filter);
12814   xfree (self->addr_string_range_end);
12815 }
12816
12817 static struct bp_location *
12818 base_breakpoint_allocate_location (struct breakpoint *self)
12819 {
12820   struct bp_location *loc;
12821
12822   loc = XNEW (struct bp_location);
12823   init_bp_location (loc, &bp_location_ops, self);
12824   return loc;
12825 }
12826
12827 static void
12828 base_breakpoint_re_set (struct breakpoint *b)
12829 {
12830   /* Nothing to re-set. */
12831 }
12832
12833 #define internal_error_pure_virtual_called() \
12834   gdb_assert_not_reached ("pure virtual function called")
12835
12836 static int
12837 base_breakpoint_insert_location (struct bp_location *bl)
12838 {
12839   internal_error_pure_virtual_called ();
12840 }
12841
12842 static int
12843 base_breakpoint_remove_location (struct bp_location *bl)
12844 {
12845   internal_error_pure_virtual_called ();
12846 }
12847
12848 static int
12849 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12850                                 struct address_space *aspace,
12851                                 CORE_ADDR bp_addr,
12852                                 const struct target_waitstatus *ws)
12853 {
12854   internal_error_pure_virtual_called ();
12855 }
12856
12857 static void
12858 base_breakpoint_check_status (bpstat bs)
12859 {
12860   /* Always stop.   */
12861 }
12862
12863 /* A "works_in_software_mode" breakpoint_ops method that just internal
12864    errors.  */
12865
12866 static int
12867 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12868 {
12869   internal_error_pure_virtual_called ();
12870 }
12871
12872 /* A "resources_needed" breakpoint_ops method that just internal
12873    errors.  */
12874
12875 static int
12876 base_breakpoint_resources_needed (const struct bp_location *bl)
12877 {
12878   internal_error_pure_virtual_called ();
12879 }
12880
12881 static enum print_stop_action
12882 base_breakpoint_print_it (bpstat bs)
12883 {
12884   internal_error_pure_virtual_called ();
12885 }
12886
12887 static void
12888 base_breakpoint_print_one_detail (const struct breakpoint *self,
12889                                   struct ui_out *uiout)
12890 {
12891   /* nothing */
12892 }
12893
12894 static void
12895 base_breakpoint_print_mention (struct breakpoint *b)
12896 {
12897   internal_error_pure_virtual_called ();
12898 }
12899
12900 static void
12901 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12902 {
12903   internal_error_pure_virtual_called ();
12904 }
12905
12906 static void
12907 base_breakpoint_create_sals_from_address (char **arg,
12908                                           struct linespec_result *canonical,
12909                                           enum bptype type_wanted,
12910                                           char *addr_start,
12911                                           char **copy_arg)
12912 {
12913   internal_error_pure_virtual_called ();
12914 }
12915
12916 static void
12917 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12918                                         struct linespec_result *c,
12919                                         struct linespec_sals *lsal,
12920                                         char *cond_string,
12921                                         char *extra_string,
12922                                         enum bptype type_wanted,
12923                                         enum bpdisp disposition,
12924                                         int thread,
12925                                         int task, int ignore_count,
12926                                         const struct breakpoint_ops *o,
12927                                         int from_tty, int enabled,
12928                                         int internal, unsigned flags)
12929 {
12930   internal_error_pure_virtual_called ();
12931 }
12932
12933 static void
12934 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12935                                  struct symtabs_and_lines *sals)
12936 {
12937   internal_error_pure_virtual_called ();
12938 }
12939
12940 /* The default 'explains_signal' method.  */
12941
12942 static enum bpstat_signal_value
12943 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
12944 {
12945   return BPSTAT_SIGNAL_HIDE;
12946 }
12947
12948 /* The default "after_condition_true" method.  */
12949
12950 static void
12951 base_breakpoint_after_condition_true (struct bpstats *bs)
12952 {
12953   /* Nothing to do.   */
12954 }
12955
12956 struct breakpoint_ops base_breakpoint_ops =
12957 {
12958   base_breakpoint_dtor,
12959   base_breakpoint_allocate_location,
12960   base_breakpoint_re_set,
12961   base_breakpoint_insert_location,
12962   base_breakpoint_remove_location,
12963   base_breakpoint_breakpoint_hit,
12964   base_breakpoint_check_status,
12965   base_breakpoint_resources_needed,
12966   base_breakpoint_works_in_software_mode,
12967   base_breakpoint_print_it,
12968   NULL,
12969   base_breakpoint_print_one_detail,
12970   base_breakpoint_print_mention,
12971   base_breakpoint_print_recreate,
12972   base_breakpoint_create_sals_from_address,
12973   base_breakpoint_create_breakpoints_sal,
12974   base_breakpoint_decode_linespec,
12975   base_breakpoint_explains_signal,
12976   base_breakpoint_after_condition_true,
12977 };
12978
12979 /* Default breakpoint_ops methods.  */
12980
12981 static void
12982 bkpt_re_set (struct breakpoint *b)
12983 {
12984   /* FIXME: is this still reachable?  */
12985   if (b->addr_string == NULL)
12986     {
12987       /* Anything without a string can't be re-set.  */
12988       delete_breakpoint (b);
12989       return;
12990     }
12991
12992   breakpoint_re_set_default (b);
12993 }
12994
12995 static int
12996 bkpt_insert_location (struct bp_location *bl)
12997 {
12998   if (bl->loc_type == bp_loc_hardware_breakpoint)
12999     return target_insert_hw_breakpoint (bl->gdbarch,
13000                                         &bl->target_info);
13001   else
13002     return target_insert_breakpoint (bl->gdbarch,
13003                                      &bl->target_info);
13004 }
13005
13006 static int
13007 bkpt_remove_location (struct bp_location *bl)
13008 {
13009   if (bl->loc_type == bp_loc_hardware_breakpoint)
13010     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13011   else
13012     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13013 }
13014
13015 static int
13016 bkpt_breakpoint_hit (const struct bp_location *bl,
13017                      struct address_space *aspace, CORE_ADDR bp_addr,
13018                      const struct target_waitstatus *ws)
13019 {
13020   struct breakpoint *b = bl->owner;
13021
13022   if (ws->kind != TARGET_WAITKIND_STOPPED
13023       || ws->value.sig != GDB_SIGNAL_TRAP)
13024     return 0;
13025
13026   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13027                                  aspace, bp_addr))
13028     return 0;
13029
13030   if (overlay_debugging         /* unmapped overlay section */
13031       && section_is_overlay (bl->section)
13032       && !section_is_mapped (bl->section))
13033     return 0;
13034
13035   return 1;
13036 }
13037
13038 static int
13039 bkpt_resources_needed (const struct bp_location *bl)
13040 {
13041   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13042
13043   return 1;
13044 }
13045
13046 static enum print_stop_action
13047 bkpt_print_it (bpstat bs)
13048 {
13049   struct breakpoint *b;
13050   const struct bp_location *bl;
13051   int bp_temp;
13052   struct ui_out *uiout = current_uiout;
13053
13054   gdb_assert (bs->bp_location_at != NULL);
13055
13056   bl = bs->bp_location_at;
13057   b = bs->breakpoint_at;
13058
13059   bp_temp = b->disposition == disp_del;
13060   if (bl->address != bl->requested_address)
13061     breakpoint_adjustment_warning (bl->requested_address,
13062                                    bl->address,
13063                                    b->number, 1);
13064   annotate_breakpoint (b->number);
13065   if (bp_temp)
13066     ui_out_text (uiout, "\nTemporary breakpoint ");
13067   else
13068     ui_out_text (uiout, "\nBreakpoint ");
13069   if (ui_out_is_mi_like_p (uiout))
13070     {
13071       ui_out_field_string (uiout, "reason",
13072                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13073       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13074     }
13075   ui_out_field_int (uiout, "bkptno", b->number);
13076   ui_out_text (uiout, ", ");
13077
13078   return PRINT_SRC_AND_LOC;
13079 }
13080
13081 static void
13082 bkpt_print_mention (struct breakpoint *b)
13083 {
13084   if (ui_out_is_mi_like_p (current_uiout))
13085     return;
13086
13087   switch (b->type)
13088     {
13089     case bp_breakpoint:
13090     case bp_gnu_ifunc_resolver:
13091       if (b->disposition == disp_del)
13092         printf_filtered (_("Temporary breakpoint"));
13093       else
13094         printf_filtered (_("Breakpoint"));
13095       printf_filtered (_(" %d"), b->number);
13096       if (b->type == bp_gnu_ifunc_resolver)
13097         printf_filtered (_(" at gnu-indirect-function resolver"));
13098       break;
13099     case bp_hardware_breakpoint:
13100       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13101       break;
13102     case bp_dprintf:
13103       printf_filtered (_("Dprintf %d"), b->number);
13104       break;
13105     }
13106
13107   say_where (b);
13108 }
13109
13110 static void
13111 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13112 {
13113   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13114     fprintf_unfiltered (fp, "tbreak");
13115   else if (tp->type == bp_breakpoint)
13116     fprintf_unfiltered (fp, "break");
13117   else if (tp->type == bp_hardware_breakpoint
13118            && tp->disposition == disp_del)
13119     fprintf_unfiltered (fp, "thbreak");
13120   else if (tp->type == bp_hardware_breakpoint)
13121     fprintf_unfiltered (fp, "hbreak");
13122   else
13123     internal_error (__FILE__, __LINE__,
13124                     _("unhandled breakpoint type %d"), (int) tp->type);
13125
13126   fprintf_unfiltered (fp, " %s", tp->addr_string);
13127   print_recreate_thread (tp, fp);
13128 }
13129
13130 static void
13131 bkpt_create_sals_from_address (char **arg,
13132                                struct linespec_result *canonical,
13133                                enum bptype type_wanted,
13134                                char *addr_start, char **copy_arg)
13135 {
13136   create_sals_from_address_default (arg, canonical, type_wanted,
13137                                     addr_start, copy_arg);
13138 }
13139
13140 static void
13141 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13142                              struct linespec_result *canonical,
13143                              struct linespec_sals *lsal,
13144                              char *cond_string,
13145                              char *extra_string,
13146                              enum bptype type_wanted,
13147                              enum bpdisp disposition,
13148                              int thread,
13149                              int task, int ignore_count,
13150                              const struct breakpoint_ops *ops,
13151                              int from_tty, int enabled,
13152                              int internal, unsigned flags)
13153 {
13154   create_breakpoints_sal_default (gdbarch, canonical, lsal,
13155                                   cond_string, extra_string,
13156                                   type_wanted,
13157                                   disposition, thread, task,
13158                                   ignore_count, ops, from_tty,
13159                                   enabled, internal, flags);
13160 }
13161
13162 static void
13163 bkpt_decode_linespec (struct breakpoint *b, char **s,
13164                       struct symtabs_and_lines *sals)
13165 {
13166   decode_linespec_default (b, s, sals);
13167 }
13168
13169 /* Virtual table for internal breakpoints.  */
13170
13171 static void
13172 internal_bkpt_re_set (struct breakpoint *b)
13173 {
13174   switch (b->type)
13175     {
13176       /* Delete overlay event and longjmp master breakpoints; they
13177          will be reset later by breakpoint_re_set.  */
13178     case bp_overlay_event:
13179     case bp_longjmp_master:
13180     case bp_std_terminate_master:
13181     case bp_exception_master:
13182       delete_breakpoint (b);
13183       break;
13184
13185       /* This breakpoint is special, it's set up when the inferior
13186          starts and we really don't want to touch it.  */
13187     case bp_shlib_event:
13188
13189       /* Like bp_shlib_event, this breakpoint type is special.  Once
13190          it is set up, we do not want to touch it.  */
13191     case bp_thread_event:
13192       break;
13193     }
13194 }
13195
13196 static void
13197 internal_bkpt_check_status (bpstat bs)
13198 {
13199   if (bs->breakpoint_at->type == bp_shlib_event)
13200     {
13201       /* If requested, stop when the dynamic linker notifies GDB of
13202          events.  This allows the user to get control and place
13203          breakpoints in initializer routines for dynamically loaded
13204          objects (among other things).  */
13205       bs->stop = stop_on_solib_events;
13206       bs->print = stop_on_solib_events;
13207     }
13208   else
13209     bs->stop = 0;
13210 }
13211
13212 static enum print_stop_action
13213 internal_bkpt_print_it (bpstat bs)
13214 {
13215   struct ui_out *uiout = current_uiout;
13216   struct breakpoint *b;
13217
13218   b = bs->breakpoint_at;
13219
13220   switch (b->type)
13221     {
13222     case bp_shlib_event:
13223       /* Did we stop because the user set the stop_on_solib_events
13224          variable?  (If so, we report this as a generic, "Stopped due
13225          to shlib event" message.) */
13226       print_solib_event (0);
13227       break;
13228
13229     case bp_thread_event:
13230       /* Not sure how we will get here.
13231          GDB should not stop for these breakpoints.  */
13232       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13233       break;
13234
13235     case bp_overlay_event:
13236       /* By analogy with the thread event, GDB should not stop for these.  */
13237       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13238       break;
13239
13240     case bp_longjmp_master:
13241       /* These should never be enabled.  */
13242       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13243       break;
13244
13245     case bp_std_terminate_master:
13246       /* These should never be enabled.  */
13247       printf_filtered (_("std::terminate Master Breakpoint: "
13248                          "gdb should not stop!\n"));
13249       break;
13250
13251     case bp_exception_master:
13252       /* These should never be enabled.  */
13253       printf_filtered (_("Exception Master Breakpoint: "
13254                          "gdb should not stop!\n"));
13255       break;
13256     }
13257
13258   return PRINT_NOTHING;
13259 }
13260
13261 static void
13262 internal_bkpt_print_mention (struct breakpoint *b)
13263 {
13264   /* Nothing to mention.  These breakpoints are internal.  */
13265 }
13266
13267 /* Virtual table for momentary breakpoints  */
13268
13269 static void
13270 momentary_bkpt_re_set (struct breakpoint *b)
13271 {
13272   /* Keep temporary breakpoints, which can be encountered when we step
13273      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
13274      Otherwise these should have been blown away via the cleanup chain
13275      or by breakpoint_init_inferior when we rerun the executable.  */
13276 }
13277
13278 static void
13279 momentary_bkpt_check_status (bpstat bs)
13280 {
13281   /* Nothing.  The point of these breakpoints is causing a stop.  */
13282 }
13283
13284 static enum print_stop_action
13285 momentary_bkpt_print_it (bpstat bs)
13286 {
13287   struct ui_out *uiout = current_uiout;
13288
13289   if (ui_out_is_mi_like_p (uiout))
13290     {
13291       struct breakpoint *b = bs->breakpoint_at;
13292
13293       switch (b->type)
13294         {
13295         case bp_finish:
13296           ui_out_field_string
13297             (uiout, "reason",
13298              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13299           break;
13300
13301         case bp_until:
13302           ui_out_field_string
13303             (uiout, "reason",
13304              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13305           break;
13306         }
13307     }
13308
13309   return PRINT_UNKNOWN;
13310 }
13311
13312 static void
13313 momentary_bkpt_print_mention (struct breakpoint *b)
13314 {
13315   /* Nothing to mention.  These breakpoints are internal.  */
13316 }
13317
13318 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13319
13320    It gets cleared already on the removal of the first one of such placed
13321    breakpoints.  This is OK as they get all removed altogether.  */
13322
13323 static void
13324 longjmp_bkpt_dtor (struct breakpoint *self)
13325 {
13326   struct thread_info *tp = find_thread_id (self->thread);
13327
13328   if (tp)
13329     tp->initiating_frame = null_frame_id;
13330
13331   momentary_breakpoint_ops.dtor (self);
13332 }
13333
13334 /* Specific methods for probe breakpoints.  */
13335
13336 static int
13337 bkpt_probe_insert_location (struct bp_location *bl)
13338 {
13339   int v = bkpt_insert_location (bl);
13340
13341   if (v == 0)
13342     {
13343       /* The insertion was successful, now let's set the probe's semaphore
13344          if needed.  */
13345       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
13346     }
13347
13348   return v;
13349 }
13350
13351 static int
13352 bkpt_probe_remove_location (struct bp_location *bl)
13353 {
13354   /* Let's clear the semaphore before removing the location.  */
13355   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
13356
13357   return bkpt_remove_location (bl);
13358 }
13359
13360 static void
13361 bkpt_probe_create_sals_from_address (char **arg,
13362                                      struct linespec_result *canonical,
13363                                      enum bptype type_wanted,
13364                                      char *addr_start, char **copy_arg)
13365 {
13366   struct linespec_sals lsal;
13367
13368   lsal.sals = parse_probes (arg, canonical);
13369
13370   *copy_arg = xstrdup (canonical->addr_string);
13371   lsal.canonical = xstrdup (*copy_arg);
13372
13373   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13374 }
13375
13376 static void
13377 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13378                             struct symtabs_and_lines *sals)
13379 {
13380   *sals = parse_probes (s, NULL);
13381   if (!sals->sals)
13382     error (_("probe not found"));
13383 }
13384
13385 /* The breakpoint_ops structure to be used in tracepoints.  */
13386
13387 static void
13388 tracepoint_re_set (struct breakpoint *b)
13389 {
13390   breakpoint_re_set_default (b);
13391 }
13392
13393 static int
13394 tracepoint_breakpoint_hit (const struct bp_location *bl,
13395                            struct address_space *aspace, CORE_ADDR bp_addr,
13396                            const struct target_waitstatus *ws)
13397 {
13398   /* By definition, the inferior does not report stops at
13399      tracepoints.  */
13400   return 0;
13401 }
13402
13403 static void
13404 tracepoint_print_one_detail (const struct breakpoint *self,
13405                              struct ui_out *uiout)
13406 {
13407   struct tracepoint *tp = (struct tracepoint *) self;
13408   if (tp->static_trace_marker_id)
13409     {
13410       gdb_assert (self->type == bp_static_tracepoint);
13411
13412       ui_out_text (uiout, "\tmarker id is ");
13413       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13414                            tp->static_trace_marker_id);
13415       ui_out_text (uiout, "\n");
13416     }
13417 }
13418
13419 static void
13420 tracepoint_print_mention (struct breakpoint *b)
13421 {
13422   if (ui_out_is_mi_like_p (current_uiout))
13423     return;
13424
13425   switch (b->type)
13426     {
13427     case bp_tracepoint:
13428       printf_filtered (_("Tracepoint"));
13429       printf_filtered (_(" %d"), b->number);
13430       break;
13431     case bp_fast_tracepoint:
13432       printf_filtered (_("Fast tracepoint"));
13433       printf_filtered (_(" %d"), b->number);
13434       break;
13435     case bp_static_tracepoint:
13436       printf_filtered (_("Static tracepoint"));
13437       printf_filtered (_(" %d"), b->number);
13438       break;
13439     default:
13440       internal_error (__FILE__, __LINE__,
13441                       _("unhandled tracepoint type %d"), (int) b->type);
13442     }
13443
13444   say_where (b);
13445 }
13446
13447 static void
13448 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13449 {
13450   struct tracepoint *tp = (struct tracepoint *) self;
13451
13452   if (self->type == bp_fast_tracepoint)
13453     fprintf_unfiltered (fp, "ftrace");
13454   if (self->type == bp_static_tracepoint)
13455     fprintf_unfiltered (fp, "strace");
13456   else if (self->type == bp_tracepoint)
13457     fprintf_unfiltered (fp, "trace");
13458   else
13459     internal_error (__FILE__, __LINE__,
13460                     _("unhandled tracepoint type %d"), (int) self->type);
13461
13462   fprintf_unfiltered (fp, " %s", self->addr_string);
13463   print_recreate_thread (self, fp);
13464
13465   if (tp->pass_count)
13466     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13467 }
13468
13469 static void
13470 tracepoint_create_sals_from_address (char **arg,
13471                                      struct linespec_result *canonical,
13472                                      enum bptype type_wanted,
13473                                      char *addr_start, char **copy_arg)
13474 {
13475   create_sals_from_address_default (arg, canonical, type_wanted,
13476                                     addr_start, copy_arg);
13477 }
13478
13479 static void
13480 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13481                                    struct linespec_result *canonical,
13482                                    struct linespec_sals *lsal,
13483                                    char *cond_string,
13484                                    char *extra_string,
13485                                    enum bptype type_wanted,
13486                                    enum bpdisp disposition,
13487                                    int thread,
13488                                    int task, int ignore_count,
13489                                    const struct breakpoint_ops *ops,
13490                                    int from_tty, int enabled,
13491                                    int internal, unsigned flags)
13492 {
13493   create_breakpoints_sal_default (gdbarch, canonical, lsal,
13494                                   cond_string, extra_string,
13495                                   type_wanted,
13496                                   disposition, thread, task,
13497                                   ignore_count, ops, from_tty,
13498                                   enabled, internal, flags);
13499 }
13500
13501 static void
13502 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13503                             struct symtabs_and_lines *sals)
13504 {
13505   decode_linespec_default (b, s, sals);
13506 }
13507
13508 struct breakpoint_ops tracepoint_breakpoint_ops;
13509
13510 /* The breakpoint_ops structure to be use on tracepoints placed in a
13511    static probe.  */
13512
13513 static void
13514 tracepoint_probe_create_sals_from_address (char **arg,
13515                                            struct linespec_result *canonical,
13516                                            enum bptype type_wanted,
13517                                            char *addr_start, char **copy_arg)
13518 {
13519   /* We use the same method for breakpoint on probes.  */
13520   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13521                                        addr_start, copy_arg);
13522 }
13523
13524 static void
13525 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13526                                   struct symtabs_and_lines *sals)
13527 {
13528   /* We use the same method for breakpoint on probes.  */
13529   bkpt_probe_decode_linespec (b, s, sals);
13530 }
13531
13532 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13533
13534 /* Dprintf breakpoint_ops methods.  */
13535
13536 static void
13537 dprintf_re_set (struct breakpoint *b)
13538 {
13539   breakpoint_re_set_default (b);
13540
13541   /* This breakpoint could have been pending, and be resolved now, and
13542      if so, we should now have the extra string.  If we don't, the
13543      dprintf was malformed when created, but we couldn't tell because
13544      we can't extract the extra string until the location is
13545      resolved.  */
13546   if (b->loc != NULL && b->extra_string == NULL)
13547     error (_("Format string required"));
13548
13549   /* 1 - connect to target 1, that can run breakpoint commands.
13550      2 - create a dprintf, which resolves fine.
13551      3 - disconnect from target 1
13552      4 - connect to target 2, that can NOT run breakpoint commands.
13553
13554      After steps #3/#4, you'll want the dprintf command list to
13555      be updated, because target 1 and 2 may well return different
13556      answers for target_can_run_breakpoint_commands().
13557      Given absence of finer grained resetting, we get to do
13558      it all the time.  */
13559   if (b->extra_string != NULL)
13560     update_dprintf_command_list (b);
13561 }
13562
13563 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13564
13565 static void
13566 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13567 {
13568   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13569                       tp->extra_string);
13570   print_recreate_thread (tp, fp);
13571 }
13572
13573 /* Implement the "after_condition_true" breakpoint_ops method for
13574    dprintf.
13575
13576    dprintf's are implemented with regular commands in their command
13577    list, but we run the commands here instead of before presenting the
13578    stop to the user, as dprintf's don't actually cause a stop.  This
13579    also makes it so that the commands of multiple dprintfs at the same
13580    address are all handled.  */
13581
13582 static void
13583 dprintf_after_condition_true (struct bpstats *bs)
13584 {
13585   struct cleanup *old_chain;
13586   struct bpstats tmp_bs = { NULL };
13587   struct bpstats *tmp_bs_p = &tmp_bs;
13588
13589   /* dprintf's never cause a stop.  This wasn't set in the
13590      check_status hook instead because that would make the dprintf's
13591      condition not be evaluated.  */
13592   bs->stop = 0;
13593
13594   /* Run the command list here.  Take ownership of it instead of
13595      copying.  We never want these commands to run later in
13596      bpstat_do_actions, if a breakpoint that causes a stop happens to
13597      be set at same address as this dprintf, or even if running the
13598      commands here throws.  */
13599   tmp_bs.commands = bs->commands;
13600   bs->commands = NULL;
13601   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13602
13603   bpstat_do_actions_1 (&tmp_bs_p);
13604
13605   /* 'tmp_bs.commands' will usually be NULL by now, but
13606      bpstat_do_actions_1 may return early without processing the whole
13607      list.  */
13608   do_cleanups (old_chain);
13609 }
13610
13611 /* The breakpoint_ops structure to be used on static tracepoints with
13612    markers (`-m').  */
13613
13614 static void
13615 strace_marker_create_sals_from_address (char **arg,
13616                                         struct linespec_result *canonical,
13617                                         enum bptype type_wanted,
13618                                         char *addr_start, char **copy_arg)
13619 {
13620   struct linespec_sals lsal;
13621
13622   lsal.sals = decode_static_tracepoint_spec (arg);
13623
13624   *copy_arg = savestring (addr_start, *arg - addr_start);
13625
13626   canonical->addr_string = xstrdup (*copy_arg);
13627   lsal.canonical = xstrdup (*copy_arg);
13628   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13629 }
13630
13631 static void
13632 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13633                                       struct linespec_result *canonical,
13634                                       struct linespec_sals *lsal,
13635                                       char *cond_string,
13636                                       char *extra_string,
13637                                       enum bptype type_wanted,
13638                                       enum bpdisp disposition,
13639                                       int thread,
13640                                       int task, int ignore_count,
13641                                       const struct breakpoint_ops *ops,
13642                                       int from_tty, int enabled,
13643                                       int internal, unsigned flags)
13644 {
13645   int i;
13646
13647   /* If the user is creating a static tracepoint by marker id
13648      (strace -m MARKER_ID), then store the sals index, so that
13649      breakpoint_re_set can try to match up which of the newly
13650      found markers corresponds to this one, and, don't try to
13651      expand multiple locations for each sal, given than SALS
13652      already should contain all sals for MARKER_ID.  */
13653
13654   for (i = 0; i < lsal->sals.nelts; ++i)
13655     {
13656       struct symtabs_and_lines expanded;
13657       struct tracepoint *tp;
13658       struct cleanup *old_chain;
13659       char *addr_string;
13660
13661       expanded.nelts = 1;
13662       expanded.sals = &lsal->sals.sals[i];
13663
13664       addr_string = xstrdup (canonical->addr_string);
13665       old_chain = make_cleanup (xfree, addr_string);
13666
13667       tp = XCNEW (struct tracepoint);
13668       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13669                            addr_string, NULL,
13670                            cond_string, extra_string,
13671                            type_wanted, disposition,
13672                            thread, task, ignore_count, ops,
13673                            from_tty, enabled, internal, flags,
13674                            canonical->special_display);
13675       /* Given that its possible to have multiple markers with
13676          the same string id, if the user is creating a static
13677          tracepoint by marker id ("strace -m MARKER_ID"), then
13678          store the sals index, so that breakpoint_re_set can
13679          try to match up which of the newly found markers
13680          corresponds to this one  */
13681       tp->static_trace_marker_id_idx = i;
13682
13683       install_breakpoint (internal, &tp->base, 0);
13684
13685       discard_cleanups (old_chain);
13686     }
13687 }
13688
13689 static void
13690 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13691                                struct symtabs_and_lines *sals)
13692 {
13693   struct tracepoint *tp = (struct tracepoint *) b;
13694
13695   *sals = decode_static_tracepoint_spec (s);
13696   if (sals->nelts > tp->static_trace_marker_id_idx)
13697     {
13698       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13699       sals->nelts = 1;
13700     }
13701   else
13702     error (_("marker %s not found"), tp->static_trace_marker_id);
13703 }
13704
13705 static struct breakpoint_ops strace_marker_breakpoint_ops;
13706
13707 static int
13708 strace_marker_p (struct breakpoint *b)
13709 {
13710   return b->ops == &strace_marker_breakpoint_ops;
13711 }
13712
13713 /* Delete a breakpoint and clean up all traces of it in the data
13714    structures.  */
13715
13716 void
13717 delete_breakpoint (struct breakpoint *bpt)
13718 {
13719   struct breakpoint *b;
13720
13721   gdb_assert (bpt != NULL);
13722
13723   /* Has this bp already been deleted?  This can happen because
13724      multiple lists can hold pointers to bp's.  bpstat lists are
13725      especial culprits.
13726
13727      One example of this happening is a watchpoint's scope bp.  When
13728      the scope bp triggers, we notice that the watchpoint is out of
13729      scope, and delete it.  We also delete its scope bp.  But the
13730      scope bp is marked "auto-deleting", and is already on a bpstat.
13731      That bpstat is then checked for auto-deleting bp's, which are
13732      deleted.
13733
13734      A real solution to this problem might involve reference counts in
13735      bp's, and/or giving them pointers back to their referencing
13736      bpstat's, and teaching delete_breakpoint to only free a bp's
13737      storage when no more references were extent.  A cheaper bandaid
13738      was chosen.  */
13739   if (bpt->type == bp_none)
13740     return;
13741
13742   /* At least avoid this stale reference until the reference counting
13743      of breakpoints gets resolved.  */
13744   if (bpt->related_breakpoint != bpt)
13745     {
13746       struct breakpoint *related;
13747       struct watchpoint *w;
13748
13749       if (bpt->type == bp_watchpoint_scope)
13750         w = (struct watchpoint *) bpt->related_breakpoint;
13751       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13752         w = (struct watchpoint *) bpt;
13753       else
13754         w = NULL;
13755       if (w != NULL)
13756         watchpoint_del_at_next_stop (w);
13757
13758       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13759       for (related = bpt; related->related_breakpoint != bpt;
13760            related = related->related_breakpoint);
13761       related->related_breakpoint = bpt->related_breakpoint;
13762       bpt->related_breakpoint = bpt;
13763     }
13764
13765   /* watch_command_1 creates a watchpoint but only sets its number if
13766      update_watchpoint succeeds in creating its bp_locations.  If there's
13767      a problem in that process, we'll be asked to delete the half-created
13768      watchpoint.  In that case, don't announce the deletion.  */
13769   if (bpt->number)
13770     observer_notify_breakpoint_deleted (bpt);
13771
13772   if (breakpoint_chain == bpt)
13773     breakpoint_chain = bpt->next;
13774
13775   ALL_BREAKPOINTS (b)
13776     if (b->next == bpt)
13777     {
13778       b->next = bpt->next;
13779       break;
13780     }
13781
13782   /* Be sure no bpstat's are pointing at the breakpoint after it's
13783      been freed.  */
13784   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13785      in all threads for now.  Note that we cannot just remove bpstats
13786      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13787      commands are associated with the bpstat; if we remove it here,
13788      then the later call to bpstat_do_actions (&stop_bpstat); in
13789      event-top.c won't do anything, and temporary breakpoints with
13790      commands won't work.  */
13791
13792   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13793
13794   /* Now that breakpoint is removed from breakpoint list, update the
13795      global location list.  This will remove locations that used to
13796      belong to this breakpoint.  Do this before freeing the breakpoint
13797      itself, since remove_breakpoint looks at location's owner.  It
13798      might be better design to have location completely
13799      self-contained, but it's not the case now.  */
13800   update_global_location_list (0);
13801
13802   bpt->ops->dtor (bpt);
13803   /* On the chance that someone will soon try again to delete this
13804      same bp, we mark it as deleted before freeing its storage.  */
13805   bpt->type = bp_none;
13806   xfree (bpt);
13807 }
13808
13809 static void
13810 do_delete_breakpoint_cleanup (void *b)
13811 {
13812   delete_breakpoint (b);
13813 }
13814
13815 struct cleanup *
13816 make_cleanup_delete_breakpoint (struct breakpoint *b)
13817 {
13818   return make_cleanup (do_delete_breakpoint_cleanup, b);
13819 }
13820
13821 /* Iterator function to call a user-provided callback function once
13822    for each of B and its related breakpoints.  */
13823
13824 static void
13825 iterate_over_related_breakpoints (struct breakpoint *b,
13826                                   void (*function) (struct breakpoint *,
13827                                                     void *),
13828                                   void *data)
13829 {
13830   struct breakpoint *related;
13831
13832   related = b;
13833   do
13834     {
13835       struct breakpoint *next;
13836
13837       /* FUNCTION may delete RELATED.  */
13838       next = related->related_breakpoint;
13839
13840       if (next == related)
13841         {
13842           /* RELATED is the last ring entry.  */
13843           function (related, data);
13844
13845           /* FUNCTION may have deleted it, so we'd never reach back to
13846              B.  There's nothing left to do anyway, so just break
13847              out.  */
13848           break;
13849         }
13850       else
13851         function (related, data);
13852
13853       related = next;
13854     }
13855   while (related != b);
13856 }
13857
13858 static void
13859 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13860 {
13861   delete_breakpoint (b);
13862 }
13863
13864 /* A callback for map_breakpoint_numbers that calls
13865    delete_breakpoint.  */
13866
13867 static void
13868 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13869 {
13870   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13871 }
13872
13873 void
13874 delete_command (char *arg, int from_tty)
13875 {
13876   struct breakpoint *b, *b_tmp;
13877
13878   dont_repeat ();
13879
13880   if (arg == 0)
13881     {
13882       int breaks_to_delete = 0;
13883
13884       /* Delete all breakpoints if no argument.  Do not delete
13885          internal breakpoints, these have to be deleted with an
13886          explicit breakpoint number argument.  */
13887       ALL_BREAKPOINTS (b)
13888         if (user_breakpoint_p (b))
13889           {
13890             breaks_to_delete = 1;
13891             break;
13892           }
13893
13894       /* Ask user only if there are some breakpoints to delete.  */
13895       if (!from_tty
13896           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13897         {
13898           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13899             if (user_breakpoint_p (b))
13900               delete_breakpoint (b);
13901         }
13902     }
13903   else
13904     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13905 }
13906
13907 static int
13908 all_locations_are_pending (struct bp_location *loc)
13909 {
13910   for (; loc; loc = loc->next)
13911     if (!loc->shlib_disabled
13912         && !loc->pspace->executing_startup)
13913       return 0;
13914   return 1;
13915 }
13916
13917 /* Subroutine of update_breakpoint_locations to simplify it.
13918    Return non-zero if multiple fns in list LOC have the same name.
13919    Null names are ignored.  */
13920
13921 static int
13922 ambiguous_names_p (struct bp_location *loc)
13923 {
13924   struct bp_location *l;
13925   htab_t htab = htab_create_alloc (13, htab_hash_string,
13926                                    (int (*) (const void *, 
13927                                              const void *)) streq,
13928                                    NULL, xcalloc, xfree);
13929
13930   for (l = loc; l != NULL; l = l->next)
13931     {
13932       const char **slot;
13933       const char *name = l->function_name;
13934
13935       /* Allow for some names to be NULL, ignore them.  */
13936       if (name == NULL)
13937         continue;
13938
13939       slot = (const char **) htab_find_slot (htab, (const void *) name,
13940                                              INSERT);
13941       /* NOTE: We can assume slot != NULL here because xcalloc never
13942          returns NULL.  */
13943       if (*slot != NULL)
13944         {
13945           htab_delete (htab);
13946           return 1;
13947         }
13948       *slot = name;
13949     }
13950
13951   htab_delete (htab);
13952   return 0;
13953 }
13954
13955 /* When symbols change, it probably means the sources changed as well,
13956    and it might mean the static tracepoint markers are no longer at
13957    the same address or line numbers they used to be at last we
13958    checked.  Losing your static tracepoints whenever you rebuild is
13959    undesirable.  This function tries to resync/rematch gdb static
13960    tracepoints with the markers on the target, for static tracepoints
13961    that have not been set by marker id.  Static tracepoint that have
13962    been set by marker id are reset by marker id in breakpoint_re_set.
13963    The heuristic is:
13964
13965    1) For a tracepoint set at a specific address, look for a marker at
13966    the old PC.  If one is found there, assume to be the same marker.
13967    If the name / string id of the marker found is different from the
13968    previous known name, assume that means the user renamed the marker
13969    in the sources, and output a warning.
13970
13971    2) For a tracepoint set at a given line number, look for a marker
13972    at the new address of the old line number.  If one is found there,
13973    assume to be the same marker.  If the name / string id of the
13974    marker found is different from the previous known name, assume that
13975    means the user renamed the marker in the sources, and output a
13976    warning.
13977
13978    3) If a marker is no longer found at the same address or line, it
13979    may mean the marker no longer exists.  But it may also just mean
13980    the code changed a bit.  Maybe the user added a few lines of code
13981    that made the marker move up or down (in line number terms).  Ask
13982    the target for info about the marker with the string id as we knew
13983    it.  If found, update line number and address in the matching
13984    static tracepoint.  This will get confused if there's more than one
13985    marker with the same ID (possible in UST, although unadvised
13986    precisely because it confuses tools).  */
13987
13988 static struct symtab_and_line
13989 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13990 {
13991   struct tracepoint *tp = (struct tracepoint *) b;
13992   struct static_tracepoint_marker marker;
13993   CORE_ADDR pc;
13994
13995   pc = sal.pc;
13996   if (sal.line)
13997     find_line_pc (sal.symtab, sal.line, &pc);
13998
13999   if (target_static_tracepoint_marker_at (pc, &marker))
14000     {
14001       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14002         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14003                  b->number,
14004                  tp->static_trace_marker_id, marker.str_id);
14005
14006       xfree (tp->static_trace_marker_id);
14007       tp->static_trace_marker_id = xstrdup (marker.str_id);
14008       release_static_tracepoint_marker (&marker);
14009
14010       return sal;
14011     }
14012
14013   /* Old marker wasn't found on target at lineno.  Try looking it up
14014      by string ID.  */
14015   if (!sal.explicit_pc
14016       && sal.line != 0
14017       && sal.symtab != NULL
14018       && tp->static_trace_marker_id != NULL)
14019     {
14020       VEC(static_tracepoint_marker_p) *markers;
14021
14022       markers
14023         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14024
14025       if (!VEC_empty(static_tracepoint_marker_p, markers))
14026         {
14027           struct symtab_and_line sal2;
14028           struct symbol *sym;
14029           struct static_tracepoint_marker *tpmarker;
14030           struct ui_out *uiout = current_uiout;
14031
14032           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14033
14034           xfree (tp->static_trace_marker_id);
14035           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14036
14037           warning (_("marker for static tracepoint %d (%s) not "
14038                      "found at previous line number"),
14039                    b->number, tp->static_trace_marker_id);
14040
14041           init_sal (&sal2);
14042
14043           sal2.pc = tpmarker->address;
14044
14045           sal2 = find_pc_line (tpmarker->address, 0);
14046           sym = find_pc_sect_function (tpmarker->address, NULL);
14047           ui_out_text (uiout, "Now in ");
14048           if (sym)
14049             {
14050               ui_out_field_string (uiout, "func",
14051                                    SYMBOL_PRINT_NAME (sym));
14052               ui_out_text (uiout, " at ");
14053             }
14054           ui_out_field_string (uiout, "file",
14055                                symtab_to_filename_for_display (sal2.symtab));
14056           ui_out_text (uiout, ":");
14057
14058           if (ui_out_is_mi_like_p (uiout))
14059             {
14060               const char *fullname = symtab_to_fullname (sal2.symtab);
14061
14062               ui_out_field_string (uiout, "fullname", fullname);
14063             }
14064
14065           ui_out_field_int (uiout, "line", sal2.line);
14066           ui_out_text (uiout, "\n");
14067
14068           b->loc->line_number = sal2.line;
14069           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14070
14071           xfree (b->addr_string);
14072           b->addr_string = xstrprintf ("%s:%d",
14073                                    symtab_to_filename_for_display (sal2.symtab),
14074                                        b->loc->line_number);
14075
14076           /* Might be nice to check if function changed, and warn if
14077              so.  */
14078
14079           release_static_tracepoint_marker (tpmarker);
14080         }
14081     }
14082   return sal;
14083 }
14084
14085 /* Returns 1 iff locations A and B are sufficiently same that
14086    we don't need to report breakpoint as changed.  */
14087
14088 static int
14089 locations_are_equal (struct bp_location *a, struct bp_location *b)
14090 {
14091   while (a && b)
14092     {
14093       if (a->address != b->address)
14094         return 0;
14095
14096       if (a->shlib_disabled != b->shlib_disabled)
14097         return 0;
14098
14099       if (a->enabled != b->enabled)
14100         return 0;
14101
14102       a = a->next;
14103       b = b->next;
14104     }
14105
14106   if ((a == NULL) != (b == NULL))
14107     return 0;
14108
14109   return 1;
14110 }
14111
14112 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14113    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14114    a ranged breakpoint.  */
14115
14116 void
14117 update_breakpoint_locations (struct breakpoint *b,
14118                              struct symtabs_and_lines sals,
14119                              struct symtabs_and_lines sals_end)
14120 {
14121   int i;
14122   struct bp_location *existing_locations = b->loc;
14123
14124   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14125     {
14126       /* Ranged breakpoints have only one start location and one end
14127          location.  */
14128       b->enable_state = bp_disabled;
14129       update_global_location_list (1);
14130       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14131                            "multiple locations found\n"),
14132                          b->number);
14133       return;
14134     }
14135
14136   /* If there's no new locations, and all existing locations are
14137      pending, don't do anything.  This optimizes the common case where
14138      all locations are in the same shared library, that was unloaded.
14139      We'd like to retain the location, so that when the library is
14140      loaded again, we don't loose the enabled/disabled status of the
14141      individual locations.  */
14142   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14143     return;
14144
14145   b->loc = NULL;
14146
14147   for (i = 0; i < sals.nelts; ++i)
14148     {
14149       struct bp_location *new_loc;
14150
14151       switch_to_program_space_and_thread (sals.sals[i].pspace);
14152
14153       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14154
14155       /* Reparse conditions, they might contain references to the
14156          old symtab.  */
14157       if (b->cond_string != NULL)
14158         {
14159           const char *s;
14160           volatile struct gdb_exception e;
14161
14162           s = b->cond_string;
14163           TRY_CATCH (e, RETURN_MASK_ERROR)
14164             {
14165               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14166                                            block_for_pc (sals.sals[i].pc), 
14167                                            0);
14168             }
14169           if (e.reason < 0)
14170             {
14171               warning (_("failed to reevaluate condition "
14172                          "for breakpoint %d: %s"), 
14173                        b->number, e.message);
14174               new_loc->enabled = 0;
14175             }
14176         }
14177
14178       if (sals_end.nelts)
14179         {
14180           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14181
14182           new_loc->length = end - sals.sals[0].pc + 1;
14183         }
14184     }
14185
14186   /* Update locations of permanent breakpoints.  */
14187   if (b->enable_state == bp_permanent)
14188     make_breakpoint_permanent (b);
14189
14190   /* If possible, carry over 'disable' status from existing
14191      breakpoints.  */
14192   {
14193     struct bp_location *e = existing_locations;
14194     /* If there are multiple breakpoints with the same function name,
14195        e.g. for inline functions, comparing function names won't work.
14196        Instead compare pc addresses; this is just a heuristic as things
14197        may have moved, but in practice it gives the correct answer
14198        often enough until a better solution is found.  */
14199     int have_ambiguous_names = ambiguous_names_p (b->loc);
14200
14201     for (; e; e = e->next)
14202       {
14203         if (!e->enabled && e->function_name)
14204           {
14205             struct bp_location *l = b->loc;
14206             if (have_ambiguous_names)
14207               {
14208                 for (; l; l = l->next)
14209                   if (breakpoint_locations_match (e, l))
14210                     {
14211                       l->enabled = 0;
14212                       break;
14213                     }
14214               }
14215             else
14216               {
14217                 for (; l; l = l->next)
14218                   if (l->function_name
14219                       && strcmp (e->function_name, l->function_name) == 0)
14220                     {
14221                       l->enabled = 0;
14222                       break;
14223                     }
14224               }
14225           }
14226       }
14227   }
14228
14229   if (!locations_are_equal (existing_locations, b->loc))
14230     observer_notify_breakpoint_modified (b);
14231
14232   update_global_location_list (1);
14233 }
14234
14235 /* Find the SaL locations corresponding to the given ADDR_STRING.
14236    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14237
14238 static struct symtabs_and_lines
14239 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14240 {
14241   char *s;
14242   struct symtabs_and_lines sals = {0};
14243   volatile struct gdb_exception e;
14244
14245   gdb_assert (b->ops != NULL);
14246   s = addr_string;
14247
14248   TRY_CATCH (e, RETURN_MASK_ERROR)
14249     {
14250       b->ops->decode_linespec (b, &s, &sals);
14251     }
14252   if (e.reason < 0)
14253     {
14254       int not_found_and_ok = 0;
14255       /* For pending breakpoints, it's expected that parsing will
14256          fail until the right shared library is loaded.  User has
14257          already told to create pending breakpoints and don't need
14258          extra messages.  If breakpoint is in bp_shlib_disabled
14259          state, then user already saw the message about that
14260          breakpoint being disabled, and don't want to see more
14261          errors.  */
14262       if (e.error == NOT_FOUND_ERROR
14263           && (b->condition_not_parsed 
14264               || (b->loc && b->loc->shlib_disabled)
14265               || (b->loc && b->loc->pspace->executing_startup)
14266               || b->enable_state == bp_disabled))
14267         not_found_and_ok = 1;
14268
14269       if (!not_found_and_ok)
14270         {
14271           /* We surely don't want to warn about the same breakpoint
14272              10 times.  One solution, implemented here, is disable
14273              the breakpoint on error.  Another solution would be to
14274              have separate 'warning emitted' flag.  Since this
14275              happens only when a binary has changed, I don't know
14276              which approach is better.  */
14277           b->enable_state = bp_disabled;
14278           throw_exception (e);
14279         }
14280     }
14281
14282   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14283     {
14284       int i;
14285
14286       for (i = 0; i < sals.nelts; ++i)
14287         resolve_sal_pc (&sals.sals[i]);
14288       if (b->condition_not_parsed && s && s[0])
14289         {
14290           char *cond_string, *extra_string;
14291           int thread, task;
14292
14293           find_condition_and_thread (s, sals.sals[0].pc,
14294                                      &cond_string, &thread, &task,
14295                                      &extra_string);
14296           if (cond_string)
14297             b->cond_string = cond_string;
14298           b->thread = thread;
14299           b->task = task;
14300           if (extra_string)
14301             b->extra_string = extra_string;
14302           b->condition_not_parsed = 0;
14303         }
14304
14305       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14306         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14307
14308       *found = 1;
14309     }
14310   else
14311     *found = 0;
14312
14313   return sals;
14314 }
14315
14316 /* The default re_set method, for typical hardware or software
14317    breakpoints.  Reevaluate the breakpoint and recreate its
14318    locations.  */
14319
14320 static void
14321 breakpoint_re_set_default (struct breakpoint *b)
14322 {
14323   int found;
14324   struct symtabs_and_lines sals, sals_end;
14325   struct symtabs_and_lines expanded = {0};
14326   struct symtabs_and_lines expanded_end = {0};
14327
14328   sals = addr_string_to_sals (b, b->addr_string, &found);
14329   if (found)
14330     {
14331       make_cleanup (xfree, sals.sals);
14332       expanded = sals;
14333     }
14334
14335   if (b->addr_string_range_end)
14336     {
14337       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14338       if (found)
14339         {
14340           make_cleanup (xfree, sals_end.sals);
14341           expanded_end = sals_end;
14342         }
14343     }
14344
14345   update_breakpoint_locations (b, expanded, expanded_end);
14346 }
14347
14348 /* Default method for creating SALs from an address string.  It basically
14349    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14350
14351 static void
14352 create_sals_from_address_default (char **arg,
14353                                   struct linespec_result *canonical,
14354                                   enum bptype type_wanted,
14355                                   char *addr_start, char **copy_arg)
14356 {
14357   parse_breakpoint_sals (arg, canonical);
14358 }
14359
14360 /* Call create_breakpoints_sal for the given arguments.  This is the default
14361    function for the `create_breakpoints_sal' method of
14362    breakpoint_ops.  */
14363
14364 static void
14365 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14366                                 struct linespec_result *canonical,
14367                                 struct linespec_sals *lsal,
14368                                 char *cond_string,
14369                                 char *extra_string,
14370                                 enum bptype type_wanted,
14371                                 enum bpdisp disposition,
14372                                 int thread,
14373                                 int task, int ignore_count,
14374                                 const struct breakpoint_ops *ops,
14375                                 int from_tty, int enabled,
14376                                 int internal, unsigned flags)
14377 {
14378   create_breakpoints_sal (gdbarch, canonical, cond_string,
14379                           extra_string,
14380                           type_wanted, disposition,
14381                           thread, task, ignore_count, ops, from_tty,
14382                           enabled, internal, flags);
14383 }
14384
14385 /* Decode the line represented by S by calling decode_line_full.  This is the
14386    default function for the `decode_linespec' method of breakpoint_ops.  */
14387
14388 static void
14389 decode_linespec_default (struct breakpoint *b, char **s,
14390                          struct symtabs_and_lines *sals)
14391 {
14392   struct linespec_result canonical;
14393
14394   init_linespec_result (&canonical);
14395   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14396                     (struct symtab *) NULL, 0,
14397                     &canonical, multiple_symbols_all,
14398                     b->filter);
14399
14400   /* We should get 0 or 1 resulting SALs.  */
14401   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14402
14403   if (VEC_length (linespec_sals, canonical.sals) > 0)
14404     {
14405       struct linespec_sals *lsal;
14406
14407       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14408       *sals = lsal->sals;
14409       /* Arrange it so the destructor does not free the
14410          contents.  */
14411       lsal->sals.sals = NULL;
14412     }
14413
14414   destroy_linespec_result (&canonical);
14415 }
14416
14417 /* Prepare the global context for a re-set of breakpoint B.  */
14418
14419 static struct cleanup *
14420 prepare_re_set_context (struct breakpoint *b)
14421 {
14422   struct cleanup *cleanups;
14423
14424   input_radix = b->input_radix;
14425   cleanups = save_current_space_and_thread ();
14426   if (b->pspace != NULL)
14427     switch_to_program_space_and_thread (b->pspace);
14428   set_language (b->language);
14429
14430   return cleanups;
14431 }
14432
14433 /* Reset a breakpoint given it's struct breakpoint * BINT.
14434    The value we return ends up being the return value from catch_errors.
14435    Unused in this case.  */
14436
14437 static int
14438 breakpoint_re_set_one (void *bint)
14439 {
14440   /* Get past catch_errs.  */
14441   struct breakpoint *b = (struct breakpoint *) bint;
14442   struct cleanup *cleanups;
14443
14444   cleanups = prepare_re_set_context (b);
14445   b->ops->re_set (b);
14446   do_cleanups (cleanups);
14447   return 0;
14448 }
14449
14450 /* Re-set all breakpoints after symbols have been re-loaded.  */
14451 void
14452 breakpoint_re_set (void)
14453 {
14454   struct breakpoint *b, *b_tmp;
14455   enum language save_language;
14456   int save_input_radix;
14457   struct cleanup *old_chain;
14458
14459   save_language = current_language->la_language;
14460   save_input_radix = input_radix;
14461   old_chain = save_current_program_space ();
14462
14463   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14464   {
14465     /* Format possible error msg.  */
14466     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14467                                 b->number);
14468     struct cleanup *cleanups = make_cleanup (xfree, message);
14469     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14470     do_cleanups (cleanups);
14471   }
14472   set_language (save_language);
14473   input_radix = save_input_radix;
14474
14475   jit_breakpoint_re_set ();
14476
14477   do_cleanups (old_chain);
14478
14479   create_overlay_event_breakpoint ();
14480   create_longjmp_master_breakpoint ();
14481   create_std_terminate_master_breakpoint ();
14482   create_exception_master_breakpoint ();
14483 }
14484 \f
14485 /* Reset the thread number of this breakpoint:
14486
14487    - If the breakpoint is for all threads, leave it as-is.
14488    - Else, reset it to the current thread for inferior_ptid.  */
14489 void
14490 breakpoint_re_set_thread (struct breakpoint *b)
14491 {
14492   if (b->thread != -1)
14493     {
14494       if (in_thread_list (inferior_ptid))
14495         b->thread = pid_to_thread_id (inferior_ptid);
14496
14497       /* We're being called after following a fork.  The new fork is
14498          selected as current, and unless this was a vfork will have a
14499          different program space from the original thread.  Reset that
14500          as well.  */
14501       b->loc->pspace = current_program_space;
14502     }
14503 }
14504
14505 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14506    If from_tty is nonzero, it prints a message to that effect,
14507    which ends with a period (no newline).  */
14508
14509 void
14510 set_ignore_count (int bptnum, int count, int from_tty)
14511 {
14512   struct breakpoint *b;
14513
14514   if (count < 0)
14515     count = 0;
14516
14517   ALL_BREAKPOINTS (b)
14518     if (b->number == bptnum)
14519     {
14520       if (is_tracepoint (b))
14521         {
14522           if (from_tty && count != 0)
14523             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14524                              bptnum);
14525           return;
14526         }
14527       
14528       b->ignore_count = count;
14529       if (from_tty)
14530         {
14531           if (count == 0)
14532             printf_filtered (_("Will stop next time "
14533                                "breakpoint %d is reached."),
14534                              bptnum);
14535           else if (count == 1)
14536             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14537                              bptnum);
14538           else
14539             printf_filtered (_("Will ignore next %d "
14540                                "crossings of breakpoint %d."),
14541                              count, bptnum);
14542         }
14543       observer_notify_breakpoint_modified (b);
14544       return;
14545     }
14546
14547   error (_("No breakpoint number %d."), bptnum);
14548 }
14549
14550 /* Command to set ignore-count of breakpoint N to COUNT.  */
14551
14552 static void
14553 ignore_command (char *args, int from_tty)
14554 {
14555   char *p = args;
14556   int num;
14557
14558   if (p == 0)
14559     error_no_arg (_("a breakpoint number"));
14560
14561   num = get_number (&p);
14562   if (num == 0)
14563     error (_("bad breakpoint number: '%s'"), args);
14564   if (*p == 0)
14565     error (_("Second argument (specified ignore-count) is missing."));
14566
14567   set_ignore_count (num,
14568                     longest_to_int (value_as_long (parse_and_eval (p))),
14569                     from_tty);
14570   if (from_tty)
14571     printf_filtered ("\n");
14572 }
14573 \f
14574 /* Call FUNCTION on each of the breakpoints
14575    whose numbers are given in ARGS.  */
14576
14577 static void
14578 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14579                                                       void *),
14580                         void *data)
14581 {
14582   int num;
14583   struct breakpoint *b, *tmp;
14584   int match;
14585   struct get_number_or_range_state state;
14586
14587   if (args == 0)
14588     error_no_arg (_("one or more breakpoint numbers"));
14589
14590   init_number_or_range (&state, args);
14591
14592   while (!state.finished)
14593     {
14594       char *p = state.string;
14595
14596       match = 0;
14597
14598       num = get_number_or_range (&state);
14599       if (num == 0)
14600         {
14601           warning (_("bad breakpoint number at or near '%s'"), p);
14602         }
14603       else
14604         {
14605           ALL_BREAKPOINTS_SAFE (b, tmp)
14606             if (b->number == num)
14607               {
14608                 match = 1;
14609                 function (b, data);
14610                 break;
14611               }
14612           if (match == 0)
14613             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14614         }
14615     }
14616 }
14617
14618 static struct bp_location *
14619 find_location_by_number (char *number)
14620 {
14621   char *dot = strchr (number, '.');
14622   char *p1;
14623   int bp_num;
14624   int loc_num;
14625   struct breakpoint *b;
14626   struct bp_location *loc;  
14627
14628   *dot = '\0';
14629
14630   p1 = number;
14631   bp_num = get_number (&p1);
14632   if (bp_num == 0)
14633     error (_("Bad breakpoint number '%s'"), number);
14634
14635   ALL_BREAKPOINTS (b)
14636     if (b->number == bp_num)
14637       {
14638         break;
14639       }
14640
14641   if (!b || b->number != bp_num)
14642     error (_("Bad breakpoint number '%s'"), number);
14643   
14644   p1 = dot+1;
14645   loc_num = get_number (&p1);
14646   if (loc_num == 0)
14647     error (_("Bad breakpoint location number '%s'"), number);
14648
14649   --loc_num;
14650   loc = b->loc;
14651   for (;loc_num && loc; --loc_num, loc = loc->next)
14652     ;
14653   if (!loc)
14654     error (_("Bad breakpoint location number '%s'"), dot+1);
14655     
14656   return loc;  
14657 }
14658
14659
14660 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14661    If from_tty is nonzero, it prints a message to that effect,
14662    which ends with a period (no newline).  */
14663
14664 void
14665 disable_breakpoint (struct breakpoint *bpt)
14666 {
14667   /* Never disable a watchpoint scope breakpoint; we want to
14668      hit them when we leave scope so we can delete both the
14669      watchpoint and its scope breakpoint at that time.  */
14670   if (bpt->type == bp_watchpoint_scope)
14671     return;
14672
14673   /* You can't disable permanent breakpoints.  */
14674   if (bpt->enable_state == bp_permanent)
14675     return;
14676
14677   bpt->enable_state = bp_disabled;
14678
14679   /* Mark breakpoint locations modified.  */
14680   mark_breakpoint_modified (bpt);
14681
14682   if (target_supports_enable_disable_tracepoint ()
14683       && current_trace_status ()->running && is_tracepoint (bpt))
14684     {
14685       struct bp_location *location;
14686      
14687       for (location = bpt->loc; location; location = location->next)
14688         target_disable_tracepoint (location);
14689     }
14690
14691   update_global_location_list (0);
14692
14693   observer_notify_breakpoint_modified (bpt);
14694 }
14695
14696 /* A callback for iterate_over_related_breakpoints.  */
14697
14698 static void
14699 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14700 {
14701   disable_breakpoint (b);
14702 }
14703
14704 /* A callback for map_breakpoint_numbers that calls
14705    disable_breakpoint.  */
14706
14707 static void
14708 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14709 {
14710   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14711 }
14712
14713 static void
14714 disable_command (char *args, int from_tty)
14715 {
14716   if (args == 0)
14717     {
14718       struct breakpoint *bpt;
14719
14720       ALL_BREAKPOINTS (bpt)
14721         if (user_breakpoint_p (bpt))
14722           disable_breakpoint (bpt);
14723     }
14724   else if (strchr (args, '.'))
14725     {
14726       struct bp_location *loc = find_location_by_number (args);
14727       if (loc)
14728         {
14729           if (loc->enabled)
14730             {
14731               loc->enabled = 0;
14732               mark_breakpoint_location_modified (loc);
14733             }
14734           if (target_supports_enable_disable_tracepoint ()
14735               && current_trace_status ()->running && loc->owner
14736               && is_tracepoint (loc->owner))
14737             target_disable_tracepoint (loc);
14738         }
14739       update_global_location_list (0);
14740     }
14741   else
14742     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
14743 }
14744
14745 static void
14746 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14747                         int count)
14748 {
14749   int target_resources_ok;
14750
14751   if (bpt->type == bp_hardware_breakpoint)
14752     {
14753       int i;
14754       i = hw_breakpoint_used_count ();
14755       target_resources_ok = 
14756         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14757                                             i + 1, 0);
14758       if (target_resources_ok == 0)
14759         error (_("No hardware breakpoint support in the target."));
14760       else if (target_resources_ok < 0)
14761         error (_("Hardware breakpoints used exceeds limit."));
14762     }
14763
14764   if (is_watchpoint (bpt))
14765     {
14766       /* Initialize it just to avoid a GCC false warning.  */
14767       enum enable_state orig_enable_state = 0;
14768       volatile struct gdb_exception e;
14769
14770       TRY_CATCH (e, RETURN_MASK_ALL)
14771         {
14772           struct watchpoint *w = (struct watchpoint *) bpt;
14773
14774           orig_enable_state = bpt->enable_state;
14775           bpt->enable_state = bp_enabled;
14776           update_watchpoint (w, 1 /* reparse */);
14777         }
14778       if (e.reason < 0)
14779         {
14780           bpt->enable_state = orig_enable_state;
14781           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14782                              bpt->number);
14783           return;
14784         }
14785     }
14786
14787   if (bpt->enable_state != bp_permanent)
14788     bpt->enable_state = bp_enabled;
14789
14790   bpt->enable_state = bp_enabled;
14791
14792   /* Mark breakpoint locations modified.  */
14793   mark_breakpoint_modified (bpt);
14794
14795   if (target_supports_enable_disable_tracepoint ()
14796       && current_trace_status ()->running && is_tracepoint (bpt))
14797     {
14798       struct bp_location *location;
14799
14800       for (location = bpt->loc; location; location = location->next)
14801         target_enable_tracepoint (location);
14802     }
14803
14804   bpt->disposition = disposition;
14805   bpt->enable_count = count;
14806   update_global_location_list (1);
14807
14808   observer_notify_breakpoint_modified (bpt);
14809 }
14810
14811
14812 void
14813 enable_breakpoint (struct breakpoint *bpt)
14814 {
14815   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14816 }
14817
14818 static void
14819 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14820 {
14821   enable_breakpoint (bpt);
14822 }
14823
14824 /* A callback for map_breakpoint_numbers that calls
14825    enable_breakpoint.  */
14826
14827 static void
14828 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14829 {
14830   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14831 }
14832
14833 /* The enable command enables the specified breakpoints (or all defined
14834    breakpoints) so they once again become (or continue to be) effective
14835    in stopping the inferior.  */
14836
14837 static void
14838 enable_command (char *args, int from_tty)
14839 {
14840   if (args == 0)
14841     {
14842       struct breakpoint *bpt;
14843
14844       ALL_BREAKPOINTS (bpt)
14845         if (user_breakpoint_p (bpt))
14846           enable_breakpoint (bpt);
14847     }
14848   else if (strchr (args, '.'))
14849     {
14850       struct bp_location *loc = find_location_by_number (args);
14851       if (loc)
14852         {
14853           if (!loc->enabled)
14854             {
14855               loc->enabled = 1;
14856               mark_breakpoint_location_modified (loc);
14857             }
14858           if (target_supports_enable_disable_tracepoint ()
14859               && current_trace_status ()->running && loc->owner
14860               && is_tracepoint (loc->owner))
14861             target_enable_tracepoint (loc);
14862         }
14863       update_global_location_list (1);
14864     }
14865   else
14866     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
14867 }
14868
14869 /* This struct packages up disposition data for application to multiple
14870    breakpoints.  */
14871
14872 struct disp_data
14873 {
14874   enum bpdisp disp;
14875   int count;
14876 };
14877
14878 static void
14879 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14880 {
14881   struct disp_data disp_data = *(struct disp_data *) arg;
14882
14883   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14884 }
14885
14886 static void
14887 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14888 {
14889   struct disp_data disp = { disp_disable, 1 };
14890
14891   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14892 }
14893
14894 static void
14895 enable_once_command (char *args, int from_tty)
14896 {
14897   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14898 }
14899
14900 static void
14901 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14902 {
14903   struct disp_data disp = { disp_disable, *(int *) countptr };
14904
14905   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14906 }
14907
14908 static void
14909 enable_count_command (char *args, int from_tty)
14910 {
14911   int count = get_number (&args);
14912
14913   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14914 }
14915
14916 static void
14917 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14918 {
14919   struct disp_data disp = { disp_del, 1 };
14920
14921   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14922 }
14923
14924 static void
14925 enable_delete_command (char *args, int from_tty)
14926 {
14927   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14928 }
14929 \f
14930 static void
14931 set_breakpoint_cmd (char *args, int from_tty)
14932 {
14933 }
14934
14935 static void
14936 show_breakpoint_cmd (char *args, int from_tty)
14937 {
14938 }
14939
14940 /* Invalidate last known value of any hardware watchpoint if
14941    the memory which that value represents has been written to by
14942    GDB itself.  */
14943
14944 static void
14945 invalidate_bp_value_on_memory_change (struct inferior *inferior,
14946                                       CORE_ADDR addr, ssize_t len,
14947                                       const bfd_byte *data)
14948 {
14949   struct breakpoint *bp;
14950
14951   ALL_BREAKPOINTS (bp)
14952     if (bp->enable_state == bp_enabled
14953         && bp->type == bp_hardware_watchpoint)
14954       {
14955         struct watchpoint *wp = (struct watchpoint *) bp;
14956
14957         if (wp->val_valid && wp->val)
14958           {
14959             struct bp_location *loc;
14960
14961             for (loc = bp->loc; loc != NULL; loc = loc->next)
14962               if (loc->loc_type == bp_loc_hardware_watchpoint
14963                   && loc->address + loc->length > addr
14964                   && addr + len > loc->address)
14965                 {
14966                   value_free (wp->val);
14967                   wp->val = NULL;
14968                   wp->val_valid = 0;
14969                 }
14970           }
14971       }
14972 }
14973
14974 /* Create and insert a raw software breakpoint at PC.  Return an
14975    identifier, which should be used to remove the breakpoint later.
14976    In general, places which call this should be using something on the
14977    breakpoint chain instead; this function should be eliminated
14978    someday.  */
14979
14980 void *
14981 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14982                                   struct address_space *aspace, CORE_ADDR pc)
14983 {
14984   struct bp_target_info *bp_tgt;
14985
14986   bp_tgt = XZALLOC (struct bp_target_info);
14987
14988   bp_tgt->placed_address_space = aspace;
14989   bp_tgt->placed_address = pc;
14990
14991   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14992     {
14993       /* Could not insert the breakpoint.  */
14994       xfree (bp_tgt);
14995       return NULL;
14996     }
14997
14998   return bp_tgt;
14999 }
15000
15001 /* Remove a breakpoint BP inserted by
15002    deprecated_insert_raw_breakpoint.  */
15003
15004 int
15005 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15006 {
15007   struct bp_target_info *bp_tgt = bp;
15008   int ret;
15009
15010   ret = target_remove_breakpoint (gdbarch, bp_tgt);
15011   xfree (bp_tgt);
15012
15013   return ret;
15014 }
15015
15016 /* One (or perhaps two) breakpoints used for software single
15017    stepping.  */
15018
15019 static void *single_step_breakpoints[2];
15020 static struct gdbarch *single_step_gdbarch[2];
15021
15022 /* Create and insert a breakpoint for software single step.  */
15023
15024 void
15025 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15026                                struct address_space *aspace, 
15027                                CORE_ADDR next_pc)
15028 {
15029   void **bpt_p;
15030
15031   if (single_step_breakpoints[0] == NULL)
15032     {
15033       bpt_p = &single_step_breakpoints[0];
15034       single_step_gdbarch[0] = gdbarch;
15035     }
15036   else
15037     {
15038       gdb_assert (single_step_breakpoints[1] == NULL);
15039       bpt_p = &single_step_breakpoints[1];
15040       single_step_gdbarch[1] = gdbarch;
15041     }
15042
15043   /* NOTE drow/2006-04-11: A future improvement to this function would
15044      be to only create the breakpoints once, and actually put them on
15045      the breakpoint chain.  That would let us use set_raw_breakpoint.
15046      We could adjust the addresses each time they were needed.  Doing
15047      this requires corresponding changes elsewhere where single step
15048      breakpoints are handled, however.  So, for now, we use this.  */
15049
15050   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15051   if (*bpt_p == NULL)
15052     error (_("Could not insert single-step breakpoint at %s"),
15053              paddress (gdbarch, next_pc));
15054 }
15055
15056 /* Check if the breakpoints used for software single stepping
15057    were inserted or not.  */
15058
15059 int
15060 single_step_breakpoints_inserted (void)
15061 {
15062   return (single_step_breakpoints[0] != NULL
15063           || single_step_breakpoints[1] != NULL);
15064 }
15065
15066 /* Remove and delete any breakpoints used for software single step.  */
15067
15068 void
15069 remove_single_step_breakpoints (void)
15070 {
15071   gdb_assert (single_step_breakpoints[0] != NULL);
15072
15073   /* See insert_single_step_breakpoint for more about this deprecated
15074      call.  */
15075   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15076                                     single_step_breakpoints[0]);
15077   single_step_gdbarch[0] = NULL;
15078   single_step_breakpoints[0] = NULL;
15079
15080   if (single_step_breakpoints[1] != NULL)
15081     {
15082       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15083                                         single_step_breakpoints[1]);
15084       single_step_gdbarch[1] = NULL;
15085       single_step_breakpoints[1] = NULL;
15086     }
15087 }
15088
15089 /* Delete software single step breakpoints without removing them from
15090    the inferior.  This is intended to be used if the inferior's address
15091    space where they were inserted is already gone, e.g. after exit or
15092    exec.  */
15093
15094 void
15095 cancel_single_step_breakpoints (void)
15096 {
15097   int i;
15098
15099   for (i = 0; i < 2; i++)
15100     if (single_step_breakpoints[i])
15101       {
15102         xfree (single_step_breakpoints[i]);
15103         single_step_breakpoints[i] = NULL;
15104         single_step_gdbarch[i] = NULL;
15105       }
15106 }
15107
15108 /* Detach software single-step breakpoints from INFERIOR_PTID without
15109    removing them.  */
15110
15111 static void
15112 detach_single_step_breakpoints (void)
15113 {
15114   int i;
15115
15116   for (i = 0; i < 2; i++)
15117     if (single_step_breakpoints[i])
15118       target_remove_breakpoint (single_step_gdbarch[i],
15119                                 single_step_breakpoints[i]);
15120 }
15121
15122 /* Check whether a software single-step breakpoint is inserted at
15123    PC.  */
15124
15125 static int
15126 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15127                                         CORE_ADDR pc)
15128 {
15129   int i;
15130
15131   for (i = 0; i < 2; i++)
15132     {
15133       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15134       if (bp_tgt
15135           && breakpoint_address_match (bp_tgt->placed_address_space,
15136                                        bp_tgt->placed_address,
15137                                        aspace, pc))
15138         return 1;
15139     }
15140
15141   return 0;
15142 }
15143
15144 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15145    non-zero otherwise.  */
15146 static int
15147 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15148 {
15149   if (syscall_catchpoint_p (bp)
15150       && bp->enable_state != bp_disabled
15151       && bp->enable_state != bp_call_disabled)
15152     return 1;
15153   else
15154     return 0;
15155 }
15156
15157 int
15158 catch_syscall_enabled (void)
15159 {
15160   struct catch_syscall_inferior_data *inf_data
15161     = get_catch_syscall_inferior_data (current_inferior ());
15162
15163   return inf_data->total_syscalls_count != 0;
15164 }
15165
15166 int
15167 catching_syscall_number (int syscall_number)
15168 {
15169   struct breakpoint *bp;
15170
15171   ALL_BREAKPOINTS (bp)
15172     if (is_syscall_catchpoint_enabled (bp))
15173       {
15174         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15175
15176         if (c->syscalls_to_be_caught)
15177           {
15178             int i, iter;
15179             for (i = 0;
15180                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15181                  i++)
15182               if (syscall_number == iter)
15183                 return 1;
15184           }
15185         else
15186           return 1;
15187       }
15188
15189   return 0;
15190 }
15191
15192 /* Complete syscall names.  Used by "catch syscall".  */
15193 static VEC (char_ptr) *
15194 catch_syscall_completer (struct cmd_list_element *cmd,
15195                          char *text, char *word)
15196 {
15197   const char **list = get_syscall_names ();
15198   VEC (char_ptr) *retlist
15199     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15200
15201   xfree (list);
15202   return retlist;
15203 }
15204
15205 /* Tracepoint-specific operations.  */
15206
15207 /* Set tracepoint count to NUM.  */
15208 static void
15209 set_tracepoint_count (int num)
15210 {
15211   tracepoint_count = num;
15212   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15213 }
15214
15215 static void
15216 trace_command (char *arg, int from_tty)
15217 {
15218   struct breakpoint_ops *ops;
15219   const char *arg_cp = arg;
15220
15221   if (arg && probe_linespec_to_ops (&arg_cp))
15222     ops = &tracepoint_probe_breakpoint_ops;
15223   else
15224     ops = &tracepoint_breakpoint_ops;
15225
15226   create_breakpoint (get_current_arch (),
15227                      arg,
15228                      NULL, 0, NULL, 1 /* parse arg */,
15229                      0 /* tempflag */,
15230                      bp_tracepoint /* type_wanted */,
15231                      0 /* Ignore count */,
15232                      pending_break_support,
15233                      ops,
15234                      from_tty,
15235                      1 /* enabled */,
15236                      0 /* internal */, 0);
15237 }
15238
15239 static void
15240 ftrace_command (char *arg, int from_tty)
15241 {
15242   create_breakpoint (get_current_arch (),
15243                      arg,
15244                      NULL, 0, NULL, 1 /* parse arg */,
15245                      0 /* tempflag */,
15246                      bp_fast_tracepoint /* type_wanted */,
15247                      0 /* Ignore count */,
15248                      pending_break_support,
15249                      &tracepoint_breakpoint_ops,
15250                      from_tty,
15251                      1 /* enabled */,
15252                      0 /* internal */, 0);
15253 }
15254
15255 /* strace command implementation.  Creates a static tracepoint.  */
15256
15257 static void
15258 strace_command (char *arg, int from_tty)
15259 {
15260   struct breakpoint_ops *ops;
15261
15262   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15263      or with a normal static tracepoint.  */
15264   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15265     ops = &strace_marker_breakpoint_ops;
15266   else
15267     ops = &tracepoint_breakpoint_ops;
15268
15269   create_breakpoint (get_current_arch (),
15270                      arg,
15271                      NULL, 0, NULL, 1 /* parse arg */,
15272                      0 /* tempflag */,
15273                      bp_static_tracepoint /* type_wanted */,
15274                      0 /* Ignore count */,
15275                      pending_break_support,
15276                      ops,
15277                      from_tty,
15278                      1 /* enabled */,
15279                      0 /* internal */, 0);
15280 }
15281
15282 /* Set up a fake reader function that gets command lines from a linked
15283    list that was acquired during tracepoint uploading.  */
15284
15285 static struct uploaded_tp *this_utp;
15286 static int next_cmd;
15287
15288 static char *
15289 read_uploaded_action (void)
15290 {
15291   char *rslt;
15292
15293   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15294
15295   next_cmd++;
15296
15297   return rslt;
15298 }
15299
15300 /* Given information about a tracepoint as recorded on a target (which
15301    can be either a live system or a trace file), attempt to create an
15302    equivalent GDB tracepoint.  This is not a reliable process, since
15303    the target does not necessarily have all the information used when
15304    the tracepoint was originally defined.  */
15305   
15306 struct tracepoint *
15307 create_tracepoint_from_upload (struct uploaded_tp *utp)
15308 {
15309   char *addr_str, small_buf[100];
15310   struct tracepoint *tp;
15311
15312   if (utp->at_string)
15313     addr_str = utp->at_string;
15314   else
15315     {
15316       /* In the absence of a source location, fall back to raw
15317          address.  Since there is no way to confirm that the address
15318          means the same thing as when the trace was started, warn the
15319          user.  */
15320       warning (_("Uploaded tracepoint %d has no "
15321                  "source location, using raw address"),
15322                utp->number);
15323       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15324       addr_str = small_buf;
15325     }
15326
15327   /* There's not much we can do with a sequence of bytecodes.  */
15328   if (utp->cond && !utp->cond_string)
15329     warning (_("Uploaded tracepoint %d condition "
15330                "has no source form, ignoring it"),
15331              utp->number);
15332
15333   if (!create_breakpoint (get_current_arch (),
15334                           addr_str,
15335                           utp->cond_string, -1, NULL,
15336                           0 /* parse cond/thread */,
15337                           0 /* tempflag */,
15338                           utp->type /* type_wanted */,
15339                           0 /* Ignore count */,
15340                           pending_break_support,
15341                           &tracepoint_breakpoint_ops,
15342                           0 /* from_tty */,
15343                           utp->enabled /* enabled */,
15344                           0 /* internal */,
15345                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15346     return NULL;
15347
15348   /* Get the tracepoint we just created.  */
15349   tp = get_tracepoint (tracepoint_count);
15350   gdb_assert (tp != NULL);
15351
15352   if (utp->pass > 0)
15353     {
15354       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15355                  tp->base.number);
15356
15357       trace_pass_command (small_buf, 0);
15358     }
15359
15360   /* If we have uploaded versions of the original commands, set up a
15361      special-purpose "reader" function and call the usual command line
15362      reader, then pass the result to the breakpoint command-setting
15363      function.  */
15364   if (!VEC_empty (char_ptr, utp->cmd_strings))
15365     {
15366       struct command_line *cmd_list;
15367
15368       this_utp = utp;
15369       next_cmd = 0;
15370
15371       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15372
15373       breakpoint_set_commands (&tp->base, cmd_list);
15374     }
15375   else if (!VEC_empty (char_ptr, utp->actions)
15376            || !VEC_empty (char_ptr, utp->step_actions))
15377     warning (_("Uploaded tracepoint %d actions "
15378                "have no source form, ignoring them"),
15379              utp->number);
15380
15381   /* Copy any status information that might be available.  */
15382   tp->base.hit_count = utp->hit_count;
15383   tp->traceframe_usage = utp->traceframe_usage;
15384
15385   return tp;
15386 }
15387   
15388 /* Print information on tracepoint number TPNUM_EXP, or all if
15389    omitted.  */
15390
15391 static void
15392 tracepoints_info (char *args, int from_tty)
15393 {
15394   struct ui_out *uiout = current_uiout;
15395   int num_printed;
15396
15397   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15398
15399   if (num_printed == 0)
15400     {
15401       if (args == NULL || *args == '\0')
15402         ui_out_message (uiout, 0, "No tracepoints.\n");
15403       else
15404         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15405     }
15406
15407   default_collect_info ();
15408 }
15409
15410 /* The 'enable trace' command enables tracepoints.
15411    Not supported by all targets.  */
15412 static void
15413 enable_trace_command (char *args, int from_tty)
15414 {
15415   enable_command (args, from_tty);
15416 }
15417
15418 /* The 'disable trace' command disables tracepoints.
15419    Not supported by all targets.  */
15420 static void
15421 disable_trace_command (char *args, int from_tty)
15422 {
15423   disable_command (args, from_tty);
15424 }
15425
15426 /* Remove a tracepoint (or all if no argument).  */
15427 static void
15428 delete_trace_command (char *arg, int from_tty)
15429 {
15430   struct breakpoint *b, *b_tmp;
15431
15432   dont_repeat ();
15433
15434   if (arg == 0)
15435     {
15436       int breaks_to_delete = 0;
15437
15438       /* Delete all breakpoints if no argument.
15439          Do not delete internal or call-dummy breakpoints, these
15440          have to be deleted with an explicit breakpoint number 
15441          argument.  */
15442       ALL_TRACEPOINTS (b)
15443         if (is_tracepoint (b) && user_breakpoint_p (b))
15444           {
15445             breaks_to_delete = 1;
15446             break;
15447           }
15448
15449       /* Ask user only if there are some breakpoints to delete.  */
15450       if (!from_tty
15451           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15452         {
15453           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15454             if (is_tracepoint (b) && user_breakpoint_p (b))
15455               delete_breakpoint (b);
15456         }
15457     }
15458   else
15459     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15460 }
15461
15462 /* Helper function for trace_pass_command.  */
15463
15464 static void
15465 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15466 {
15467   tp->pass_count = count;
15468   observer_notify_breakpoint_modified (&tp->base);
15469   if (from_tty)
15470     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15471                      tp->base.number, count);
15472 }
15473
15474 /* Set passcount for tracepoint.
15475
15476    First command argument is passcount, second is tracepoint number.
15477    If tracepoint number omitted, apply to most recently defined.
15478    Also accepts special argument "all".  */
15479
15480 static void
15481 trace_pass_command (char *args, int from_tty)
15482 {
15483   struct tracepoint *t1;
15484   unsigned int count;
15485
15486   if (args == 0 || *args == 0)
15487     error (_("passcount command requires an "
15488              "argument (count + optional TP num)"));
15489
15490   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15491
15492   args = skip_spaces (args);
15493   if (*args && strncasecmp (args, "all", 3) == 0)
15494     {
15495       struct breakpoint *b;
15496
15497       args += 3;                        /* Skip special argument "all".  */
15498       if (*args)
15499         error (_("Junk at end of arguments."));
15500
15501       ALL_TRACEPOINTS (b)
15502       {
15503         t1 = (struct tracepoint *) b;
15504         trace_pass_set_count (t1, count, from_tty);
15505       }
15506     }
15507   else if (*args == '\0')
15508     {
15509       t1 = get_tracepoint_by_number (&args, NULL, 1);
15510       if (t1)
15511         trace_pass_set_count (t1, count, from_tty);
15512     }
15513   else
15514     {
15515       struct get_number_or_range_state state;
15516
15517       init_number_or_range (&state, args);
15518       while (!state.finished)
15519         {
15520           t1 = get_tracepoint_by_number (&args, &state, 1);
15521           if (t1)
15522             trace_pass_set_count (t1, count, from_tty);
15523         }
15524     }
15525 }
15526
15527 struct tracepoint *
15528 get_tracepoint (int num)
15529 {
15530   struct breakpoint *t;
15531
15532   ALL_TRACEPOINTS (t)
15533     if (t->number == num)
15534       return (struct tracepoint *) t;
15535
15536   return NULL;
15537 }
15538
15539 /* Find the tracepoint with the given target-side number (which may be
15540    different from the tracepoint number after disconnecting and
15541    reconnecting).  */
15542
15543 struct tracepoint *
15544 get_tracepoint_by_number_on_target (int num)
15545 {
15546   struct breakpoint *b;
15547
15548   ALL_TRACEPOINTS (b)
15549     {
15550       struct tracepoint *t = (struct tracepoint *) b;
15551
15552       if (t->number_on_target == num)
15553         return t;
15554     }
15555
15556   return NULL;
15557 }
15558
15559 /* Utility: parse a tracepoint number and look it up in the list.
15560    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15561    If OPTIONAL_P is true, then if the argument is missing, the most
15562    recent tracepoint (tracepoint_count) is returned.  */
15563 struct tracepoint *
15564 get_tracepoint_by_number (char **arg,
15565                           struct get_number_or_range_state *state,
15566                           int optional_p)
15567 {
15568   struct breakpoint *t;
15569   int tpnum;
15570   char *instring = arg == NULL ? NULL : *arg;
15571
15572   if (state)
15573     {
15574       gdb_assert (!state->finished);
15575       tpnum = get_number_or_range (state);
15576     }
15577   else if (arg == NULL || *arg == NULL || ! **arg)
15578     {
15579       if (optional_p)
15580         tpnum = tracepoint_count;
15581       else
15582         error_no_arg (_("tracepoint number"));
15583     }
15584   else
15585     tpnum = get_number (arg);
15586
15587   if (tpnum <= 0)
15588     {
15589       if (instring && *instring)
15590         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15591                          instring);
15592       else
15593         printf_filtered (_("Tracepoint argument missing "
15594                            "and no previous tracepoint\n"));
15595       return NULL;
15596     }
15597
15598   ALL_TRACEPOINTS (t)
15599     if (t->number == tpnum)
15600     {
15601       return (struct tracepoint *) t;
15602     }
15603
15604   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15605   return NULL;
15606 }
15607
15608 void
15609 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15610 {
15611   if (b->thread != -1)
15612     fprintf_unfiltered (fp, " thread %d", b->thread);
15613
15614   if (b->task != 0)
15615     fprintf_unfiltered (fp, " task %d", b->task);
15616
15617   fprintf_unfiltered (fp, "\n");
15618 }
15619
15620 /* Save information on user settable breakpoints (watchpoints, etc) to
15621    a new script file named FILENAME.  If FILTER is non-NULL, call it
15622    on each breakpoint and only include the ones for which it returns
15623    non-zero.  */
15624
15625 static void
15626 save_breakpoints (char *filename, int from_tty,
15627                   int (*filter) (const struct breakpoint *))
15628 {
15629   struct breakpoint *tp;
15630   int any = 0;
15631   char *pathname;
15632   struct cleanup *cleanup;
15633   struct ui_file *fp;
15634   int extra_trace_bits = 0;
15635
15636   if (filename == 0 || *filename == 0)
15637     error (_("Argument required (file name in which to save)"));
15638
15639   /* See if we have anything to save.  */
15640   ALL_BREAKPOINTS (tp)
15641   {
15642     /* Skip internal and momentary breakpoints.  */
15643     if (!user_breakpoint_p (tp))
15644       continue;
15645
15646     /* If we have a filter, only save the breakpoints it accepts.  */
15647     if (filter && !filter (tp))
15648       continue;
15649
15650     any = 1;
15651
15652     if (is_tracepoint (tp))
15653       {
15654         extra_trace_bits = 1;
15655
15656         /* We can stop searching.  */
15657         break;
15658       }
15659   }
15660
15661   if (!any)
15662     {
15663       warning (_("Nothing to save."));
15664       return;
15665     }
15666
15667   pathname = tilde_expand (filename);
15668   cleanup = make_cleanup (xfree, pathname);
15669   fp = gdb_fopen (pathname, "w");
15670   if (!fp)
15671     error (_("Unable to open file '%s' for saving (%s)"),
15672            filename, safe_strerror (errno));
15673   make_cleanup_ui_file_delete (fp);
15674
15675   if (extra_trace_bits)
15676     save_trace_state_variables (fp);
15677
15678   ALL_BREAKPOINTS (tp)
15679   {
15680     /* Skip internal and momentary breakpoints.  */
15681     if (!user_breakpoint_p (tp))
15682       continue;
15683
15684     /* If we have a filter, only save the breakpoints it accepts.  */
15685     if (filter && !filter (tp))
15686       continue;
15687
15688     tp->ops->print_recreate (tp, fp);
15689
15690     /* Note, we can't rely on tp->number for anything, as we can't
15691        assume the recreated breakpoint numbers will match.  Use $bpnum
15692        instead.  */
15693
15694     if (tp->cond_string)
15695       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15696
15697     if (tp->ignore_count)
15698       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15699
15700     if (tp->type != bp_dprintf && tp->commands)
15701       {
15702         volatile struct gdb_exception ex;       
15703
15704         fprintf_unfiltered (fp, "  commands\n");
15705         
15706         ui_out_redirect (current_uiout, fp);
15707         TRY_CATCH (ex, RETURN_MASK_ALL)
15708           {
15709             print_command_lines (current_uiout, tp->commands->commands, 2);
15710           }
15711         ui_out_redirect (current_uiout, NULL);
15712
15713         if (ex.reason < 0)
15714           throw_exception (ex);
15715
15716         fprintf_unfiltered (fp, "  end\n");
15717       }
15718
15719     if (tp->enable_state == bp_disabled)
15720       fprintf_unfiltered (fp, "disable\n");
15721
15722     /* If this is a multi-location breakpoint, check if the locations
15723        should be individually disabled.  Watchpoint locations are
15724        special, and not user visible.  */
15725     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15726       {
15727         struct bp_location *loc;
15728         int n = 1;
15729
15730         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15731           if (!loc->enabled)
15732             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15733       }
15734   }
15735
15736   if (extra_trace_bits && *default_collect)
15737     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15738
15739   do_cleanups (cleanup);
15740   if (from_tty)
15741     printf_filtered (_("Saved to file '%s'.\n"), filename);
15742 }
15743
15744 /* The `save breakpoints' command.  */
15745
15746 static void
15747 save_breakpoints_command (char *args, int from_tty)
15748 {
15749   save_breakpoints (args, from_tty, NULL);
15750 }
15751
15752 /* The `save tracepoints' command.  */
15753
15754 static void
15755 save_tracepoints_command (char *args, int from_tty)
15756 {
15757   save_breakpoints (args, from_tty, is_tracepoint);
15758 }
15759
15760 /* Create a vector of all tracepoints.  */
15761
15762 VEC(breakpoint_p) *
15763 all_tracepoints (void)
15764 {
15765   VEC(breakpoint_p) *tp_vec = 0;
15766   struct breakpoint *tp;
15767
15768   ALL_TRACEPOINTS (tp)
15769   {
15770     VEC_safe_push (breakpoint_p, tp_vec, tp);
15771   }
15772
15773   return tp_vec;
15774 }
15775
15776 \f
15777 /* This help string is used for the break, hbreak, tbreak and thbreak
15778    commands.  It is defined as a macro to prevent duplication.
15779    COMMAND should be a string constant containing the name of the
15780    command.  */
15781 #define BREAK_ARGS_HELP(command) \
15782 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15783 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15784 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15785 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15786 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15787 If a line number is specified, break at start of code for that line.\n\
15788 If a function is specified, break at start of code for that function.\n\
15789 If an address is specified, break at that exact address.\n\
15790 With no LOCATION, uses current execution address of the selected\n\
15791 stack frame.  This is useful for breaking on return to a stack frame.\n\
15792 \n\
15793 THREADNUM is the number from \"info threads\".\n\
15794 CONDITION is a boolean expression.\n\
15795 \n\
15796 Multiple breakpoints at one place are permitted, and useful if their\n\
15797 conditions are different.\n\
15798 \n\
15799 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15800
15801 /* List of subcommands for "catch".  */
15802 static struct cmd_list_element *catch_cmdlist;
15803
15804 /* List of subcommands for "tcatch".  */
15805 static struct cmd_list_element *tcatch_cmdlist;
15806
15807 void
15808 add_catch_command (char *name, char *docstring,
15809                    void (*sfunc) (char *args, int from_tty,
15810                                   struct cmd_list_element *command),
15811                    completer_ftype *completer,
15812                    void *user_data_catch,
15813                    void *user_data_tcatch)
15814 {
15815   struct cmd_list_element *command;
15816
15817   command = add_cmd (name, class_breakpoint, NULL, docstring,
15818                      &catch_cmdlist);
15819   set_cmd_sfunc (command, sfunc);
15820   set_cmd_context (command, user_data_catch);
15821   set_cmd_completer (command, completer);
15822
15823   command = add_cmd (name, class_breakpoint, NULL, docstring,
15824                      &tcatch_cmdlist);
15825   set_cmd_sfunc (command, sfunc);
15826   set_cmd_context (command, user_data_tcatch);
15827   set_cmd_completer (command, completer);
15828 }
15829
15830 static void
15831 clear_syscall_counts (struct inferior *inf)
15832 {
15833   struct catch_syscall_inferior_data *inf_data
15834     = get_catch_syscall_inferior_data (inf);
15835
15836   inf_data->total_syscalls_count = 0;
15837   inf_data->any_syscall_count = 0;
15838   VEC_free (int, inf_data->syscalls_counts);
15839 }
15840
15841 static void
15842 save_command (char *arg, int from_tty)
15843 {
15844   printf_unfiltered (_("\"save\" must be followed by "
15845                        "the name of a save subcommand.\n"));
15846   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15847 }
15848
15849 struct breakpoint *
15850 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15851                           void *data)
15852 {
15853   struct breakpoint *b, *b_tmp;
15854
15855   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15856     {
15857       if ((*callback) (b, data))
15858         return b;
15859     }
15860
15861   return NULL;
15862 }
15863
15864 /* Zero if any of the breakpoint's locations could be a location where
15865    functions have been inlined, nonzero otherwise.  */
15866
15867 static int
15868 is_non_inline_function (struct breakpoint *b)
15869 {
15870   /* The shared library event breakpoint is set on the address of a
15871      non-inline function.  */
15872   if (b->type == bp_shlib_event)
15873     return 1;
15874
15875   return 0;
15876 }
15877
15878 /* Nonzero if the specified PC cannot be a location where functions
15879    have been inlined.  */
15880
15881 int
15882 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15883                            const struct target_waitstatus *ws)
15884 {
15885   struct breakpoint *b;
15886   struct bp_location *bl;
15887
15888   ALL_BREAKPOINTS (b)
15889     {
15890       if (!is_non_inline_function (b))
15891         continue;
15892
15893       for (bl = b->loc; bl != NULL; bl = bl->next)
15894         {
15895           if (!bl->shlib_disabled
15896               && bpstat_check_location (bl, aspace, pc, ws))
15897             return 1;
15898         }
15899     }
15900
15901   return 0;
15902 }
15903
15904 /* Remove any references to OBJFILE which is going to be freed.  */
15905
15906 void
15907 breakpoint_free_objfile (struct objfile *objfile)
15908 {
15909   struct bp_location **locp, *loc;
15910
15911   ALL_BP_LOCATIONS (loc, locp)
15912     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
15913       loc->symtab = NULL;
15914 }
15915
15916 void
15917 initialize_breakpoint_ops (void)
15918 {
15919   static int initialized = 0;
15920
15921   struct breakpoint_ops *ops;
15922
15923   if (initialized)
15924     return;
15925   initialized = 1;
15926
15927   /* The breakpoint_ops structure to be inherit by all kinds of
15928      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15929      internal and momentary breakpoints, etc.).  */
15930   ops = &bkpt_base_breakpoint_ops;
15931   *ops = base_breakpoint_ops;
15932   ops->re_set = bkpt_re_set;
15933   ops->insert_location = bkpt_insert_location;
15934   ops->remove_location = bkpt_remove_location;
15935   ops->breakpoint_hit = bkpt_breakpoint_hit;
15936   ops->create_sals_from_address = bkpt_create_sals_from_address;
15937   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15938   ops->decode_linespec = bkpt_decode_linespec;
15939
15940   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15941   ops = &bkpt_breakpoint_ops;
15942   *ops = bkpt_base_breakpoint_ops;
15943   ops->re_set = bkpt_re_set;
15944   ops->resources_needed = bkpt_resources_needed;
15945   ops->print_it = bkpt_print_it;
15946   ops->print_mention = bkpt_print_mention;
15947   ops->print_recreate = bkpt_print_recreate;
15948
15949   /* Ranged breakpoints.  */
15950   ops = &ranged_breakpoint_ops;
15951   *ops = bkpt_breakpoint_ops;
15952   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15953   ops->resources_needed = resources_needed_ranged_breakpoint;
15954   ops->print_it = print_it_ranged_breakpoint;
15955   ops->print_one = print_one_ranged_breakpoint;
15956   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15957   ops->print_mention = print_mention_ranged_breakpoint;
15958   ops->print_recreate = print_recreate_ranged_breakpoint;
15959
15960   /* Internal breakpoints.  */
15961   ops = &internal_breakpoint_ops;
15962   *ops = bkpt_base_breakpoint_ops;
15963   ops->re_set = internal_bkpt_re_set;
15964   ops->check_status = internal_bkpt_check_status;
15965   ops->print_it = internal_bkpt_print_it;
15966   ops->print_mention = internal_bkpt_print_mention;
15967
15968   /* Momentary breakpoints.  */
15969   ops = &momentary_breakpoint_ops;
15970   *ops = bkpt_base_breakpoint_ops;
15971   ops->re_set = momentary_bkpt_re_set;
15972   ops->check_status = momentary_bkpt_check_status;
15973   ops->print_it = momentary_bkpt_print_it;
15974   ops->print_mention = momentary_bkpt_print_mention;
15975
15976   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15977   ops = &longjmp_breakpoint_ops;
15978   *ops = momentary_breakpoint_ops;
15979   ops->dtor = longjmp_bkpt_dtor;
15980
15981   /* Probe breakpoints.  */
15982   ops = &bkpt_probe_breakpoint_ops;
15983   *ops = bkpt_breakpoint_ops;
15984   ops->insert_location = bkpt_probe_insert_location;
15985   ops->remove_location = bkpt_probe_remove_location;
15986   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15987   ops->decode_linespec = bkpt_probe_decode_linespec;
15988
15989   /* GNU v3 exception catchpoints.  */
15990   ops = &gnu_v3_exception_catchpoint_ops;
15991   *ops = bkpt_breakpoint_ops;
15992   ops->print_it = print_it_exception_catchpoint;
15993   ops->print_one = print_one_exception_catchpoint;
15994   ops->print_mention = print_mention_exception_catchpoint;
15995   ops->print_recreate = print_recreate_exception_catchpoint;
15996
15997   /* Watchpoints.  */
15998   ops = &watchpoint_breakpoint_ops;
15999   *ops = base_breakpoint_ops;
16000   ops->dtor = dtor_watchpoint;
16001   ops->re_set = re_set_watchpoint;
16002   ops->insert_location = insert_watchpoint;
16003   ops->remove_location = remove_watchpoint;
16004   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16005   ops->check_status = check_status_watchpoint;
16006   ops->resources_needed = resources_needed_watchpoint;
16007   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16008   ops->print_it = print_it_watchpoint;
16009   ops->print_mention = print_mention_watchpoint;
16010   ops->print_recreate = print_recreate_watchpoint;
16011   ops->explains_signal = explains_signal_watchpoint;
16012
16013   /* Masked watchpoints.  */
16014   ops = &masked_watchpoint_breakpoint_ops;
16015   *ops = watchpoint_breakpoint_ops;
16016   ops->insert_location = insert_masked_watchpoint;
16017   ops->remove_location = remove_masked_watchpoint;
16018   ops->resources_needed = resources_needed_masked_watchpoint;
16019   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16020   ops->print_it = print_it_masked_watchpoint;
16021   ops->print_one_detail = print_one_detail_masked_watchpoint;
16022   ops->print_mention = print_mention_masked_watchpoint;
16023   ops->print_recreate = print_recreate_masked_watchpoint;
16024
16025   /* Tracepoints.  */
16026   ops = &tracepoint_breakpoint_ops;
16027   *ops = base_breakpoint_ops;
16028   ops->re_set = tracepoint_re_set;
16029   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16030   ops->print_one_detail = tracepoint_print_one_detail;
16031   ops->print_mention = tracepoint_print_mention;
16032   ops->print_recreate = tracepoint_print_recreate;
16033   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16034   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16035   ops->decode_linespec = tracepoint_decode_linespec;
16036
16037   /* Probe tracepoints.  */
16038   ops = &tracepoint_probe_breakpoint_ops;
16039   *ops = tracepoint_breakpoint_ops;
16040   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16041   ops->decode_linespec = tracepoint_probe_decode_linespec;
16042
16043   /* Static tracepoints with marker (`-m').  */
16044   ops = &strace_marker_breakpoint_ops;
16045   *ops = tracepoint_breakpoint_ops;
16046   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16047   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16048   ops->decode_linespec = strace_marker_decode_linespec;
16049
16050   /* Fork catchpoints.  */
16051   ops = &catch_fork_breakpoint_ops;
16052   *ops = base_breakpoint_ops;
16053   ops->insert_location = insert_catch_fork;
16054   ops->remove_location = remove_catch_fork;
16055   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16056   ops->print_it = print_it_catch_fork;
16057   ops->print_one = print_one_catch_fork;
16058   ops->print_mention = print_mention_catch_fork;
16059   ops->print_recreate = print_recreate_catch_fork;
16060
16061   /* Vfork catchpoints.  */
16062   ops = &catch_vfork_breakpoint_ops;
16063   *ops = base_breakpoint_ops;
16064   ops->insert_location = insert_catch_vfork;
16065   ops->remove_location = remove_catch_vfork;
16066   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16067   ops->print_it = print_it_catch_vfork;
16068   ops->print_one = print_one_catch_vfork;
16069   ops->print_mention = print_mention_catch_vfork;
16070   ops->print_recreate = print_recreate_catch_vfork;
16071
16072   /* Exec catchpoints.  */
16073   ops = &catch_exec_breakpoint_ops;
16074   *ops = base_breakpoint_ops;
16075   ops->dtor = dtor_catch_exec;
16076   ops->insert_location = insert_catch_exec;
16077   ops->remove_location = remove_catch_exec;
16078   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16079   ops->print_it = print_it_catch_exec;
16080   ops->print_one = print_one_catch_exec;
16081   ops->print_mention = print_mention_catch_exec;
16082   ops->print_recreate = print_recreate_catch_exec;
16083
16084   /* Syscall catchpoints.  */
16085   ops = &catch_syscall_breakpoint_ops;
16086   *ops = base_breakpoint_ops;
16087   ops->dtor = dtor_catch_syscall;
16088   ops->insert_location = insert_catch_syscall;
16089   ops->remove_location = remove_catch_syscall;
16090   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16091   ops->print_it = print_it_catch_syscall;
16092   ops->print_one = print_one_catch_syscall;
16093   ops->print_mention = print_mention_catch_syscall;
16094   ops->print_recreate = print_recreate_catch_syscall;
16095
16096   /* Solib-related catchpoints.  */
16097   ops = &catch_solib_breakpoint_ops;
16098   *ops = base_breakpoint_ops;
16099   ops->dtor = dtor_catch_solib;
16100   ops->insert_location = insert_catch_solib;
16101   ops->remove_location = remove_catch_solib;
16102   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16103   ops->check_status = check_status_catch_solib;
16104   ops->print_it = print_it_catch_solib;
16105   ops->print_one = print_one_catch_solib;
16106   ops->print_mention = print_mention_catch_solib;
16107   ops->print_recreate = print_recreate_catch_solib;
16108
16109   ops = &dprintf_breakpoint_ops;
16110   *ops = bkpt_base_breakpoint_ops;
16111   ops->re_set = dprintf_re_set;
16112   ops->resources_needed = bkpt_resources_needed;
16113   ops->print_it = bkpt_print_it;
16114   ops->print_mention = bkpt_print_mention;
16115   ops->print_recreate = dprintf_print_recreate;
16116   ops->after_condition_true = dprintf_after_condition_true;
16117 }
16118
16119 /* Chain containing all defined "enable breakpoint" subcommands.  */
16120
16121 static struct cmd_list_element *enablebreaklist = NULL;
16122
16123 void
16124 _initialize_breakpoint (void)
16125 {
16126   struct cmd_list_element *c;
16127
16128   initialize_breakpoint_ops ();
16129
16130   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16131   observer_attach_inferior_exit (clear_syscall_counts);
16132   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16133
16134   breakpoint_objfile_key
16135     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16136
16137   catch_syscall_inferior_data
16138     = register_inferior_data_with_cleanup (NULL,
16139                                            catch_syscall_inferior_data_cleanup);
16140
16141   breakpoint_chain = 0;
16142   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16143      before a breakpoint is set.  */
16144   breakpoint_count = 0;
16145
16146   tracepoint_count = 0;
16147
16148   add_com ("ignore", class_breakpoint, ignore_command, _("\
16149 Set ignore-count of breakpoint number N to COUNT.\n\
16150 Usage is `ignore N COUNT'."));
16151   if (xdb_commands)
16152     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16153
16154   add_com ("commands", class_breakpoint, commands_command, _("\
16155 Set commands to be executed when a breakpoint is hit.\n\
16156 Give breakpoint number as argument after \"commands\".\n\
16157 With no argument, the targeted breakpoint is the last one set.\n\
16158 The commands themselves follow starting on the next line.\n\
16159 Type a line containing \"end\" to indicate the end of them.\n\
16160 Give \"silent\" as the first line to make the breakpoint silent;\n\
16161 then no output is printed when it is hit, except what the commands print."));
16162
16163   c = add_com ("condition", class_breakpoint, condition_command, _("\
16164 Specify breakpoint number N to break only if COND is true.\n\
16165 Usage is `condition N COND', where N is an integer and COND is an\n\
16166 expression to be evaluated whenever breakpoint N is reached."));
16167   set_cmd_completer (c, condition_completer);
16168
16169   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16170 Set a temporary breakpoint.\n\
16171 Like \"break\" except the breakpoint is only temporary,\n\
16172 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16173 by using \"enable delete\" on the breakpoint number.\n\
16174 \n"
16175 BREAK_ARGS_HELP ("tbreak")));
16176   set_cmd_completer (c, location_completer);
16177
16178   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16179 Set a hardware assisted breakpoint.\n\
16180 Like \"break\" except the breakpoint requires hardware support,\n\
16181 some target hardware may not have this support.\n\
16182 \n"
16183 BREAK_ARGS_HELP ("hbreak")));
16184   set_cmd_completer (c, location_completer);
16185
16186   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16187 Set a temporary hardware assisted breakpoint.\n\
16188 Like \"hbreak\" except the breakpoint is only temporary,\n\
16189 so it will be deleted when hit.\n\
16190 \n"
16191 BREAK_ARGS_HELP ("thbreak")));
16192   set_cmd_completer (c, location_completer);
16193
16194   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16195 Enable some breakpoints.\n\
16196 Give breakpoint numbers (separated by spaces) as arguments.\n\
16197 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16198 This is used to cancel the effect of the \"disable\" command.\n\
16199 With a subcommand you can enable temporarily."),
16200                   &enablelist, "enable ", 1, &cmdlist);
16201   if (xdb_commands)
16202     add_com ("ab", class_breakpoint, enable_command, _("\
16203 Enable some breakpoints.\n\
16204 Give breakpoint numbers (separated by spaces) as arguments.\n\
16205 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16206 This is used to cancel the effect of the \"disable\" command.\n\
16207 With a subcommand you can enable temporarily."));
16208
16209   add_com_alias ("en", "enable", class_breakpoint, 1);
16210
16211   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16212 Enable some breakpoints.\n\
16213 Give breakpoint numbers (separated by spaces) as arguments.\n\
16214 This is used to cancel the effect of the \"disable\" command.\n\
16215 May be abbreviated to simply \"enable\".\n"),
16216                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16217
16218   add_cmd ("once", no_class, enable_once_command, _("\
16219 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16220 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16221            &enablebreaklist);
16222
16223   add_cmd ("delete", no_class, enable_delete_command, _("\
16224 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16225 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16226            &enablebreaklist);
16227
16228   add_cmd ("count", no_class, enable_count_command, _("\
16229 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16230 If a breakpoint is hit while enabled in this fashion,\n\
16231 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16232            &enablebreaklist);
16233
16234   add_cmd ("delete", no_class, enable_delete_command, _("\
16235 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16236 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16237            &enablelist);
16238
16239   add_cmd ("once", no_class, enable_once_command, _("\
16240 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16241 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16242            &enablelist);
16243
16244   add_cmd ("count", no_class, enable_count_command, _("\
16245 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16246 If a breakpoint is hit while enabled in this fashion,\n\
16247 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16248            &enablelist);
16249
16250   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16251 Disable some breakpoints.\n\
16252 Arguments are breakpoint numbers with spaces in between.\n\
16253 To disable all breakpoints, give no argument.\n\
16254 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16255                   &disablelist, "disable ", 1, &cmdlist);
16256   add_com_alias ("dis", "disable", class_breakpoint, 1);
16257   add_com_alias ("disa", "disable", class_breakpoint, 1);
16258   if (xdb_commands)
16259     add_com ("sb", class_breakpoint, disable_command, _("\
16260 Disable some breakpoints.\n\
16261 Arguments are breakpoint numbers with spaces in between.\n\
16262 To disable all breakpoints, give no argument.\n\
16263 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16264
16265   add_cmd ("breakpoints", class_alias, disable_command, _("\
16266 Disable some breakpoints.\n\
16267 Arguments are breakpoint numbers with spaces in between.\n\
16268 To disable all breakpoints, give no argument.\n\
16269 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16270 This command may be abbreviated \"disable\"."),
16271            &disablelist);
16272
16273   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16274 Delete some breakpoints or auto-display expressions.\n\
16275 Arguments are breakpoint numbers with spaces in between.\n\
16276 To delete all breakpoints, give no argument.\n\
16277 \n\
16278 Also a prefix command for deletion of other GDB objects.\n\
16279 The \"unset\" command is also an alias for \"delete\"."),
16280                   &deletelist, "delete ", 1, &cmdlist);
16281   add_com_alias ("d", "delete", class_breakpoint, 1);
16282   add_com_alias ("del", "delete", class_breakpoint, 1);
16283   if (xdb_commands)
16284     add_com ("db", class_breakpoint, delete_command, _("\
16285 Delete some breakpoints.\n\
16286 Arguments are breakpoint numbers with spaces in between.\n\
16287 To delete all breakpoints, give no argument.\n"));
16288
16289   add_cmd ("breakpoints", class_alias, delete_command, _("\
16290 Delete some breakpoints or auto-display expressions.\n\
16291 Arguments are breakpoint numbers with spaces in between.\n\
16292 To delete all breakpoints, give no argument.\n\
16293 This command may be abbreviated \"delete\"."),
16294            &deletelist);
16295
16296   add_com ("clear", class_breakpoint, clear_command, _("\
16297 Clear breakpoint at specified line or function.\n\
16298 Argument may be line number, function name, or \"*\" and an address.\n\
16299 If line number is specified, all breakpoints in that line are cleared.\n\
16300 If function is specified, breakpoints at beginning of function are cleared.\n\
16301 If an address is specified, breakpoints at that address are cleared.\n\
16302 \n\
16303 With no argument, clears all breakpoints in the line that the selected frame\n\
16304 is executing in.\n\
16305 \n\
16306 See also the \"delete\" command which clears breakpoints by number."));
16307   add_com_alias ("cl", "clear", class_breakpoint, 1);
16308
16309   c = add_com ("break", class_breakpoint, break_command, _("\
16310 Set breakpoint at specified line or function.\n"
16311 BREAK_ARGS_HELP ("break")));
16312   set_cmd_completer (c, location_completer);
16313
16314   add_com_alias ("b", "break", class_run, 1);
16315   add_com_alias ("br", "break", class_run, 1);
16316   add_com_alias ("bre", "break", class_run, 1);
16317   add_com_alias ("brea", "break", class_run, 1);
16318
16319   if (xdb_commands)
16320    add_com_alias ("ba", "break", class_breakpoint, 1);
16321
16322   if (dbx_commands)
16323     {
16324       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16325 Break in function/address or break at a line in the current file."),
16326                              &stoplist, "stop ", 1, &cmdlist);
16327       add_cmd ("in", class_breakpoint, stopin_command,
16328                _("Break in function or address."), &stoplist);
16329       add_cmd ("at", class_breakpoint, stopat_command,
16330                _("Break at a line in the current file."), &stoplist);
16331       add_com ("status", class_info, breakpoints_info, _("\
16332 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16333 The \"Type\" column indicates one of:\n\
16334 \tbreakpoint     - normal breakpoint\n\
16335 \twatchpoint     - watchpoint\n\
16336 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16337 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16338 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16339 address and file/line number respectively.\n\
16340 \n\
16341 Convenience variable \"$_\" and default examine address for \"x\"\n\
16342 are set to the address of the last breakpoint listed unless the command\n\
16343 is prefixed with \"server \".\n\n\
16344 Convenience variable \"$bpnum\" contains the number of the last\n\
16345 breakpoint set."));
16346     }
16347
16348   add_info ("breakpoints", breakpoints_info, _("\
16349 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16350 The \"Type\" column indicates one of:\n\
16351 \tbreakpoint     - normal breakpoint\n\
16352 \twatchpoint     - watchpoint\n\
16353 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16354 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16355 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16356 address and file/line number respectively.\n\
16357 \n\
16358 Convenience variable \"$_\" and default examine address for \"x\"\n\
16359 are set to the address of the last breakpoint listed unless the command\n\
16360 is prefixed with \"server \".\n\n\
16361 Convenience variable \"$bpnum\" contains the number of the last\n\
16362 breakpoint set."));
16363
16364   add_info_alias ("b", "breakpoints", 1);
16365
16366   if (xdb_commands)
16367     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16368 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16369 The \"Type\" column indicates one of:\n\
16370 \tbreakpoint     - normal breakpoint\n\
16371 \twatchpoint     - watchpoint\n\
16372 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16373 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16374 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16375 address and file/line number respectively.\n\
16376 \n\
16377 Convenience variable \"$_\" and default examine address for \"x\"\n\
16378 are set to the address of the last breakpoint listed unless the command\n\
16379 is prefixed with \"server \".\n\n\
16380 Convenience variable \"$bpnum\" contains the number of the last\n\
16381 breakpoint set."));
16382
16383   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16384 Status of all breakpoints, or breakpoint number NUMBER.\n\
16385 The \"Type\" column indicates one of:\n\
16386 \tbreakpoint     - normal breakpoint\n\
16387 \twatchpoint     - watchpoint\n\
16388 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16389 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16390 \tuntil          - internal breakpoint used by the \"until\" command\n\
16391 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16392 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16393 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16394 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16395 address and file/line number respectively.\n\
16396 \n\
16397 Convenience variable \"$_\" and default examine address for \"x\"\n\
16398 are set to the address of the last breakpoint listed unless the command\n\
16399 is prefixed with \"server \".\n\n\
16400 Convenience variable \"$bpnum\" contains the number of the last\n\
16401 breakpoint set."),
16402            &maintenanceinfolist);
16403
16404   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16405 Set catchpoints to catch events."),
16406                   &catch_cmdlist, "catch ",
16407                   0/*allow-unknown*/, &cmdlist);
16408
16409   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16410 Set temporary catchpoints to catch events."),
16411                   &tcatch_cmdlist, "tcatch ",
16412                   0/*allow-unknown*/, &cmdlist);
16413
16414   /* Add catch and tcatch sub-commands.  */
16415   add_catch_command ("catch", _("\
16416 Catch an exception, when caught."),
16417                      catch_catch_command,
16418                      NULL,
16419                      CATCH_PERMANENT,
16420                      CATCH_TEMPORARY);
16421   add_catch_command ("throw", _("\
16422 Catch an exception, when thrown."),
16423                      catch_throw_command,
16424                      NULL,
16425                      CATCH_PERMANENT,
16426                      CATCH_TEMPORARY);
16427   add_catch_command ("fork", _("Catch calls to fork."),
16428                      catch_fork_command_1,
16429                      NULL,
16430                      (void *) (uintptr_t) catch_fork_permanent,
16431                      (void *) (uintptr_t) catch_fork_temporary);
16432   add_catch_command ("vfork", _("Catch calls to vfork."),
16433                      catch_fork_command_1,
16434                      NULL,
16435                      (void *) (uintptr_t) catch_vfork_permanent,
16436                      (void *) (uintptr_t) catch_vfork_temporary);
16437   add_catch_command ("exec", _("Catch calls to exec."),
16438                      catch_exec_command_1,
16439                      NULL,
16440                      CATCH_PERMANENT,
16441                      CATCH_TEMPORARY);
16442   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16443 Usage: catch load [REGEX]\n\
16444 If REGEX is given, only stop for libraries matching the regular expression."),
16445                      catch_load_command_1,
16446                      NULL,
16447                      CATCH_PERMANENT,
16448                      CATCH_TEMPORARY);
16449   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16450 Usage: catch unload [REGEX]\n\
16451 If REGEX is given, only stop for libraries matching the regular expression."),
16452                      catch_unload_command_1,
16453                      NULL,
16454                      CATCH_PERMANENT,
16455                      CATCH_TEMPORARY);
16456   add_catch_command ("syscall", _("\
16457 Catch system calls by their names and/or numbers.\n\
16458 Arguments say which system calls to catch.  If no arguments\n\
16459 are given, every system call will be caught.\n\
16460 Arguments, if given, should be one or more system call names\n\
16461 (if your system supports that), or system call numbers."),
16462                      catch_syscall_command_1,
16463                      catch_syscall_completer,
16464                      CATCH_PERMANENT,
16465                      CATCH_TEMPORARY);
16466
16467   c = add_com ("watch", class_breakpoint, watch_command, _("\
16468 Set a watchpoint for an expression.\n\
16469 Usage: watch [-l|-location] EXPRESSION\n\
16470 A watchpoint stops execution of your program whenever the value of\n\
16471 an expression changes.\n\
16472 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16473 the memory to which it refers."));
16474   set_cmd_completer (c, expression_completer);
16475
16476   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16477 Set a read watchpoint for an expression.\n\
16478 Usage: rwatch [-l|-location] EXPRESSION\n\
16479 A watchpoint stops execution of your program whenever the value of\n\
16480 an expression is read.\n\
16481 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16482 the memory to which it refers."));
16483   set_cmd_completer (c, expression_completer);
16484
16485   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16486 Set a watchpoint for an expression.\n\
16487 Usage: awatch [-l|-location] EXPRESSION\n\
16488 A watchpoint stops execution of your program whenever the value of\n\
16489 an expression is either read or written.\n\
16490 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16491 the memory to which it refers."));
16492   set_cmd_completer (c, expression_completer);
16493
16494   add_info ("watchpoints", watchpoints_info, _("\
16495 Status of specified watchpoints (all watchpoints if no argument)."));
16496
16497   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16498      respond to changes - contrary to the description.  */
16499   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16500                             &can_use_hw_watchpoints, _("\
16501 Set debugger's willingness to use watchpoint hardware."), _("\
16502 Show debugger's willingness to use watchpoint hardware."), _("\
16503 If zero, gdb will not use hardware for new watchpoints, even if\n\
16504 such is available.  (However, any hardware watchpoints that were\n\
16505 created before setting this to nonzero, will continue to use watchpoint\n\
16506 hardware.)"),
16507                             NULL,
16508                             show_can_use_hw_watchpoints,
16509                             &setlist, &showlist);
16510
16511   can_use_hw_watchpoints = 1;
16512
16513   /* Tracepoint manipulation commands.  */
16514
16515   c = add_com ("trace", class_breakpoint, trace_command, _("\
16516 Set a tracepoint at specified line or function.\n\
16517 \n"
16518 BREAK_ARGS_HELP ("trace") "\n\
16519 Do \"help tracepoints\" for info on other tracepoint commands."));
16520   set_cmd_completer (c, location_completer);
16521
16522   add_com_alias ("tp", "trace", class_alias, 0);
16523   add_com_alias ("tr", "trace", class_alias, 1);
16524   add_com_alias ("tra", "trace", class_alias, 1);
16525   add_com_alias ("trac", "trace", class_alias, 1);
16526
16527   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16528 Set a fast tracepoint at specified line or function.\n\
16529 \n"
16530 BREAK_ARGS_HELP ("ftrace") "\n\
16531 Do \"help tracepoints\" for info on other tracepoint commands."));
16532   set_cmd_completer (c, location_completer);
16533
16534   c = add_com ("strace", class_breakpoint, strace_command, _("\
16535 Set a static tracepoint at specified line, function or marker.\n\
16536 \n\
16537 strace [LOCATION] [if CONDITION]\n\
16538 LOCATION may be a line number, function name, \"*\" and an address,\n\
16539 or -m MARKER_ID.\n\
16540 If a line number is specified, probe the marker at start of code\n\
16541 for that line.  If a function is specified, probe the marker at start\n\
16542 of code for that function.  If an address is specified, probe the marker\n\
16543 at that exact address.  If a marker id is specified, probe the marker\n\
16544 with that name.  With no LOCATION, uses current execution address of\n\
16545 the selected stack frame.\n\
16546 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16547 This collects arbitrary user data passed in the probe point call to the\n\
16548 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16549 by printing the $_sdata variable like any other convenience variable.\n\
16550 \n\
16551 CONDITION is a boolean expression.\n\
16552 \n\
16553 Multiple tracepoints at one place are permitted, and useful if their\n\
16554 conditions are different.\n\
16555 \n\
16556 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16557 Do \"help tracepoints\" for info on other tracepoint commands."));
16558   set_cmd_completer (c, location_completer);
16559
16560   add_info ("tracepoints", tracepoints_info, _("\
16561 Status of specified tracepoints (all tracepoints if no argument).\n\
16562 Convenience variable \"$tpnum\" contains the number of the\n\
16563 last tracepoint set."));
16564
16565   add_info_alias ("tp", "tracepoints", 1);
16566
16567   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16568 Delete specified tracepoints.\n\
16569 Arguments are tracepoint numbers, separated by spaces.\n\
16570 No argument means delete all tracepoints."),
16571            &deletelist);
16572   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16573
16574   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16575 Disable specified tracepoints.\n\
16576 Arguments are tracepoint numbers, separated by spaces.\n\
16577 No argument means disable all tracepoints."),
16578            &disablelist);
16579   deprecate_cmd (c, "disable");
16580
16581   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16582 Enable specified tracepoints.\n\
16583 Arguments are tracepoint numbers, separated by spaces.\n\
16584 No argument means enable all tracepoints."),
16585            &enablelist);
16586   deprecate_cmd (c, "enable");
16587
16588   add_com ("passcount", class_trace, trace_pass_command, _("\
16589 Set the passcount for a tracepoint.\n\
16590 The trace will end when the tracepoint has been passed 'count' times.\n\
16591 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16592 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16593
16594   add_prefix_cmd ("save", class_breakpoint, save_command,
16595                   _("Save breakpoint definitions as a script."),
16596                   &save_cmdlist, "save ",
16597                   0/*allow-unknown*/, &cmdlist);
16598
16599   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16600 Save current breakpoint definitions as a script.\n\
16601 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16602 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16603 session to restore them."),
16604                &save_cmdlist);
16605   set_cmd_completer (c, filename_completer);
16606
16607   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16608 Save current tracepoint definitions as a script.\n\
16609 Use the 'source' command in another debug session to restore them."),
16610                &save_cmdlist);
16611   set_cmd_completer (c, filename_completer);
16612
16613   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16614   deprecate_cmd (c, "save tracepoints");
16615
16616   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16617 Breakpoint specific settings\n\
16618 Configure various breakpoint-specific variables such as\n\
16619 pending breakpoint behavior"),
16620                   &breakpoint_set_cmdlist, "set breakpoint ",
16621                   0/*allow-unknown*/, &setlist);
16622   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16623 Breakpoint specific settings\n\
16624 Configure various breakpoint-specific variables such as\n\
16625 pending breakpoint behavior"),
16626                   &breakpoint_show_cmdlist, "show breakpoint ",
16627                   0/*allow-unknown*/, &showlist);
16628
16629   add_setshow_auto_boolean_cmd ("pending", no_class,
16630                                 &pending_break_support, _("\
16631 Set debugger's behavior regarding pending breakpoints."), _("\
16632 Show debugger's behavior regarding pending breakpoints."), _("\
16633 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16634 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16635 an error.  If auto, an unrecognized breakpoint location results in a\n\
16636 user-query to see if a pending breakpoint should be created."),
16637                                 NULL,
16638                                 show_pending_break_support,
16639                                 &breakpoint_set_cmdlist,
16640                                 &breakpoint_show_cmdlist);
16641
16642   pending_break_support = AUTO_BOOLEAN_AUTO;
16643
16644   add_setshow_boolean_cmd ("auto-hw", no_class,
16645                            &automatic_hardware_breakpoints, _("\
16646 Set automatic usage of hardware breakpoints."), _("\
16647 Show automatic usage of hardware breakpoints."), _("\
16648 If set, the debugger will automatically use hardware breakpoints for\n\
16649 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16650 a warning will be emitted for such breakpoints."),
16651                            NULL,
16652                            show_automatic_hardware_breakpoints,
16653                            &breakpoint_set_cmdlist,
16654                            &breakpoint_show_cmdlist);
16655
16656   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16657                                 &always_inserted_mode, _("\
16658 Set mode for inserting breakpoints."), _("\
16659 Show mode for inserting breakpoints."), _("\
16660 When this mode is off, breakpoints are inserted in inferior when it is\n\
16661 resumed, and removed when execution stops.  When this mode is on,\n\
16662 breakpoints are inserted immediately and removed only when the user\n\
16663 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16664 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16665 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16666 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16667 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16668                                 NULL,
16669                                 &show_always_inserted_mode,
16670                                 &breakpoint_set_cmdlist,
16671                                 &breakpoint_show_cmdlist);
16672
16673   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16674                         condition_evaluation_enums,
16675                         &condition_evaluation_mode_1, _("\
16676 Set mode of breakpoint condition evaluation."), _("\
16677 Show mode of breakpoint condition evaluation."), _("\
16678 When this is set to \"host\", breakpoint conditions will be\n\
16679 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16680 breakpoint conditions will be downloaded to the target (if the target\n\
16681 supports such feature) and conditions will be evaluated on the target's side.\n\
16682 If this is set to \"auto\" (default), this will be automatically set to\n\
16683 \"target\" if it supports condition evaluation, otherwise it will\n\
16684 be set to \"gdb\""),
16685                            &set_condition_evaluation_mode,
16686                            &show_condition_evaluation_mode,
16687                            &breakpoint_set_cmdlist,
16688                            &breakpoint_show_cmdlist);
16689
16690   add_com ("break-range", class_breakpoint, break_range_command, _("\
16691 Set a breakpoint for an address range.\n\
16692 break-range START-LOCATION, END-LOCATION\n\
16693 where START-LOCATION and END-LOCATION can be one of the following:\n\
16694   LINENUM, for that line in the current file,\n\
16695   FILE:LINENUM, for that line in that file,\n\
16696   +OFFSET, for that number of lines after the current line\n\
16697            or the start of the range\n\
16698   FUNCTION, for the first line in that function,\n\
16699   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16700   *ADDRESS, for the instruction at that address.\n\
16701 \n\
16702 The breakpoint will stop execution of the inferior whenever it executes\n\
16703 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16704 range (including START-LOCATION and END-LOCATION)."));
16705
16706   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16707 Set a dynamic printf at specified line or function.\n\
16708 dprintf location,format string,arg1,arg2,...\n\
16709 location may be a line number, function name, or \"*\" and an address.\n\
16710 If a line number is specified, break at start of code for that line.\n\
16711 If a function is specified, break at start of code for that function.\n\
16712 "));
16713   set_cmd_completer (c, location_completer);
16714
16715   add_setshow_enum_cmd ("dprintf-style", class_support,
16716                         dprintf_style_enums, &dprintf_style, _("\
16717 Set the style of usage for dynamic printf."), _("\
16718 Show the style of usage for dynamic printf."), _("\
16719 This setting chooses how GDB will do a dynamic printf.\n\
16720 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16721 console, as with the \"printf\" command.\n\
16722 If the value is \"call\", the print is done by calling a function in your\n\
16723 program; by default printf(), but you can choose a different function or\n\
16724 output stream by setting dprintf-function and dprintf-channel."),
16725                         update_dprintf_commands, NULL,
16726                         &setlist, &showlist);
16727
16728   dprintf_function = xstrdup ("printf");
16729   add_setshow_string_cmd ("dprintf-function", class_support,
16730                           &dprintf_function, _("\
16731 Set the function to use for dynamic printf"), _("\
16732 Show the function to use for dynamic printf"), NULL,
16733                           update_dprintf_commands, NULL,
16734                           &setlist, &showlist);
16735
16736   dprintf_channel = xstrdup ("");
16737   add_setshow_string_cmd ("dprintf-channel", class_support,
16738                           &dprintf_channel, _("\
16739 Set the channel to use for dynamic printf"), _("\
16740 Show the channel to use for dynamic printf"), NULL,
16741                           update_dprintf_commands, NULL,
16742                           &setlist, &showlist);
16743
16744   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16745                            &disconnected_dprintf, _("\
16746 Set whether dprintf continues after GDB disconnects."), _("\
16747 Show whether dprintf continues after GDB disconnects."), _("\
16748 Use this to let dprintf commands continue to hit and produce output\n\
16749 even if GDB disconnects or detaches from the target."),
16750                            NULL,
16751                            NULL,
16752                            &setlist, &showlist);
16753
16754   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16755 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16756 (target agent only) This is useful for formatted output in user-defined commands."));
16757
16758   automatic_hardware_breakpoints = 1;
16759
16760   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16761 }