breakpoint shadowing, take single-step breakpoints into account.
[platform/upstream/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include <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 "ax-gdb.h"
70 #include "dummy-frame.h"
71
72 #include "format.h"
73
74 /* readline include files */
75 #include "readline/readline.h"
76 #include "readline/history.h"
77
78 /* readline defines this.  */
79 #undef savestring
80
81 #include "mi/mi-common.h"
82 #include "extension.h"
83
84 /* Enums for exception-handling support.  */
85 enum exception_event_kind
86 {
87   EX_EVENT_THROW,
88   EX_EVENT_RETHROW,
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                                             char *, char *, enum bptype,
122                                             enum bpdisp, int, int,
123                                             int,
124                                             const struct breakpoint_ops *,
125                                             int, int, int, unsigned);
126
127 static void decode_linespec_default (struct breakpoint *, char **,
128                                      struct symtabs_and_lines *);
129
130 static void clear_command (char *, int);
131
132 static void catch_command (char *, int);
133
134 static int can_use_hardware_watchpoint (struct value *);
135
136 static void break_command_1 (char *, int, int);
137
138 static void mention (struct breakpoint *);
139
140 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
141                                                                enum bptype,
142                                                                const struct breakpoint_ops *);
143 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
144                                                        const struct symtab_and_line *);
145
146 /* This function is used in gdbtk sources and thus can not be made
147    static.  */
148 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
149                                        struct symtab_and_line,
150                                        enum bptype,
151                                        const struct breakpoint_ops *);
152
153 static struct breakpoint *
154   momentary_breakpoint_from_master (struct breakpoint *orig,
155                                     enum bptype type,
156                                     const struct breakpoint_ops *ops);
157
158 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
159
160 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
161                                             CORE_ADDR bpaddr,
162                                             enum bptype bptype);
163
164 static void describe_other_breakpoints (struct gdbarch *,
165                                         struct program_space *, CORE_ADDR,
166                                         struct obj_section *, int);
167
168 static int watchpoint_locations_match (struct bp_location *loc1,
169                                        struct bp_location *loc2);
170
171 static int breakpoint_location_address_match (struct bp_location *bl,
172                                               struct address_space *aspace,
173                                               CORE_ADDR addr);
174
175 static void breakpoints_info (char *, int);
176
177 static void watchpoints_info (char *, int);
178
179 static int breakpoint_1 (char *, int, 
180                          int (*) (const struct breakpoint *));
181
182 static int breakpoint_cond_eval (void *);
183
184 static void cleanup_executing_breakpoints (void *);
185
186 static void commands_command (char *, int);
187
188 static void condition_command (char *, int);
189
190 typedef enum
191   {
192     mark_inserted,
193     mark_uninserted
194   }
195 insertion_state_t;
196
197 static int remove_breakpoint (struct bp_location *, insertion_state_t);
198 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
199
200 static enum print_stop_action print_bp_stop_message (bpstat bs);
201
202 static int watchpoint_check (void *);
203
204 static void maintenance_info_breakpoints (char *, int);
205
206 static int hw_breakpoint_used_count (void);
207
208 static int hw_watchpoint_use_count (struct breakpoint *);
209
210 static int hw_watchpoint_used_count_others (struct breakpoint *except,
211                                             enum bptype type,
212                                             int *other_type_used);
213
214 static void hbreak_command (char *, int);
215
216 static void thbreak_command (char *, int);
217
218 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
219                                     int count);
220
221 static void stop_command (char *arg, int from_tty);
222
223 static void stopin_command (char *arg, int from_tty);
224
225 static void stopat_command (char *arg, int from_tty);
226
227 static void tcatch_command (char *arg, int from_tty);
228
229 static void detach_single_step_breakpoints (void);
230
231 static void free_bp_location (struct bp_location *loc);
232 static void incref_bp_location (struct bp_location *loc);
233 static void decref_bp_location (struct bp_location **loc);
234
235 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
236
237 static void update_global_location_list (int);
238
239 static void update_global_location_list_nothrow (int);
240
241 static int is_hardware_watchpoint (const struct breakpoint *bpt);
242
243 static void insert_breakpoint_locations (void);
244
245 static int syscall_catchpoint_p (struct breakpoint *b);
246
247 static void tracepoints_info (char *, int);
248
249 static void delete_trace_command (char *, int);
250
251 static void enable_trace_command (char *, int);
252
253 static void disable_trace_command (char *, int);
254
255 static void trace_pass_command (char *, int);
256
257 static void set_tracepoint_count (int num);
258
259 static int is_masked_watchpoint (const struct breakpoint *b);
260
261 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
262
263 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
264    otherwise.  */
265
266 static int strace_marker_p (struct breakpoint *b);
267
268 /* The abstract base class all breakpoint_ops structures inherit
269    from.  */
270 struct breakpoint_ops base_breakpoint_ops;
271
272 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
273    that are implemented on top of software or hardware breakpoints
274    (user breakpoints, internal and momentary breakpoints, etc.).  */
275 static struct breakpoint_ops bkpt_base_breakpoint_ops;
276
277 /* Internal breakpoints class type.  */
278 static struct breakpoint_ops internal_breakpoint_ops;
279
280 /* Momentary breakpoints class type.  */
281 static struct breakpoint_ops momentary_breakpoint_ops;
282
283 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
284 static struct breakpoint_ops longjmp_breakpoint_ops;
285
286 /* The breakpoint_ops structure to be used in regular user created
287    breakpoints.  */
288 struct breakpoint_ops bkpt_breakpoint_ops;
289
290 /* Breakpoints set on probes.  */
291 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
292
293 /* Dynamic printf class type.  */
294 struct breakpoint_ops dprintf_breakpoint_ops;
295
296 /* One (or perhaps two) breakpoints used for software single
297    stepping.  */
298
299 static void *single_step_breakpoints[2];
300 static struct gdbarch *single_step_gdbarch[2];
301
302 /* The style in which to perform a dynamic printf.  This is a user
303    option because different output options have different tradeoffs;
304    if GDB does the printing, there is better error handling if there
305    is a problem with any of the arguments, but using an inferior
306    function lets you have special-purpose printers and sending of
307    output to the same place as compiled-in print functions.  */
308
309 static const char dprintf_style_gdb[] = "gdb";
310 static const char dprintf_style_call[] = "call";
311 static const char dprintf_style_agent[] = "agent";
312 static const char *const dprintf_style_enums[] = {
313   dprintf_style_gdb,
314   dprintf_style_call,
315   dprintf_style_agent,
316   NULL
317 };
318 static const char *dprintf_style = dprintf_style_gdb;
319
320 /* The function to use for dynamic printf if the preferred style is to
321    call into the inferior.  The value is simply a string that is
322    copied into the command, so it can be anything that GDB can
323    evaluate to a callable address, not necessarily a function name.  */
324
325 static char *dprintf_function = "";
326
327 /* The channel to use for dynamic printf if the preferred style is to
328    call into the inferior; if a nonempty string, it will be passed to
329    the call as the first argument, with the format string as the
330    second.  As with the dprintf function, this can be anything that
331    GDB knows how to evaluate, so in addition to common choices like
332    "stderr", this could be an app-specific expression like
333    "mystreams[curlogger]".  */
334
335 static char *dprintf_channel = "";
336
337 /* True if dprintf commands should continue to operate even if GDB
338    has disconnected.  */
339 static int disconnected_dprintf = 1;
340
341 /* A reference-counted struct command_line.  This lets multiple
342    breakpoints share a single command list.  */
343 struct counted_command_line
344 {
345   /* The reference count.  */
346   int refc;
347
348   /* The command list.  */
349   struct command_line *commands;
350 };
351
352 struct command_line *
353 breakpoint_commands (struct breakpoint *b)
354 {
355   return b->commands ? b->commands->commands : NULL;
356 }
357
358 /* Flag indicating that a command has proceeded the inferior past the
359    current breakpoint.  */
360
361 static int breakpoint_proceeded;
362
363 const char *
364 bpdisp_text (enum bpdisp disp)
365 {
366   /* NOTE: the following values are a part of MI protocol and
367      represent values of 'disp' field returned when inferior stops at
368      a breakpoint.  */
369   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
370
371   return bpdisps[(int) disp];
372 }
373
374 /* Prototypes for exported functions.  */
375 /* If FALSE, gdb will not use hardware support for watchpoints, even
376    if such is available.  */
377 static int can_use_hw_watchpoints;
378
379 static void
380 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
381                              struct cmd_list_element *c,
382                              const char *value)
383 {
384   fprintf_filtered (file,
385                     _("Debugger's willingness to use "
386                       "watchpoint hardware is %s.\n"),
387                     value);
388 }
389
390 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
391    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
392    for unrecognized breakpoint locations.
393    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
394 static enum auto_boolean pending_break_support;
395 static void
396 show_pending_break_support (struct ui_file *file, int from_tty,
397                             struct cmd_list_element *c,
398                             const char *value)
399 {
400   fprintf_filtered (file,
401                     _("Debugger's behavior regarding "
402                       "pending breakpoints is %s.\n"),
403                     value);
404 }
405
406 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
407    set with "break" but falling in read-only memory.
408    If 0, gdb will warn about such breakpoints, but won't automatically
409    use hardware breakpoints.  */
410 static int automatic_hardware_breakpoints;
411 static void
412 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
413                                      struct cmd_list_element *c,
414                                      const char *value)
415 {
416   fprintf_filtered (file,
417                     _("Automatic usage of hardware breakpoints is %s.\n"),
418                     value);
419 }
420
421 /* If on, gdb will keep breakpoints inserted even as inferior is
422    stopped, and immediately insert any new breakpoints.  If off, gdb
423    will insert breakpoints into inferior only when resuming it, and
424    will remove breakpoints upon stop.  If auto, GDB will behave as ON
425    if in non-stop mode, and as OFF if all-stop mode.*/
426
427 static enum auto_boolean always_inserted_mode = AUTO_BOOLEAN_AUTO;
428
429 static void
430 show_always_inserted_mode (struct ui_file *file, int from_tty,
431                      struct cmd_list_element *c, const char *value)
432 {
433   if (always_inserted_mode == AUTO_BOOLEAN_AUTO)
434     fprintf_filtered (file,
435                       _("Always inserted breakpoint "
436                         "mode is %s (currently %s).\n"),
437                       value,
438                       breakpoints_always_inserted_mode () ? "on" : "off");
439   else
440     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
441                       value);
442 }
443
444 int
445 breakpoints_always_inserted_mode (void)
446 {
447   return (always_inserted_mode == AUTO_BOOLEAN_TRUE
448           || (always_inserted_mode == AUTO_BOOLEAN_AUTO && non_stop));
449 }
450
451 static const char condition_evaluation_both[] = "host or target";
452
453 /* Modes for breakpoint condition evaluation.  */
454 static const char condition_evaluation_auto[] = "auto";
455 static const char condition_evaluation_host[] = "host";
456 static const char condition_evaluation_target[] = "target";
457 static const char *const condition_evaluation_enums[] = {
458   condition_evaluation_auto,
459   condition_evaluation_host,
460   condition_evaluation_target,
461   NULL
462 };
463
464 /* Global that holds the current mode for breakpoint condition evaluation.  */
465 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
466
467 /* Global that we use to display information to the user (gets its value from
468    condition_evaluation_mode_1.  */
469 static const char *condition_evaluation_mode = condition_evaluation_auto;
470
471 /* Translate a condition evaluation mode MODE into either "host"
472    or "target".  This is used mostly to translate from "auto" to the
473    real setting that is being used.  It returns the translated
474    evaluation mode.  */
475
476 static const char *
477 translate_condition_evaluation_mode (const char *mode)
478 {
479   if (mode == condition_evaluation_auto)
480     {
481       if (target_supports_evaluation_of_breakpoint_conditions ())
482         return condition_evaluation_target;
483       else
484         return condition_evaluation_host;
485     }
486   else
487     return mode;
488 }
489
490 /* Discovers what condition_evaluation_auto translates to.  */
491
492 static const char *
493 breakpoint_condition_evaluation_mode (void)
494 {
495   return translate_condition_evaluation_mode (condition_evaluation_mode);
496 }
497
498 /* Return true if GDB should evaluate breakpoint conditions or false
499    otherwise.  */
500
501 static int
502 gdb_evaluates_breakpoint_condition_p (void)
503 {
504   const char *mode = breakpoint_condition_evaluation_mode ();
505
506   return (mode == condition_evaluation_host);
507 }
508
509 void _initialize_breakpoint (void);
510
511 /* Are we executing breakpoint commands?  */
512 static int executing_breakpoint_commands;
513
514 /* Are overlay event breakpoints enabled? */
515 static int overlay_events_enabled;
516
517 /* See description in breakpoint.h. */
518 int target_exact_watchpoints = 0;
519
520 /* Walk the following statement or block through all breakpoints.
521    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
522    current breakpoint.  */
523
524 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
525
526 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
527         for (B = breakpoint_chain;      \
528              B ? (TMP=B->next, 1): 0;   \
529              B = TMP)
530
531 /* Similar iterator for the low-level breakpoints.  SAFE variant is
532    not provided so update_global_location_list must not be called
533    while executing the block of ALL_BP_LOCATIONS.  */
534
535 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
536         for (BP_TMP = bp_location;                                      \
537              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
538              BP_TMP++)
539
540 /* Iterates through locations with address ADDRESS for the currently selected
541    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
542    to where the loop should start from.
543    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
544    appropriate location to start with.  */
545
546 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
547         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
548              BP_LOCP_TMP = BP_LOCP_START;                               \
549              BP_LOCP_START                                              \
550              && (BP_LOCP_TMP < bp_location + bp_location_count          \
551              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
552              BP_LOCP_TMP++)
553
554 /* Iterator for tracepoints only.  */
555
556 #define ALL_TRACEPOINTS(B)  \
557   for (B = breakpoint_chain; B; B = B->next)  \
558     if (is_tracepoint (B))
559
560 /* Chains of all breakpoints defined.  */
561
562 struct breakpoint *breakpoint_chain;
563
564 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
565
566 static struct bp_location **bp_location;
567
568 /* Number of elements of BP_LOCATION.  */
569
570 static unsigned bp_location_count;
571
572 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
573    ADDRESS for the current elements of BP_LOCATION which get a valid
574    result from bp_location_has_shadow.  You can use it for roughly
575    limiting the subrange of BP_LOCATION to scan for shadow bytes for
576    an address you need to read.  */
577
578 static CORE_ADDR bp_location_placed_address_before_address_max;
579
580 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
581    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
582    BP_LOCATION which get a valid result from bp_location_has_shadow.
583    You can use it for roughly limiting the subrange of BP_LOCATION to
584    scan for shadow bytes for an address you need to read.  */
585
586 static CORE_ADDR bp_location_shadow_len_after_address_max;
587
588 /* The locations that no longer correspond to any breakpoint, unlinked
589    from bp_location array, but for which a hit may still be reported
590    by a target.  */
591 VEC(bp_location_p) *moribund_locations = NULL;
592
593 /* Number of last breakpoint made.  */
594
595 static int breakpoint_count;
596
597 /* The value of `breakpoint_count' before the last command that
598    created breakpoints.  If the last (break-like) command created more
599    than one breakpoint, then the difference between BREAKPOINT_COUNT
600    and PREV_BREAKPOINT_COUNT is more than one.  */
601 static int prev_breakpoint_count;
602
603 /* Number of last tracepoint made.  */
604
605 static int tracepoint_count;
606
607 static struct cmd_list_element *breakpoint_set_cmdlist;
608 static struct cmd_list_element *breakpoint_show_cmdlist;
609 struct cmd_list_element *save_cmdlist;
610
611 /* Return whether a breakpoint is an active enabled breakpoint.  */
612 static int
613 breakpoint_enabled (struct breakpoint *b)
614 {
615   return (b->enable_state == bp_enabled);
616 }
617
618 /* Set breakpoint count to NUM.  */
619
620 static void
621 set_breakpoint_count (int num)
622 {
623   prev_breakpoint_count = breakpoint_count;
624   breakpoint_count = num;
625   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
626 }
627
628 /* Used by `start_rbreak_breakpoints' below, to record the current
629    breakpoint count before "rbreak" creates any breakpoint.  */
630 static int rbreak_start_breakpoint_count;
631
632 /* Called at the start an "rbreak" command to record the first
633    breakpoint made.  */
634
635 void
636 start_rbreak_breakpoints (void)
637 {
638   rbreak_start_breakpoint_count = breakpoint_count;
639 }
640
641 /* Called at the end of an "rbreak" command to record the last
642    breakpoint made.  */
643
644 void
645 end_rbreak_breakpoints (void)
646 {
647   prev_breakpoint_count = rbreak_start_breakpoint_count;
648 }
649
650 /* Used in run_command to zero the hit count when a new run starts.  */
651
652 void
653 clear_breakpoint_hit_counts (void)
654 {
655   struct breakpoint *b;
656
657   ALL_BREAKPOINTS (b)
658     b->hit_count = 0;
659 }
660
661 /* Allocate a new counted_command_line with reference count of 1.
662    The new structure owns COMMANDS.  */
663
664 static struct counted_command_line *
665 alloc_counted_command_line (struct command_line *commands)
666 {
667   struct counted_command_line *result
668     = xmalloc (sizeof (struct counted_command_line));
669
670   result->refc = 1;
671   result->commands = commands;
672   return result;
673 }
674
675 /* Increment reference count.  This does nothing if CMD is NULL.  */
676
677 static void
678 incref_counted_command_line (struct counted_command_line *cmd)
679 {
680   if (cmd)
681     ++cmd->refc;
682 }
683
684 /* Decrement reference count.  If the reference count reaches 0,
685    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
686    nothing if *CMDP is NULL.  */
687
688 static void
689 decref_counted_command_line (struct counted_command_line **cmdp)
690 {
691   if (*cmdp)
692     {
693       if (--(*cmdp)->refc == 0)
694         {
695           free_command_lines (&(*cmdp)->commands);
696           xfree (*cmdp);
697         }
698       *cmdp = NULL;
699     }
700 }
701
702 /* A cleanup function that calls decref_counted_command_line.  */
703
704 static void
705 do_cleanup_counted_command_line (void *arg)
706 {
707   decref_counted_command_line (arg);
708 }
709
710 /* Create a cleanup that calls decref_counted_command_line on the
711    argument.  */
712
713 static struct cleanup *
714 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
715 {
716   return make_cleanup (do_cleanup_counted_command_line, cmdp);
717 }
718
719 \f
720 /* Return the breakpoint with the specified number, or NULL
721    if the number does not refer to an existing breakpoint.  */
722
723 struct breakpoint *
724 get_breakpoint (int num)
725 {
726   struct breakpoint *b;
727
728   ALL_BREAKPOINTS (b)
729     if (b->number == num)
730       return b;
731   
732   return NULL;
733 }
734
735 \f
736
737 /* Mark locations as "conditions have changed" in case the target supports
738    evaluating conditions on its side.  */
739
740 static void
741 mark_breakpoint_modified (struct breakpoint *b)
742 {
743   struct bp_location *loc;
744
745   /* This is only meaningful if the target is
746      evaluating conditions and if the user has
747      opted for condition evaluation on the target's
748      side.  */
749   if (gdb_evaluates_breakpoint_condition_p ()
750       || !target_supports_evaluation_of_breakpoint_conditions ())
751     return;
752
753   if (!is_breakpoint (b))
754     return;
755
756   for (loc = b->loc; loc; loc = loc->next)
757     loc->condition_changed = condition_modified;
758 }
759
760 /* Mark location as "conditions have changed" in case the target supports
761    evaluating conditions on its side.  */
762
763 static void
764 mark_breakpoint_location_modified (struct bp_location *loc)
765 {
766   /* This is only meaningful if the target is
767      evaluating conditions and if the user has
768      opted for condition evaluation on the target's
769      side.  */
770   if (gdb_evaluates_breakpoint_condition_p ()
771       || !target_supports_evaluation_of_breakpoint_conditions ())
772
773     return;
774
775   if (!is_breakpoint (loc->owner))
776     return;
777
778   loc->condition_changed = condition_modified;
779 }
780
781 /* Sets the condition-evaluation mode using the static global
782    condition_evaluation_mode.  */
783
784 static void
785 set_condition_evaluation_mode (char *args, int from_tty,
786                                struct cmd_list_element *c)
787 {
788   const char *old_mode, *new_mode;
789
790   if ((condition_evaluation_mode_1 == condition_evaluation_target)
791       && !target_supports_evaluation_of_breakpoint_conditions ())
792     {
793       condition_evaluation_mode_1 = condition_evaluation_mode;
794       warning (_("Target does not support breakpoint condition evaluation.\n"
795                  "Using host evaluation mode instead."));
796       return;
797     }
798
799   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
800   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
801
802   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
803      settings was "auto".  */
804   condition_evaluation_mode = condition_evaluation_mode_1;
805
806   /* Only update the mode if the user picked a different one.  */
807   if (new_mode != old_mode)
808     {
809       struct bp_location *loc, **loc_tmp;
810       /* If the user switched to a different evaluation mode, we
811          need to synch the changes with the target as follows:
812
813          "host" -> "target": Send all (valid) conditions to the target.
814          "target" -> "host": Remove all the conditions from the target.
815       */
816
817       if (new_mode == condition_evaluation_target)
818         {
819           /* Mark everything modified and synch conditions with the
820              target.  */
821           ALL_BP_LOCATIONS (loc, loc_tmp)
822             mark_breakpoint_location_modified (loc);
823         }
824       else
825         {
826           /* Manually mark non-duplicate locations to synch conditions
827              with the target.  We do this to remove all the conditions the
828              target knows about.  */
829           ALL_BP_LOCATIONS (loc, loc_tmp)
830             if (is_breakpoint (loc->owner) && loc->inserted)
831               loc->needs_update = 1;
832         }
833
834       /* Do the update.  */
835       update_global_location_list (1);
836     }
837
838   return;
839 }
840
841 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
842    what "auto" is translating to.  */
843
844 static void
845 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
846                                 struct cmd_list_element *c, const char *value)
847 {
848   if (condition_evaluation_mode == condition_evaluation_auto)
849     fprintf_filtered (file,
850                       _("Breakpoint condition evaluation "
851                         "mode is %s (currently %s).\n"),
852                       value,
853                       breakpoint_condition_evaluation_mode ());
854   else
855     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
856                       value);
857 }
858
859 /* A comparison function for bp_location AP and BP that is used by
860    bsearch.  This comparison function only cares about addresses, unlike
861    the more general bp_location_compare function.  */
862
863 static int
864 bp_location_compare_addrs (const void *ap, const void *bp)
865 {
866   struct bp_location *a = *(void **) ap;
867   struct bp_location *b = *(void **) bp;
868
869   if (a->address == b->address)
870     return 0;
871   else
872     return ((a->address > b->address) - (a->address < b->address));
873 }
874
875 /* Helper function to skip all bp_locations with addresses
876    less than ADDRESS.  It returns the first bp_location that
877    is greater than or equal to ADDRESS.  If none is found, just
878    return NULL.  */
879
880 static struct bp_location **
881 get_first_locp_gte_addr (CORE_ADDR address)
882 {
883   struct bp_location dummy_loc;
884   struct bp_location *dummy_locp = &dummy_loc;
885   struct bp_location **locp_found = NULL;
886
887   /* Initialize the dummy location's address field.  */
888   memset (&dummy_loc, 0, sizeof (struct bp_location));
889   dummy_loc.address = address;
890
891   /* Find a close match to the first location at ADDRESS.  */
892   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
893                         sizeof (struct bp_location **),
894                         bp_location_compare_addrs);
895
896   /* Nothing was found, nothing left to do.  */
897   if (locp_found == NULL)
898     return NULL;
899
900   /* We may have found a location that is at ADDRESS but is not the first in the
901      location's list.  Go backwards (if possible) and locate the first one.  */
902   while ((locp_found - 1) >= bp_location
903          && (*(locp_found - 1))->address == address)
904     locp_found--;
905
906   return locp_found;
907 }
908
909 void
910 set_breakpoint_condition (struct breakpoint *b, char *exp,
911                           int from_tty)
912 {
913   xfree (b->cond_string);
914   b->cond_string = NULL;
915
916   if (is_watchpoint (b))
917     {
918       struct watchpoint *w = (struct watchpoint *) b;
919
920       xfree (w->cond_exp);
921       w->cond_exp = NULL;
922     }
923   else
924     {
925       struct bp_location *loc;
926
927       for (loc = b->loc; loc; loc = loc->next)
928         {
929           xfree (loc->cond);
930           loc->cond = NULL;
931
932           /* No need to free the condition agent expression
933              bytecode (if we have one).  We will handle this
934              when we go through update_global_location_list.  */
935         }
936     }
937
938   if (*exp == 0)
939     {
940       if (from_tty)
941         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
942     }
943   else
944     {
945       const char *arg = exp;
946
947       /* I don't know if it matters whether this is the string the user
948          typed in or the decompiled expression.  */
949       b->cond_string = xstrdup (arg);
950       b->condition_not_parsed = 0;
951
952       if (is_watchpoint (b))
953         {
954           struct watchpoint *w = (struct watchpoint *) b;
955
956           innermost_block = NULL;
957           arg = exp;
958           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
959           if (*arg)
960             error (_("Junk at end of expression"));
961           w->cond_exp_valid_block = innermost_block;
962         }
963       else
964         {
965           struct bp_location *loc;
966
967           for (loc = b->loc; loc; loc = loc->next)
968             {
969               arg = exp;
970               loc->cond =
971                 parse_exp_1 (&arg, loc->address,
972                              block_for_pc (loc->address), 0);
973               if (*arg)
974                 error (_("Junk at end of expression"));
975             }
976         }
977     }
978   mark_breakpoint_modified (b);
979
980   observer_notify_breakpoint_modified (b);
981 }
982
983 /* Completion for the "condition" command.  */
984
985 static VEC (char_ptr) *
986 condition_completer (struct cmd_list_element *cmd,
987                      const char *text, const char *word)
988 {
989   const char *space;
990
991   text = skip_spaces_const (text);
992   space = skip_to_space_const (text);
993   if (*space == '\0')
994     {
995       int len;
996       struct breakpoint *b;
997       VEC (char_ptr) *result = NULL;
998
999       if (text[0] == '$')
1000         {
1001           /* We don't support completion of history indices.  */
1002           if (isdigit (text[1]))
1003             return NULL;
1004           return complete_internalvar (&text[1]);
1005         }
1006
1007       /* We're completing the breakpoint number.  */
1008       len = strlen (text);
1009
1010       ALL_BREAKPOINTS (b)
1011         {
1012           char number[50];
1013
1014           xsnprintf (number, sizeof (number), "%d", b->number);
1015
1016           if (strncmp (number, text, len) == 0)
1017             VEC_safe_push (char_ptr, result, xstrdup (number));
1018         }
1019
1020       return result;
1021     }
1022
1023   /* We're completing the expression part.  */
1024   text = skip_spaces_const (space);
1025   return expression_completer (cmd, text, word);
1026 }
1027
1028 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1029
1030 static void
1031 condition_command (char *arg, int from_tty)
1032 {
1033   struct breakpoint *b;
1034   char *p;
1035   int bnum;
1036
1037   if (arg == 0)
1038     error_no_arg (_("breakpoint number"));
1039
1040   p = arg;
1041   bnum = get_number (&p);
1042   if (bnum == 0)
1043     error (_("Bad breakpoint argument: '%s'"), arg);
1044
1045   ALL_BREAKPOINTS (b)
1046     if (b->number == bnum)
1047       {
1048         /* Check if this breakpoint has a "stop" method implemented in an
1049            extension language.  This method and conditions entered into GDB
1050            from the CLI are mutually exclusive.  */
1051         const struct extension_language_defn *extlang
1052           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1053
1054         if (extlang != NULL)
1055           {
1056             error (_("Only one stop condition allowed.  There is currently"
1057                      " a %s stop condition defined for this breakpoint."),
1058                    ext_lang_capitalized_name (extlang));
1059           }
1060         set_breakpoint_condition (b, p, from_tty);
1061
1062         if (is_breakpoint (b))
1063           update_global_location_list (1);
1064
1065         return;
1066       }
1067
1068   error (_("No breakpoint number %d."), bnum);
1069 }
1070
1071 /* Check that COMMAND do not contain commands that are suitable
1072    only for tracepoints and not suitable for ordinary breakpoints.
1073    Throw if any such commands is found.  */
1074
1075 static void
1076 check_no_tracepoint_commands (struct command_line *commands)
1077 {
1078   struct command_line *c;
1079
1080   for (c = commands; c; c = c->next)
1081     {
1082       int i;
1083
1084       if (c->control_type == while_stepping_control)
1085         error (_("The 'while-stepping' command can "
1086                  "only be used for tracepoints"));
1087
1088       for (i = 0; i < c->body_count; ++i)
1089         check_no_tracepoint_commands ((c->body_list)[i]);
1090
1091       /* Not that command parsing removes leading whitespace and comment
1092          lines and also empty lines.  So, we only need to check for
1093          command directly.  */
1094       if (strstr (c->line, "collect ") == c->line)
1095         error (_("The 'collect' command can only be used for tracepoints"));
1096
1097       if (strstr (c->line, "teval ") == c->line)
1098         error (_("The 'teval' command can only be used for tracepoints"));
1099     }
1100 }
1101
1102 /* Encapsulate tests for different types of tracepoints.  */
1103
1104 static int
1105 is_tracepoint_type (enum bptype type)
1106 {
1107   return (type == bp_tracepoint
1108           || type == bp_fast_tracepoint
1109           || type == bp_static_tracepoint);
1110 }
1111
1112 int
1113 is_tracepoint (const struct breakpoint *b)
1114 {
1115   return is_tracepoint_type (b->type);
1116 }
1117
1118 /* A helper function that validates that COMMANDS are valid for a
1119    breakpoint.  This function will throw an exception if a problem is
1120    found.  */
1121
1122 static void
1123 validate_commands_for_breakpoint (struct breakpoint *b,
1124                                   struct command_line *commands)
1125 {
1126   if (is_tracepoint (b))
1127     {
1128       struct tracepoint *t = (struct tracepoint *) b;
1129       struct command_line *c;
1130       struct command_line *while_stepping = 0;
1131
1132       /* Reset the while-stepping step count.  The previous commands
1133          might have included a while-stepping action, while the new
1134          ones might not.  */
1135       t->step_count = 0;
1136
1137       /* We need to verify that each top-level element of commands is
1138          valid for tracepoints, that there's at most one
1139          while-stepping element, and that the while-stepping's body
1140          has valid tracing commands excluding nested while-stepping.
1141          We also need to validate the tracepoint action line in the
1142          context of the tracepoint --- validate_actionline actually
1143          has side effects, like setting the tracepoint's
1144          while-stepping STEP_COUNT, in addition to checking if the
1145          collect/teval actions parse and make sense in the
1146          tracepoint's context.  */
1147       for (c = commands; c; c = c->next)
1148         {
1149           if (c->control_type == while_stepping_control)
1150             {
1151               if (b->type == bp_fast_tracepoint)
1152                 error (_("The 'while-stepping' command "
1153                          "cannot be used for fast tracepoint"));
1154               else if (b->type == bp_static_tracepoint)
1155                 error (_("The 'while-stepping' command "
1156                          "cannot be used for static tracepoint"));
1157
1158               if (while_stepping)
1159                 error (_("The 'while-stepping' command "
1160                          "can be used only once"));
1161               else
1162                 while_stepping = c;
1163             }
1164
1165           validate_actionline (c->line, b);
1166         }
1167       if (while_stepping)
1168         {
1169           struct command_line *c2;
1170
1171           gdb_assert (while_stepping->body_count == 1);
1172           c2 = while_stepping->body_list[0];
1173           for (; c2; c2 = c2->next)
1174             {
1175               if (c2->control_type == while_stepping_control)
1176                 error (_("The 'while-stepping' command cannot be nested"));
1177             }
1178         }
1179     }
1180   else
1181     {
1182       check_no_tracepoint_commands (commands);
1183     }
1184 }
1185
1186 /* Return a vector of all the static tracepoints set at ADDR.  The
1187    caller is responsible for releasing the vector.  */
1188
1189 VEC(breakpoint_p) *
1190 static_tracepoints_here (CORE_ADDR addr)
1191 {
1192   struct breakpoint *b;
1193   VEC(breakpoint_p) *found = 0;
1194   struct bp_location *loc;
1195
1196   ALL_BREAKPOINTS (b)
1197     if (b->type == bp_static_tracepoint)
1198       {
1199         for (loc = b->loc; loc; loc = loc->next)
1200           if (loc->address == addr)
1201             VEC_safe_push(breakpoint_p, found, b);
1202       }
1203
1204   return found;
1205 }
1206
1207 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1208    validate that only allowed commands are included.  */
1209
1210 void
1211 breakpoint_set_commands (struct breakpoint *b, 
1212                          struct command_line *commands)
1213 {
1214   validate_commands_for_breakpoint (b, commands);
1215
1216   decref_counted_command_line (&b->commands);
1217   b->commands = alloc_counted_command_line (commands);
1218   observer_notify_breakpoint_modified (b);
1219 }
1220
1221 /* Set the internal `silent' flag on the breakpoint.  Note that this
1222    is not the same as the "silent" that may appear in the breakpoint's
1223    commands.  */
1224
1225 void
1226 breakpoint_set_silent (struct breakpoint *b, int silent)
1227 {
1228   int old_silent = b->silent;
1229
1230   b->silent = silent;
1231   if (old_silent != silent)
1232     observer_notify_breakpoint_modified (b);
1233 }
1234
1235 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1236    breakpoint work for any thread.  */
1237
1238 void
1239 breakpoint_set_thread (struct breakpoint *b, int thread)
1240 {
1241   int old_thread = b->thread;
1242
1243   b->thread = thread;
1244   if (old_thread != thread)
1245     observer_notify_breakpoint_modified (b);
1246 }
1247
1248 /* Set the task for this breakpoint.  If TASK is 0, make the
1249    breakpoint work for any task.  */
1250
1251 void
1252 breakpoint_set_task (struct breakpoint *b, int task)
1253 {
1254   int old_task = b->task;
1255
1256   b->task = task;
1257   if (old_task != task)
1258     observer_notify_breakpoint_modified (b);
1259 }
1260
1261 void
1262 check_tracepoint_command (char *line, void *closure)
1263 {
1264   struct breakpoint *b = closure;
1265
1266   validate_actionline (line, b);
1267 }
1268
1269 /* A structure used to pass information through
1270    map_breakpoint_numbers.  */
1271
1272 struct commands_info
1273 {
1274   /* True if the command was typed at a tty.  */
1275   int from_tty;
1276
1277   /* The breakpoint range spec.  */
1278   char *arg;
1279
1280   /* Non-NULL if the body of the commands are being read from this
1281      already-parsed command.  */
1282   struct command_line *control;
1283
1284   /* The command lines read from the user, or NULL if they have not
1285      yet been read.  */
1286   struct counted_command_line *cmd;
1287 };
1288
1289 /* A callback for map_breakpoint_numbers that sets the commands for
1290    commands_command.  */
1291
1292 static void
1293 do_map_commands_command (struct breakpoint *b, void *data)
1294 {
1295   struct commands_info *info = data;
1296
1297   if (info->cmd == NULL)
1298     {
1299       struct command_line *l;
1300
1301       if (info->control != NULL)
1302         l = copy_command_lines (info->control->body_list[0]);
1303       else
1304         {
1305           struct cleanup *old_chain;
1306           char *str;
1307
1308           str = xstrprintf (_("Type commands for breakpoint(s) "
1309                               "%s, one per line."),
1310                             info->arg);
1311
1312           old_chain = make_cleanup (xfree, str);
1313
1314           l = read_command_lines (str,
1315                                   info->from_tty, 1,
1316                                   (is_tracepoint (b)
1317                                    ? check_tracepoint_command : 0),
1318                                   b);
1319
1320           do_cleanups (old_chain);
1321         }
1322
1323       info->cmd = alloc_counted_command_line (l);
1324     }
1325
1326   /* If a breakpoint was on the list more than once, we don't need to
1327      do anything.  */
1328   if (b->commands != info->cmd)
1329     {
1330       validate_commands_for_breakpoint (b, info->cmd->commands);
1331       incref_counted_command_line (info->cmd);
1332       decref_counted_command_line (&b->commands);
1333       b->commands = info->cmd;
1334       observer_notify_breakpoint_modified (b);
1335     }
1336 }
1337
1338 static void
1339 commands_command_1 (char *arg, int from_tty, 
1340                     struct command_line *control)
1341 {
1342   struct cleanup *cleanups;
1343   struct commands_info info;
1344
1345   info.from_tty = from_tty;
1346   info.control = control;
1347   info.cmd = NULL;
1348   /* If we read command lines from the user, then `info' will hold an
1349      extra reference to the commands that we must clean up.  */
1350   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1351
1352   if (arg == NULL || !*arg)
1353     {
1354       if (breakpoint_count - prev_breakpoint_count > 1)
1355         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1356                           breakpoint_count);
1357       else if (breakpoint_count > 0)
1358         arg = xstrprintf ("%d", breakpoint_count);
1359       else
1360         {
1361           /* So that we don't try to free the incoming non-NULL
1362              argument in the cleanup below.  Mapping breakpoint
1363              numbers will fail in this case.  */
1364           arg = NULL;
1365         }
1366     }
1367   else
1368     /* The command loop has some static state, so we need to preserve
1369        our argument.  */
1370     arg = xstrdup (arg);
1371
1372   if (arg != NULL)
1373     make_cleanup (xfree, arg);
1374
1375   info.arg = arg;
1376
1377   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1378
1379   if (info.cmd == NULL)
1380     error (_("No breakpoints specified."));
1381
1382   do_cleanups (cleanups);
1383 }
1384
1385 static void
1386 commands_command (char *arg, int from_tty)
1387 {
1388   commands_command_1 (arg, from_tty, NULL);
1389 }
1390
1391 /* Like commands_command, but instead of reading the commands from
1392    input stream, takes them from an already parsed command structure.
1393
1394    This is used by cli-script.c to DTRT with breakpoint commands
1395    that are part of if and while bodies.  */
1396 enum command_control_type
1397 commands_from_control_command (char *arg, struct command_line *cmd)
1398 {
1399   commands_command_1 (arg, 0, cmd);
1400   return simple_control;
1401 }
1402
1403 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1404
1405 static int
1406 bp_location_has_shadow (struct bp_location *bl)
1407 {
1408   if (bl->loc_type != bp_loc_software_breakpoint)
1409     return 0;
1410   if (!bl->inserted)
1411     return 0;
1412   if (bl->target_info.shadow_len == 0)
1413     /* BL isn't valid, or doesn't shadow memory.  */
1414     return 0;
1415   return 1;
1416 }
1417
1418 /* Update BUF, which is LEN bytes read from the target address
1419    MEMADDR, by replacing a memory breakpoint with its shadowed
1420    contents.
1421
1422    If READBUF is not NULL, this buffer must not overlap with the of
1423    the breakpoint location's shadow_contents buffer.  Otherwise, a
1424    failed assertion internal error will be raised.  */
1425
1426 static void
1427 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1428                             const gdb_byte *writebuf_org,
1429                             ULONGEST memaddr, LONGEST len,
1430                             struct bp_target_info *target_info,
1431                             struct gdbarch *gdbarch)
1432 {
1433   /* Now do full processing of the found relevant range of elements.  */
1434   CORE_ADDR bp_addr = 0;
1435   int bp_size = 0;
1436   int bptoffset = 0;
1437
1438   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1439                                  current_program_space->aspace, 0))
1440     {
1441       /* The breakpoint is inserted in a different address space.  */
1442       return;
1443     }
1444
1445   /* Addresses and length of the part of the breakpoint that
1446      we need to copy.  */
1447   bp_addr = target_info->placed_address;
1448   bp_size = target_info->shadow_len;
1449
1450   if (bp_addr + bp_size <= memaddr)
1451     {
1452       /* The breakpoint is entirely before the chunk of memory we are
1453          reading.  */
1454       return;
1455     }
1456
1457   if (bp_addr >= memaddr + len)
1458     {
1459       /* The breakpoint is entirely after the chunk of memory we are
1460          reading.  */
1461       return;
1462     }
1463
1464   /* Offset within shadow_contents.  */
1465   if (bp_addr < memaddr)
1466     {
1467       /* Only copy the second part of the breakpoint.  */
1468       bp_size -= memaddr - bp_addr;
1469       bptoffset = memaddr - bp_addr;
1470       bp_addr = memaddr;
1471     }
1472
1473   if (bp_addr + bp_size > memaddr + len)
1474     {
1475       /* Only copy the first part of the breakpoint.  */
1476       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1477     }
1478
1479   if (readbuf != NULL)
1480     {
1481       /* Verify that the readbuf buffer does not overlap with the
1482          shadow_contents buffer.  */
1483       gdb_assert (target_info->shadow_contents >= readbuf + len
1484                   || readbuf >= (target_info->shadow_contents
1485                                  + target_info->shadow_len));
1486
1487       /* Update the read buffer with this inserted breakpoint's
1488          shadow.  */
1489       memcpy (readbuf + bp_addr - memaddr,
1490               target_info->shadow_contents + bptoffset, bp_size);
1491     }
1492   else
1493     {
1494       const unsigned char *bp;
1495       CORE_ADDR placed_address = target_info->placed_address;
1496       int placed_size = target_info->placed_size;
1497
1498       /* Update the shadow with what we want to write to memory.  */
1499       memcpy (target_info->shadow_contents + bptoffset,
1500               writebuf_org + bp_addr - memaddr, bp_size);
1501
1502       /* Determine appropriate breakpoint contents and size for this
1503          address.  */
1504       bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1505
1506       /* Update the final write buffer with this inserted
1507          breakpoint's INSN.  */
1508       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1509     }
1510 }
1511
1512 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1513    by replacing any memory breakpoints with their shadowed contents.
1514
1515    If READBUF is not NULL, this buffer must not overlap with any of
1516    the breakpoint location's shadow_contents buffers.  Otherwise,
1517    a failed assertion internal error will be raised.
1518
1519    The range of shadowed area by each bp_location is:
1520      bl->address - bp_location_placed_address_before_address_max
1521      up to bl->address + bp_location_shadow_len_after_address_max
1522    The range we were requested to resolve shadows for is:
1523      memaddr ... memaddr + len
1524    Thus the safe cutoff boundaries for performance optimization are
1525      memaddr + len <= (bl->address
1526                        - bp_location_placed_address_before_address_max)
1527    and:
1528      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1529
1530 void
1531 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1532                         const gdb_byte *writebuf_org,
1533                         ULONGEST memaddr, LONGEST len)
1534 {
1535   /* Left boundary, right boundary and median element of our binary
1536      search.  */
1537   unsigned bc_l, bc_r, bc;
1538   size_t i;
1539
1540   /* Find BC_L which is a leftmost element which may affect BUF
1541      content.  It is safe to report lower value but a failure to
1542      report higher one.  */
1543
1544   bc_l = 0;
1545   bc_r = bp_location_count;
1546   while (bc_l + 1 < bc_r)
1547     {
1548       struct bp_location *bl;
1549
1550       bc = (bc_l + bc_r) / 2;
1551       bl = bp_location[bc];
1552
1553       /* Check first BL->ADDRESS will not overflow due to the added
1554          constant.  Then advance the left boundary only if we are sure
1555          the BC element can in no way affect the BUF content (MEMADDR
1556          to MEMADDR + LEN range).
1557
1558          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1559          offset so that we cannot miss a breakpoint with its shadow
1560          range tail still reaching MEMADDR.  */
1561
1562       if ((bl->address + bp_location_shadow_len_after_address_max
1563            >= bl->address)
1564           && (bl->address + bp_location_shadow_len_after_address_max
1565               <= memaddr))
1566         bc_l = bc;
1567       else
1568         bc_r = bc;
1569     }
1570
1571   /* Due to the binary search above, we need to make sure we pick the
1572      first location that's at BC_L's address.  E.g., if there are
1573      multiple locations at the same address, BC_L may end up pointing
1574      at a duplicate location, and miss the "master"/"inserted"
1575      location.  Say, given locations L1, L2 and L3 at addresses A and
1576      B:
1577
1578       L1@A, L2@A, L3@B, ...
1579
1580      BC_L could end up pointing at location L2, while the "master"
1581      location could be L1.  Since the `loc->inserted' flag is only set
1582      on "master" locations, we'd forget to restore the shadow of L1
1583      and L2.  */
1584   while (bc_l > 0
1585          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1586     bc_l--;
1587
1588   /* Now do full processing of the found relevant range of elements.  */
1589
1590   for (bc = bc_l; bc < bp_location_count; bc++)
1591   {
1592     struct bp_location *bl = bp_location[bc];
1593     CORE_ADDR bp_addr = 0;
1594     int bp_size = 0;
1595     int bptoffset = 0;
1596
1597     /* bp_location array has BL->OWNER always non-NULL.  */
1598     if (bl->owner->type == bp_none)
1599       warning (_("reading through apparently deleted breakpoint #%d?"),
1600                bl->owner->number);
1601
1602     /* Performance optimization: any further element can no longer affect BUF
1603        content.  */
1604
1605     if (bl->address >= bp_location_placed_address_before_address_max
1606         && memaddr + len <= (bl->address
1607                              - bp_location_placed_address_before_address_max))
1608       break;
1609
1610     if (!bp_location_has_shadow (bl))
1611       continue;
1612
1613     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1614                                 memaddr, len, &bl->target_info, bl->gdbarch);
1615   }
1616
1617   /* Now process single-step breakpoints.  These are not found in the
1618      bp_location array.  */
1619   for (i = 0; i < 2; i++)
1620     {
1621       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
1622
1623       if (bp_tgt != NULL)
1624         {
1625           struct gdbarch *gdbarch = single_step_gdbarch[i];
1626
1627           one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1628                                       memaddr, len, bp_tgt, gdbarch);
1629         }
1630     }
1631 }
1632
1633 \f
1634
1635 /* Return true if BPT is either a software breakpoint or a hardware
1636    breakpoint.  */
1637
1638 int
1639 is_breakpoint (const struct breakpoint *bpt)
1640 {
1641   return (bpt->type == bp_breakpoint
1642           || bpt->type == bp_hardware_breakpoint
1643           || bpt->type == bp_dprintf);
1644 }
1645
1646 /* Return true if BPT is of any hardware watchpoint kind.  */
1647
1648 static int
1649 is_hardware_watchpoint (const struct breakpoint *bpt)
1650 {
1651   return (bpt->type == bp_hardware_watchpoint
1652           || bpt->type == bp_read_watchpoint
1653           || bpt->type == bp_access_watchpoint);
1654 }
1655
1656 /* Return true if BPT is of any watchpoint kind, hardware or
1657    software.  */
1658
1659 int
1660 is_watchpoint (const struct breakpoint *bpt)
1661 {
1662   return (is_hardware_watchpoint (bpt)
1663           || bpt->type == bp_watchpoint);
1664 }
1665
1666 /* Returns true if the current thread and its running state are safe
1667    to evaluate or update watchpoint B.  Watchpoints on local
1668    expressions need to be evaluated in the context of the thread that
1669    was current when the watchpoint was created, and, that thread needs
1670    to be stopped to be able to select the correct frame context.
1671    Watchpoints on global expressions can be evaluated on any thread,
1672    and in any state.  It is presently left to the target allowing
1673    memory accesses when threads are running.  */
1674
1675 static int
1676 watchpoint_in_thread_scope (struct watchpoint *b)
1677 {
1678   return (b->base.pspace == current_program_space
1679           && (ptid_equal (b->watchpoint_thread, null_ptid)
1680               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1681                   && !is_executing (inferior_ptid))));
1682 }
1683
1684 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1685    associated bp_watchpoint_scope breakpoint.  */
1686
1687 static void
1688 watchpoint_del_at_next_stop (struct watchpoint *w)
1689 {
1690   struct breakpoint *b = &w->base;
1691
1692   if (b->related_breakpoint != b)
1693     {
1694       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1695       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1696       b->related_breakpoint->disposition = disp_del_at_next_stop;
1697       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1698       b->related_breakpoint = b;
1699     }
1700   b->disposition = disp_del_at_next_stop;
1701 }
1702
1703 /* Assuming that B is a watchpoint:
1704    - Reparse watchpoint expression, if REPARSE is non-zero
1705    - Evaluate expression and store the result in B->val
1706    - Evaluate the condition if there is one, and store the result
1707      in b->loc->cond.
1708    - Update the list of values that must be watched in B->loc.
1709
1710    If the watchpoint disposition is disp_del_at_next_stop, then do
1711    nothing.  If this is local watchpoint that is out of scope, delete
1712    it.
1713
1714    Even with `set breakpoint always-inserted on' the watchpoints are
1715    removed + inserted on each stop here.  Normal breakpoints must
1716    never be removed because they might be missed by a running thread
1717    when debugging in non-stop mode.  On the other hand, hardware
1718    watchpoints (is_hardware_watchpoint; processed here) are specific
1719    to each LWP since they are stored in each LWP's hardware debug
1720    registers.  Therefore, such LWP must be stopped first in order to
1721    be able to modify its hardware watchpoints.
1722
1723    Hardware watchpoints must be reset exactly once after being
1724    presented to the user.  It cannot be done sooner, because it would
1725    reset the data used to present the watchpoint hit to the user.  And
1726    it must not be done later because it could display the same single
1727    watchpoint hit during multiple GDB stops.  Note that the latter is
1728    relevant only to the hardware watchpoint types bp_read_watchpoint
1729    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1730    not user-visible - its hit is suppressed if the memory content has
1731    not changed.
1732
1733    The following constraints influence the location where we can reset
1734    hardware watchpoints:
1735
1736    * target_stopped_by_watchpoint and target_stopped_data_address are
1737      called several times when GDB stops.
1738
1739    [linux] 
1740    * Multiple hardware watchpoints can be hit at the same time,
1741      causing GDB to stop.  GDB only presents one hardware watchpoint
1742      hit at a time as the reason for stopping, and all the other hits
1743      are presented later, one after the other, each time the user
1744      requests the execution to be resumed.  Execution is not resumed
1745      for the threads still having pending hit event stored in
1746      LWP_INFO->STATUS.  While the watchpoint is already removed from
1747      the inferior on the first stop the thread hit event is kept being
1748      reported from its cached value by linux_nat_stopped_data_address
1749      until the real thread resume happens after the watchpoint gets
1750      presented and thus its LWP_INFO->STATUS gets reset.
1751
1752    Therefore the hardware watchpoint hit can get safely reset on the
1753    watchpoint removal from inferior.  */
1754
1755 static void
1756 update_watchpoint (struct watchpoint *b, int reparse)
1757 {
1758   int within_current_scope;
1759   struct frame_id saved_frame_id;
1760   int frame_saved;
1761
1762   /* If this is a local watchpoint, we only want to check if the
1763      watchpoint frame is in scope if the current thread is the thread
1764      that was used to create the watchpoint.  */
1765   if (!watchpoint_in_thread_scope (b))
1766     return;
1767
1768   if (b->base.disposition == disp_del_at_next_stop)
1769     return;
1770  
1771   frame_saved = 0;
1772
1773   /* Determine if the watchpoint is within scope.  */
1774   if (b->exp_valid_block == NULL)
1775     within_current_scope = 1;
1776   else
1777     {
1778       struct frame_info *fi = get_current_frame ();
1779       struct gdbarch *frame_arch = get_frame_arch (fi);
1780       CORE_ADDR frame_pc = get_frame_pc (fi);
1781
1782       /* If we're in a function epilogue, unwinding may not work
1783          properly, so do not attempt to recreate locations at this
1784          point.  See similar comments in watchpoint_check.  */
1785       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1786         return;
1787
1788       /* Save the current frame's ID so we can restore it after
1789          evaluating the watchpoint expression on its own frame.  */
1790       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1791          took a frame parameter, so that we didn't have to change the
1792          selected frame.  */
1793       frame_saved = 1;
1794       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1795
1796       fi = frame_find_by_id (b->watchpoint_frame);
1797       within_current_scope = (fi != NULL);
1798       if (within_current_scope)
1799         select_frame (fi);
1800     }
1801
1802   /* We don't free locations.  They are stored in the bp_location array
1803      and update_global_location_list will eventually delete them and
1804      remove breakpoints if needed.  */
1805   b->base.loc = NULL;
1806
1807   if (within_current_scope && reparse)
1808     {
1809       const char *s;
1810
1811       if (b->exp)
1812         {
1813           xfree (b->exp);
1814           b->exp = NULL;
1815         }
1816       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1817       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1818       /* If the meaning of expression itself changed, the old value is
1819          no longer relevant.  We don't want to report a watchpoint hit
1820          to the user when the old value and the new value may actually
1821          be completely different objects.  */
1822       value_free (b->val);
1823       b->val = NULL;
1824       b->val_valid = 0;
1825
1826       /* Note that unlike with breakpoints, the watchpoint's condition
1827          expression is stored in the breakpoint object, not in the
1828          locations (re)created below.  */
1829       if (b->base.cond_string != NULL)
1830         {
1831           if (b->cond_exp != NULL)
1832             {
1833               xfree (b->cond_exp);
1834               b->cond_exp = NULL;
1835             }
1836
1837           s = b->base.cond_string;
1838           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1839         }
1840     }
1841
1842   /* If we failed to parse the expression, for example because
1843      it refers to a global variable in a not-yet-loaded shared library,
1844      don't try to insert watchpoint.  We don't automatically delete
1845      such watchpoint, though, since failure to parse expression
1846      is different from out-of-scope watchpoint.  */
1847   if (!target_has_execution)
1848     {
1849       /* Without execution, memory can't change.  No use to try and
1850          set watchpoint locations.  The watchpoint will be reset when
1851          the target gains execution, through breakpoint_re_set.  */
1852       if (!can_use_hw_watchpoints)
1853         {
1854           if (b->base.ops->works_in_software_mode (&b->base))
1855             b->base.type = bp_watchpoint;
1856           else
1857             error (_("Can't set read/access watchpoint when "
1858                      "hardware watchpoints are disabled."));
1859         }
1860     }
1861   else if (within_current_scope && b->exp)
1862     {
1863       int pc = 0;
1864       struct value *val_chain, *v, *result, *next;
1865       struct program_space *frame_pspace;
1866
1867       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1868
1869       /* Avoid setting b->val if it's already set.  The meaning of
1870          b->val is 'the last value' user saw, and we should update
1871          it only if we reported that last value to user.  As it
1872          happens, the code that reports it updates b->val directly.
1873          We don't keep track of the memory value for masked
1874          watchpoints.  */
1875       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1876         {
1877           b->val = v;
1878           b->val_valid = 1;
1879         }
1880
1881       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1882
1883       /* Look at each value on the value chain.  */
1884       for (v = val_chain; v; v = value_next (v))
1885         {
1886           /* If it's a memory location, and GDB actually needed
1887              its contents to evaluate the expression, then we
1888              must watch it.  If the first value returned is
1889              still lazy, that means an error occurred reading it;
1890              watch it anyway in case it becomes readable.  */
1891           if (VALUE_LVAL (v) == lval_memory
1892               && (v == val_chain || ! value_lazy (v)))
1893             {
1894               struct type *vtype = check_typedef (value_type (v));
1895
1896               /* We only watch structs and arrays if user asked
1897                  for it explicitly, never if they just happen to
1898                  appear in the middle of some value chain.  */
1899               if (v == result
1900                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1901                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1902                 {
1903                   CORE_ADDR addr;
1904                   int type;
1905                   struct bp_location *loc, **tmp;
1906
1907                   addr = value_address (v);
1908                   type = hw_write;
1909                   if (b->base.type == bp_read_watchpoint)
1910                     type = hw_read;
1911                   else if (b->base.type == bp_access_watchpoint)
1912                     type = hw_access;
1913
1914                   loc = allocate_bp_location (&b->base);
1915                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1916                     ;
1917                   *tmp = loc;
1918                   loc->gdbarch = get_type_arch (value_type (v));
1919
1920                   loc->pspace = frame_pspace;
1921                   loc->address = addr;
1922                   loc->length = TYPE_LENGTH (value_type (v));
1923                   loc->watchpoint_type = type;
1924                 }
1925             }
1926         }
1927
1928       /* Change the type of breakpoint between hardware assisted or
1929          an ordinary watchpoint depending on the hardware support
1930          and free hardware slots.  REPARSE is set when the inferior
1931          is started.  */
1932       if (reparse)
1933         {
1934           int reg_cnt;
1935           enum bp_loc_type loc_type;
1936           struct bp_location *bl;
1937
1938           reg_cnt = can_use_hardware_watchpoint (val_chain);
1939
1940           if (reg_cnt)
1941             {
1942               int i, target_resources_ok, other_type_used;
1943               enum bptype type;
1944
1945               /* Use an exact watchpoint when there's only one memory region to be
1946                  watched, and only one debug register is needed to watch it.  */
1947               b->exact = target_exact_watchpoints && reg_cnt == 1;
1948
1949               /* We need to determine how many resources are already
1950                  used for all other hardware watchpoints plus this one
1951                  to see if we still have enough resources to also fit
1952                  this watchpoint in as well.  */
1953
1954               /* If this is a software watchpoint, we try to turn it
1955                  to a hardware one -- count resources as if B was of
1956                  hardware watchpoint type.  */
1957               type = b->base.type;
1958               if (type == bp_watchpoint)
1959                 type = bp_hardware_watchpoint;
1960
1961               /* This watchpoint may or may not have been placed on
1962                  the list yet at this point (it won't be in the list
1963                  if we're trying to create it for the first time,
1964                  through watch_command), so always account for it
1965                  manually.  */
1966
1967               /* Count resources used by all watchpoints except B.  */
1968               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1969
1970               /* Add in the resources needed for B.  */
1971               i += hw_watchpoint_use_count (&b->base);
1972
1973               target_resources_ok
1974                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1975               if (target_resources_ok <= 0)
1976                 {
1977                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1978
1979                   if (target_resources_ok == 0 && !sw_mode)
1980                     error (_("Target does not support this type of "
1981                              "hardware watchpoint."));
1982                   else if (target_resources_ok < 0 && !sw_mode)
1983                     error (_("There are not enough available hardware "
1984                              "resources for this watchpoint."));
1985
1986                   /* Downgrade to software watchpoint.  */
1987                   b->base.type = bp_watchpoint;
1988                 }
1989               else
1990                 {
1991                   /* If this was a software watchpoint, we've just
1992                      found we have enough resources to turn it to a
1993                      hardware watchpoint.  Otherwise, this is a
1994                      nop.  */
1995                   b->base.type = type;
1996                 }
1997             }
1998           else if (!b->base.ops->works_in_software_mode (&b->base))
1999             {
2000               if (!can_use_hw_watchpoints)
2001                 error (_("Can't set read/access watchpoint when "
2002                          "hardware watchpoints are disabled."));
2003               else
2004                 error (_("Expression cannot be implemented with "
2005                          "read/access watchpoint."));
2006             }
2007           else
2008             b->base.type = bp_watchpoint;
2009
2010           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2011                       : bp_loc_hardware_watchpoint);
2012           for (bl = b->base.loc; bl; bl = bl->next)
2013             bl->loc_type = loc_type;
2014         }
2015
2016       for (v = val_chain; v; v = next)
2017         {
2018           next = value_next (v);
2019           if (v != b->val)
2020             value_free (v);
2021         }
2022
2023       /* If a software watchpoint is not watching any memory, then the
2024          above left it without any location set up.  But,
2025          bpstat_stop_status requires a location to be able to report
2026          stops, so make sure there's at least a dummy one.  */
2027       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2028         {
2029           struct breakpoint *base = &b->base;
2030           base->loc = allocate_bp_location (base);
2031           base->loc->pspace = frame_pspace;
2032           base->loc->address = -1;
2033           base->loc->length = -1;
2034           base->loc->watchpoint_type = -1;
2035         }
2036     }
2037   else if (!within_current_scope)
2038     {
2039       printf_filtered (_("\
2040 Watchpoint %d deleted because the program has left the block\n\
2041 in which its expression is valid.\n"),
2042                        b->base.number);
2043       watchpoint_del_at_next_stop (b);
2044     }
2045
2046   /* Restore the selected frame.  */
2047   if (frame_saved)
2048     select_frame (frame_find_by_id (saved_frame_id));
2049 }
2050
2051
2052 /* Returns 1 iff breakpoint location should be
2053    inserted in the inferior.  We don't differentiate the type of BL's owner
2054    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2055    breakpoint_ops is not defined, because in insert_bp_location,
2056    tracepoint's insert_location will not be called.  */
2057 static int
2058 should_be_inserted (struct bp_location *bl)
2059 {
2060   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2061     return 0;
2062
2063   if (bl->owner->disposition == disp_del_at_next_stop)
2064     return 0;
2065
2066   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2067     return 0;
2068
2069   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2070     return 0;
2071
2072   /* This is set for example, when we're attached to the parent of a
2073      vfork, and have detached from the child.  The child is running
2074      free, and we expect it to do an exec or exit, at which point the
2075      OS makes the parent schedulable again (and the target reports
2076      that the vfork is done).  Until the child is done with the shared
2077      memory region, do not insert breakpoints in the parent, otherwise
2078      the child could still trip on the parent's breakpoints.  Since
2079      the parent is blocked anyway, it won't miss any breakpoint.  */
2080   if (bl->pspace->breakpoints_not_allowed)
2081     return 0;
2082
2083   /* Don't insert a breakpoint if we're trying to step past its
2084      location.  */
2085   if ((bl->loc_type == bp_loc_software_breakpoint
2086        || bl->loc_type == bp_loc_hardware_breakpoint)
2087       && stepping_past_instruction_at (bl->pspace->aspace,
2088                                        bl->address))
2089     return 0;
2090
2091   return 1;
2092 }
2093
2094 /* Same as should_be_inserted but does the check assuming
2095    that the location is not duplicated.  */
2096
2097 static int
2098 unduplicated_should_be_inserted (struct bp_location *bl)
2099 {
2100   int result;
2101   const int save_duplicate = bl->duplicate;
2102
2103   bl->duplicate = 0;
2104   result = should_be_inserted (bl);
2105   bl->duplicate = save_duplicate;
2106   return result;
2107 }
2108
2109 /* Parses a conditional described by an expression COND into an
2110    agent expression bytecode suitable for evaluation
2111    by the bytecode interpreter.  Return NULL if there was
2112    any error during parsing.  */
2113
2114 static struct agent_expr *
2115 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2116 {
2117   struct agent_expr *aexpr = NULL;
2118   volatile struct gdb_exception ex;
2119
2120   if (!cond)
2121     return NULL;
2122
2123   /* We don't want to stop processing, so catch any errors
2124      that may show up.  */
2125   TRY_CATCH (ex, RETURN_MASK_ERROR)
2126     {
2127       aexpr = gen_eval_for_expr (scope, cond);
2128     }
2129
2130   if (ex.reason < 0)
2131     {
2132       /* If we got here, it means the condition could not be parsed to a valid
2133          bytecode expression and thus can't be evaluated on the target's side.
2134          It's no use iterating through the conditions.  */
2135       return NULL;
2136     }
2137
2138   /* We have a valid agent expression.  */
2139   return aexpr;
2140 }
2141
2142 /* Based on location BL, create a list of breakpoint conditions to be
2143    passed on to the target.  If we have duplicated locations with different
2144    conditions, we will add such conditions to the list.  The idea is that the
2145    target will evaluate the list of conditions and will only notify GDB when
2146    one of them is true.  */
2147
2148 static void
2149 build_target_condition_list (struct bp_location *bl)
2150 {
2151   struct bp_location **locp = NULL, **loc2p;
2152   int null_condition_or_parse_error = 0;
2153   int modified = bl->needs_update;
2154   struct bp_location *loc;
2155
2156   /* Release conditions left over from a previous insert.  */
2157   VEC_free (agent_expr_p, bl->target_info.conditions);
2158
2159   /* This is only meaningful if the target is
2160      evaluating conditions and if the user has
2161      opted for condition evaluation on the target's
2162      side.  */
2163   if (gdb_evaluates_breakpoint_condition_p ()
2164       || !target_supports_evaluation_of_breakpoint_conditions ())
2165     return;
2166
2167   /* Do a first pass to check for locations with no assigned
2168      conditions or conditions that fail to parse to a valid agent expression
2169      bytecode.  If any of these happen, then it's no use to send conditions
2170      to the target since this location will always trigger and generate a
2171      response back to GDB.  */
2172   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2173     {
2174       loc = (*loc2p);
2175       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2176         {
2177           if (modified)
2178             {
2179               struct agent_expr *aexpr;
2180
2181               /* Re-parse the conditions since something changed.  In that
2182                  case we already freed the condition bytecodes (see
2183                  force_breakpoint_reinsertion).  We just
2184                  need to parse the condition to bytecodes again.  */
2185               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2186               loc->cond_bytecode = aexpr;
2187
2188               /* Check if we managed to parse the conditional expression
2189                  correctly.  If not, we will not send this condition
2190                  to the target.  */
2191               if (aexpr)
2192                 continue;
2193             }
2194
2195           /* If we have a NULL bytecode expression, it means something
2196              went wrong or we have a null condition expression.  */
2197           if (!loc->cond_bytecode)
2198             {
2199               null_condition_or_parse_error = 1;
2200               break;
2201             }
2202         }
2203     }
2204
2205   /* If any of these happened, it means we will have to evaluate the conditions
2206      for the location's address on gdb's side.  It is no use keeping bytecodes
2207      for all the other duplicate locations, thus we free all of them here.
2208
2209      This is so we have a finer control over which locations' conditions are
2210      being evaluated by GDB or the remote stub.  */
2211   if (null_condition_or_parse_error)
2212     {
2213       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2214         {
2215           loc = (*loc2p);
2216           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2217             {
2218               /* Only go as far as the first NULL bytecode is
2219                  located.  */
2220               if (!loc->cond_bytecode)
2221                 return;
2222
2223               free_agent_expr (loc->cond_bytecode);
2224               loc->cond_bytecode = NULL;
2225             }
2226         }
2227     }
2228
2229   /* No NULL conditions or failed bytecode generation.  Build a condition list
2230      for this location's address.  */
2231   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2232     {
2233       loc = (*loc2p);
2234       if (loc->cond
2235           && is_breakpoint (loc->owner)
2236           && loc->pspace->num == bl->pspace->num
2237           && loc->owner->enable_state == bp_enabled
2238           && loc->enabled)
2239         /* Add the condition to the vector.  This will be used later to send the
2240            conditions to the target.  */
2241         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2242                        loc->cond_bytecode);
2243     }
2244
2245   return;
2246 }
2247
2248 /* Parses a command described by string CMD into an agent expression
2249    bytecode suitable for evaluation by the bytecode interpreter.
2250    Return NULL if there was any error during parsing.  */
2251
2252 static struct agent_expr *
2253 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2254 {
2255   struct cleanup *old_cleanups = 0;
2256   struct expression *expr, **argvec;
2257   struct agent_expr *aexpr = NULL;
2258   volatile struct gdb_exception ex;
2259   const char *cmdrest;
2260   const char *format_start, *format_end;
2261   struct format_piece *fpieces;
2262   int nargs;
2263   struct gdbarch *gdbarch = get_current_arch ();
2264
2265   if (!cmd)
2266     return NULL;
2267
2268   cmdrest = cmd;
2269
2270   if (*cmdrest == ',')
2271     ++cmdrest;
2272   cmdrest = skip_spaces_const (cmdrest);
2273
2274   if (*cmdrest++ != '"')
2275     error (_("No format string following the location"));
2276
2277   format_start = cmdrest;
2278
2279   fpieces = parse_format_string (&cmdrest);
2280
2281   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2282
2283   format_end = cmdrest;
2284
2285   if (*cmdrest++ != '"')
2286     error (_("Bad format string, non-terminated '\"'."));
2287   
2288   cmdrest = skip_spaces_const (cmdrest);
2289
2290   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2291     error (_("Invalid argument syntax"));
2292
2293   if (*cmdrest == ',')
2294     cmdrest++;
2295   cmdrest = skip_spaces_const (cmdrest);
2296
2297   /* For each argument, make an expression.  */
2298
2299   argvec = (struct expression **) alloca (strlen (cmd)
2300                                          * sizeof (struct expression *));
2301
2302   nargs = 0;
2303   while (*cmdrest != '\0')
2304     {
2305       const char *cmd1;
2306
2307       cmd1 = cmdrest;
2308       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2309       argvec[nargs++] = expr;
2310       cmdrest = cmd1;
2311       if (*cmdrest == ',')
2312         ++cmdrest;
2313     }
2314
2315   /* We don't want to stop processing, so catch any errors
2316      that may show up.  */
2317   TRY_CATCH (ex, RETURN_MASK_ERROR)
2318     {
2319       aexpr = gen_printf (scope, gdbarch, 0, 0,
2320                           format_start, format_end - format_start,
2321                           fpieces, nargs, argvec);
2322     }
2323
2324   do_cleanups (old_cleanups);
2325
2326   if (ex.reason < 0)
2327     {
2328       /* If we got here, it means the command could not be parsed to a valid
2329          bytecode expression and thus can't be evaluated on the target's side.
2330          It's no use iterating through the other commands.  */
2331       return NULL;
2332     }
2333
2334   /* We have a valid agent expression, return it.  */
2335   return aexpr;
2336 }
2337
2338 /* Based on location BL, create a list of breakpoint commands to be
2339    passed on to the target.  If we have duplicated locations with
2340    different commands, we will add any such to the list.  */
2341
2342 static void
2343 build_target_command_list (struct bp_location *bl)
2344 {
2345   struct bp_location **locp = NULL, **loc2p;
2346   int null_command_or_parse_error = 0;
2347   int modified = bl->needs_update;
2348   struct bp_location *loc;
2349
2350   /* Release commands left over from a previous insert.  */
2351   VEC_free (agent_expr_p, bl->target_info.tcommands);
2352
2353   /* For now, limit to agent-style dprintf breakpoints.  */
2354   if (bl->owner->type != bp_dprintf
2355       || strcmp (dprintf_style, dprintf_style_agent) != 0)
2356     return;
2357
2358   if (!target_can_run_breakpoint_commands ())
2359     return;
2360
2361   /* Do a first pass to check for locations with no assigned
2362      conditions or conditions that fail to parse to a valid agent expression
2363      bytecode.  If any of these happen, then it's no use to send conditions
2364      to the target since this location will always trigger and generate a
2365      response back to GDB.  */
2366   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2367     {
2368       loc = (*loc2p);
2369       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2370         {
2371           if (modified)
2372             {
2373               struct agent_expr *aexpr;
2374
2375               /* Re-parse the commands since something changed.  In that
2376                  case we already freed the command bytecodes (see
2377                  force_breakpoint_reinsertion).  We just
2378                  need to parse the command to bytecodes again.  */
2379               aexpr = parse_cmd_to_aexpr (bl->address,
2380                                           loc->owner->extra_string);
2381               loc->cmd_bytecode = aexpr;
2382
2383               if (!aexpr)
2384                 continue;
2385             }
2386
2387           /* If we have a NULL bytecode expression, it means something
2388              went wrong or we have a null command expression.  */
2389           if (!loc->cmd_bytecode)
2390             {
2391               null_command_or_parse_error = 1;
2392               break;
2393             }
2394         }
2395     }
2396
2397   /* If anything failed, then we're not doing target-side commands,
2398      and so clean up.  */
2399   if (null_command_or_parse_error)
2400     {
2401       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2402         {
2403           loc = (*loc2p);
2404           if (is_breakpoint (loc->owner)
2405               && loc->pspace->num == bl->pspace->num)
2406             {
2407               /* Only go as far as the first NULL bytecode is
2408                  located.  */
2409               if (loc->cmd_bytecode == NULL)
2410                 return;
2411
2412               free_agent_expr (loc->cmd_bytecode);
2413               loc->cmd_bytecode = NULL;
2414             }
2415         }
2416     }
2417
2418   /* No NULL commands or failed bytecode generation.  Build a command list
2419      for this location's address.  */
2420   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2421     {
2422       loc = (*loc2p);
2423       if (loc->owner->extra_string
2424           && is_breakpoint (loc->owner)
2425           && loc->pspace->num == bl->pspace->num
2426           && loc->owner->enable_state == bp_enabled
2427           && loc->enabled)
2428         /* Add the command to the vector.  This will be used later
2429            to send the commands to the target.  */
2430         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2431                        loc->cmd_bytecode);
2432     }
2433
2434   bl->target_info.persist = 0;
2435   /* Maybe flag this location as persistent.  */
2436   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2437     bl->target_info.persist = 1;
2438 }
2439
2440 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2441    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2442    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2443    Returns 0 for success, 1 if the bp_location type is not supported or
2444    -1 for failure.
2445
2446    NOTE drow/2003-09-09: This routine could be broken down to an
2447    object-style method for each breakpoint or catchpoint type.  */
2448 static int
2449 insert_bp_location (struct bp_location *bl,
2450                     struct ui_file *tmp_error_stream,
2451                     int *disabled_breaks,
2452                     int *hw_breakpoint_error,
2453                     int *hw_bp_error_explained_already)
2454 {
2455   enum errors bp_err = GDB_NO_ERROR;
2456   const char *bp_err_message = NULL;
2457   volatile struct gdb_exception e;
2458
2459   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2460     return 0;
2461
2462   /* Note we don't initialize bl->target_info, as that wipes out
2463      the breakpoint location's shadow_contents if the breakpoint
2464      is still inserted at that location.  This in turn breaks
2465      target_read_memory which depends on these buffers when
2466      a memory read is requested at the breakpoint location:
2467      Once the target_info has been wiped, we fail to see that
2468      we have a breakpoint inserted at that address and thus
2469      read the breakpoint instead of returning the data saved in
2470      the breakpoint location's shadow contents.  */
2471   bl->target_info.placed_address = bl->address;
2472   bl->target_info.placed_address_space = bl->pspace->aspace;
2473   bl->target_info.length = bl->length;
2474
2475   /* When working with target-side conditions, we must pass all the conditions
2476      for the same breakpoint address down to the target since GDB will not
2477      insert those locations.  With a list of breakpoint conditions, the target
2478      can decide when to stop and notify GDB.  */
2479
2480   if (is_breakpoint (bl->owner))
2481     {
2482       build_target_condition_list (bl);
2483       build_target_command_list (bl);
2484       /* Reset the modification marker.  */
2485       bl->needs_update = 0;
2486     }
2487
2488   if (bl->loc_type == bp_loc_software_breakpoint
2489       || bl->loc_type == bp_loc_hardware_breakpoint)
2490     {
2491       if (bl->owner->type != bp_hardware_breakpoint)
2492         {
2493           /* If the explicitly specified breakpoint type
2494              is not hardware breakpoint, check the memory map to see
2495              if the breakpoint address is in read only memory or not.
2496
2497              Two important cases are:
2498              - location type is not hardware breakpoint, memory
2499              is readonly.  We change the type of the location to
2500              hardware breakpoint.
2501              - location type is hardware breakpoint, memory is
2502              read-write.  This means we've previously made the
2503              location hardware one, but then the memory map changed,
2504              so we undo.
2505              
2506              When breakpoints are removed, remove_breakpoints will use
2507              location types we've just set here, the only possible
2508              problem is that memory map has changed during running
2509              program, but it's not going to work anyway with current
2510              gdb.  */
2511           struct mem_region *mr 
2512             = lookup_mem_region (bl->target_info.placed_address);
2513           
2514           if (mr)
2515             {
2516               if (automatic_hardware_breakpoints)
2517                 {
2518                   enum bp_loc_type new_type;
2519                   
2520                   if (mr->attrib.mode != MEM_RW)
2521                     new_type = bp_loc_hardware_breakpoint;
2522                   else 
2523                     new_type = bp_loc_software_breakpoint;
2524                   
2525                   if (new_type != bl->loc_type)
2526                     {
2527                       static int said = 0;
2528
2529                       bl->loc_type = new_type;
2530                       if (!said)
2531                         {
2532                           fprintf_filtered (gdb_stdout,
2533                                             _("Note: automatically using "
2534                                               "hardware breakpoints for "
2535                                               "read-only addresses.\n"));
2536                           said = 1;
2537                         }
2538                     }
2539                 }
2540               else if (bl->loc_type == bp_loc_software_breakpoint
2541                        && mr->attrib.mode != MEM_RW)        
2542                 warning (_("cannot set software breakpoint "
2543                            "at readonly address %s"),
2544                          paddress (bl->gdbarch, bl->address));
2545             }
2546         }
2547         
2548       /* First check to see if we have to handle an overlay.  */
2549       if (overlay_debugging == ovly_off
2550           || bl->section == NULL
2551           || !(section_is_overlay (bl->section)))
2552         {
2553           /* No overlay handling: just set the breakpoint.  */
2554           TRY_CATCH (e, RETURN_MASK_ALL)
2555             {
2556               int val;
2557
2558               val = bl->owner->ops->insert_location (bl);
2559               if (val)
2560                 bp_err = GENERIC_ERROR;
2561             }
2562           if (e.reason < 0)
2563             {
2564               bp_err = e.error;
2565               bp_err_message = e.message;
2566             }
2567         }
2568       else
2569         {
2570           /* This breakpoint is in an overlay section.
2571              Shall we set a breakpoint at the LMA?  */
2572           if (!overlay_events_enabled)
2573             {
2574               /* Yes -- overlay event support is not active, 
2575                  so we must try to set a breakpoint at the LMA.
2576                  This will not work for a hardware breakpoint.  */
2577               if (bl->loc_type == bp_loc_hardware_breakpoint)
2578                 warning (_("hardware breakpoint %d not supported in overlay!"),
2579                          bl->owner->number);
2580               else
2581                 {
2582                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2583                                                              bl->section);
2584                   /* Set a software (trap) breakpoint at the LMA.  */
2585                   bl->overlay_target_info = bl->target_info;
2586                   bl->overlay_target_info.placed_address = addr;
2587
2588                   /* No overlay handling: just set the breakpoint.  */
2589                   TRY_CATCH (e, RETURN_MASK_ALL)
2590                     {
2591                       int val;
2592
2593                       val = target_insert_breakpoint (bl->gdbarch,
2594                                                       &bl->overlay_target_info);
2595                       if (val)
2596                         bp_err = GENERIC_ERROR;
2597                     }
2598                   if (e.reason < 0)
2599                     {
2600                       bp_err = e.error;
2601                       bp_err_message = e.message;
2602                     }
2603
2604                   if (bp_err != GDB_NO_ERROR)
2605                     fprintf_unfiltered (tmp_error_stream,
2606                                         "Overlay breakpoint %d "
2607                                         "failed: in ROM?\n",
2608                                         bl->owner->number);
2609                 }
2610             }
2611           /* Shall we set a breakpoint at the VMA? */
2612           if (section_is_mapped (bl->section))
2613             {
2614               /* Yes.  This overlay section is mapped into memory.  */
2615               TRY_CATCH (e, RETURN_MASK_ALL)
2616                 {
2617                   int val;
2618
2619                   val = bl->owner->ops->insert_location (bl);
2620                   if (val)
2621                     bp_err = GENERIC_ERROR;
2622                 }
2623               if (e.reason < 0)
2624                 {
2625                   bp_err = e.error;
2626                   bp_err_message = e.message;
2627                 }
2628             }
2629           else
2630             {
2631               /* No.  This breakpoint will not be inserted.  
2632                  No error, but do not mark the bp as 'inserted'.  */
2633               return 0;
2634             }
2635         }
2636
2637       if (bp_err != GDB_NO_ERROR)
2638         {
2639           /* Can't set the breakpoint.  */
2640
2641           /* In some cases, we might not be able to insert a
2642              breakpoint in a shared library that has already been
2643              removed, but we have not yet processed the shlib unload
2644              event.  Unfortunately, some targets that implement
2645              breakpoint insertion themselves (necessary if this is a
2646              HW breakpoint, but SW breakpoints likewise) can't tell
2647              why the breakpoint insertion failed (e.g., the remote
2648              target doesn't define error codes), so we must treat
2649              generic errors as memory errors.  */
2650           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2651               && solib_name_from_address (bl->pspace, bl->address))
2652             {
2653               /* See also: disable_breakpoints_in_shlibs.  */
2654               bl->shlib_disabled = 1;
2655               observer_notify_breakpoint_modified (bl->owner);
2656               if (!*disabled_breaks)
2657                 {
2658                   fprintf_unfiltered (tmp_error_stream, 
2659                                       "Cannot insert breakpoint %d.\n", 
2660                                       bl->owner->number);
2661                   fprintf_unfiltered (tmp_error_stream, 
2662                                       "Temporarily disabling shared "
2663                                       "library breakpoints:\n");
2664                 }
2665               *disabled_breaks = 1;
2666               fprintf_unfiltered (tmp_error_stream,
2667                                   "breakpoint #%d\n", bl->owner->number);
2668               return 0;
2669             }
2670           else
2671             {
2672               if (bl->loc_type == bp_loc_hardware_breakpoint)
2673                 {
2674                   *hw_breakpoint_error = 1;
2675                   *hw_bp_error_explained_already = bp_err_message != NULL;
2676                   fprintf_unfiltered (tmp_error_stream,
2677                                       "Cannot insert hardware breakpoint %d%s",
2678                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2679                   if (bp_err_message != NULL)
2680                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2681                 }
2682               else
2683                 {
2684                   if (bp_err_message == NULL)
2685                     {
2686                       char *message
2687                         = memory_error_message (TARGET_XFER_E_IO,
2688                                                 bl->gdbarch, bl->address);
2689                       struct cleanup *old_chain = make_cleanup (xfree, message);
2690
2691                       fprintf_unfiltered (tmp_error_stream,
2692                                           "Cannot insert breakpoint %d.\n"
2693                                           "%s\n",
2694                                           bl->owner->number, message);
2695                       do_cleanups (old_chain);
2696                     }
2697                   else
2698                     {
2699                       fprintf_unfiltered (tmp_error_stream,
2700                                           "Cannot insert breakpoint %d: %s\n",
2701                                           bl->owner->number,
2702                                           bp_err_message);
2703                     }
2704                 }
2705               return 1;
2706
2707             }
2708         }
2709       else
2710         bl->inserted = 1;
2711
2712       return 0;
2713     }
2714
2715   else if (bl->loc_type == bp_loc_hardware_watchpoint
2716            /* NOTE drow/2003-09-08: This state only exists for removing
2717               watchpoints.  It's not clear that it's necessary...  */
2718            && bl->owner->disposition != disp_del_at_next_stop)
2719     {
2720       int val;
2721
2722       gdb_assert (bl->owner->ops != NULL
2723                   && bl->owner->ops->insert_location != NULL);
2724
2725       val = bl->owner->ops->insert_location (bl);
2726
2727       /* If trying to set a read-watchpoint, and it turns out it's not
2728          supported, try emulating one with an access watchpoint.  */
2729       if (val == 1 && bl->watchpoint_type == hw_read)
2730         {
2731           struct bp_location *loc, **loc_temp;
2732
2733           /* But don't try to insert it, if there's already another
2734              hw_access location that would be considered a duplicate
2735              of this one.  */
2736           ALL_BP_LOCATIONS (loc, loc_temp)
2737             if (loc != bl
2738                 && loc->watchpoint_type == hw_access
2739                 && watchpoint_locations_match (bl, loc))
2740               {
2741                 bl->duplicate = 1;
2742                 bl->inserted = 1;
2743                 bl->target_info = loc->target_info;
2744                 bl->watchpoint_type = hw_access;
2745                 val = 0;
2746                 break;
2747               }
2748
2749           if (val == 1)
2750             {
2751               bl->watchpoint_type = hw_access;
2752               val = bl->owner->ops->insert_location (bl);
2753
2754               if (val)
2755                 /* Back to the original value.  */
2756                 bl->watchpoint_type = hw_read;
2757             }
2758         }
2759
2760       bl->inserted = (val == 0);
2761     }
2762
2763   else if (bl->owner->type == bp_catchpoint)
2764     {
2765       int val;
2766
2767       gdb_assert (bl->owner->ops != NULL
2768                   && bl->owner->ops->insert_location != NULL);
2769
2770       val = bl->owner->ops->insert_location (bl);
2771       if (val)
2772         {
2773           bl->owner->enable_state = bp_disabled;
2774
2775           if (val == 1)
2776             warning (_("\
2777 Error inserting catchpoint %d: Your system does not support this type\n\
2778 of catchpoint."), bl->owner->number);
2779           else
2780             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2781         }
2782
2783       bl->inserted = (val == 0);
2784
2785       /* We've already printed an error message if there was a problem
2786          inserting this catchpoint, and we've disabled the catchpoint,
2787          so just return success.  */
2788       return 0;
2789     }
2790
2791   return 0;
2792 }
2793
2794 /* This function is called when program space PSPACE is about to be
2795    deleted.  It takes care of updating breakpoints to not reference
2796    PSPACE anymore.  */
2797
2798 void
2799 breakpoint_program_space_exit (struct program_space *pspace)
2800 {
2801   struct breakpoint *b, *b_temp;
2802   struct bp_location *loc, **loc_temp;
2803
2804   /* Remove any breakpoint that was set through this program space.  */
2805   ALL_BREAKPOINTS_SAFE (b, b_temp)
2806     {
2807       if (b->pspace == pspace)
2808         delete_breakpoint (b);
2809     }
2810
2811   /* Breakpoints set through other program spaces could have locations
2812      bound to PSPACE as well.  Remove those.  */
2813   ALL_BP_LOCATIONS (loc, loc_temp)
2814     {
2815       struct bp_location *tmp;
2816
2817       if (loc->pspace == pspace)
2818         {
2819           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2820           if (loc->owner->loc == loc)
2821             loc->owner->loc = loc->next;
2822           else
2823             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2824               if (tmp->next == loc)
2825                 {
2826                   tmp->next = loc->next;
2827                   break;
2828                 }
2829         }
2830     }
2831
2832   /* Now update the global location list to permanently delete the
2833      removed locations above.  */
2834   update_global_location_list (0);
2835 }
2836
2837 /* Make sure all breakpoints are inserted in inferior.
2838    Throws exception on any error.
2839    A breakpoint that is already inserted won't be inserted
2840    again, so calling this function twice is safe.  */
2841 void
2842 insert_breakpoints (void)
2843 {
2844   struct breakpoint *bpt;
2845
2846   ALL_BREAKPOINTS (bpt)
2847     if (is_hardware_watchpoint (bpt))
2848       {
2849         struct watchpoint *w = (struct watchpoint *) bpt;
2850
2851         update_watchpoint (w, 0 /* don't reparse.  */);
2852       }
2853
2854   update_global_location_list (1);
2855
2856   /* update_global_location_list does not insert breakpoints when
2857      always_inserted_mode is not enabled.  Explicitly insert them
2858      now.  */
2859   if (!breakpoints_always_inserted_mode ())
2860     insert_breakpoint_locations ();
2861 }
2862
2863 /* Invoke CALLBACK for each of bp_location.  */
2864
2865 void
2866 iterate_over_bp_locations (walk_bp_location_callback callback)
2867 {
2868   struct bp_location *loc, **loc_tmp;
2869
2870   ALL_BP_LOCATIONS (loc, loc_tmp)
2871     {
2872       callback (loc, NULL);
2873     }
2874 }
2875
2876 /* This is used when we need to synch breakpoint conditions between GDB and the
2877    target.  It is the case with deleting and disabling of breakpoints when using
2878    always-inserted mode.  */
2879
2880 static void
2881 update_inserted_breakpoint_locations (void)
2882 {
2883   struct bp_location *bl, **blp_tmp;
2884   int error_flag = 0;
2885   int val = 0;
2886   int disabled_breaks = 0;
2887   int hw_breakpoint_error = 0;
2888   int hw_bp_details_reported = 0;
2889
2890   struct ui_file *tmp_error_stream = mem_fileopen ();
2891   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2892
2893   /* Explicitly mark the warning -- this will only be printed if
2894      there was an error.  */
2895   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2896
2897   save_current_space_and_thread ();
2898
2899   ALL_BP_LOCATIONS (bl, blp_tmp)
2900     {
2901       /* We only want to update software breakpoints and hardware
2902          breakpoints.  */
2903       if (!is_breakpoint (bl->owner))
2904         continue;
2905
2906       /* We only want to update locations that are already inserted
2907          and need updating.  This is to avoid unwanted insertion during
2908          deletion of breakpoints.  */
2909       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2910         continue;
2911
2912       switch_to_program_space_and_thread (bl->pspace);
2913
2914       /* For targets that support global breakpoints, there's no need
2915          to select an inferior to insert breakpoint to.  In fact, even
2916          if we aren't attached to any process yet, we should still
2917          insert breakpoints.  */
2918       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2919           && ptid_equal (inferior_ptid, null_ptid))
2920         continue;
2921
2922       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2923                                     &hw_breakpoint_error, &hw_bp_details_reported);
2924       if (val)
2925         error_flag = val;
2926     }
2927
2928   if (error_flag)
2929     {
2930       target_terminal_ours_for_output ();
2931       error_stream (tmp_error_stream);
2932     }
2933
2934   do_cleanups (cleanups);
2935 }
2936
2937 /* Used when starting or continuing the program.  */
2938
2939 static void
2940 insert_breakpoint_locations (void)
2941 {
2942   struct breakpoint *bpt;
2943   struct bp_location *bl, **blp_tmp;
2944   int error_flag = 0;
2945   int val = 0;
2946   int disabled_breaks = 0;
2947   int hw_breakpoint_error = 0;
2948   int hw_bp_error_explained_already = 0;
2949
2950   struct ui_file *tmp_error_stream = mem_fileopen ();
2951   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2952   
2953   /* Explicitly mark the warning -- this will only be printed if
2954      there was an error.  */
2955   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2956
2957   save_current_space_and_thread ();
2958
2959   ALL_BP_LOCATIONS (bl, blp_tmp)
2960     {
2961       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2962         continue;
2963
2964       /* There is no point inserting thread-specific breakpoints if
2965          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2966          has BL->OWNER always non-NULL.  */
2967       if (bl->owner->thread != -1
2968           && !valid_thread_id (bl->owner->thread))
2969         continue;
2970
2971       switch_to_program_space_and_thread (bl->pspace);
2972
2973       /* For targets that support global breakpoints, there's no need
2974          to select an inferior to insert breakpoint to.  In fact, even
2975          if we aren't attached to any process yet, we should still
2976          insert breakpoints.  */
2977       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
2978           && ptid_equal (inferior_ptid, null_ptid))
2979         continue;
2980
2981       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2982                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
2983       if (val)
2984         error_flag = val;
2985     }
2986
2987   /* If we failed to insert all locations of a watchpoint, remove
2988      them, as half-inserted watchpoint is of limited use.  */
2989   ALL_BREAKPOINTS (bpt)  
2990     {
2991       int some_failed = 0;
2992       struct bp_location *loc;
2993
2994       if (!is_hardware_watchpoint (bpt))
2995         continue;
2996
2997       if (!breakpoint_enabled (bpt))
2998         continue;
2999
3000       if (bpt->disposition == disp_del_at_next_stop)
3001         continue;
3002       
3003       for (loc = bpt->loc; loc; loc = loc->next)
3004         if (!loc->inserted && should_be_inserted (loc))
3005           {
3006             some_failed = 1;
3007             break;
3008           }
3009       if (some_failed)
3010         {
3011           for (loc = bpt->loc; loc; loc = loc->next)
3012             if (loc->inserted)
3013               remove_breakpoint (loc, mark_uninserted);
3014
3015           hw_breakpoint_error = 1;
3016           fprintf_unfiltered (tmp_error_stream,
3017                               "Could not insert hardware watchpoint %d.\n", 
3018                               bpt->number);
3019           error_flag = -1;
3020         }
3021     }
3022
3023   if (error_flag)
3024     {
3025       /* If a hardware breakpoint or watchpoint was inserted, add a
3026          message about possibly exhausted resources.  */
3027       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3028         {
3029           fprintf_unfiltered (tmp_error_stream, 
3030                               "Could not insert hardware breakpoints:\n\
3031 You may have requested too many hardware breakpoints/watchpoints.\n");
3032         }
3033       target_terminal_ours_for_output ();
3034       error_stream (tmp_error_stream);
3035     }
3036
3037   do_cleanups (cleanups);
3038 }
3039
3040 /* Used when the program stops.
3041    Returns zero if successful, or non-zero if there was a problem
3042    removing a breakpoint location.  */
3043
3044 int
3045 remove_breakpoints (void)
3046 {
3047   struct bp_location *bl, **blp_tmp;
3048   int val = 0;
3049
3050   ALL_BP_LOCATIONS (bl, blp_tmp)
3051   {
3052     if (bl->inserted && !is_tracepoint (bl->owner))
3053       val |= remove_breakpoint (bl, mark_uninserted);
3054   }
3055   return val;
3056 }
3057
3058 /* When a thread exits, remove breakpoints that are related to
3059    that thread.  */
3060
3061 static void
3062 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3063 {
3064   struct breakpoint *b, *b_tmp;
3065
3066   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3067     {
3068       if (b->thread == tp->num && user_breakpoint_p (b))
3069         {
3070           b->disposition = disp_del_at_next_stop;
3071
3072           printf_filtered (_("\
3073 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3074                           b->number, tp->num);
3075
3076           /* Hide it from the user.  */
3077           b->number = 0;
3078        }
3079     }
3080 }
3081
3082 /* Remove breakpoints of process PID.  */
3083
3084 int
3085 remove_breakpoints_pid (int pid)
3086 {
3087   struct bp_location *bl, **blp_tmp;
3088   int val;
3089   struct inferior *inf = find_inferior_pid (pid);
3090
3091   ALL_BP_LOCATIONS (bl, blp_tmp)
3092   {
3093     if (bl->pspace != inf->pspace)
3094       continue;
3095
3096     if (bl->owner->type == bp_dprintf)
3097       continue;
3098
3099     if (bl->inserted)
3100       {
3101         val = remove_breakpoint (bl, mark_uninserted);
3102         if (val != 0)
3103           return val;
3104       }
3105   }
3106   return 0;
3107 }
3108
3109 int
3110 reattach_breakpoints (int pid)
3111 {
3112   struct cleanup *old_chain;
3113   struct bp_location *bl, **blp_tmp;
3114   int val;
3115   struct ui_file *tmp_error_stream;
3116   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3117   struct inferior *inf;
3118   struct thread_info *tp;
3119
3120   tp = any_live_thread_of_process (pid);
3121   if (tp == NULL)
3122     return 1;
3123
3124   inf = find_inferior_pid (pid);
3125   old_chain = save_inferior_ptid ();
3126
3127   inferior_ptid = tp->ptid;
3128
3129   tmp_error_stream = mem_fileopen ();
3130   make_cleanup_ui_file_delete (tmp_error_stream);
3131
3132   ALL_BP_LOCATIONS (bl, blp_tmp)
3133   {
3134     if (bl->pspace != inf->pspace)
3135       continue;
3136
3137     if (bl->inserted)
3138       {
3139         bl->inserted = 0;
3140         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3141         if (val != 0)
3142           {
3143             do_cleanups (old_chain);
3144             return val;
3145           }
3146       }
3147   }
3148   do_cleanups (old_chain);
3149   return 0;
3150 }
3151
3152 static int internal_breakpoint_number = -1;
3153
3154 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3155    If INTERNAL is non-zero, the breakpoint number will be populated
3156    from internal_breakpoint_number and that variable decremented.
3157    Otherwise the breakpoint number will be populated from
3158    breakpoint_count and that value incremented.  Internal breakpoints
3159    do not set the internal var bpnum.  */
3160 static void
3161 set_breakpoint_number (int internal, struct breakpoint *b)
3162 {
3163   if (internal)
3164     b->number = internal_breakpoint_number--;
3165   else
3166     {
3167       set_breakpoint_count (breakpoint_count + 1);
3168       b->number = breakpoint_count;
3169     }
3170 }
3171
3172 static struct breakpoint *
3173 create_internal_breakpoint (struct gdbarch *gdbarch,
3174                             CORE_ADDR address, enum bptype type,
3175                             const struct breakpoint_ops *ops)
3176 {
3177   struct symtab_and_line sal;
3178   struct breakpoint *b;
3179
3180   init_sal (&sal);              /* Initialize to zeroes.  */
3181
3182   sal.pc = address;
3183   sal.section = find_pc_overlay (sal.pc);
3184   sal.pspace = current_program_space;
3185
3186   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3187   b->number = internal_breakpoint_number--;
3188   b->disposition = disp_donttouch;
3189
3190   return b;
3191 }
3192
3193 static const char *const longjmp_names[] =
3194   {
3195     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3196   };
3197 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3198
3199 /* Per-objfile data private to breakpoint.c.  */
3200 struct breakpoint_objfile_data
3201 {
3202   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3203   struct bound_minimal_symbol overlay_msym;
3204
3205   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3206   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3207
3208   /* True if we have looked for longjmp probes.  */
3209   int longjmp_searched;
3210
3211   /* SystemTap probe points for longjmp (if any).  */
3212   VEC (probe_p) *longjmp_probes;
3213
3214   /* Minimal symbol for "std::terminate()" (if any).  */
3215   struct bound_minimal_symbol terminate_msym;
3216
3217   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3218   struct bound_minimal_symbol exception_msym;
3219
3220   /* True if we have looked for exception probes.  */
3221   int exception_searched;
3222
3223   /* SystemTap probe points for unwinding (if any).  */
3224   VEC (probe_p) *exception_probes;
3225 };
3226
3227 static const struct objfile_data *breakpoint_objfile_key;
3228
3229 /* Minimal symbol not found sentinel.  */
3230 static struct minimal_symbol msym_not_found;
3231
3232 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3233
3234 static int
3235 msym_not_found_p (const struct minimal_symbol *msym)
3236 {
3237   return msym == &msym_not_found;
3238 }
3239
3240 /* Return per-objfile data needed by breakpoint.c.
3241    Allocate the data if necessary.  */
3242
3243 static struct breakpoint_objfile_data *
3244 get_breakpoint_objfile_data (struct objfile *objfile)
3245 {
3246   struct breakpoint_objfile_data *bp_objfile_data;
3247
3248   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3249   if (bp_objfile_data == NULL)
3250     {
3251       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3252                                        sizeof (*bp_objfile_data));
3253
3254       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3255       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3256     }
3257   return bp_objfile_data;
3258 }
3259
3260 static void
3261 free_breakpoint_probes (struct objfile *obj, void *data)
3262 {
3263   struct breakpoint_objfile_data *bp_objfile_data = data;
3264
3265   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3266   VEC_free (probe_p, bp_objfile_data->exception_probes);
3267 }
3268
3269 static void
3270 create_overlay_event_breakpoint (void)
3271 {
3272   struct objfile *objfile;
3273   const char *const func_name = "_ovly_debug_event";
3274
3275   ALL_OBJFILES (objfile)
3276     {
3277       struct breakpoint *b;
3278       struct breakpoint_objfile_data *bp_objfile_data;
3279       CORE_ADDR addr;
3280
3281       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3282
3283       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3284         continue;
3285
3286       if (bp_objfile_data->overlay_msym.minsym == NULL)
3287         {
3288           struct bound_minimal_symbol m;
3289
3290           m = lookup_minimal_symbol_text (func_name, objfile);
3291           if (m.minsym == NULL)
3292             {
3293               /* Avoid future lookups in this objfile.  */
3294               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3295               continue;
3296             }
3297           bp_objfile_data->overlay_msym = m;
3298         }
3299
3300       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3301       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3302                                       bp_overlay_event,
3303                                       &internal_breakpoint_ops);
3304       b->addr_string = xstrdup (func_name);
3305
3306       if (overlay_debugging == ovly_auto)
3307         {
3308           b->enable_state = bp_enabled;
3309           overlay_events_enabled = 1;
3310         }
3311       else
3312        {
3313          b->enable_state = bp_disabled;
3314          overlay_events_enabled = 0;
3315        }
3316     }
3317   update_global_location_list (1);
3318 }
3319
3320 static void
3321 create_longjmp_master_breakpoint (void)
3322 {
3323   struct program_space *pspace;
3324   struct cleanup *old_chain;
3325
3326   old_chain = save_current_program_space ();
3327
3328   ALL_PSPACES (pspace)
3329   {
3330     struct objfile *objfile;
3331
3332     set_current_program_space (pspace);
3333
3334     ALL_OBJFILES (objfile)
3335     {
3336       int i;
3337       struct gdbarch *gdbarch;
3338       struct breakpoint_objfile_data *bp_objfile_data;
3339
3340       gdbarch = get_objfile_arch (objfile);
3341
3342       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3343
3344       if (!bp_objfile_data->longjmp_searched)
3345         {
3346           VEC (probe_p) *ret;
3347
3348           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3349           if (ret != NULL)
3350             {
3351               /* We are only interested in checking one element.  */
3352               struct probe *p = VEC_index (probe_p, ret, 0);
3353
3354               if (!can_evaluate_probe_arguments (p))
3355                 {
3356                   /* We cannot use the probe interface here, because it does
3357                      not know how to evaluate arguments.  */
3358                   VEC_free (probe_p, ret);
3359                   ret = NULL;
3360                 }
3361             }
3362           bp_objfile_data->longjmp_probes = ret;
3363           bp_objfile_data->longjmp_searched = 1;
3364         }
3365
3366       if (bp_objfile_data->longjmp_probes != NULL)
3367         {
3368           int i;
3369           struct probe *probe;
3370           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3371
3372           for (i = 0;
3373                VEC_iterate (probe_p,
3374                             bp_objfile_data->longjmp_probes,
3375                             i, probe);
3376                ++i)
3377             {
3378               struct breakpoint *b;
3379
3380               b = create_internal_breakpoint (gdbarch,
3381                                               get_probe_address (probe,
3382                                                                  objfile),
3383                                               bp_longjmp_master,
3384                                               &internal_breakpoint_ops);
3385               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3386               b->enable_state = bp_disabled;
3387             }
3388
3389           continue;
3390         }
3391
3392       if (!gdbarch_get_longjmp_target_p (gdbarch))
3393         continue;
3394
3395       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3396         {
3397           struct breakpoint *b;
3398           const char *func_name;
3399           CORE_ADDR addr;
3400
3401           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3402             continue;
3403
3404           func_name = longjmp_names[i];
3405           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3406             {
3407               struct bound_minimal_symbol m;
3408
3409               m = lookup_minimal_symbol_text (func_name, objfile);
3410               if (m.minsym == NULL)
3411                 {
3412                   /* Prevent future lookups in this objfile.  */
3413                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3414                   continue;
3415                 }
3416               bp_objfile_data->longjmp_msym[i] = m;
3417             }
3418
3419           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3420           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3421                                           &internal_breakpoint_ops);
3422           b->addr_string = xstrdup (func_name);
3423           b->enable_state = bp_disabled;
3424         }
3425     }
3426   }
3427   update_global_location_list (1);
3428
3429   do_cleanups (old_chain);
3430 }
3431
3432 /* Create a master std::terminate breakpoint.  */
3433 static void
3434 create_std_terminate_master_breakpoint (void)
3435 {
3436   struct program_space *pspace;
3437   struct cleanup *old_chain;
3438   const char *const func_name = "std::terminate()";
3439
3440   old_chain = save_current_program_space ();
3441
3442   ALL_PSPACES (pspace)
3443   {
3444     struct objfile *objfile;
3445     CORE_ADDR addr;
3446
3447     set_current_program_space (pspace);
3448
3449     ALL_OBJFILES (objfile)
3450     {
3451       struct breakpoint *b;
3452       struct breakpoint_objfile_data *bp_objfile_data;
3453
3454       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3455
3456       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3457         continue;
3458
3459       if (bp_objfile_data->terminate_msym.minsym == NULL)
3460         {
3461           struct bound_minimal_symbol m;
3462
3463           m = lookup_minimal_symbol (func_name, NULL, objfile);
3464           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3465                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3466             {
3467               /* Prevent future lookups in this objfile.  */
3468               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3469               continue;
3470             }
3471           bp_objfile_data->terminate_msym = m;
3472         }
3473
3474       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3475       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3476                                       bp_std_terminate_master,
3477                                       &internal_breakpoint_ops);
3478       b->addr_string = xstrdup (func_name);
3479       b->enable_state = bp_disabled;
3480     }
3481   }
3482
3483   update_global_location_list (1);
3484
3485   do_cleanups (old_chain);
3486 }
3487
3488 /* Install a master breakpoint on the unwinder's debug hook.  */
3489
3490 static void
3491 create_exception_master_breakpoint (void)
3492 {
3493   struct objfile *objfile;
3494   const char *const func_name = "_Unwind_DebugHook";
3495
3496   ALL_OBJFILES (objfile)
3497     {
3498       struct breakpoint *b;
3499       struct gdbarch *gdbarch;
3500       struct breakpoint_objfile_data *bp_objfile_data;
3501       CORE_ADDR addr;
3502
3503       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3504
3505       /* We prefer the SystemTap probe point if it exists.  */
3506       if (!bp_objfile_data->exception_searched)
3507         {
3508           VEC (probe_p) *ret;
3509
3510           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3511
3512           if (ret != NULL)
3513             {
3514               /* We are only interested in checking one element.  */
3515               struct probe *p = VEC_index (probe_p, ret, 0);
3516
3517               if (!can_evaluate_probe_arguments (p))
3518                 {
3519                   /* We cannot use the probe interface here, because it does
3520                      not know how to evaluate arguments.  */
3521                   VEC_free (probe_p, ret);
3522                   ret = NULL;
3523                 }
3524             }
3525           bp_objfile_data->exception_probes = ret;
3526           bp_objfile_data->exception_searched = 1;
3527         }
3528
3529       if (bp_objfile_data->exception_probes != NULL)
3530         {
3531           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3532           int i;
3533           struct probe *probe;
3534
3535           for (i = 0;
3536                VEC_iterate (probe_p,
3537                             bp_objfile_data->exception_probes,
3538                             i, probe);
3539                ++i)
3540             {
3541               struct breakpoint *b;
3542
3543               b = create_internal_breakpoint (gdbarch,
3544                                               get_probe_address (probe,
3545                                                                  objfile),
3546                                               bp_exception_master,
3547                                               &internal_breakpoint_ops);
3548               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3549               b->enable_state = bp_disabled;
3550             }
3551
3552           continue;
3553         }
3554
3555       /* Otherwise, try the hook function.  */
3556
3557       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3558         continue;
3559
3560       gdbarch = get_objfile_arch (objfile);
3561
3562       if (bp_objfile_data->exception_msym.minsym == NULL)
3563         {
3564           struct bound_minimal_symbol debug_hook;
3565
3566           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3567           if (debug_hook.minsym == NULL)
3568             {
3569               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3570               continue;
3571             }
3572
3573           bp_objfile_data->exception_msym = debug_hook;
3574         }
3575
3576       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3577       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3578                                                  &current_target);
3579       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3580                                       &internal_breakpoint_ops);
3581       b->addr_string = xstrdup (func_name);
3582       b->enable_state = bp_disabled;
3583     }
3584
3585   update_global_location_list (1);
3586 }
3587
3588 void
3589 update_breakpoints_after_exec (void)
3590 {
3591   struct breakpoint *b, *b_tmp;
3592   struct bp_location *bploc, **bplocp_tmp;
3593
3594   /* We're about to delete breakpoints from GDB's lists.  If the
3595      INSERTED flag is true, GDB will try to lift the breakpoints by
3596      writing the breakpoints' "shadow contents" back into memory.  The
3597      "shadow contents" are NOT valid after an exec, so GDB should not
3598      do that.  Instead, the target is responsible from marking
3599      breakpoints out as soon as it detects an exec.  We don't do that
3600      here instead, because there may be other attempts to delete
3601      breakpoints after detecting an exec and before reaching here.  */
3602   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3603     if (bploc->pspace == current_program_space)
3604       gdb_assert (!bploc->inserted);
3605
3606   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3607   {
3608     if (b->pspace != current_program_space)
3609       continue;
3610
3611     /* Solib breakpoints must be explicitly reset after an exec().  */
3612     if (b->type == bp_shlib_event)
3613       {
3614         delete_breakpoint (b);
3615         continue;
3616       }
3617
3618     /* JIT breakpoints must be explicitly reset after an exec().  */
3619     if (b->type == bp_jit_event)
3620       {
3621         delete_breakpoint (b);
3622         continue;
3623       }
3624
3625     /* Thread event breakpoints must be set anew after an exec(),
3626        as must overlay event and longjmp master breakpoints.  */
3627     if (b->type == bp_thread_event || b->type == bp_overlay_event
3628         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3629         || b->type == bp_exception_master)
3630       {
3631         delete_breakpoint (b);
3632         continue;
3633       }
3634
3635     /* Step-resume breakpoints are meaningless after an exec().  */
3636     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3637       {
3638         delete_breakpoint (b);
3639         continue;
3640       }
3641
3642     /* Longjmp and longjmp-resume breakpoints are also meaningless
3643        after an exec.  */
3644     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3645         || b->type == bp_longjmp_call_dummy
3646         || b->type == bp_exception || b->type == bp_exception_resume)
3647       {
3648         delete_breakpoint (b);
3649         continue;
3650       }
3651
3652     if (b->type == bp_catchpoint)
3653       {
3654         /* For now, none of the bp_catchpoint breakpoints need to
3655            do anything at this point.  In the future, if some of
3656            the catchpoints need to something, we will need to add
3657            a new method, and call this method from here.  */
3658         continue;
3659       }
3660
3661     /* bp_finish is a special case.  The only way we ought to be able
3662        to see one of these when an exec() has happened, is if the user
3663        caught a vfork, and then said "finish".  Ordinarily a finish just
3664        carries them to the call-site of the current callee, by setting
3665        a temporary bp there and resuming.  But in this case, the finish
3666        will carry them entirely through the vfork & exec.
3667
3668        We don't want to allow a bp_finish to remain inserted now.  But
3669        we can't safely delete it, 'cause finish_command has a handle to
3670        the bp on a bpstat, and will later want to delete it.  There's a
3671        chance (and I've seen it happen) that if we delete the bp_finish
3672        here, that its storage will get reused by the time finish_command
3673        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3674        We really must allow finish_command to delete a bp_finish.
3675
3676        In the absence of a general solution for the "how do we know
3677        it's safe to delete something others may have handles to?"
3678        problem, what we'll do here is just uninsert the bp_finish, and
3679        let finish_command delete it.
3680
3681        (We know the bp_finish is "doomed" in the sense that it's
3682        momentary, and will be deleted as soon as finish_command sees
3683        the inferior stopped.  So it doesn't matter that the bp's
3684        address is probably bogus in the new a.out, unlike e.g., the
3685        solib breakpoints.)  */
3686
3687     if (b->type == bp_finish)
3688       {
3689         continue;
3690       }
3691
3692     /* Without a symbolic address, we have little hope of the
3693        pre-exec() address meaning the same thing in the post-exec()
3694        a.out.  */
3695     if (b->addr_string == NULL)
3696       {
3697         delete_breakpoint (b);
3698         continue;
3699       }
3700   }
3701   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3702   create_overlay_event_breakpoint ();
3703   create_longjmp_master_breakpoint ();
3704   create_std_terminate_master_breakpoint ();
3705   create_exception_master_breakpoint ();
3706 }
3707
3708 int
3709 detach_breakpoints (ptid_t ptid)
3710 {
3711   struct bp_location *bl, **blp_tmp;
3712   int val = 0;
3713   struct cleanup *old_chain = save_inferior_ptid ();
3714   struct inferior *inf = current_inferior ();
3715
3716   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3717     error (_("Cannot detach breakpoints of inferior_ptid"));
3718
3719   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3720   inferior_ptid = ptid;
3721   ALL_BP_LOCATIONS (bl, blp_tmp)
3722   {
3723     if (bl->pspace != inf->pspace)
3724       continue;
3725
3726     /* This function must physically remove breakpoints locations
3727        from the specified ptid, without modifying the breakpoint
3728        package's state.  Locations of type bp_loc_other are only
3729        maintained at GDB side.  So, there is no need to remove
3730        these bp_loc_other locations.  Moreover, removing these
3731        would modify the breakpoint package's state.  */
3732     if (bl->loc_type == bp_loc_other)
3733       continue;
3734
3735     if (bl->inserted)
3736       val |= remove_breakpoint_1 (bl, mark_inserted);
3737   }
3738
3739   /* Detach single-step breakpoints as well.  */
3740   detach_single_step_breakpoints ();
3741
3742   do_cleanups (old_chain);
3743   return val;
3744 }
3745
3746 /* Remove the breakpoint location BL from the current address space.
3747    Note that this is used to detach breakpoints from a child fork.
3748    When we get here, the child isn't in the inferior list, and neither
3749    do we have objects to represent its address space --- we should
3750    *not* look at bl->pspace->aspace here.  */
3751
3752 static int
3753 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3754 {
3755   int val;
3756
3757   /* BL is never in moribund_locations by our callers.  */
3758   gdb_assert (bl->owner != NULL);
3759
3760   if (bl->owner->enable_state == bp_permanent)
3761     /* Permanent breakpoints cannot be inserted or removed.  */
3762     return 0;
3763
3764   /* The type of none suggests that owner is actually deleted.
3765      This should not ever happen.  */
3766   gdb_assert (bl->owner->type != bp_none);
3767
3768   if (bl->loc_type == bp_loc_software_breakpoint
3769       || bl->loc_type == bp_loc_hardware_breakpoint)
3770     {
3771       /* "Normal" instruction breakpoint: either the standard
3772          trap-instruction bp (bp_breakpoint), or a
3773          bp_hardware_breakpoint.  */
3774
3775       /* First check to see if we have to handle an overlay.  */
3776       if (overlay_debugging == ovly_off
3777           || bl->section == NULL
3778           || !(section_is_overlay (bl->section)))
3779         {
3780           /* No overlay handling: just remove the breakpoint.  */
3781           val = bl->owner->ops->remove_location (bl);
3782         }
3783       else
3784         {
3785           /* This breakpoint is in an overlay section.
3786              Did we set a breakpoint at the LMA?  */
3787           if (!overlay_events_enabled)
3788               {
3789                 /* Yes -- overlay event support is not active, so we
3790                    should have set a breakpoint at the LMA.  Remove it.  
3791                 */
3792                 /* Ignore any failures: if the LMA is in ROM, we will
3793                    have already warned when we failed to insert it.  */
3794                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3795                   target_remove_hw_breakpoint (bl->gdbarch,
3796                                                &bl->overlay_target_info);
3797                 else
3798                   target_remove_breakpoint (bl->gdbarch,
3799                                             &bl->overlay_target_info);
3800               }
3801           /* Did we set a breakpoint at the VMA? 
3802              If so, we will have marked the breakpoint 'inserted'.  */
3803           if (bl->inserted)
3804             {
3805               /* Yes -- remove it.  Previously we did not bother to
3806                  remove the breakpoint if the section had been
3807                  unmapped, but let's not rely on that being safe.  We
3808                  don't know what the overlay manager might do.  */
3809
3810               /* However, we should remove *software* breakpoints only
3811                  if the section is still mapped, or else we overwrite
3812                  wrong code with the saved shadow contents.  */
3813               if (bl->loc_type == bp_loc_hardware_breakpoint
3814                   || section_is_mapped (bl->section))
3815                 val = bl->owner->ops->remove_location (bl);
3816               else
3817                 val = 0;
3818             }
3819           else
3820             {
3821               /* No -- not inserted, so no need to remove.  No error.  */
3822               val = 0;
3823             }
3824         }
3825
3826       /* In some cases, we might not be able to remove a breakpoint
3827          in a shared library that has already been removed, but we
3828          have not yet processed the shlib unload event.  */
3829       if (val && solib_name_from_address (bl->pspace, bl->address))
3830         val = 0;
3831
3832       if (val)
3833         return val;
3834       bl->inserted = (is == mark_inserted);
3835     }
3836   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3837     {
3838       gdb_assert (bl->owner->ops != NULL
3839                   && bl->owner->ops->remove_location != NULL);
3840
3841       bl->inserted = (is == mark_inserted);
3842       bl->owner->ops->remove_location (bl);
3843
3844       /* Failure to remove any of the hardware watchpoints comes here.  */
3845       if ((is == mark_uninserted) && (bl->inserted))
3846         warning (_("Could not remove hardware watchpoint %d."),
3847                  bl->owner->number);
3848     }
3849   else if (bl->owner->type == bp_catchpoint
3850            && breakpoint_enabled (bl->owner)
3851            && !bl->duplicate)
3852     {
3853       gdb_assert (bl->owner->ops != NULL
3854                   && bl->owner->ops->remove_location != NULL);
3855
3856       val = bl->owner->ops->remove_location (bl);
3857       if (val)
3858         return val;
3859
3860       bl->inserted = (is == mark_inserted);
3861     }
3862
3863   return 0;
3864 }
3865
3866 static int
3867 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3868 {
3869   int ret;
3870   struct cleanup *old_chain;
3871
3872   /* BL is never in moribund_locations by our callers.  */
3873   gdb_assert (bl->owner != NULL);
3874
3875   if (bl->owner->enable_state == bp_permanent)
3876     /* Permanent breakpoints cannot be inserted or removed.  */
3877     return 0;
3878
3879   /* The type of none suggests that owner is actually deleted.
3880      This should not ever happen.  */
3881   gdb_assert (bl->owner->type != bp_none);
3882
3883   old_chain = save_current_space_and_thread ();
3884
3885   switch_to_program_space_and_thread (bl->pspace);
3886
3887   ret = remove_breakpoint_1 (bl, is);
3888
3889   do_cleanups (old_chain);
3890   return ret;
3891 }
3892
3893 /* Clear the "inserted" flag in all breakpoints.  */
3894
3895 void
3896 mark_breakpoints_out (void)
3897 {
3898   struct bp_location *bl, **blp_tmp;
3899
3900   ALL_BP_LOCATIONS (bl, blp_tmp)
3901     if (bl->pspace == current_program_space)
3902       bl->inserted = 0;
3903 }
3904
3905 /* Clear the "inserted" flag in all breakpoints and delete any
3906    breakpoints which should go away between runs of the program.
3907
3908    Plus other such housekeeping that has to be done for breakpoints
3909    between runs.
3910
3911    Note: this function gets called at the end of a run (by
3912    generic_mourn_inferior) and when a run begins (by
3913    init_wait_for_inferior).  */
3914
3915
3916
3917 void
3918 breakpoint_init_inferior (enum inf_context context)
3919 {
3920   struct breakpoint *b, *b_tmp;
3921   struct bp_location *bl, **blp_tmp;
3922   int ix;
3923   struct program_space *pspace = current_program_space;
3924
3925   /* If breakpoint locations are shared across processes, then there's
3926      nothing to do.  */
3927   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
3928     return;
3929
3930   ALL_BP_LOCATIONS (bl, blp_tmp)
3931   {
3932     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3933     if (bl->pspace == pspace
3934         && bl->owner->enable_state != bp_permanent)
3935       bl->inserted = 0;
3936   }
3937
3938   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3939   {
3940     if (b->loc && b->loc->pspace != pspace)
3941       continue;
3942
3943     switch (b->type)
3944       {
3945       case bp_call_dummy:
3946       case bp_longjmp_call_dummy:
3947
3948         /* If the call dummy breakpoint is at the entry point it will
3949            cause problems when the inferior is rerun, so we better get
3950            rid of it.  */
3951
3952       case bp_watchpoint_scope:
3953
3954         /* Also get rid of scope breakpoints.  */
3955
3956       case bp_shlib_event:
3957
3958         /* Also remove solib event breakpoints.  Their addresses may
3959            have changed since the last time we ran the program.
3960            Actually we may now be debugging against different target;
3961            and so the solib backend that installed this breakpoint may
3962            not be used in by the target.  E.g.,
3963
3964            (gdb) file prog-linux
3965            (gdb) run               # native linux target
3966            ...
3967            (gdb) kill
3968            (gdb) file prog-win.exe
3969            (gdb) tar rem :9999     # remote Windows gdbserver.
3970         */
3971
3972       case bp_step_resume:
3973
3974         /* Also remove step-resume breakpoints.  */
3975
3976         delete_breakpoint (b);
3977         break;
3978
3979       case bp_watchpoint:
3980       case bp_hardware_watchpoint:
3981       case bp_read_watchpoint:
3982       case bp_access_watchpoint:
3983         {
3984           struct watchpoint *w = (struct watchpoint *) b;
3985
3986           /* Likewise for watchpoints on local expressions.  */
3987           if (w->exp_valid_block != NULL)
3988             delete_breakpoint (b);
3989           else if (context == inf_starting)
3990             {
3991               /* Reset val field to force reread of starting value in
3992                  insert_breakpoints.  */
3993               if (w->val)
3994                 value_free (w->val);
3995               w->val = NULL;
3996               w->val_valid = 0;
3997           }
3998         }
3999         break;
4000       default:
4001         break;
4002       }
4003   }
4004
4005   /* Get rid of the moribund locations.  */
4006   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4007     decref_bp_location (&bl);
4008   VEC_free (bp_location_p, moribund_locations);
4009 }
4010
4011 /* These functions concern about actual breakpoints inserted in the
4012    target --- to e.g. check if we need to do decr_pc adjustment or if
4013    we need to hop over the bkpt --- so we check for address space
4014    match, not program space.  */
4015
4016 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4017    exists at PC.  It returns ordinary_breakpoint_here if it's an
4018    ordinary breakpoint, or permanent_breakpoint_here if it's a
4019    permanent breakpoint.
4020    - When continuing from a location with an ordinary breakpoint, we
4021      actually single step once before calling insert_breakpoints.
4022    - When continuing from a location with a permanent breakpoint, we
4023      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4024      the target, to advance the PC past the breakpoint.  */
4025
4026 enum breakpoint_here
4027 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4028 {
4029   struct bp_location *bl, **blp_tmp;
4030   int any_breakpoint_here = 0;
4031
4032   ALL_BP_LOCATIONS (bl, blp_tmp)
4033     {
4034       if (bl->loc_type != bp_loc_software_breakpoint
4035           && bl->loc_type != bp_loc_hardware_breakpoint)
4036         continue;
4037
4038       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4039       if ((breakpoint_enabled (bl->owner)
4040            || bl->owner->enable_state == bp_permanent)
4041           && breakpoint_location_address_match (bl, aspace, pc))
4042         {
4043           if (overlay_debugging 
4044               && section_is_overlay (bl->section)
4045               && !section_is_mapped (bl->section))
4046             continue;           /* unmapped overlay -- can't be a match */
4047           else if (bl->owner->enable_state == bp_permanent)
4048             return permanent_breakpoint_here;
4049           else
4050             any_breakpoint_here = 1;
4051         }
4052     }
4053
4054   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4055 }
4056
4057 /* Return true if there's a moribund breakpoint at PC.  */
4058
4059 int
4060 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4061 {
4062   struct bp_location *loc;
4063   int ix;
4064
4065   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4066     if (breakpoint_location_address_match (loc, aspace, pc))
4067       return 1;
4068
4069   return 0;
4070 }
4071
4072 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4073    inserted using regular breakpoint_chain / bp_location array
4074    mechanism.  This does not check for single-step breakpoints, which
4075    are inserted and removed using direct target manipulation.  */
4076
4077 int
4078 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4079                                     CORE_ADDR pc)
4080 {
4081   struct bp_location *bl, **blp_tmp;
4082
4083   ALL_BP_LOCATIONS (bl, blp_tmp)
4084     {
4085       if (bl->loc_type != bp_loc_software_breakpoint
4086           && bl->loc_type != bp_loc_hardware_breakpoint)
4087         continue;
4088
4089       if (bl->inserted
4090           && breakpoint_location_address_match (bl, aspace, pc))
4091         {
4092           if (overlay_debugging 
4093               && section_is_overlay (bl->section)
4094               && !section_is_mapped (bl->section))
4095             continue;           /* unmapped overlay -- can't be a match */
4096           else
4097             return 1;
4098         }
4099     }
4100   return 0;
4101 }
4102
4103 /* Returns non-zero iff there's either regular breakpoint
4104    or a single step breakpoint inserted at PC.  */
4105
4106 int
4107 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4108 {
4109   if (regular_breakpoint_inserted_here_p (aspace, pc))
4110     return 1;
4111
4112   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4113     return 1;
4114
4115   return 0;
4116 }
4117
4118 /* This function returns non-zero iff there is a software breakpoint
4119    inserted at PC.  */
4120
4121 int
4122 software_breakpoint_inserted_here_p (struct address_space *aspace,
4123                                      CORE_ADDR pc)
4124 {
4125   struct bp_location *bl, **blp_tmp;
4126
4127   ALL_BP_LOCATIONS (bl, blp_tmp)
4128     {
4129       if (bl->loc_type != bp_loc_software_breakpoint)
4130         continue;
4131
4132       if (bl->inserted
4133           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4134                                        aspace, pc))
4135         {
4136           if (overlay_debugging 
4137               && section_is_overlay (bl->section)
4138               && !section_is_mapped (bl->section))
4139             continue;           /* unmapped overlay -- can't be a match */
4140           else
4141             return 1;
4142         }
4143     }
4144
4145   /* Also check for software single-step breakpoints.  */
4146   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4147     return 1;
4148
4149   return 0;
4150 }
4151
4152 int
4153 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4154                                        CORE_ADDR addr, ULONGEST len)
4155 {
4156   struct breakpoint *bpt;
4157
4158   ALL_BREAKPOINTS (bpt)
4159     {
4160       struct bp_location *loc;
4161
4162       if (bpt->type != bp_hardware_watchpoint
4163           && bpt->type != bp_access_watchpoint)
4164         continue;
4165
4166       if (!breakpoint_enabled (bpt))
4167         continue;
4168
4169       for (loc = bpt->loc; loc; loc = loc->next)
4170         if (loc->pspace->aspace == aspace && loc->inserted)
4171           {
4172             CORE_ADDR l, h;
4173
4174             /* Check for intersection.  */
4175             l = max (loc->address, addr);
4176             h = min (loc->address + loc->length, addr + len);
4177             if (l < h)
4178               return 1;
4179           }
4180     }
4181   return 0;
4182 }
4183
4184 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4185    PC is valid for process/thread PTID.  */
4186
4187 int
4188 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4189                          ptid_t ptid)
4190 {
4191   struct bp_location *bl, **blp_tmp;
4192   /* The thread and task IDs associated to PTID, computed lazily.  */
4193   int thread = -1;
4194   int task = 0;
4195   
4196   ALL_BP_LOCATIONS (bl, blp_tmp)
4197     {
4198       if (bl->loc_type != bp_loc_software_breakpoint
4199           && bl->loc_type != bp_loc_hardware_breakpoint)
4200         continue;
4201
4202       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4203       if (!breakpoint_enabled (bl->owner)
4204           && bl->owner->enable_state != bp_permanent)
4205         continue;
4206
4207       if (!breakpoint_location_address_match (bl, aspace, pc))
4208         continue;
4209
4210       if (bl->owner->thread != -1)
4211         {
4212           /* This is a thread-specific breakpoint.  Check that ptid
4213              matches that thread.  If thread hasn't been computed yet,
4214              it is now time to do so.  */
4215           if (thread == -1)
4216             thread = pid_to_thread_id (ptid);
4217           if (bl->owner->thread != thread)
4218             continue;
4219         }
4220
4221       if (bl->owner->task != 0)
4222         {
4223           /* This is a task-specific breakpoint.  Check that ptid
4224              matches that task.  If task hasn't been computed yet,
4225              it is now time to do so.  */
4226           if (task == 0)
4227             task = ada_get_task_number (ptid);
4228           if (bl->owner->task != task)
4229             continue;
4230         }
4231
4232       if (overlay_debugging 
4233           && section_is_overlay (bl->section)
4234           && !section_is_mapped (bl->section))
4235         continue;           /* unmapped overlay -- can't be a match */
4236
4237       return 1;
4238     }
4239
4240   return 0;
4241 }
4242 \f
4243
4244 /* bpstat stuff.  External routines' interfaces are documented
4245    in breakpoint.h.  */
4246
4247 int
4248 is_catchpoint (struct breakpoint *ep)
4249 {
4250   return (ep->type == bp_catchpoint);
4251 }
4252
4253 /* Frees any storage that is part of a bpstat.  Does not walk the
4254    'next' chain.  */
4255
4256 static void
4257 bpstat_free (bpstat bs)
4258 {
4259   if (bs->old_val != NULL)
4260     value_free (bs->old_val);
4261   decref_counted_command_line (&bs->commands);
4262   decref_bp_location (&bs->bp_location_at);
4263   xfree (bs);
4264 }
4265
4266 /* Clear a bpstat so that it says we are not at any breakpoint.
4267    Also free any storage that is part of a bpstat.  */
4268
4269 void
4270 bpstat_clear (bpstat *bsp)
4271 {
4272   bpstat p;
4273   bpstat q;
4274
4275   if (bsp == 0)
4276     return;
4277   p = *bsp;
4278   while (p != NULL)
4279     {
4280       q = p->next;
4281       bpstat_free (p);
4282       p = q;
4283     }
4284   *bsp = NULL;
4285 }
4286
4287 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4288    is part of the bpstat is copied as well.  */
4289
4290 bpstat
4291 bpstat_copy (bpstat bs)
4292 {
4293   bpstat p = NULL;
4294   bpstat tmp;
4295   bpstat retval = NULL;
4296
4297   if (bs == NULL)
4298     return bs;
4299
4300   for (; bs != NULL; bs = bs->next)
4301     {
4302       tmp = (bpstat) xmalloc (sizeof (*tmp));
4303       memcpy (tmp, bs, sizeof (*tmp));
4304       incref_counted_command_line (tmp->commands);
4305       incref_bp_location (tmp->bp_location_at);
4306       if (bs->old_val != NULL)
4307         {
4308           tmp->old_val = value_copy (bs->old_val);
4309           release_value (tmp->old_val);
4310         }
4311
4312       if (p == NULL)
4313         /* This is the first thing in the chain.  */
4314         retval = tmp;
4315       else
4316         p->next = tmp;
4317       p = tmp;
4318     }
4319   p->next = NULL;
4320   return retval;
4321 }
4322
4323 /* Find the bpstat associated with this breakpoint.  */
4324
4325 bpstat
4326 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4327 {
4328   if (bsp == NULL)
4329     return NULL;
4330
4331   for (; bsp != NULL; bsp = bsp->next)
4332     {
4333       if (bsp->breakpoint_at == breakpoint)
4334         return bsp;
4335     }
4336   return NULL;
4337 }
4338
4339 /* See breakpoint.h.  */
4340
4341 int
4342 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4343 {
4344   for (; bsp != NULL; bsp = bsp->next)
4345     {
4346       if (bsp->breakpoint_at == NULL)
4347         {
4348           /* A moribund location can never explain a signal other than
4349              GDB_SIGNAL_TRAP.  */
4350           if (sig == GDB_SIGNAL_TRAP)
4351             return 1;
4352         }
4353       else
4354         {
4355           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4356                                                         sig))
4357             return 1;
4358         }
4359     }
4360
4361   return 0;
4362 }
4363
4364 /* Put in *NUM the breakpoint number of the first breakpoint we are
4365    stopped at.  *BSP upon return is a bpstat which points to the
4366    remaining breakpoints stopped at (but which is not guaranteed to be
4367    good for anything but further calls to bpstat_num).
4368
4369    Return 0 if passed a bpstat which does not indicate any breakpoints.
4370    Return -1 if stopped at a breakpoint that has been deleted since
4371    we set it.
4372    Return 1 otherwise.  */
4373
4374 int
4375 bpstat_num (bpstat *bsp, int *num)
4376 {
4377   struct breakpoint *b;
4378
4379   if ((*bsp) == NULL)
4380     return 0;                   /* No more breakpoint values */
4381
4382   /* We assume we'll never have several bpstats that correspond to a
4383      single breakpoint -- otherwise, this function might return the
4384      same number more than once and this will look ugly.  */
4385   b = (*bsp)->breakpoint_at;
4386   *bsp = (*bsp)->next;
4387   if (b == NULL)
4388     return -1;                  /* breakpoint that's been deleted since */
4389
4390   *num = b->number;             /* We have its number */
4391   return 1;
4392 }
4393
4394 /* See breakpoint.h.  */
4395
4396 void
4397 bpstat_clear_actions (void)
4398 {
4399   struct thread_info *tp;
4400   bpstat bs;
4401
4402   if (ptid_equal (inferior_ptid, null_ptid))
4403     return;
4404
4405   tp = find_thread_ptid (inferior_ptid);
4406   if (tp == NULL)
4407     return;
4408
4409   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4410     {
4411       decref_counted_command_line (&bs->commands);
4412
4413       if (bs->old_val != NULL)
4414         {
4415           value_free (bs->old_val);
4416           bs->old_val = NULL;
4417         }
4418     }
4419 }
4420
4421 /* Called when a command is about to proceed the inferior.  */
4422
4423 static void
4424 breakpoint_about_to_proceed (void)
4425 {
4426   if (!ptid_equal (inferior_ptid, null_ptid))
4427     {
4428       struct thread_info *tp = inferior_thread ();
4429
4430       /* Allow inferior function calls in breakpoint commands to not
4431          interrupt the command list.  When the call finishes
4432          successfully, the inferior will be standing at the same
4433          breakpoint as if nothing happened.  */
4434       if (tp->control.in_infcall)
4435         return;
4436     }
4437
4438   breakpoint_proceeded = 1;
4439 }
4440
4441 /* Stub for cleaning up our state if we error-out of a breakpoint
4442    command.  */
4443 static void
4444 cleanup_executing_breakpoints (void *ignore)
4445 {
4446   executing_breakpoint_commands = 0;
4447 }
4448
4449 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4450    or its equivalent.  */
4451
4452 static int
4453 command_line_is_silent (struct command_line *cmd)
4454 {
4455   return cmd && (strcmp ("silent", cmd->line) == 0
4456                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4457 }
4458
4459 /* Execute all the commands associated with all the breakpoints at
4460    this location.  Any of these commands could cause the process to
4461    proceed beyond this point, etc.  We look out for such changes by
4462    checking the global "breakpoint_proceeded" after each command.
4463
4464    Returns true if a breakpoint command resumed the inferior.  In that
4465    case, it is the caller's responsibility to recall it again with the
4466    bpstat of the current thread.  */
4467
4468 static int
4469 bpstat_do_actions_1 (bpstat *bsp)
4470 {
4471   bpstat bs;
4472   struct cleanup *old_chain;
4473   int again = 0;
4474
4475   /* Avoid endless recursion if a `source' command is contained
4476      in bs->commands.  */
4477   if (executing_breakpoint_commands)
4478     return 0;
4479
4480   executing_breakpoint_commands = 1;
4481   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4482
4483   prevent_dont_repeat ();
4484
4485   /* This pointer will iterate over the list of bpstat's.  */
4486   bs = *bsp;
4487
4488   breakpoint_proceeded = 0;
4489   for (; bs != NULL; bs = bs->next)
4490     {
4491       struct counted_command_line *ccmd;
4492       struct command_line *cmd;
4493       struct cleanup *this_cmd_tree_chain;
4494
4495       /* Take ownership of the BSP's command tree, if it has one.
4496
4497          The command tree could legitimately contain commands like
4498          'step' and 'next', which call clear_proceed_status, which
4499          frees stop_bpstat's command tree.  To make sure this doesn't
4500          free the tree we're executing out from under us, we need to
4501          take ownership of the tree ourselves.  Since a given bpstat's
4502          commands are only executed once, we don't need to copy it; we
4503          can clear the pointer in the bpstat, and make sure we free
4504          the tree when we're done.  */
4505       ccmd = bs->commands;
4506       bs->commands = NULL;
4507       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4508       cmd = ccmd ? ccmd->commands : NULL;
4509       if (command_line_is_silent (cmd))
4510         {
4511           /* The action has been already done by bpstat_stop_status.  */
4512           cmd = cmd->next;
4513         }
4514
4515       while (cmd != NULL)
4516         {
4517           execute_control_command (cmd);
4518
4519           if (breakpoint_proceeded)
4520             break;
4521           else
4522             cmd = cmd->next;
4523         }
4524
4525       /* We can free this command tree now.  */
4526       do_cleanups (this_cmd_tree_chain);
4527
4528       if (breakpoint_proceeded)
4529         {
4530           if (target_can_async_p ())
4531             /* If we are in async mode, then the target might be still
4532                running, not stopped at any breakpoint, so nothing for
4533                us to do here -- just return to the event loop.  */
4534             ;
4535           else
4536             /* In sync mode, when execute_control_command returns
4537                we're already standing on the next breakpoint.
4538                Breakpoint commands for that stop were not run, since
4539                execute_command does not run breakpoint commands --
4540                only command_line_handler does, but that one is not
4541                involved in execution of breakpoint commands.  So, we
4542                can now execute breakpoint commands.  It should be
4543                noted that making execute_command do bpstat actions is
4544                not an option -- in this case we'll have recursive
4545                invocation of bpstat for each breakpoint with a
4546                command, and can easily blow up GDB stack.  Instead, we
4547                return true, which will trigger the caller to recall us
4548                with the new stop_bpstat.  */
4549             again = 1;
4550           break;
4551         }
4552     }
4553   do_cleanups (old_chain);
4554   return again;
4555 }
4556
4557 void
4558 bpstat_do_actions (void)
4559 {
4560   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4561
4562   /* Do any commands attached to breakpoint we are stopped at.  */
4563   while (!ptid_equal (inferior_ptid, null_ptid)
4564          && target_has_execution
4565          && !is_exited (inferior_ptid)
4566          && !is_executing (inferior_ptid))
4567     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4568        and only return when it is stopped at the next breakpoint, we
4569        keep doing breakpoint actions until it returns false to
4570        indicate the inferior was not resumed.  */
4571     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4572       break;
4573
4574   discard_cleanups (cleanup_if_error);
4575 }
4576
4577 /* Print out the (old or new) value associated with a watchpoint.  */
4578
4579 static void
4580 watchpoint_value_print (struct value *val, struct ui_file *stream)
4581 {
4582   if (val == NULL)
4583     fprintf_unfiltered (stream, _("<unreadable>"));
4584   else
4585     {
4586       struct value_print_options opts;
4587       get_user_print_options (&opts);
4588       value_print (val, stream, &opts);
4589     }
4590 }
4591
4592 /* Generic routine for printing messages indicating why we
4593    stopped.  The behavior of this function depends on the value
4594    'print_it' in the bpstat structure.  Under some circumstances we
4595    may decide not to print anything here and delegate the task to
4596    normal_stop().  */
4597
4598 static enum print_stop_action
4599 print_bp_stop_message (bpstat bs)
4600 {
4601   switch (bs->print_it)
4602     {
4603     case print_it_noop:
4604       /* Nothing should be printed for this bpstat entry.  */
4605       return PRINT_UNKNOWN;
4606       break;
4607
4608     case print_it_done:
4609       /* We still want to print the frame, but we already printed the
4610          relevant messages.  */
4611       return PRINT_SRC_AND_LOC;
4612       break;
4613
4614     case print_it_normal:
4615       {
4616         struct breakpoint *b = bs->breakpoint_at;
4617
4618         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4619            which has since been deleted.  */
4620         if (b == NULL)
4621           return PRINT_UNKNOWN;
4622
4623         /* Normal case.  Call the breakpoint's print_it method.  */
4624         return b->ops->print_it (bs);
4625       }
4626       break;
4627
4628     default:
4629       internal_error (__FILE__, __LINE__,
4630                       _("print_bp_stop_message: unrecognized enum value"));
4631       break;
4632     }
4633 }
4634
4635 /* A helper function that prints a shared library stopped event.  */
4636
4637 static void
4638 print_solib_event (int is_catchpoint)
4639 {
4640   int any_deleted
4641     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4642   int any_added
4643     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4644
4645   if (!is_catchpoint)
4646     {
4647       if (any_added || any_deleted)
4648         ui_out_text (current_uiout,
4649                      _("Stopped due to shared library event:\n"));
4650       else
4651         ui_out_text (current_uiout,
4652                      _("Stopped due to shared library event (no "
4653                        "libraries added or removed)\n"));
4654     }
4655
4656   if (ui_out_is_mi_like_p (current_uiout))
4657     ui_out_field_string (current_uiout, "reason",
4658                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4659
4660   if (any_deleted)
4661     {
4662       struct cleanup *cleanup;
4663       char *name;
4664       int ix;
4665
4666       ui_out_text (current_uiout, _("  Inferior unloaded "));
4667       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4668                                                     "removed");
4669       for (ix = 0;
4670            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4671                         ix, name);
4672            ++ix)
4673         {
4674           if (ix > 0)
4675             ui_out_text (current_uiout, "    ");
4676           ui_out_field_string (current_uiout, "library", name);
4677           ui_out_text (current_uiout, "\n");
4678         }
4679
4680       do_cleanups (cleanup);
4681     }
4682
4683   if (any_added)
4684     {
4685       struct so_list *iter;
4686       int ix;
4687       struct cleanup *cleanup;
4688
4689       ui_out_text (current_uiout, _("  Inferior loaded "));
4690       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4691                                                     "added");
4692       for (ix = 0;
4693            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4694                         ix, iter);
4695            ++ix)
4696         {
4697           if (ix > 0)
4698             ui_out_text (current_uiout, "    ");
4699           ui_out_field_string (current_uiout, "library", iter->so_name);
4700           ui_out_text (current_uiout, "\n");
4701         }
4702
4703       do_cleanups (cleanup);
4704     }
4705 }
4706
4707 /* Print a message indicating what happened.  This is called from
4708    normal_stop().  The input to this routine is the head of the bpstat
4709    list - a list of the eventpoints that caused this stop.  KIND is
4710    the target_waitkind for the stopping event.  This
4711    routine calls the generic print routine for printing a message
4712    about reasons for stopping.  This will print (for example) the
4713    "Breakpoint n," part of the output.  The return value of this
4714    routine is one of:
4715
4716    PRINT_UNKNOWN: Means we printed nothing.
4717    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4718    code to print the location.  An example is 
4719    "Breakpoint 1, " which should be followed by
4720    the location.
4721    PRINT_SRC_ONLY: Means we printed something, but there is no need
4722    to also print the location part of the message.
4723    An example is the catch/throw messages, which
4724    don't require a location appended to the end.
4725    PRINT_NOTHING: We have done some printing and we don't need any 
4726    further info to be printed.  */
4727
4728 enum print_stop_action
4729 bpstat_print (bpstat bs, int kind)
4730 {
4731   int val;
4732
4733   /* Maybe another breakpoint in the chain caused us to stop.
4734      (Currently all watchpoints go on the bpstat whether hit or not.
4735      That probably could (should) be changed, provided care is taken
4736      with respect to bpstat_explains_signal).  */
4737   for (; bs; bs = bs->next)
4738     {
4739       val = print_bp_stop_message (bs);
4740       if (val == PRINT_SRC_ONLY 
4741           || val == PRINT_SRC_AND_LOC 
4742           || val == PRINT_NOTHING)
4743         return val;
4744     }
4745
4746   /* If we had hit a shared library event breakpoint,
4747      print_bp_stop_message would print out this message.  If we hit an
4748      OS-level shared library event, do the same thing.  */
4749   if (kind == TARGET_WAITKIND_LOADED)
4750     {
4751       print_solib_event (0);
4752       return PRINT_NOTHING;
4753     }
4754
4755   /* We reached the end of the chain, or we got a null BS to start
4756      with and nothing was printed.  */
4757   return PRINT_UNKNOWN;
4758 }
4759
4760 /* Evaluate the expression EXP and return 1 if value is zero.
4761    This returns the inverse of the condition because it is called
4762    from catch_errors which returns 0 if an exception happened, and if an
4763    exception happens we want execution to stop.
4764    The argument is a "struct expression *" that has been cast to a
4765    "void *" to make it pass through catch_errors.  */
4766
4767 static int
4768 breakpoint_cond_eval (void *exp)
4769 {
4770   struct value *mark = value_mark ();
4771   int i = !value_true (evaluate_expression ((struct expression *) exp));
4772
4773   value_free_to_mark (mark);
4774   return i;
4775 }
4776
4777 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4778
4779 static bpstat
4780 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4781 {
4782   bpstat bs;
4783
4784   bs = (bpstat) xmalloc (sizeof (*bs));
4785   bs->next = NULL;
4786   **bs_link_pointer = bs;
4787   *bs_link_pointer = &bs->next;
4788   bs->breakpoint_at = bl->owner;
4789   bs->bp_location_at = bl;
4790   incref_bp_location (bl);
4791   /* If the condition is false, etc., don't do the commands.  */
4792   bs->commands = NULL;
4793   bs->old_val = NULL;
4794   bs->print_it = print_it_normal;
4795   return bs;
4796 }
4797 \f
4798 /* The target has stopped with waitstatus WS.  Check if any hardware
4799    watchpoints have triggered, according to the target.  */
4800
4801 int
4802 watchpoints_triggered (struct target_waitstatus *ws)
4803 {
4804   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4805   CORE_ADDR addr;
4806   struct breakpoint *b;
4807
4808   if (!stopped_by_watchpoint)
4809     {
4810       /* We were not stopped by a watchpoint.  Mark all watchpoints
4811          as not triggered.  */
4812       ALL_BREAKPOINTS (b)
4813         if (is_hardware_watchpoint (b))
4814           {
4815             struct watchpoint *w = (struct watchpoint *) b;
4816
4817             w->watchpoint_triggered = watch_triggered_no;
4818           }
4819
4820       return 0;
4821     }
4822
4823   if (!target_stopped_data_address (&current_target, &addr))
4824     {
4825       /* We were stopped by a watchpoint, but we don't know where.
4826          Mark all watchpoints as unknown.  */
4827       ALL_BREAKPOINTS (b)
4828         if (is_hardware_watchpoint (b))
4829           {
4830             struct watchpoint *w = (struct watchpoint *) b;
4831
4832             w->watchpoint_triggered = watch_triggered_unknown;
4833           }
4834
4835       return 1;
4836     }
4837
4838   /* The target could report the data address.  Mark watchpoints
4839      affected by this data address as triggered, and all others as not
4840      triggered.  */
4841
4842   ALL_BREAKPOINTS (b)
4843     if (is_hardware_watchpoint (b))
4844       {
4845         struct watchpoint *w = (struct watchpoint *) b;
4846         struct bp_location *loc;
4847
4848         w->watchpoint_triggered = watch_triggered_no;
4849         for (loc = b->loc; loc; loc = loc->next)
4850           {
4851             if (is_masked_watchpoint (b))
4852               {
4853                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4854                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4855
4856                 if (newaddr == start)
4857                   {
4858                     w->watchpoint_triggered = watch_triggered_yes;
4859                     break;
4860                   }
4861               }
4862             /* Exact match not required.  Within range is sufficient.  */
4863             else if (target_watchpoint_addr_within_range (&current_target,
4864                                                          addr, loc->address,
4865                                                          loc->length))
4866               {
4867                 w->watchpoint_triggered = watch_triggered_yes;
4868                 break;
4869               }
4870           }
4871       }
4872
4873   return 1;
4874 }
4875
4876 /* Possible return values for watchpoint_check (this can't be an enum
4877    because of check_errors).  */
4878 /* The watchpoint has been deleted.  */
4879 #define WP_DELETED 1
4880 /* The value has changed.  */
4881 #define WP_VALUE_CHANGED 2
4882 /* The value has not changed.  */
4883 #define WP_VALUE_NOT_CHANGED 3
4884 /* Ignore this watchpoint, no matter if the value changed or not.  */
4885 #define WP_IGNORE 4
4886
4887 #define BP_TEMPFLAG 1
4888 #define BP_HARDWAREFLAG 2
4889
4890 /* Evaluate watchpoint condition expression and check if its value
4891    changed.
4892
4893    P should be a pointer to struct bpstat, but is defined as a void *
4894    in order for this function to be usable with catch_errors.  */
4895
4896 static int
4897 watchpoint_check (void *p)
4898 {
4899   bpstat bs = (bpstat) p;
4900   struct watchpoint *b;
4901   struct frame_info *fr;
4902   int within_current_scope;
4903
4904   /* BS is built from an existing struct breakpoint.  */
4905   gdb_assert (bs->breakpoint_at != NULL);
4906   b = (struct watchpoint *) bs->breakpoint_at;
4907
4908   /* If this is a local watchpoint, we only want to check if the
4909      watchpoint frame is in scope if the current thread is the thread
4910      that was used to create the watchpoint.  */
4911   if (!watchpoint_in_thread_scope (b))
4912     return WP_IGNORE;
4913
4914   if (b->exp_valid_block == NULL)
4915     within_current_scope = 1;
4916   else
4917     {
4918       struct frame_info *frame = get_current_frame ();
4919       struct gdbarch *frame_arch = get_frame_arch (frame);
4920       CORE_ADDR frame_pc = get_frame_pc (frame);
4921
4922       /* in_function_epilogue_p() returns a non-zero value if we're
4923          still in the function but the stack frame has already been
4924          invalidated.  Since we can't rely on the values of local
4925          variables after the stack has been destroyed, we are treating
4926          the watchpoint in that state as `not changed' without further
4927          checking.  Don't mark watchpoints as changed if the current
4928          frame is in an epilogue - even if they are in some other
4929          frame, our view of the stack is likely to be wrong and
4930          frame_find_by_id could error out.  */
4931       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4932         return WP_IGNORE;
4933
4934       fr = frame_find_by_id (b->watchpoint_frame);
4935       within_current_scope = (fr != NULL);
4936
4937       /* If we've gotten confused in the unwinder, we might have
4938          returned a frame that can't describe this variable.  */
4939       if (within_current_scope)
4940         {
4941           struct symbol *function;
4942
4943           function = get_frame_function (fr);
4944           if (function == NULL
4945               || !contained_in (b->exp_valid_block,
4946                                 SYMBOL_BLOCK_VALUE (function)))
4947             within_current_scope = 0;
4948         }
4949
4950       if (within_current_scope)
4951         /* If we end up stopping, the current frame will get selected
4952            in normal_stop.  So this call to select_frame won't affect
4953            the user.  */
4954         select_frame (fr);
4955     }
4956
4957   if (within_current_scope)
4958     {
4959       /* We use value_{,free_to_}mark because it could be a *long*
4960          time before we return to the command level and call
4961          free_all_values.  We can't call free_all_values because we
4962          might be in the middle of evaluating a function call.  */
4963
4964       int pc = 0;
4965       struct value *mark;
4966       struct value *new_val;
4967
4968       if (is_masked_watchpoint (&b->base))
4969         /* Since we don't know the exact trigger address (from
4970            stopped_data_address), just tell the user we've triggered
4971            a mask watchpoint.  */
4972         return WP_VALUE_CHANGED;
4973
4974       mark = value_mark ();
4975       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
4976
4977       /* We use value_equal_contents instead of value_equal because
4978          the latter coerces an array to a pointer, thus comparing just
4979          the address of the array instead of its contents.  This is
4980          not what we want.  */
4981       if ((b->val != NULL) != (new_val != NULL)
4982           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4983         {
4984           if (new_val != NULL)
4985             {
4986               release_value (new_val);
4987               value_free_to_mark (mark);
4988             }
4989           bs->old_val = b->val;
4990           b->val = new_val;
4991           b->val_valid = 1;
4992           return WP_VALUE_CHANGED;
4993         }
4994       else
4995         {
4996           /* Nothing changed.  */
4997           value_free_to_mark (mark);
4998           return WP_VALUE_NOT_CHANGED;
4999         }
5000     }
5001   else
5002     {
5003       struct ui_out *uiout = current_uiout;
5004
5005       /* This seems like the only logical thing to do because
5006          if we temporarily ignored the watchpoint, then when
5007          we reenter the block in which it is valid it contains
5008          garbage (in the case of a function, it may have two
5009          garbage values, one before and one after the prologue).
5010          So we can't even detect the first assignment to it and
5011          watch after that (since the garbage may or may not equal
5012          the first value assigned).  */
5013       /* We print all the stop information in
5014          breakpoint_ops->print_it, but in this case, by the time we
5015          call breakpoint_ops->print_it this bp will be deleted
5016          already.  So we have no choice but print the information
5017          here.  */
5018       if (ui_out_is_mi_like_p (uiout))
5019         ui_out_field_string
5020           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5021       ui_out_text (uiout, "\nWatchpoint ");
5022       ui_out_field_int (uiout, "wpnum", b->base.number);
5023       ui_out_text (uiout,
5024                    " deleted because the program has left the block in\n\
5025 which its expression is valid.\n");     
5026
5027       /* Make sure the watchpoint's commands aren't executed.  */
5028       decref_counted_command_line (&b->base.commands);
5029       watchpoint_del_at_next_stop (b);
5030
5031       return WP_DELETED;
5032     }
5033 }
5034
5035 /* Return true if it looks like target has stopped due to hitting
5036    breakpoint location BL.  This function does not check if we should
5037    stop, only if BL explains the stop.  */
5038
5039 static int
5040 bpstat_check_location (const struct bp_location *bl,
5041                        struct address_space *aspace, CORE_ADDR bp_addr,
5042                        const struct target_waitstatus *ws)
5043 {
5044   struct breakpoint *b = bl->owner;
5045
5046   /* BL is from an existing breakpoint.  */
5047   gdb_assert (b != NULL);
5048
5049   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5050 }
5051
5052 /* Determine if the watched values have actually changed, and we
5053    should stop.  If not, set BS->stop to 0.  */
5054
5055 static void
5056 bpstat_check_watchpoint (bpstat bs)
5057 {
5058   const struct bp_location *bl;
5059   struct watchpoint *b;
5060
5061   /* BS is built for existing struct breakpoint.  */
5062   bl = bs->bp_location_at;
5063   gdb_assert (bl != NULL);
5064   b = (struct watchpoint *) bs->breakpoint_at;
5065   gdb_assert (b != NULL);
5066
5067     {
5068       int must_check_value = 0;
5069       
5070       if (b->base.type == bp_watchpoint)
5071         /* For a software watchpoint, we must always check the
5072            watched value.  */
5073         must_check_value = 1;
5074       else if (b->watchpoint_triggered == watch_triggered_yes)
5075         /* We have a hardware watchpoint (read, write, or access)
5076            and the target earlier reported an address watched by
5077            this watchpoint.  */
5078         must_check_value = 1;
5079       else if (b->watchpoint_triggered == watch_triggered_unknown
5080                && b->base.type == bp_hardware_watchpoint)
5081         /* We were stopped by a hardware watchpoint, but the target could
5082            not report the data address.  We must check the watchpoint's
5083            value.  Access and read watchpoints are out of luck; without
5084            a data address, we can't figure it out.  */
5085         must_check_value = 1;
5086
5087       if (must_check_value)
5088         {
5089           char *message
5090             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5091                           b->base.number);
5092           struct cleanup *cleanups = make_cleanup (xfree, message);
5093           int e = catch_errors (watchpoint_check, bs, message,
5094                                 RETURN_MASK_ALL);
5095           do_cleanups (cleanups);
5096           switch (e)
5097             {
5098             case WP_DELETED:
5099               /* We've already printed what needs to be printed.  */
5100               bs->print_it = print_it_done;
5101               /* Stop.  */
5102               break;
5103             case WP_IGNORE:
5104               bs->print_it = print_it_noop;
5105               bs->stop = 0;
5106               break;
5107             case WP_VALUE_CHANGED:
5108               if (b->base.type == bp_read_watchpoint)
5109                 {
5110                   /* There are two cases to consider here:
5111
5112                      1. We're watching the triggered memory for reads.
5113                      In that case, trust the target, and always report
5114                      the watchpoint hit to the user.  Even though
5115                      reads don't cause value changes, the value may
5116                      have changed since the last time it was read, and
5117                      since we're not trapping writes, we will not see
5118                      those, and as such we should ignore our notion of
5119                      old value.
5120
5121                      2. We're watching the triggered memory for both
5122                      reads and writes.  There are two ways this may
5123                      happen:
5124
5125                      2.1. This is a target that can't break on data
5126                      reads only, but can break on accesses (reads or
5127                      writes), such as e.g., x86.  We detect this case
5128                      at the time we try to insert read watchpoints.
5129
5130                      2.2. Otherwise, the target supports read
5131                      watchpoints, but, the user set an access or write
5132                      watchpoint watching the same memory as this read
5133                      watchpoint.
5134
5135                      If we're watching memory writes as well as reads,
5136                      ignore watchpoint hits when we find that the
5137                      value hasn't changed, as reads don't cause
5138                      changes.  This still gives false positives when
5139                      the program writes the same value to memory as
5140                      what there was already in memory (we will confuse
5141                      it for a read), but it's much better than
5142                      nothing.  */
5143
5144                   int other_write_watchpoint = 0;
5145
5146                   if (bl->watchpoint_type == hw_read)
5147                     {
5148                       struct breakpoint *other_b;
5149
5150                       ALL_BREAKPOINTS (other_b)
5151                         if (other_b->type == bp_hardware_watchpoint
5152                             || other_b->type == bp_access_watchpoint)
5153                           {
5154                             struct watchpoint *other_w =
5155                               (struct watchpoint *) other_b;
5156
5157                             if (other_w->watchpoint_triggered
5158                                 == watch_triggered_yes)
5159                               {
5160                                 other_write_watchpoint = 1;
5161                                 break;
5162                               }
5163                           }
5164                     }
5165
5166                   if (other_write_watchpoint
5167                       || bl->watchpoint_type == hw_access)
5168                     {
5169                       /* We're watching the same memory for writes,
5170                          and the value changed since the last time we
5171                          updated it, so this trap must be for a write.
5172                          Ignore it.  */
5173                       bs->print_it = print_it_noop;
5174                       bs->stop = 0;
5175                     }
5176                 }
5177               break;
5178             case WP_VALUE_NOT_CHANGED:
5179               if (b->base.type == bp_hardware_watchpoint
5180                   || b->base.type == bp_watchpoint)
5181                 {
5182                   /* Don't stop: write watchpoints shouldn't fire if
5183                      the value hasn't changed.  */
5184                   bs->print_it = print_it_noop;
5185                   bs->stop = 0;
5186                 }
5187               /* Stop.  */
5188               break;
5189             default:
5190               /* Can't happen.  */
5191             case 0:
5192               /* Error from catch_errors.  */
5193               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5194               watchpoint_del_at_next_stop (b);
5195               /* We've already printed what needs to be printed.  */
5196               bs->print_it = print_it_done;
5197               break;
5198             }
5199         }
5200       else      /* must_check_value == 0 */
5201         {
5202           /* This is a case where some watchpoint(s) triggered, but
5203              not at the address of this watchpoint, or else no
5204              watchpoint triggered after all.  So don't print
5205              anything for this watchpoint.  */
5206           bs->print_it = print_it_noop;
5207           bs->stop = 0;
5208         }
5209     }
5210 }
5211
5212 /* For breakpoints that are currently marked as telling gdb to stop,
5213    check conditions (condition proper, frame, thread and ignore count)
5214    of breakpoint referred to by BS.  If we should not stop for this
5215    breakpoint, set BS->stop to 0.  */
5216
5217 static void
5218 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5219 {
5220   const struct bp_location *bl;
5221   struct breakpoint *b;
5222   int value_is_zero = 0;
5223   struct expression *cond;
5224
5225   gdb_assert (bs->stop);
5226
5227   /* BS is built for existing struct breakpoint.  */
5228   bl = bs->bp_location_at;
5229   gdb_assert (bl != NULL);
5230   b = bs->breakpoint_at;
5231   gdb_assert (b != NULL);
5232
5233   /* Even if the target evaluated the condition on its end and notified GDB, we
5234      need to do so again since GDB does not know if we stopped due to a
5235      breakpoint or a single step breakpoint.  */
5236
5237   if (frame_id_p (b->frame_id)
5238       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5239     {
5240       bs->stop = 0;
5241       return;
5242     }
5243
5244   /* If this is a thread/task-specific breakpoint, don't waste cpu
5245      evaluating the condition if this isn't the specified
5246      thread/task.  */
5247   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5248       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5249
5250     {
5251       bs->stop = 0;
5252       return;
5253     }
5254
5255   /* Evaluate extension language breakpoints that have a "stop" method
5256      implemented.  */
5257   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5258
5259   if (is_watchpoint (b))
5260     {
5261       struct watchpoint *w = (struct watchpoint *) b;
5262
5263       cond = w->cond_exp;
5264     }
5265   else
5266     cond = bl->cond;
5267
5268   if (cond && b->disposition != disp_del_at_next_stop)
5269     {
5270       int within_current_scope = 1;
5271       struct watchpoint * w;
5272
5273       /* We use value_mark and value_free_to_mark because it could
5274          be a long time before we return to the command level and
5275          call free_all_values.  We can't call free_all_values
5276          because we might be in the middle of evaluating a
5277          function call.  */
5278       struct value *mark = value_mark ();
5279
5280       if (is_watchpoint (b))
5281         w = (struct watchpoint *) b;
5282       else
5283         w = NULL;
5284
5285       /* Need to select the frame, with all that implies so that
5286          the conditions will have the right context.  Because we
5287          use the frame, we will not see an inlined function's
5288          variables when we arrive at a breakpoint at the start
5289          of the inlined function; the current frame will be the
5290          call site.  */
5291       if (w == NULL || w->cond_exp_valid_block == NULL)
5292         select_frame (get_current_frame ());
5293       else
5294         {
5295           struct frame_info *frame;
5296
5297           /* For local watchpoint expressions, which particular
5298              instance of a local is being watched matters, so we
5299              keep track of the frame to evaluate the expression
5300              in.  To evaluate the condition however, it doesn't
5301              really matter which instantiation of the function
5302              where the condition makes sense triggers the
5303              watchpoint.  This allows an expression like "watch
5304              global if q > 10" set in `func', catch writes to
5305              global on all threads that call `func', or catch
5306              writes on all recursive calls of `func' by a single
5307              thread.  We simply always evaluate the condition in
5308              the innermost frame that's executing where it makes
5309              sense to evaluate the condition.  It seems
5310              intuitive.  */
5311           frame = block_innermost_frame (w->cond_exp_valid_block);
5312           if (frame != NULL)
5313             select_frame (frame);
5314           else
5315             within_current_scope = 0;
5316         }
5317       if (within_current_scope)
5318         value_is_zero
5319           = catch_errors (breakpoint_cond_eval, cond,
5320                           "Error in testing breakpoint condition:\n",
5321                           RETURN_MASK_ALL);
5322       else
5323         {
5324           warning (_("Watchpoint condition cannot be tested "
5325                      "in the current scope"));
5326           /* If we failed to set the right context for this
5327              watchpoint, unconditionally report it.  */
5328           value_is_zero = 0;
5329         }
5330       /* FIXME-someday, should give breakpoint #.  */
5331       value_free_to_mark (mark);
5332     }
5333
5334   if (cond && value_is_zero)
5335     {
5336       bs->stop = 0;
5337     }
5338   else if (b->ignore_count > 0)
5339     {
5340       b->ignore_count--;
5341       bs->stop = 0;
5342       /* Increase the hit count even though we don't stop.  */
5343       ++(b->hit_count);
5344       observer_notify_breakpoint_modified (b);
5345     }   
5346 }
5347
5348
5349 /* Get a bpstat associated with having just stopped at address
5350    BP_ADDR in thread PTID.
5351
5352    Determine whether we stopped at a breakpoint, etc, or whether we
5353    don't understand this stop.  Result is a chain of bpstat's such
5354    that:
5355
5356    if we don't understand the stop, the result is a null pointer.
5357
5358    if we understand why we stopped, the result is not null.
5359
5360    Each element of the chain refers to a particular breakpoint or
5361    watchpoint at which we have stopped.  (We may have stopped for
5362    several reasons concurrently.)
5363
5364    Each element of the chain has valid next, breakpoint_at,
5365    commands, FIXME??? fields.  */
5366
5367 bpstat
5368 bpstat_stop_status (struct address_space *aspace,
5369                     CORE_ADDR bp_addr, ptid_t ptid,
5370                     const struct target_waitstatus *ws)
5371 {
5372   struct breakpoint *b = NULL;
5373   struct bp_location *bl;
5374   struct bp_location *loc;
5375   /* First item of allocated bpstat's.  */
5376   bpstat bs_head = NULL, *bs_link = &bs_head;
5377   /* Pointer to the last thing in the chain currently.  */
5378   bpstat bs;
5379   int ix;
5380   int need_remove_insert;
5381   int removed_any;
5382
5383   /* First, build the bpstat chain with locations that explain a
5384      target stop, while being careful to not set the target running,
5385      as that may invalidate locations (in particular watchpoint
5386      locations are recreated).  Resuming will happen here with
5387      breakpoint conditions or watchpoint expressions that include
5388      inferior function calls.  */
5389
5390   ALL_BREAKPOINTS (b)
5391     {
5392       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5393         continue;
5394
5395       for (bl = b->loc; bl != NULL; bl = bl->next)
5396         {
5397           /* For hardware watchpoints, we look only at the first
5398              location.  The watchpoint_check function will work on the
5399              entire expression, not the individual locations.  For
5400              read watchpoints, the watchpoints_triggered function has
5401              checked all locations already.  */
5402           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5403             break;
5404
5405           if (!bl->enabled || bl->shlib_disabled)
5406             continue;
5407
5408           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5409             continue;
5410
5411           /* Come here if it's a watchpoint, or if the break address
5412              matches.  */
5413
5414           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5415                                                    explain stop.  */
5416
5417           /* Assume we stop.  Should we find a watchpoint that is not
5418              actually triggered, or if the condition of the breakpoint
5419              evaluates as false, we'll reset 'stop' to 0.  */
5420           bs->stop = 1;
5421           bs->print = 1;
5422
5423           /* If this is a scope breakpoint, mark the associated
5424              watchpoint as triggered so that we will handle the
5425              out-of-scope event.  We'll get to the watchpoint next
5426              iteration.  */
5427           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5428             {
5429               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5430
5431               w->watchpoint_triggered = watch_triggered_yes;
5432             }
5433         }
5434     }
5435
5436   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5437     {
5438       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5439         {
5440           bs = bpstat_alloc (loc, &bs_link);
5441           /* For hits of moribund locations, we should just proceed.  */
5442           bs->stop = 0;
5443           bs->print = 0;
5444           bs->print_it = print_it_noop;
5445         }
5446     }
5447
5448   /* A bit of special processing for shlib breakpoints.  We need to
5449      process solib loading here, so that the lists of loaded and
5450      unloaded libraries are correct before we handle "catch load" and
5451      "catch unload".  */
5452   for (bs = bs_head; bs != NULL; bs = bs->next)
5453     {
5454       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5455         {
5456           handle_solib_event ();
5457           break;
5458         }
5459     }
5460
5461   /* Now go through the locations that caused the target to stop, and
5462      check whether we're interested in reporting this stop to higher
5463      layers, or whether we should resume the target transparently.  */
5464
5465   removed_any = 0;
5466
5467   for (bs = bs_head; bs != NULL; bs = bs->next)
5468     {
5469       if (!bs->stop)
5470         continue;
5471
5472       b = bs->breakpoint_at;
5473       b->ops->check_status (bs);
5474       if (bs->stop)
5475         {
5476           bpstat_check_breakpoint_conditions (bs, ptid);
5477
5478           if (bs->stop)
5479             {
5480               ++(b->hit_count);
5481               observer_notify_breakpoint_modified (b);
5482
5483               /* We will stop here.  */
5484               if (b->disposition == disp_disable)
5485                 {
5486                   --(b->enable_count);
5487                   if (b->enable_count <= 0
5488                       && b->enable_state != bp_permanent)
5489                     b->enable_state = bp_disabled;
5490                   removed_any = 1;
5491                 }
5492               if (b->silent)
5493                 bs->print = 0;
5494               bs->commands = b->commands;
5495               incref_counted_command_line (bs->commands);
5496               if (command_line_is_silent (bs->commands
5497                                           ? bs->commands->commands : NULL))
5498                 bs->print = 0;
5499
5500               b->ops->after_condition_true (bs);
5501             }
5502
5503         }
5504
5505       /* Print nothing for this entry if we don't stop or don't
5506          print.  */
5507       if (!bs->stop || !bs->print)
5508         bs->print_it = print_it_noop;
5509     }
5510
5511   /* If we aren't stopping, the value of some hardware watchpoint may
5512      not have changed, but the intermediate memory locations we are
5513      watching may have.  Don't bother if we're stopping; this will get
5514      done later.  */
5515   need_remove_insert = 0;
5516   if (! bpstat_causes_stop (bs_head))
5517     for (bs = bs_head; bs != NULL; bs = bs->next)
5518       if (!bs->stop
5519           && bs->breakpoint_at
5520           && is_hardware_watchpoint (bs->breakpoint_at))
5521         {
5522           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5523
5524           update_watchpoint (w, 0 /* don't reparse.  */);
5525           need_remove_insert = 1;
5526         }
5527
5528   if (need_remove_insert)
5529     update_global_location_list (1);
5530   else if (removed_any)
5531     update_global_location_list (0);
5532
5533   return bs_head;
5534 }
5535
5536 static void
5537 handle_jit_event (void)
5538 {
5539   struct frame_info *frame;
5540   struct gdbarch *gdbarch;
5541
5542   /* Switch terminal for any messages produced by
5543      breakpoint_re_set.  */
5544   target_terminal_ours_for_output ();
5545
5546   frame = get_current_frame ();
5547   gdbarch = get_frame_arch (frame);
5548
5549   jit_event_handler (gdbarch);
5550
5551   target_terminal_inferior ();
5552 }
5553
5554 /* Prepare WHAT final decision for infrun.  */
5555
5556 /* Decide what infrun needs to do with this bpstat.  */
5557
5558 struct bpstat_what
5559 bpstat_what (bpstat bs_head)
5560 {
5561   struct bpstat_what retval;
5562   int jit_event = 0;
5563   bpstat bs;
5564
5565   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5566   retval.call_dummy = STOP_NONE;
5567   retval.is_longjmp = 0;
5568
5569   for (bs = bs_head; bs != NULL; bs = bs->next)
5570     {
5571       /* Extract this BS's action.  After processing each BS, we check
5572          if its action overrides all we've seem so far.  */
5573       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5574       enum bptype bptype;
5575
5576       if (bs->breakpoint_at == NULL)
5577         {
5578           /* I suspect this can happen if it was a momentary
5579              breakpoint which has since been deleted.  */
5580           bptype = bp_none;
5581         }
5582       else
5583         bptype = bs->breakpoint_at->type;
5584
5585       switch (bptype)
5586         {
5587         case bp_none:
5588           break;
5589         case bp_breakpoint:
5590         case bp_hardware_breakpoint:
5591         case bp_until:
5592         case bp_finish:
5593         case bp_shlib_event:
5594           if (bs->stop)
5595             {
5596               if (bs->print)
5597                 this_action = BPSTAT_WHAT_STOP_NOISY;
5598               else
5599                 this_action = BPSTAT_WHAT_STOP_SILENT;
5600             }
5601           else
5602             this_action = BPSTAT_WHAT_SINGLE;
5603           break;
5604         case bp_watchpoint:
5605         case bp_hardware_watchpoint:
5606         case bp_read_watchpoint:
5607         case bp_access_watchpoint:
5608           if (bs->stop)
5609             {
5610               if (bs->print)
5611                 this_action = BPSTAT_WHAT_STOP_NOISY;
5612               else
5613                 this_action = BPSTAT_WHAT_STOP_SILENT;
5614             }
5615           else
5616             {
5617               /* There was a watchpoint, but we're not stopping.
5618                  This requires no further action.  */
5619             }
5620           break;
5621         case bp_longjmp:
5622         case bp_longjmp_call_dummy:
5623         case bp_exception:
5624           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5625           retval.is_longjmp = bptype != bp_exception;
5626           break;
5627         case bp_longjmp_resume:
5628         case bp_exception_resume:
5629           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5630           retval.is_longjmp = bptype == bp_longjmp_resume;
5631           break;
5632         case bp_step_resume:
5633           if (bs->stop)
5634             this_action = BPSTAT_WHAT_STEP_RESUME;
5635           else
5636             {
5637               /* It is for the wrong frame.  */
5638               this_action = BPSTAT_WHAT_SINGLE;
5639             }
5640           break;
5641         case bp_hp_step_resume:
5642           if (bs->stop)
5643             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5644           else
5645             {
5646               /* It is for the wrong frame.  */
5647               this_action = BPSTAT_WHAT_SINGLE;
5648             }
5649           break;
5650         case bp_watchpoint_scope:
5651         case bp_thread_event:
5652         case bp_overlay_event:
5653         case bp_longjmp_master:
5654         case bp_std_terminate_master:
5655         case bp_exception_master:
5656           this_action = BPSTAT_WHAT_SINGLE;
5657           break;
5658         case bp_catchpoint:
5659           if (bs->stop)
5660             {
5661               if (bs->print)
5662                 this_action = BPSTAT_WHAT_STOP_NOISY;
5663               else
5664                 this_action = BPSTAT_WHAT_STOP_SILENT;
5665             }
5666           else
5667             {
5668               /* There was a catchpoint, but we're not stopping.
5669                  This requires no further action.  */
5670             }
5671           break;
5672         case bp_jit_event:
5673           jit_event = 1;
5674           this_action = BPSTAT_WHAT_SINGLE;
5675           break;
5676         case bp_call_dummy:
5677           /* Make sure the action is stop (silent or noisy),
5678              so infrun.c pops the dummy frame.  */
5679           retval.call_dummy = STOP_STACK_DUMMY;
5680           this_action = BPSTAT_WHAT_STOP_SILENT;
5681           break;
5682         case bp_std_terminate:
5683           /* Make sure the action is stop (silent or noisy),
5684              so infrun.c pops the dummy frame.  */
5685           retval.call_dummy = STOP_STD_TERMINATE;
5686           this_action = BPSTAT_WHAT_STOP_SILENT;
5687           break;
5688         case bp_tracepoint:
5689         case bp_fast_tracepoint:
5690         case bp_static_tracepoint:
5691           /* Tracepoint hits should not be reported back to GDB, and
5692              if one got through somehow, it should have been filtered
5693              out already.  */
5694           internal_error (__FILE__, __LINE__,
5695                           _("bpstat_what: tracepoint encountered"));
5696           break;
5697         case bp_gnu_ifunc_resolver:
5698           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5699           this_action = BPSTAT_WHAT_SINGLE;
5700           break;
5701         case bp_gnu_ifunc_resolver_return:
5702           /* The breakpoint will be removed, execution will restart from the
5703              PC of the former breakpoint.  */
5704           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5705           break;
5706
5707         case bp_dprintf:
5708           if (bs->stop)
5709             this_action = BPSTAT_WHAT_STOP_SILENT;
5710           else
5711             this_action = BPSTAT_WHAT_SINGLE;
5712           break;
5713
5714         default:
5715           internal_error (__FILE__, __LINE__,
5716                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5717         }
5718
5719       retval.main_action = max (retval.main_action, this_action);
5720     }
5721
5722   /* These operations may affect the bs->breakpoint_at state so they are
5723      delayed after MAIN_ACTION is decided above.  */
5724
5725   if (jit_event)
5726     {
5727       if (debug_infrun)
5728         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5729
5730       handle_jit_event ();
5731     }
5732
5733   for (bs = bs_head; bs != NULL; bs = bs->next)
5734     {
5735       struct breakpoint *b = bs->breakpoint_at;
5736
5737       if (b == NULL)
5738         continue;
5739       switch (b->type)
5740         {
5741         case bp_gnu_ifunc_resolver:
5742           gnu_ifunc_resolver_stop (b);
5743           break;
5744         case bp_gnu_ifunc_resolver_return:
5745           gnu_ifunc_resolver_return_stop (b);
5746           break;
5747         }
5748     }
5749
5750   return retval;
5751 }
5752
5753 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5754    without hardware support).  This isn't related to a specific bpstat,
5755    just to things like whether watchpoints are set.  */
5756
5757 int
5758 bpstat_should_step (void)
5759 {
5760   struct breakpoint *b;
5761
5762   ALL_BREAKPOINTS (b)
5763     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5764       return 1;
5765   return 0;
5766 }
5767
5768 int
5769 bpstat_causes_stop (bpstat bs)
5770 {
5771   for (; bs != NULL; bs = bs->next)
5772     if (bs->stop)
5773       return 1;
5774
5775   return 0;
5776 }
5777
5778 \f
5779
5780 /* Compute a string of spaces suitable to indent the next line
5781    so it starts at the position corresponding to the table column
5782    named COL_NAME in the currently active table of UIOUT.  */
5783
5784 static char *
5785 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5786 {
5787   static char wrap_indent[80];
5788   int i, total_width, width, align;
5789   char *text;
5790
5791   total_width = 0;
5792   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5793     {
5794       if (strcmp (text, col_name) == 0)
5795         {
5796           gdb_assert (total_width < sizeof wrap_indent);
5797           memset (wrap_indent, ' ', total_width);
5798           wrap_indent[total_width] = 0;
5799
5800           return wrap_indent;
5801         }
5802
5803       total_width += width + 1;
5804     }
5805
5806   return NULL;
5807 }
5808
5809 /* Determine if the locations of this breakpoint will have their conditions
5810    evaluated by the target, host or a mix of both.  Returns the following:
5811
5812     "host": Host evals condition.
5813     "host or target": Host or Target evals condition.
5814     "target": Target evals condition.
5815 */
5816
5817 static const char *
5818 bp_condition_evaluator (struct breakpoint *b)
5819 {
5820   struct bp_location *bl;
5821   char host_evals = 0;
5822   char target_evals = 0;
5823
5824   if (!b)
5825     return NULL;
5826
5827   if (!is_breakpoint (b))
5828     return NULL;
5829
5830   if (gdb_evaluates_breakpoint_condition_p ()
5831       || !target_supports_evaluation_of_breakpoint_conditions ())
5832     return condition_evaluation_host;
5833
5834   for (bl = b->loc; bl; bl = bl->next)
5835     {
5836       if (bl->cond_bytecode)
5837         target_evals++;
5838       else
5839         host_evals++;
5840     }
5841
5842   if (host_evals && target_evals)
5843     return condition_evaluation_both;
5844   else if (target_evals)
5845     return condition_evaluation_target;
5846   else
5847     return condition_evaluation_host;
5848 }
5849
5850 /* Determine the breakpoint location's condition evaluator.  This is
5851    similar to bp_condition_evaluator, but for locations.  */
5852
5853 static const char *
5854 bp_location_condition_evaluator (struct bp_location *bl)
5855 {
5856   if (bl && !is_breakpoint (bl->owner))
5857     return NULL;
5858
5859   if (gdb_evaluates_breakpoint_condition_p ()
5860       || !target_supports_evaluation_of_breakpoint_conditions ())
5861     return condition_evaluation_host;
5862
5863   if (bl && bl->cond_bytecode)
5864     return condition_evaluation_target;
5865   else
5866     return condition_evaluation_host;
5867 }
5868
5869 /* Print the LOC location out of the list of B->LOC locations.  */
5870
5871 static void
5872 print_breakpoint_location (struct breakpoint *b,
5873                            struct bp_location *loc)
5874 {
5875   struct ui_out *uiout = current_uiout;
5876   struct cleanup *old_chain = save_current_program_space ();
5877
5878   if (loc != NULL && loc->shlib_disabled)
5879     loc = NULL;
5880
5881   if (loc != NULL)
5882     set_current_program_space (loc->pspace);
5883
5884   if (b->display_canonical)
5885     ui_out_field_string (uiout, "what", b->addr_string);
5886   else if (loc && loc->symtab)
5887     {
5888       struct symbol *sym 
5889         = find_pc_sect_function (loc->address, loc->section);
5890       if (sym)
5891         {
5892           ui_out_text (uiout, "in ");
5893           ui_out_field_string (uiout, "func",
5894                                SYMBOL_PRINT_NAME (sym));
5895           ui_out_text (uiout, " ");
5896           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5897           ui_out_text (uiout, "at ");
5898         }
5899       ui_out_field_string (uiout, "file",
5900                            symtab_to_filename_for_display (loc->symtab));
5901       ui_out_text (uiout, ":");
5902
5903       if (ui_out_is_mi_like_p (uiout))
5904         ui_out_field_string (uiout, "fullname",
5905                              symtab_to_fullname (loc->symtab));
5906       
5907       ui_out_field_int (uiout, "line", loc->line_number);
5908     }
5909   else if (loc)
5910     {
5911       struct ui_file *stb = mem_fileopen ();
5912       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5913
5914       print_address_symbolic (loc->gdbarch, loc->address, stb,
5915                               demangle, "");
5916       ui_out_field_stream (uiout, "at", stb);
5917
5918       do_cleanups (stb_chain);
5919     }
5920   else
5921     ui_out_field_string (uiout, "pending", b->addr_string);
5922
5923   if (loc && is_breakpoint (b)
5924       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5925       && bp_condition_evaluator (b) == condition_evaluation_both)
5926     {
5927       ui_out_text (uiout, " (");
5928       ui_out_field_string (uiout, "evaluated-by",
5929                            bp_location_condition_evaluator (loc));
5930       ui_out_text (uiout, ")");
5931     }
5932
5933   do_cleanups (old_chain);
5934 }
5935
5936 static const char *
5937 bptype_string (enum bptype type)
5938 {
5939   struct ep_type_description
5940     {
5941       enum bptype type;
5942       char *description;
5943     };
5944   static struct ep_type_description bptypes[] =
5945   {
5946     {bp_none, "?deleted?"},
5947     {bp_breakpoint, "breakpoint"},
5948     {bp_hardware_breakpoint, "hw breakpoint"},
5949     {bp_until, "until"},
5950     {bp_finish, "finish"},
5951     {bp_watchpoint, "watchpoint"},
5952     {bp_hardware_watchpoint, "hw watchpoint"},
5953     {bp_read_watchpoint, "read watchpoint"},
5954     {bp_access_watchpoint, "acc watchpoint"},
5955     {bp_longjmp, "longjmp"},
5956     {bp_longjmp_resume, "longjmp resume"},
5957     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5958     {bp_exception, "exception"},
5959     {bp_exception_resume, "exception resume"},
5960     {bp_step_resume, "step resume"},
5961     {bp_hp_step_resume, "high-priority step resume"},
5962     {bp_watchpoint_scope, "watchpoint scope"},
5963     {bp_call_dummy, "call dummy"},
5964     {bp_std_terminate, "std::terminate"},
5965     {bp_shlib_event, "shlib events"},
5966     {bp_thread_event, "thread events"},
5967     {bp_overlay_event, "overlay events"},
5968     {bp_longjmp_master, "longjmp master"},
5969     {bp_std_terminate_master, "std::terminate master"},
5970     {bp_exception_master, "exception master"},
5971     {bp_catchpoint, "catchpoint"},
5972     {bp_tracepoint, "tracepoint"},
5973     {bp_fast_tracepoint, "fast tracepoint"},
5974     {bp_static_tracepoint, "static tracepoint"},
5975     {bp_dprintf, "dprintf"},
5976     {bp_jit_event, "jit events"},
5977     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5978     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5979   };
5980
5981   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5982       || ((int) type != bptypes[(int) type].type))
5983     internal_error (__FILE__, __LINE__,
5984                     _("bptypes table does not describe type #%d."),
5985                     (int) type);
5986
5987   return bptypes[(int) type].description;
5988 }
5989
5990 /* For MI, output a field named 'thread-groups' with a list as the value.
5991    For CLI, prefix the list with the string 'inf'. */
5992
5993 static void
5994 output_thread_groups (struct ui_out *uiout,
5995                       const char *field_name,
5996                       VEC(int) *inf_num,
5997                       int mi_only)
5998 {
5999   struct cleanup *back_to;
6000   int is_mi = ui_out_is_mi_like_p (uiout);
6001   int inf;
6002   int i;
6003
6004   /* For backward compatibility, don't display inferiors in CLI unless
6005      there are several.  Always display them for MI. */
6006   if (!is_mi && mi_only)
6007     return;
6008
6009   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6010
6011   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6012     {
6013       if (is_mi)
6014         {
6015           char mi_group[10];
6016
6017           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6018           ui_out_field_string (uiout, NULL, mi_group);
6019         }
6020       else
6021         {
6022           if (i == 0)
6023             ui_out_text (uiout, " inf ");
6024           else
6025             ui_out_text (uiout, ", ");
6026         
6027           ui_out_text (uiout, plongest (inf));
6028         }
6029     }
6030
6031   do_cleanups (back_to);
6032 }
6033
6034 /* Print B to gdb_stdout.  */
6035
6036 static void
6037 print_one_breakpoint_location (struct breakpoint *b,
6038                                struct bp_location *loc,
6039                                int loc_number,
6040                                struct bp_location **last_loc,
6041                                int allflag)
6042 {
6043   struct command_line *l;
6044   static char bpenables[] = "nynny";
6045
6046   struct ui_out *uiout = current_uiout;
6047   int header_of_multiple = 0;
6048   int part_of_multiple = (loc != NULL);
6049   struct value_print_options opts;
6050
6051   get_user_print_options (&opts);
6052
6053   gdb_assert (!loc || loc_number != 0);
6054   /* See comment in print_one_breakpoint concerning treatment of
6055      breakpoints with single disabled location.  */
6056   if (loc == NULL 
6057       && (b->loc != NULL 
6058           && (b->loc->next != NULL || !b->loc->enabled)))
6059     header_of_multiple = 1;
6060   if (loc == NULL)
6061     loc = b->loc;
6062
6063   annotate_record ();
6064
6065   /* 1 */
6066   annotate_field (0);
6067   if (part_of_multiple)
6068     {
6069       char *formatted;
6070       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6071       ui_out_field_string (uiout, "number", formatted);
6072       xfree (formatted);
6073     }
6074   else
6075     {
6076       ui_out_field_int (uiout, "number", b->number);
6077     }
6078
6079   /* 2 */
6080   annotate_field (1);
6081   if (part_of_multiple)
6082     ui_out_field_skip (uiout, "type");
6083   else
6084     ui_out_field_string (uiout, "type", bptype_string (b->type));
6085
6086   /* 3 */
6087   annotate_field (2);
6088   if (part_of_multiple)
6089     ui_out_field_skip (uiout, "disp");
6090   else
6091     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6092
6093
6094   /* 4 */
6095   annotate_field (3);
6096   if (part_of_multiple)
6097     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6098   else
6099     ui_out_field_fmt (uiout, "enabled", "%c", 
6100                       bpenables[(int) b->enable_state]);
6101   ui_out_spaces (uiout, 2);
6102
6103   
6104   /* 5 and 6 */
6105   if (b->ops != NULL && b->ops->print_one != NULL)
6106     {
6107       /* Although the print_one can possibly print all locations,
6108          calling it here is not likely to get any nice result.  So,
6109          make sure there's just one location.  */
6110       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6111       b->ops->print_one (b, last_loc);
6112     }
6113   else
6114     switch (b->type)
6115       {
6116       case bp_none:
6117         internal_error (__FILE__, __LINE__,
6118                         _("print_one_breakpoint: bp_none encountered\n"));
6119         break;
6120
6121       case bp_watchpoint:
6122       case bp_hardware_watchpoint:
6123       case bp_read_watchpoint:
6124       case bp_access_watchpoint:
6125         {
6126           struct watchpoint *w = (struct watchpoint *) b;
6127
6128           /* Field 4, the address, is omitted (which makes the columns
6129              not line up too nicely with the headers, but the effect
6130              is relatively readable).  */
6131           if (opts.addressprint)
6132             ui_out_field_skip (uiout, "addr");
6133           annotate_field (5);
6134           ui_out_field_string (uiout, "what", w->exp_string);
6135         }
6136         break;
6137
6138       case bp_breakpoint:
6139       case bp_hardware_breakpoint:
6140       case bp_until:
6141       case bp_finish:
6142       case bp_longjmp:
6143       case bp_longjmp_resume:
6144       case bp_longjmp_call_dummy:
6145       case bp_exception:
6146       case bp_exception_resume:
6147       case bp_step_resume:
6148       case bp_hp_step_resume:
6149       case bp_watchpoint_scope:
6150       case bp_call_dummy:
6151       case bp_std_terminate:
6152       case bp_shlib_event:
6153       case bp_thread_event:
6154       case bp_overlay_event:
6155       case bp_longjmp_master:
6156       case bp_std_terminate_master:
6157       case bp_exception_master:
6158       case bp_tracepoint:
6159       case bp_fast_tracepoint:
6160       case bp_static_tracepoint:
6161       case bp_dprintf:
6162       case bp_jit_event:
6163       case bp_gnu_ifunc_resolver:
6164       case bp_gnu_ifunc_resolver_return:
6165         if (opts.addressprint)
6166           {
6167             annotate_field (4);
6168             if (header_of_multiple)
6169               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6170             else if (b->loc == NULL || loc->shlib_disabled)
6171               ui_out_field_string (uiout, "addr", "<PENDING>");
6172             else
6173               ui_out_field_core_addr (uiout, "addr",
6174                                       loc->gdbarch, loc->address);
6175           }
6176         annotate_field (5);
6177         if (!header_of_multiple)
6178           print_breakpoint_location (b, loc);
6179         if (b->loc)
6180           *last_loc = b->loc;
6181         break;
6182       }
6183
6184
6185   if (loc != NULL && !header_of_multiple)
6186     {
6187       struct inferior *inf;
6188       VEC(int) *inf_num = NULL;
6189       int mi_only = 1;
6190
6191       ALL_INFERIORS (inf)
6192         {
6193           if (inf->pspace == loc->pspace)
6194             VEC_safe_push (int, inf_num, inf->num);
6195         }
6196
6197         /* For backward compatibility, don't display inferiors in CLI unless
6198            there are several.  Always display for MI. */
6199         if (allflag
6200             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6201                 && (number_of_program_spaces () > 1
6202                     || number_of_inferiors () > 1)
6203                 /* LOC is for existing B, it cannot be in
6204                    moribund_locations and thus having NULL OWNER.  */
6205                 && loc->owner->type != bp_catchpoint))
6206         mi_only = 0;
6207       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6208       VEC_free (int, inf_num);
6209     }
6210
6211   if (!part_of_multiple)
6212     {
6213       if (b->thread != -1)
6214         {
6215           /* FIXME: This seems to be redundant and lost here; see the
6216              "stop only in" line a little further down.  */
6217           ui_out_text (uiout, " thread ");
6218           ui_out_field_int (uiout, "thread", b->thread);
6219         }
6220       else if (b->task != 0)
6221         {
6222           ui_out_text (uiout, " task ");
6223           ui_out_field_int (uiout, "task", b->task);
6224         }
6225     }
6226
6227   ui_out_text (uiout, "\n");
6228
6229   if (!part_of_multiple)
6230     b->ops->print_one_detail (b, uiout);
6231
6232   if (part_of_multiple && frame_id_p (b->frame_id))
6233     {
6234       annotate_field (6);
6235       ui_out_text (uiout, "\tstop only in stack frame at ");
6236       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6237          the frame ID.  */
6238       ui_out_field_core_addr (uiout, "frame",
6239                               b->gdbarch, b->frame_id.stack_addr);
6240       ui_out_text (uiout, "\n");
6241     }
6242   
6243   if (!part_of_multiple && b->cond_string)
6244     {
6245       annotate_field (7);
6246       if (is_tracepoint (b))
6247         ui_out_text (uiout, "\ttrace only if ");
6248       else
6249         ui_out_text (uiout, "\tstop only if ");
6250       ui_out_field_string (uiout, "cond", b->cond_string);
6251
6252       /* Print whether the target is doing the breakpoint's condition
6253          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6254       if (is_breakpoint (b)
6255           && breakpoint_condition_evaluation_mode ()
6256           == condition_evaluation_target)
6257         {
6258           ui_out_text (uiout, " (");
6259           ui_out_field_string (uiout, "evaluated-by",
6260                                bp_condition_evaluator (b));
6261           ui_out_text (uiout, " evals)");
6262         }
6263       ui_out_text (uiout, "\n");
6264     }
6265
6266   if (!part_of_multiple && b->thread != -1)
6267     {
6268       /* FIXME should make an annotation for this.  */
6269       ui_out_text (uiout, "\tstop only in thread ");
6270       ui_out_field_int (uiout, "thread", b->thread);
6271       ui_out_text (uiout, "\n");
6272     }
6273   
6274   if (!part_of_multiple)
6275     {
6276       if (b->hit_count)
6277         {
6278           /* FIXME should make an annotation for this.  */
6279           if (is_catchpoint (b))
6280             ui_out_text (uiout, "\tcatchpoint");
6281           else if (is_tracepoint (b))
6282             ui_out_text (uiout, "\ttracepoint");
6283           else
6284             ui_out_text (uiout, "\tbreakpoint");
6285           ui_out_text (uiout, " already hit ");
6286           ui_out_field_int (uiout, "times", b->hit_count);
6287           if (b->hit_count == 1)
6288             ui_out_text (uiout, " time\n");
6289           else
6290             ui_out_text (uiout, " times\n");
6291         }
6292       else
6293         {
6294           /* Output the count also if it is zero, but only if this is mi.  */
6295           if (ui_out_is_mi_like_p (uiout))
6296             ui_out_field_int (uiout, "times", b->hit_count);
6297         }
6298     }
6299
6300   if (!part_of_multiple && b->ignore_count)
6301     {
6302       annotate_field (8);
6303       ui_out_text (uiout, "\tignore next ");
6304       ui_out_field_int (uiout, "ignore", b->ignore_count);
6305       ui_out_text (uiout, " hits\n");
6306     }
6307
6308   /* Note that an enable count of 1 corresponds to "enable once"
6309      behavior, which is reported by the combination of enablement and
6310      disposition, so we don't need to mention it here.  */
6311   if (!part_of_multiple && b->enable_count > 1)
6312     {
6313       annotate_field (8);
6314       ui_out_text (uiout, "\tdisable after ");
6315       /* Tweak the wording to clarify that ignore and enable counts
6316          are distinct, and have additive effect.  */
6317       if (b->ignore_count)
6318         ui_out_text (uiout, "additional ");
6319       else
6320         ui_out_text (uiout, "next ");
6321       ui_out_field_int (uiout, "enable", b->enable_count);
6322       ui_out_text (uiout, " hits\n");
6323     }
6324
6325   if (!part_of_multiple && is_tracepoint (b))
6326     {
6327       struct tracepoint *tp = (struct tracepoint *) b;
6328
6329       if (tp->traceframe_usage)
6330         {
6331           ui_out_text (uiout, "\ttrace buffer usage ");
6332           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6333           ui_out_text (uiout, " bytes\n");
6334         }
6335     }
6336
6337   l = b->commands ? b->commands->commands : NULL;
6338   if (!part_of_multiple && l)
6339     {
6340       struct cleanup *script_chain;
6341
6342       annotate_field (9);
6343       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6344       print_command_lines (uiout, l, 4);
6345       do_cleanups (script_chain);
6346     }
6347
6348   if (is_tracepoint (b))
6349     {
6350       struct tracepoint *t = (struct tracepoint *) b;
6351
6352       if (!part_of_multiple && t->pass_count)
6353         {
6354           annotate_field (10);
6355           ui_out_text (uiout, "\tpass count ");
6356           ui_out_field_int (uiout, "pass", t->pass_count);
6357           ui_out_text (uiout, " \n");
6358         }
6359
6360       /* Don't display it when tracepoint or tracepoint location is
6361          pending.   */
6362       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6363         {
6364           annotate_field (11);
6365
6366           if (ui_out_is_mi_like_p (uiout))
6367             ui_out_field_string (uiout, "installed",
6368                                  loc->inserted ? "y" : "n");
6369           else
6370             {
6371               if (loc->inserted)
6372                 ui_out_text (uiout, "\t");
6373               else
6374                 ui_out_text (uiout, "\tnot ");
6375               ui_out_text (uiout, "installed on target\n");
6376             }
6377         }
6378     }
6379
6380   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6381     {
6382       if (is_watchpoint (b))
6383         {
6384           struct watchpoint *w = (struct watchpoint *) b;
6385
6386           ui_out_field_string (uiout, "original-location", w->exp_string);
6387         }
6388       else if (b->addr_string)
6389         ui_out_field_string (uiout, "original-location", b->addr_string);
6390     }
6391 }
6392
6393 static void
6394 print_one_breakpoint (struct breakpoint *b,
6395                       struct bp_location **last_loc, 
6396                       int allflag)
6397 {
6398   struct cleanup *bkpt_chain;
6399   struct ui_out *uiout = current_uiout;
6400
6401   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6402
6403   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6404   do_cleanups (bkpt_chain);
6405
6406   /* If this breakpoint has custom print function,
6407      it's already printed.  Otherwise, print individual
6408      locations, if any.  */
6409   if (b->ops == NULL || b->ops->print_one == NULL)
6410     {
6411       /* If breakpoint has a single location that is disabled, we
6412          print it as if it had several locations, since otherwise it's
6413          hard to represent "breakpoint enabled, location disabled"
6414          situation.
6415
6416          Note that while hardware watchpoints have several locations
6417          internally, that's not a property exposed to user.  */
6418       if (b->loc 
6419           && !is_hardware_watchpoint (b)
6420           && (b->loc->next || !b->loc->enabled))
6421         {
6422           struct bp_location *loc;
6423           int n = 1;
6424
6425           for (loc = b->loc; loc; loc = loc->next, ++n)
6426             {
6427               struct cleanup *inner2 =
6428                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6429               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6430               do_cleanups (inner2);
6431             }
6432         }
6433     }
6434 }
6435
6436 static int
6437 breakpoint_address_bits (struct breakpoint *b)
6438 {
6439   int print_address_bits = 0;
6440   struct bp_location *loc;
6441
6442   for (loc = b->loc; loc; loc = loc->next)
6443     {
6444       int addr_bit;
6445
6446       /* Software watchpoints that aren't watching memory don't have
6447          an address to print.  */
6448       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6449         continue;
6450
6451       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6452       if (addr_bit > print_address_bits)
6453         print_address_bits = addr_bit;
6454     }
6455
6456   return print_address_bits;
6457 }
6458
6459 struct captured_breakpoint_query_args
6460   {
6461     int bnum;
6462   };
6463
6464 static int
6465 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6466 {
6467   struct captured_breakpoint_query_args *args = data;
6468   struct breakpoint *b;
6469   struct bp_location *dummy_loc = NULL;
6470
6471   ALL_BREAKPOINTS (b)
6472     {
6473       if (args->bnum == b->number)
6474         {
6475           print_one_breakpoint (b, &dummy_loc, 0);
6476           return GDB_RC_OK;
6477         }
6478     }
6479   return GDB_RC_NONE;
6480 }
6481
6482 enum gdb_rc
6483 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6484                       char **error_message)
6485 {
6486   struct captured_breakpoint_query_args args;
6487
6488   args.bnum = bnum;
6489   /* For the moment we don't trust print_one_breakpoint() to not throw
6490      an error.  */
6491   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6492                                  error_message, RETURN_MASK_ALL) < 0)
6493     return GDB_RC_FAIL;
6494   else
6495     return GDB_RC_OK;
6496 }
6497
6498 /* Return true if this breakpoint was set by the user, false if it is
6499    internal or momentary.  */
6500
6501 int
6502 user_breakpoint_p (struct breakpoint *b)
6503 {
6504   return b->number > 0;
6505 }
6506
6507 /* Print information on user settable breakpoint (watchpoint, etc)
6508    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6509    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6510    FILTER is non-NULL, call it on each breakpoint and only include the
6511    ones for which it returns non-zero.  Return the total number of
6512    breakpoints listed.  */
6513
6514 static int
6515 breakpoint_1 (char *args, int allflag, 
6516               int (*filter) (const struct breakpoint *))
6517 {
6518   struct breakpoint *b;
6519   struct bp_location *last_loc = NULL;
6520   int nr_printable_breakpoints;
6521   struct cleanup *bkpttbl_chain;
6522   struct value_print_options opts;
6523   int print_address_bits = 0;
6524   int print_type_col_width = 14;
6525   struct ui_out *uiout = current_uiout;
6526
6527   get_user_print_options (&opts);
6528
6529   /* Compute the number of rows in the table, as well as the size
6530      required for address fields.  */
6531   nr_printable_breakpoints = 0;
6532   ALL_BREAKPOINTS (b)
6533     {
6534       /* If we have a filter, only list the breakpoints it accepts.  */
6535       if (filter && !filter (b))
6536         continue;
6537
6538       /* If we have an "args" string, it is a list of breakpoints to 
6539          accept.  Skip the others.  */
6540       if (args != NULL && *args != '\0')
6541         {
6542           if (allflag && parse_and_eval_long (args) != b->number)
6543             continue;
6544           if (!allflag && !number_is_in_list (args, b->number))
6545             continue;
6546         }
6547
6548       if (allflag || user_breakpoint_p (b))
6549         {
6550           int addr_bit, type_len;
6551
6552           addr_bit = breakpoint_address_bits (b);
6553           if (addr_bit > print_address_bits)
6554             print_address_bits = addr_bit;
6555
6556           type_len = strlen (bptype_string (b->type));
6557           if (type_len > print_type_col_width)
6558             print_type_col_width = type_len;
6559
6560           nr_printable_breakpoints++;
6561         }
6562     }
6563
6564   if (opts.addressprint)
6565     bkpttbl_chain 
6566       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6567                                              nr_printable_breakpoints,
6568                                              "BreakpointTable");
6569   else
6570     bkpttbl_chain 
6571       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6572                                              nr_printable_breakpoints,
6573                                              "BreakpointTable");
6574
6575   if (nr_printable_breakpoints > 0)
6576     annotate_breakpoints_headers ();
6577   if (nr_printable_breakpoints > 0)
6578     annotate_field (0);
6579   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6580   if (nr_printable_breakpoints > 0)
6581     annotate_field (1);
6582   ui_out_table_header (uiout, print_type_col_width, ui_left,
6583                        "type", "Type");                         /* 2 */
6584   if (nr_printable_breakpoints > 0)
6585     annotate_field (2);
6586   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6587   if (nr_printable_breakpoints > 0)
6588     annotate_field (3);
6589   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6590   if (opts.addressprint)
6591     {
6592       if (nr_printable_breakpoints > 0)
6593         annotate_field (4);
6594       if (print_address_bits <= 32)
6595         ui_out_table_header (uiout, 10, ui_left, 
6596                              "addr", "Address");                /* 5 */
6597       else
6598         ui_out_table_header (uiout, 18, ui_left, 
6599                              "addr", "Address");                /* 5 */
6600     }
6601   if (nr_printable_breakpoints > 0)
6602     annotate_field (5);
6603   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6604   ui_out_table_body (uiout);
6605   if (nr_printable_breakpoints > 0)
6606     annotate_breakpoints_table ();
6607
6608   ALL_BREAKPOINTS (b)
6609     {
6610       QUIT;
6611       /* If we have a filter, only list the breakpoints it accepts.  */
6612       if (filter && !filter (b))
6613         continue;
6614
6615       /* If we have an "args" string, it is a list of breakpoints to 
6616          accept.  Skip the others.  */
6617
6618       if (args != NULL && *args != '\0')
6619         {
6620           if (allflag)  /* maintenance info breakpoint */
6621             {
6622               if (parse_and_eval_long (args) != b->number)
6623                 continue;
6624             }
6625           else          /* all others */
6626             {
6627               if (!number_is_in_list (args, b->number))
6628                 continue;
6629             }
6630         }
6631       /* We only print out user settable breakpoints unless the
6632          allflag is set.  */
6633       if (allflag || user_breakpoint_p (b))
6634         print_one_breakpoint (b, &last_loc, allflag);
6635     }
6636
6637   do_cleanups (bkpttbl_chain);
6638
6639   if (nr_printable_breakpoints == 0)
6640     {
6641       /* If there's a filter, let the caller decide how to report
6642          empty list.  */
6643       if (!filter)
6644         {
6645           if (args == NULL || *args == '\0')
6646             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6647           else
6648             ui_out_message (uiout, 0, 
6649                             "No breakpoint or watchpoint matching '%s'.\n",
6650                             args);
6651         }
6652     }
6653   else
6654     {
6655       if (last_loc && !server_command)
6656         set_next_address (last_loc->gdbarch, last_loc->address);
6657     }
6658
6659   /* FIXME?  Should this be moved up so that it is only called when
6660      there have been breakpoints? */
6661   annotate_breakpoints_table_end ();
6662
6663   return nr_printable_breakpoints;
6664 }
6665
6666 /* Display the value of default-collect in a way that is generally
6667    compatible with the breakpoint list.  */
6668
6669 static void
6670 default_collect_info (void)
6671 {
6672   struct ui_out *uiout = current_uiout;
6673
6674   /* If it has no value (which is frequently the case), say nothing; a
6675      message like "No default-collect." gets in user's face when it's
6676      not wanted.  */
6677   if (!*default_collect)
6678     return;
6679
6680   /* The following phrase lines up nicely with per-tracepoint collect
6681      actions.  */
6682   ui_out_text (uiout, "default collect ");
6683   ui_out_field_string (uiout, "default-collect", default_collect);
6684   ui_out_text (uiout, " \n");
6685 }
6686   
6687 static void
6688 breakpoints_info (char *args, int from_tty)
6689 {
6690   breakpoint_1 (args, 0, NULL);
6691
6692   default_collect_info ();
6693 }
6694
6695 static void
6696 watchpoints_info (char *args, int from_tty)
6697 {
6698   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6699   struct ui_out *uiout = current_uiout;
6700
6701   if (num_printed == 0)
6702     {
6703       if (args == NULL || *args == '\0')
6704         ui_out_message (uiout, 0, "No watchpoints.\n");
6705       else
6706         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6707     }
6708 }
6709
6710 static void
6711 maintenance_info_breakpoints (char *args, int from_tty)
6712 {
6713   breakpoint_1 (args, 1, NULL);
6714
6715   default_collect_info ();
6716 }
6717
6718 static int
6719 breakpoint_has_pc (struct breakpoint *b,
6720                    struct program_space *pspace,
6721                    CORE_ADDR pc, struct obj_section *section)
6722 {
6723   struct bp_location *bl = b->loc;
6724
6725   for (; bl; bl = bl->next)
6726     {
6727       if (bl->pspace == pspace
6728           && bl->address == pc
6729           && (!overlay_debugging || bl->section == section))
6730         return 1;         
6731     }
6732   return 0;
6733 }
6734
6735 /* Print a message describing any user-breakpoints set at PC.  This
6736    concerns with logical breakpoints, so we match program spaces, not
6737    address spaces.  */
6738
6739 static void
6740 describe_other_breakpoints (struct gdbarch *gdbarch,
6741                             struct program_space *pspace, CORE_ADDR pc,
6742                             struct obj_section *section, int thread)
6743 {
6744   int others = 0;
6745   struct breakpoint *b;
6746
6747   ALL_BREAKPOINTS (b)
6748     others += (user_breakpoint_p (b)
6749                && breakpoint_has_pc (b, pspace, pc, section));
6750   if (others > 0)
6751     {
6752       if (others == 1)
6753         printf_filtered (_("Note: breakpoint "));
6754       else /* if (others == ???) */
6755         printf_filtered (_("Note: breakpoints "));
6756       ALL_BREAKPOINTS (b)
6757         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6758           {
6759             others--;
6760             printf_filtered ("%d", b->number);
6761             if (b->thread == -1 && thread != -1)
6762               printf_filtered (" (all threads)");
6763             else if (b->thread != -1)
6764               printf_filtered (" (thread %d)", b->thread);
6765             printf_filtered ("%s%s ",
6766                              ((b->enable_state == bp_disabled
6767                                || b->enable_state == bp_call_disabled)
6768                               ? " (disabled)"
6769                               : b->enable_state == bp_permanent 
6770                               ? " (permanent)"
6771                               : ""),
6772                              (others > 1) ? "," 
6773                              : ((others == 1) ? " and" : ""));
6774           }
6775       printf_filtered (_("also set at pc "));
6776       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6777       printf_filtered (".\n");
6778     }
6779 }
6780 \f
6781
6782 /* Return true iff it is meaningful to use the address member of
6783    BPT.  For some breakpoint types, the address member is irrelevant
6784    and it makes no sense to attempt to compare it to other addresses
6785    (or use it for any other purpose either).
6786
6787    More specifically, each of the following breakpoint types will
6788    always have a zero valued address and we don't want to mark
6789    breakpoints of any of these types to be a duplicate of an actual
6790    breakpoint at address zero:
6791
6792       bp_watchpoint
6793       bp_catchpoint
6794
6795 */
6796
6797 static int
6798 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6799 {
6800   enum bptype type = bpt->type;
6801
6802   return (type != bp_watchpoint && type != bp_catchpoint);
6803 }
6804
6805 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6806    true if LOC1 and LOC2 represent the same watchpoint location.  */
6807
6808 static int
6809 watchpoint_locations_match (struct bp_location *loc1, 
6810                             struct bp_location *loc2)
6811 {
6812   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6813   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6814
6815   /* Both of them must exist.  */
6816   gdb_assert (w1 != NULL);
6817   gdb_assert (w2 != NULL);
6818
6819   /* If the target can evaluate the condition expression in hardware,
6820      then we we need to insert both watchpoints even if they are at
6821      the same place.  Otherwise the watchpoint will only trigger when
6822      the condition of whichever watchpoint was inserted evaluates to
6823      true, not giving a chance for GDB to check the condition of the
6824      other watchpoint.  */
6825   if ((w1->cond_exp
6826        && target_can_accel_watchpoint_condition (loc1->address, 
6827                                                  loc1->length,
6828                                                  loc1->watchpoint_type,
6829                                                  w1->cond_exp))
6830       || (w2->cond_exp
6831           && target_can_accel_watchpoint_condition (loc2->address, 
6832                                                     loc2->length,
6833                                                     loc2->watchpoint_type,
6834                                                     w2->cond_exp)))
6835     return 0;
6836
6837   /* Note that this checks the owner's type, not the location's.  In
6838      case the target does not support read watchpoints, but does
6839      support access watchpoints, we'll have bp_read_watchpoint
6840      watchpoints with hw_access locations.  Those should be considered
6841      duplicates of hw_read locations.  The hw_read locations will
6842      become hw_access locations later.  */
6843   return (loc1->owner->type == loc2->owner->type
6844           && loc1->pspace->aspace == loc2->pspace->aspace
6845           && loc1->address == loc2->address
6846           && loc1->length == loc2->length);
6847 }
6848
6849 /* See breakpoint.h.  */
6850
6851 int
6852 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6853                           struct address_space *aspace2, CORE_ADDR addr2)
6854 {
6855   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6856            || aspace1 == aspace2)
6857           && addr1 == addr2);
6858 }
6859
6860 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6861    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6862    matches ASPACE2.  On targets that have global breakpoints, the address
6863    space doesn't really matter.  */
6864
6865 static int
6866 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6867                                 int len1, struct address_space *aspace2,
6868                                 CORE_ADDR addr2)
6869 {
6870   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
6871            || aspace1 == aspace2)
6872           && addr2 >= addr1 && addr2 < addr1 + len1);
6873 }
6874
6875 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6876    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6877    matches the breakpoint's address space.  On targets that have global
6878    breakpoints, the address space doesn't really matter.  */
6879
6880 static int
6881 breakpoint_location_address_match (struct bp_location *bl,
6882                                    struct address_space *aspace,
6883                                    CORE_ADDR addr)
6884 {
6885   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6886                                     aspace, addr)
6887           || (bl->length
6888               && breakpoint_address_match_range (bl->pspace->aspace,
6889                                                  bl->address, bl->length,
6890                                                  aspace, addr)));
6891 }
6892
6893 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6894    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6895    true, otherwise returns false.  */
6896
6897 static int
6898 tracepoint_locations_match (struct bp_location *loc1,
6899                             struct bp_location *loc2)
6900 {
6901   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6902     /* Since tracepoint locations are never duplicated with others', tracepoint
6903        locations at the same address of different tracepoints are regarded as
6904        different locations.  */
6905     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6906   else
6907     return 0;
6908 }
6909
6910 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6911    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6912    represent the same location.  */
6913
6914 static int
6915 breakpoint_locations_match (struct bp_location *loc1, 
6916                             struct bp_location *loc2)
6917 {
6918   int hw_point1, hw_point2;
6919
6920   /* Both of them must not be in moribund_locations.  */
6921   gdb_assert (loc1->owner != NULL);
6922   gdb_assert (loc2->owner != NULL);
6923
6924   hw_point1 = is_hardware_watchpoint (loc1->owner);
6925   hw_point2 = is_hardware_watchpoint (loc2->owner);
6926
6927   if (hw_point1 != hw_point2)
6928     return 0;
6929   else if (hw_point1)
6930     return watchpoint_locations_match (loc1, loc2);
6931   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6932     return tracepoint_locations_match (loc1, loc2);
6933   else
6934     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6935     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6936                                      loc2->pspace->aspace, loc2->address)
6937             && loc1->length == loc2->length);
6938 }
6939
6940 static void
6941 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6942                                int bnum, int have_bnum)
6943 {
6944   /* The longest string possibly returned by hex_string_custom
6945      is 50 chars.  These must be at least that big for safety.  */
6946   char astr1[64];
6947   char astr2[64];
6948
6949   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6950   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6951   if (have_bnum)
6952     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6953              bnum, astr1, astr2);
6954   else
6955     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6956 }
6957
6958 /* Adjust a breakpoint's address to account for architectural
6959    constraints on breakpoint placement.  Return the adjusted address.
6960    Note: Very few targets require this kind of adjustment.  For most
6961    targets, this function is simply the identity function.  */
6962
6963 static CORE_ADDR
6964 adjust_breakpoint_address (struct gdbarch *gdbarch,
6965                            CORE_ADDR bpaddr, enum bptype bptype)
6966 {
6967   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6968     {
6969       /* Very few targets need any kind of breakpoint adjustment.  */
6970       return bpaddr;
6971     }
6972   else if (bptype == bp_watchpoint
6973            || bptype == bp_hardware_watchpoint
6974            || bptype == bp_read_watchpoint
6975            || bptype == bp_access_watchpoint
6976            || bptype == bp_catchpoint)
6977     {
6978       /* Watchpoints and the various bp_catch_* eventpoints should not
6979          have their addresses modified.  */
6980       return bpaddr;
6981     }
6982   else
6983     {
6984       CORE_ADDR adjusted_bpaddr;
6985
6986       /* Some targets have architectural constraints on the placement
6987          of breakpoint instructions.  Obtain the adjusted address.  */
6988       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6989
6990       /* An adjusted breakpoint address can significantly alter
6991          a user's expectations.  Print a warning if an adjustment
6992          is required.  */
6993       if (adjusted_bpaddr != bpaddr)
6994         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6995
6996       return adjusted_bpaddr;
6997     }
6998 }
6999
7000 void
7001 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7002                   struct breakpoint *owner)
7003 {
7004   memset (loc, 0, sizeof (*loc));
7005
7006   gdb_assert (ops != NULL);
7007
7008   loc->ops = ops;
7009   loc->owner = owner;
7010   loc->cond = NULL;
7011   loc->cond_bytecode = NULL;
7012   loc->shlib_disabled = 0;
7013   loc->enabled = 1;
7014
7015   switch (owner->type)
7016     {
7017     case bp_breakpoint:
7018     case bp_until:
7019     case bp_finish:
7020     case bp_longjmp:
7021     case bp_longjmp_resume:
7022     case bp_longjmp_call_dummy:
7023     case bp_exception:
7024     case bp_exception_resume:
7025     case bp_step_resume:
7026     case bp_hp_step_resume:
7027     case bp_watchpoint_scope:
7028     case bp_call_dummy:
7029     case bp_std_terminate:
7030     case bp_shlib_event:
7031     case bp_thread_event:
7032     case bp_overlay_event:
7033     case bp_jit_event:
7034     case bp_longjmp_master:
7035     case bp_std_terminate_master:
7036     case bp_exception_master:
7037     case bp_gnu_ifunc_resolver:
7038     case bp_gnu_ifunc_resolver_return:
7039     case bp_dprintf:
7040       loc->loc_type = bp_loc_software_breakpoint;
7041       mark_breakpoint_location_modified (loc);
7042       break;
7043     case bp_hardware_breakpoint:
7044       loc->loc_type = bp_loc_hardware_breakpoint;
7045       mark_breakpoint_location_modified (loc);
7046       break;
7047     case bp_hardware_watchpoint:
7048     case bp_read_watchpoint:
7049     case bp_access_watchpoint:
7050       loc->loc_type = bp_loc_hardware_watchpoint;
7051       break;
7052     case bp_watchpoint:
7053     case bp_catchpoint:
7054     case bp_tracepoint:
7055     case bp_fast_tracepoint:
7056     case bp_static_tracepoint:
7057       loc->loc_type = bp_loc_other;
7058       break;
7059     default:
7060       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7061     }
7062
7063   loc->refc = 1;
7064 }
7065
7066 /* Allocate a struct bp_location.  */
7067
7068 static struct bp_location *
7069 allocate_bp_location (struct breakpoint *bpt)
7070 {
7071   return bpt->ops->allocate_location (bpt);
7072 }
7073
7074 static void
7075 free_bp_location (struct bp_location *loc)
7076 {
7077   loc->ops->dtor (loc);
7078   xfree (loc);
7079 }
7080
7081 /* Increment reference count.  */
7082
7083 static void
7084 incref_bp_location (struct bp_location *bl)
7085 {
7086   ++bl->refc;
7087 }
7088
7089 /* Decrement reference count.  If the reference count reaches 0,
7090    destroy the bp_location.  Sets *BLP to NULL.  */
7091
7092 static void
7093 decref_bp_location (struct bp_location **blp)
7094 {
7095   gdb_assert ((*blp)->refc > 0);
7096
7097   if (--(*blp)->refc == 0)
7098     free_bp_location (*blp);
7099   *blp = NULL;
7100 }
7101
7102 /* Add breakpoint B at the end of the global breakpoint chain.  */
7103
7104 static void
7105 add_to_breakpoint_chain (struct breakpoint *b)
7106 {
7107   struct breakpoint *b1;
7108
7109   /* Add this breakpoint to the end of the chain so that a list of
7110      breakpoints will come out in order of increasing numbers.  */
7111
7112   b1 = breakpoint_chain;
7113   if (b1 == 0)
7114     breakpoint_chain = b;
7115   else
7116     {
7117       while (b1->next)
7118         b1 = b1->next;
7119       b1->next = b;
7120     }
7121 }
7122
7123 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7124
7125 static void
7126 init_raw_breakpoint_without_location (struct breakpoint *b,
7127                                       struct gdbarch *gdbarch,
7128                                       enum bptype bptype,
7129                                       const struct breakpoint_ops *ops)
7130 {
7131   memset (b, 0, sizeof (*b));
7132
7133   gdb_assert (ops != NULL);
7134
7135   b->ops = ops;
7136   b->type = bptype;
7137   b->gdbarch = gdbarch;
7138   b->language = current_language->la_language;
7139   b->input_radix = input_radix;
7140   b->thread = -1;
7141   b->enable_state = bp_enabled;
7142   b->next = 0;
7143   b->silent = 0;
7144   b->ignore_count = 0;
7145   b->commands = NULL;
7146   b->frame_id = null_frame_id;
7147   b->condition_not_parsed = 0;
7148   b->py_bp_object = NULL;
7149   b->related_breakpoint = b;
7150 }
7151
7152 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7153    that has type BPTYPE and has no locations as yet.  */
7154
7155 static struct breakpoint *
7156 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7157                                      enum bptype bptype,
7158                                      const struct breakpoint_ops *ops)
7159 {
7160   struct breakpoint *b = XNEW (struct breakpoint);
7161
7162   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7163   add_to_breakpoint_chain (b);
7164   return b;
7165 }
7166
7167 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7168    resolutions should be made as the user specified the location explicitly
7169    enough.  */
7170
7171 static void
7172 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7173 {
7174   gdb_assert (loc->owner != NULL);
7175
7176   if (loc->owner->type == bp_breakpoint
7177       || loc->owner->type == bp_hardware_breakpoint
7178       || is_tracepoint (loc->owner))
7179     {
7180       int is_gnu_ifunc;
7181       const char *function_name;
7182       CORE_ADDR func_addr;
7183
7184       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7185                                           &func_addr, NULL, &is_gnu_ifunc);
7186
7187       if (is_gnu_ifunc && !explicit_loc)
7188         {
7189           struct breakpoint *b = loc->owner;
7190
7191           gdb_assert (loc->pspace == current_program_space);
7192           if (gnu_ifunc_resolve_name (function_name,
7193                                       &loc->requested_address))
7194             {
7195               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7196               loc->address = adjust_breakpoint_address (loc->gdbarch,
7197                                                         loc->requested_address,
7198                                                         b->type);
7199             }
7200           else if (b->type == bp_breakpoint && b->loc == loc
7201                    && loc->next == NULL && b->related_breakpoint == b)
7202             {
7203               /* Create only the whole new breakpoint of this type but do not
7204                  mess more complicated breakpoints with multiple locations.  */
7205               b->type = bp_gnu_ifunc_resolver;
7206               /* Remember the resolver's address for use by the return
7207                  breakpoint.  */
7208               loc->related_address = func_addr;
7209             }
7210         }
7211
7212       if (function_name)
7213         loc->function_name = xstrdup (function_name);
7214     }
7215 }
7216
7217 /* Attempt to determine architecture of location identified by SAL.  */
7218 struct gdbarch *
7219 get_sal_arch (struct symtab_and_line sal)
7220 {
7221   if (sal.section)
7222     return get_objfile_arch (sal.section->objfile);
7223   if (sal.symtab)
7224     return get_objfile_arch (sal.symtab->objfile);
7225
7226   return NULL;
7227 }
7228
7229 /* Low level routine for partially initializing a breakpoint of type
7230    BPTYPE.  The newly created breakpoint's address, section, source
7231    file name, and line number are provided by SAL.
7232
7233    It is expected that the caller will complete the initialization of
7234    the newly created breakpoint struct as well as output any status
7235    information regarding the creation of a new breakpoint.  */
7236
7237 static void
7238 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7239                      struct symtab_and_line sal, enum bptype bptype,
7240                      const struct breakpoint_ops *ops)
7241 {
7242   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7243
7244   add_location_to_breakpoint (b, &sal);
7245
7246   if (bptype != bp_catchpoint)
7247     gdb_assert (sal.pspace != NULL);
7248
7249   /* Store the program space that was used to set the breakpoint,
7250      except for ordinary breakpoints, which are independent of the
7251      program space.  */
7252   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7253     b->pspace = sal.pspace;
7254 }
7255
7256 /* set_raw_breakpoint is a low level routine for allocating and
7257    partially initializing a breakpoint of type BPTYPE.  The newly
7258    created breakpoint's address, section, source file name, and line
7259    number are provided by SAL.  The newly created and partially
7260    initialized breakpoint is added to the breakpoint chain and
7261    is also returned as the value of this function.
7262
7263    It is expected that the caller will complete the initialization of
7264    the newly created breakpoint struct as well as output any status
7265    information regarding the creation of a new breakpoint.  In
7266    particular, set_raw_breakpoint does NOT set the breakpoint
7267    number!  Care should be taken to not allow an error to occur
7268    prior to completing the initialization of the breakpoint.  If this
7269    should happen, a bogus breakpoint will be left on the chain.  */
7270
7271 struct breakpoint *
7272 set_raw_breakpoint (struct gdbarch *gdbarch,
7273                     struct symtab_and_line sal, enum bptype bptype,
7274                     const struct breakpoint_ops *ops)
7275 {
7276   struct breakpoint *b = XNEW (struct breakpoint);
7277
7278   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7279   add_to_breakpoint_chain (b);
7280   return b;
7281 }
7282
7283
7284 /* Note that the breakpoint object B describes a permanent breakpoint
7285    instruction, hard-wired into the inferior's code.  */
7286 void
7287 make_breakpoint_permanent (struct breakpoint *b)
7288 {
7289   struct bp_location *bl;
7290
7291   b->enable_state = bp_permanent;
7292
7293   /* By definition, permanent breakpoints are already present in the
7294      code.  Mark all locations as inserted.  For now,
7295      make_breakpoint_permanent is called in just one place, so it's
7296      hard to say if it's reasonable to have permanent breakpoint with
7297      multiple locations or not, but it's easy to implement.  */
7298   for (bl = b->loc; bl; bl = bl->next)
7299     bl->inserted = 1;
7300 }
7301
7302 /* Call this routine when stepping and nexting to enable a breakpoint
7303    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7304    initiated the operation.  */
7305
7306 void
7307 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7308 {
7309   struct breakpoint *b, *b_tmp;
7310   int thread = tp->num;
7311
7312   /* To avoid having to rescan all objfile symbols at every step,
7313      we maintain a list of continually-inserted but always disabled
7314      longjmp "master" breakpoints.  Here, we simply create momentary
7315      clones of those and enable them for the requested thread.  */
7316   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7317     if (b->pspace == current_program_space
7318         && (b->type == bp_longjmp_master
7319             || b->type == bp_exception_master))
7320       {
7321         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7322         struct breakpoint *clone;
7323
7324         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7325            after their removal.  */
7326         clone = momentary_breakpoint_from_master (b, type,
7327                                                   &longjmp_breakpoint_ops);
7328         clone->thread = thread;
7329       }
7330
7331   tp->initiating_frame = frame;
7332 }
7333
7334 /* Delete all longjmp breakpoints from THREAD.  */
7335 void
7336 delete_longjmp_breakpoint (int thread)
7337 {
7338   struct breakpoint *b, *b_tmp;
7339
7340   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7341     if (b->type == bp_longjmp || b->type == bp_exception)
7342       {
7343         if (b->thread == thread)
7344           delete_breakpoint (b);
7345       }
7346 }
7347
7348 void
7349 delete_longjmp_breakpoint_at_next_stop (int thread)
7350 {
7351   struct breakpoint *b, *b_tmp;
7352
7353   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7354     if (b->type == bp_longjmp || b->type == bp_exception)
7355       {
7356         if (b->thread == thread)
7357           b->disposition = disp_del_at_next_stop;
7358       }
7359 }
7360
7361 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7362    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7363    pointer to any of them.  Return NULL if this system cannot place longjmp
7364    breakpoints.  */
7365
7366 struct breakpoint *
7367 set_longjmp_breakpoint_for_call_dummy (void)
7368 {
7369   struct breakpoint *b, *retval = NULL;
7370
7371   ALL_BREAKPOINTS (b)
7372     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7373       {
7374         struct breakpoint *new_b;
7375
7376         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7377                                                   &momentary_breakpoint_ops);
7378         new_b->thread = pid_to_thread_id (inferior_ptid);
7379
7380         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7381
7382         gdb_assert (new_b->related_breakpoint == new_b);
7383         if (retval == NULL)
7384           retval = new_b;
7385         new_b->related_breakpoint = retval;
7386         while (retval->related_breakpoint != new_b->related_breakpoint)
7387           retval = retval->related_breakpoint;
7388         retval->related_breakpoint = new_b;
7389       }
7390
7391   return retval;
7392 }
7393
7394 /* Verify all existing dummy frames and their associated breakpoints for
7395    THREAD.  Remove those which can no longer be found in the current frame
7396    stack.
7397
7398    You should call this function only at places where it is safe to currently
7399    unwind the whole stack.  Failed stack unwind would discard live dummy
7400    frames.  */
7401
7402 void
7403 check_longjmp_breakpoint_for_call_dummy (int thread)
7404 {
7405   struct breakpoint *b, *b_tmp;
7406
7407   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7408     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
7409       {
7410         struct breakpoint *dummy_b = b->related_breakpoint;
7411
7412         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7413           dummy_b = dummy_b->related_breakpoint;
7414         if (dummy_b->type != bp_call_dummy
7415             || frame_find_by_id (dummy_b->frame_id) != NULL)
7416           continue;
7417         
7418         dummy_frame_discard (dummy_b->frame_id);
7419
7420         while (b->related_breakpoint != b)
7421           {
7422             if (b_tmp == b->related_breakpoint)
7423               b_tmp = b->related_breakpoint->next;
7424             delete_breakpoint (b->related_breakpoint);
7425           }
7426         delete_breakpoint (b);
7427       }
7428 }
7429
7430 void
7431 enable_overlay_breakpoints (void)
7432 {
7433   struct breakpoint *b;
7434
7435   ALL_BREAKPOINTS (b)
7436     if (b->type == bp_overlay_event)
7437     {
7438       b->enable_state = bp_enabled;
7439       update_global_location_list (1);
7440       overlay_events_enabled = 1;
7441     }
7442 }
7443
7444 void
7445 disable_overlay_breakpoints (void)
7446 {
7447   struct breakpoint *b;
7448
7449   ALL_BREAKPOINTS (b)
7450     if (b->type == bp_overlay_event)
7451     {
7452       b->enable_state = bp_disabled;
7453       update_global_location_list (0);
7454       overlay_events_enabled = 0;
7455     }
7456 }
7457
7458 /* Set an active std::terminate breakpoint for each std::terminate
7459    master breakpoint.  */
7460 void
7461 set_std_terminate_breakpoint (void)
7462 {
7463   struct breakpoint *b, *b_tmp;
7464
7465   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7466     if (b->pspace == current_program_space
7467         && b->type == bp_std_terminate_master)
7468       {
7469         momentary_breakpoint_from_master (b, bp_std_terminate,
7470                                           &momentary_breakpoint_ops);
7471       }
7472 }
7473
7474 /* Delete all the std::terminate breakpoints.  */
7475 void
7476 delete_std_terminate_breakpoint (void)
7477 {
7478   struct breakpoint *b, *b_tmp;
7479
7480   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7481     if (b->type == bp_std_terminate)
7482       delete_breakpoint (b);
7483 }
7484
7485 struct breakpoint *
7486 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7487 {
7488   struct breakpoint *b;
7489
7490   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7491                                   &internal_breakpoint_ops);
7492
7493   b->enable_state = bp_enabled;
7494   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7495   b->addr_string
7496     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7497
7498   update_global_location_list_nothrow (1);
7499
7500   return b;
7501 }
7502
7503 void
7504 remove_thread_event_breakpoints (void)
7505 {
7506   struct breakpoint *b, *b_tmp;
7507
7508   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7509     if (b->type == bp_thread_event
7510         && b->loc->pspace == current_program_space)
7511       delete_breakpoint (b);
7512 }
7513
7514 struct lang_and_radix
7515   {
7516     enum language lang;
7517     int radix;
7518   };
7519
7520 /* Create a breakpoint for JIT code registration and unregistration.  */
7521
7522 struct breakpoint *
7523 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7524 {
7525   struct breakpoint *b;
7526
7527   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7528                                   &internal_breakpoint_ops);
7529   update_global_location_list_nothrow (1);
7530   return b;
7531 }
7532
7533 /* Remove JIT code registration and unregistration breakpoint(s).  */
7534
7535 void
7536 remove_jit_event_breakpoints (void)
7537 {
7538   struct breakpoint *b, *b_tmp;
7539
7540   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7541     if (b->type == bp_jit_event
7542         && b->loc->pspace == current_program_space)
7543       delete_breakpoint (b);
7544 }
7545
7546 void
7547 remove_solib_event_breakpoints (void)
7548 {
7549   struct breakpoint *b, *b_tmp;
7550
7551   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7552     if (b->type == bp_shlib_event
7553         && b->loc->pspace == current_program_space)
7554       delete_breakpoint (b);
7555 }
7556
7557 struct breakpoint *
7558 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7559 {
7560   struct breakpoint *b;
7561
7562   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7563                                   &internal_breakpoint_ops);
7564   update_global_location_list_nothrow (1);
7565   return b;
7566 }
7567
7568 /* Disable any breakpoints that are on code in shared libraries.  Only
7569    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7570
7571 void
7572 disable_breakpoints_in_shlibs (void)
7573 {
7574   struct bp_location *loc, **locp_tmp;
7575
7576   ALL_BP_LOCATIONS (loc, locp_tmp)
7577   {
7578     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7579     struct breakpoint *b = loc->owner;
7580
7581     /* We apply the check to all breakpoints, including disabled for
7582        those with loc->duplicate set.  This is so that when breakpoint
7583        becomes enabled, or the duplicate is removed, gdb will try to
7584        insert all breakpoints.  If we don't set shlib_disabled here,
7585        we'll try to insert those breakpoints and fail.  */
7586     if (((b->type == bp_breakpoint)
7587          || (b->type == bp_jit_event)
7588          || (b->type == bp_hardware_breakpoint)
7589          || (is_tracepoint (b)))
7590         && loc->pspace == current_program_space
7591         && !loc->shlib_disabled
7592         && solib_name_from_address (loc->pspace, loc->address)
7593         )
7594       {
7595         loc->shlib_disabled = 1;
7596       }
7597   }
7598 }
7599
7600 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7601    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7602    disabled ones can just stay disabled.  */
7603
7604 static void
7605 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7606 {
7607   struct bp_location *loc, **locp_tmp;
7608   int disabled_shlib_breaks = 0;
7609
7610   /* SunOS a.out shared libraries are always mapped, so do not
7611      disable breakpoints; they will only be reported as unloaded
7612      through clear_solib when GDB discards its shared library
7613      list.  See clear_solib for more information.  */
7614   if (exec_bfd != NULL
7615       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7616     return;
7617
7618   ALL_BP_LOCATIONS (loc, locp_tmp)
7619   {
7620     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7621     struct breakpoint *b = loc->owner;
7622
7623     if (solib->pspace == loc->pspace
7624         && !loc->shlib_disabled
7625         && (((b->type == bp_breakpoint
7626               || b->type == bp_jit_event
7627               || b->type == bp_hardware_breakpoint)
7628              && (loc->loc_type == bp_loc_hardware_breakpoint
7629                  || loc->loc_type == bp_loc_software_breakpoint))
7630             || is_tracepoint (b))
7631         && solib_contains_address_p (solib, loc->address))
7632       {
7633         loc->shlib_disabled = 1;
7634         /* At this point, we cannot rely on remove_breakpoint
7635            succeeding so we must mark the breakpoint as not inserted
7636            to prevent future errors occurring in remove_breakpoints.  */
7637         loc->inserted = 0;
7638
7639         /* This may cause duplicate notifications for the same breakpoint.  */
7640         observer_notify_breakpoint_modified (b);
7641
7642         if (!disabled_shlib_breaks)
7643           {
7644             target_terminal_ours_for_output ();
7645             warning (_("Temporarily disabling breakpoints "
7646                        "for unloaded shared library \"%s\""),
7647                      solib->so_name);
7648           }
7649         disabled_shlib_breaks = 1;
7650       }
7651   }
7652 }
7653
7654 /* Disable any breakpoints and tracepoints in OBJFILE upon
7655    notification of free_objfile.  Only apply to enabled breakpoints,
7656    disabled ones can just stay disabled.  */
7657
7658 static void
7659 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7660 {
7661   struct breakpoint *b;
7662
7663   if (objfile == NULL)
7664     return;
7665
7666   /* If the file is a shared library not loaded by the user then
7667      solib_unloaded was notified and disable_breakpoints_in_unloaded_shlib
7668      was called.  In that case there is no need to take action again.  */
7669   if ((objfile->flags & OBJF_SHARED) && !(objfile->flags & OBJF_USERLOADED))
7670     return;
7671
7672   ALL_BREAKPOINTS (b)
7673     {
7674       struct bp_location *loc;
7675       int bp_modified = 0;
7676
7677       if (!is_breakpoint (b) && !is_tracepoint (b))
7678         continue;
7679
7680       for (loc = b->loc; loc != NULL; loc = loc->next)
7681         {
7682           CORE_ADDR loc_addr = loc->address;
7683
7684           if (loc->loc_type != bp_loc_hardware_breakpoint
7685               && loc->loc_type != bp_loc_software_breakpoint)
7686             continue;
7687
7688           if (loc->shlib_disabled != 0)
7689             continue;
7690
7691           if (objfile->pspace != loc->pspace)
7692             continue;
7693
7694           if (loc->loc_type != bp_loc_hardware_breakpoint
7695               && loc->loc_type != bp_loc_software_breakpoint)
7696             continue;
7697
7698           if (is_addr_in_objfile (loc_addr, objfile))
7699             {
7700               loc->shlib_disabled = 1;
7701               loc->inserted = 0;
7702
7703               mark_breakpoint_location_modified (loc);
7704
7705               bp_modified = 1;
7706             }
7707         }
7708
7709       if (bp_modified)
7710         observer_notify_breakpoint_modified (b);
7711     }
7712 }
7713
7714 /* FORK & VFORK catchpoints.  */
7715
7716 /* An instance of this type is used to represent a fork or vfork
7717    catchpoint.  It includes a "struct breakpoint" as a kind of base
7718    class; users downcast to "struct breakpoint *" when needed.  A
7719    breakpoint is really of this type iff its ops pointer points to
7720    CATCH_FORK_BREAKPOINT_OPS.  */
7721
7722 struct fork_catchpoint
7723 {
7724   /* The base class.  */
7725   struct breakpoint base;
7726
7727   /* Process id of a child process whose forking triggered this
7728      catchpoint.  This field is only valid immediately after this
7729      catchpoint has triggered.  */
7730   ptid_t forked_inferior_pid;
7731 };
7732
7733 /* Implement the "insert" breakpoint_ops method for fork
7734    catchpoints.  */
7735
7736 static int
7737 insert_catch_fork (struct bp_location *bl)
7738 {
7739   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7740 }
7741
7742 /* Implement the "remove" breakpoint_ops method for fork
7743    catchpoints.  */
7744
7745 static int
7746 remove_catch_fork (struct bp_location *bl)
7747 {
7748   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7749 }
7750
7751 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7752    catchpoints.  */
7753
7754 static int
7755 breakpoint_hit_catch_fork (const struct bp_location *bl,
7756                            struct address_space *aspace, CORE_ADDR bp_addr,
7757                            const struct target_waitstatus *ws)
7758 {
7759   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7760
7761   if (ws->kind != TARGET_WAITKIND_FORKED)
7762     return 0;
7763
7764   c->forked_inferior_pid = ws->value.related_pid;
7765   return 1;
7766 }
7767
7768 /* Implement the "print_it" breakpoint_ops method for fork
7769    catchpoints.  */
7770
7771 static enum print_stop_action
7772 print_it_catch_fork (bpstat bs)
7773 {
7774   struct ui_out *uiout = current_uiout;
7775   struct breakpoint *b = bs->breakpoint_at;
7776   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7777
7778   annotate_catchpoint (b->number);
7779   if (b->disposition == disp_del)
7780     ui_out_text (uiout, "\nTemporary catchpoint ");
7781   else
7782     ui_out_text (uiout, "\nCatchpoint ");
7783   if (ui_out_is_mi_like_p (uiout))
7784     {
7785       ui_out_field_string (uiout, "reason",
7786                            async_reason_lookup (EXEC_ASYNC_FORK));
7787       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7788     }
7789   ui_out_field_int (uiout, "bkptno", b->number);
7790   ui_out_text (uiout, " (forked process ");
7791   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7792   ui_out_text (uiout, "), ");
7793   return PRINT_SRC_AND_LOC;
7794 }
7795
7796 /* Implement the "print_one" breakpoint_ops method for fork
7797    catchpoints.  */
7798
7799 static void
7800 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7801 {
7802   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7803   struct value_print_options opts;
7804   struct ui_out *uiout = current_uiout;
7805
7806   get_user_print_options (&opts);
7807
7808   /* Field 4, the address, is omitted (which makes the columns not
7809      line up too nicely with the headers, but the effect is relatively
7810      readable).  */
7811   if (opts.addressprint)
7812     ui_out_field_skip (uiout, "addr");
7813   annotate_field (5);
7814   ui_out_text (uiout, "fork");
7815   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7816     {
7817       ui_out_text (uiout, ", process ");
7818       ui_out_field_int (uiout, "what",
7819                         ptid_get_pid (c->forked_inferior_pid));
7820       ui_out_spaces (uiout, 1);
7821     }
7822
7823   if (ui_out_is_mi_like_p (uiout))
7824     ui_out_field_string (uiout, "catch-type", "fork");
7825 }
7826
7827 /* Implement the "print_mention" breakpoint_ops method for fork
7828    catchpoints.  */
7829
7830 static void
7831 print_mention_catch_fork (struct breakpoint *b)
7832 {
7833   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7834 }
7835
7836 /* Implement the "print_recreate" breakpoint_ops method for fork
7837    catchpoints.  */
7838
7839 static void
7840 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7841 {
7842   fprintf_unfiltered (fp, "catch fork");
7843   print_recreate_thread (b, fp);
7844 }
7845
7846 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7847
7848 static struct breakpoint_ops catch_fork_breakpoint_ops;
7849
7850 /* Implement the "insert" breakpoint_ops method for vfork
7851    catchpoints.  */
7852
7853 static int
7854 insert_catch_vfork (struct bp_location *bl)
7855 {
7856   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7857 }
7858
7859 /* Implement the "remove" breakpoint_ops method for vfork
7860    catchpoints.  */
7861
7862 static int
7863 remove_catch_vfork (struct bp_location *bl)
7864 {
7865   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
7866 }
7867
7868 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7869    catchpoints.  */
7870
7871 static int
7872 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7873                             struct address_space *aspace, CORE_ADDR bp_addr,
7874                             const struct target_waitstatus *ws)
7875 {
7876   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7877
7878   if (ws->kind != TARGET_WAITKIND_VFORKED)
7879     return 0;
7880
7881   c->forked_inferior_pid = ws->value.related_pid;
7882   return 1;
7883 }
7884
7885 /* Implement the "print_it" breakpoint_ops method for vfork
7886    catchpoints.  */
7887
7888 static enum print_stop_action
7889 print_it_catch_vfork (bpstat bs)
7890 {
7891   struct ui_out *uiout = current_uiout;
7892   struct breakpoint *b = bs->breakpoint_at;
7893   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7894
7895   annotate_catchpoint (b->number);
7896   if (b->disposition == disp_del)
7897     ui_out_text (uiout, "\nTemporary catchpoint ");
7898   else
7899     ui_out_text (uiout, "\nCatchpoint ");
7900   if (ui_out_is_mi_like_p (uiout))
7901     {
7902       ui_out_field_string (uiout, "reason",
7903                            async_reason_lookup (EXEC_ASYNC_VFORK));
7904       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7905     }
7906   ui_out_field_int (uiout, "bkptno", b->number);
7907   ui_out_text (uiout, " (vforked process ");
7908   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7909   ui_out_text (uiout, "), ");
7910   return PRINT_SRC_AND_LOC;
7911 }
7912
7913 /* Implement the "print_one" breakpoint_ops method for vfork
7914    catchpoints.  */
7915
7916 static void
7917 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7918 {
7919   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7920   struct value_print_options opts;
7921   struct ui_out *uiout = current_uiout;
7922
7923   get_user_print_options (&opts);
7924   /* Field 4, the address, is omitted (which makes the columns not
7925      line up too nicely with the headers, but the effect is relatively
7926      readable).  */
7927   if (opts.addressprint)
7928     ui_out_field_skip (uiout, "addr");
7929   annotate_field (5);
7930   ui_out_text (uiout, "vfork");
7931   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7932     {
7933       ui_out_text (uiout, ", process ");
7934       ui_out_field_int (uiout, "what",
7935                         ptid_get_pid (c->forked_inferior_pid));
7936       ui_out_spaces (uiout, 1);
7937     }
7938
7939   if (ui_out_is_mi_like_p (uiout))
7940     ui_out_field_string (uiout, "catch-type", "vfork");
7941 }
7942
7943 /* Implement the "print_mention" breakpoint_ops method for vfork
7944    catchpoints.  */
7945
7946 static void
7947 print_mention_catch_vfork (struct breakpoint *b)
7948 {
7949   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7950 }
7951
7952 /* Implement the "print_recreate" breakpoint_ops method for vfork
7953    catchpoints.  */
7954
7955 static void
7956 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7957 {
7958   fprintf_unfiltered (fp, "catch vfork");
7959   print_recreate_thread (b, fp);
7960 }
7961
7962 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7963
7964 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7965
7966 /* An instance of this type is used to represent an solib catchpoint.
7967    It includes a "struct breakpoint" as a kind of base class; users
7968    downcast to "struct breakpoint *" when needed.  A breakpoint is
7969    really of this type iff its ops pointer points to
7970    CATCH_SOLIB_BREAKPOINT_OPS.  */
7971
7972 struct solib_catchpoint
7973 {
7974   /* The base class.  */
7975   struct breakpoint base;
7976
7977   /* True for "catch load", false for "catch unload".  */
7978   unsigned char is_load;
7979
7980   /* Regular expression to match, if any.  COMPILED is only valid when
7981      REGEX is non-NULL.  */
7982   char *regex;
7983   regex_t compiled;
7984 };
7985
7986 static void
7987 dtor_catch_solib (struct breakpoint *b)
7988 {
7989   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7990
7991   if (self->regex)
7992     regfree (&self->compiled);
7993   xfree (self->regex);
7994
7995   base_breakpoint_ops.dtor (b);
7996 }
7997
7998 static int
7999 insert_catch_solib (struct bp_location *ignore)
8000 {
8001   return 0;
8002 }
8003
8004 static int
8005 remove_catch_solib (struct bp_location *ignore)
8006 {
8007   return 0;
8008 }
8009
8010 static int
8011 breakpoint_hit_catch_solib (const struct bp_location *bl,
8012                             struct address_space *aspace,
8013                             CORE_ADDR bp_addr,
8014                             const struct target_waitstatus *ws)
8015 {
8016   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8017   struct breakpoint *other;
8018
8019   if (ws->kind == TARGET_WAITKIND_LOADED)
8020     return 1;
8021
8022   ALL_BREAKPOINTS (other)
8023   {
8024     struct bp_location *other_bl;
8025
8026     if (other == bl->owner)
8027       continue;
8028
8029     if (other->type != bp_shlib_event)
8030       continue;
8031
8032     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8033       continue;
8034
8035     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8036       {
8037         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8038           return 1;
8039       }
8040   }
8041
8042   return 0;
8043 }
8044
8045 static void
8046 check_status_catch_solib (struct bpstats *bs)
8047 {
8048   struct solib_catchpoint *self
8049     = (struct solib_catchpoint *) bs->breakpoint_at;
8050   int ix;
8051
8052   if (self->is_load)
8053     {
8054       struct so_list *iter;
8055
8056       for (ix = 0;
8057            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8058                         ix, iter);
8059            ++ix)
8060         {
8061           if (!self->regex
8062               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8063             return;
8064         }
8065     }
8066   else
8067     {
8068       char *iter;
8069
8070       for (ix = 0;
8071            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8072                         ix, iter);
8073            ++ix)
8074         {
8075           if (!self->regex
8076               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8077             return;
8078         }
8079     }
8080
8081   bs->stop = 0;
8082   bs->print_it = print_it_noop;
8083 }
8084
8085 static enum print_stop_action
8086 print_it_catch_solib (bpstat bs)
8087 {
8088   struct breakpoint *b = bs->breakpoint_at;
8089   struct ui_out *uiout = current_uiout;
8090
8091   annotate_catchpoint (b->number);
8092   if (b->disposition == disp_del)
8093     ui_out_text (uiout, "\nTemporary catchpoint ");
8094   else
8095     ui_out_text (uiout, "\nCatchpoint ");
8096   ui_out_field_int (uiout, "bkptno", b->number);
8097   ui_out_text (uiout, "\n");
8098   if (ui_out_is_mi_like_p (uiout))
8099     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8100   print_solib_event (1);
8101   return PRINT_SRC_AND_LOC;
8102 }
8103
8104 static void
8105 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8106 {
8107   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8108   struct value_print_options opts;
8109   struct ui_out *uiout = current_uiout;
8110   char *msg;
8111
8112   get_user_print_options (&opts);
8113   /* Field 4, the address, is omitted (which makes the columns not
8114      line up too nicely with the headers, but the effect is relatively
8115      readable).  */
8116   if (opts.addressprint)
8117     {
8118       annotate_field (4);
8119       ui_out_field_skip (uiout, "addr");
8120     }
8121
8122   annotate_field (5);
8123   if (self->is_load)
8124     {
8125       if (self->regex)
8126         msg = xstrprintf (_("load of library matching %s"), self->regex);
8127       else
8128         msg = xstrdup (_("load of library"));
8129     }
8130   else
8131     {
8132       if (self->regex)
8133         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8134       else
8135         msg = xstrdup (_("unload of library"));
8136     }
8137   ui_out_field_string (uiout, "what", msg);
8138   xfree (msg);
8139
8140   if (ui_out_is_mi_like_p (uiout))
8141     ui_out_field_string (uiout, "catch-type",
8142                          self->is_load ? "load" : "unload");
8143 }
8144
8145 static void
8146 print_mention_catch_solib (struct breakpoint *b)
8147 {
8148   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8149
8150   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8151                    self->is_load ? "load" : "unload");
8152 }
8153
8154 static void
8155 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8156 {
8157   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8158
8159   fprintf_unfiltered (fp, "%s %s",
8160                       b->disposition == disp_del ? "tcatch" : "catch",
8161                       self->is_load ? "load" : "unload");
8162   if (self->regex)
8163     fprintf_unfiltered (fp, " %s", self->regex);
8164   fprintf_unfiltered (fp, "\n");
8165 }
8166
8167 static struct breakpoint_ops catch_solib_breakpoint_ops;
8168
8169 /* Shared helper function (MI and CLI) for creating and installing
8170    a shared object event catchpoint.  If IS_LOAD is non-zero then
8171    the events to be caught are load events, otherwise they are
8172    unload events.  If IS_TEMP is non-zero the catchpoint is a
8173    temporary one.  If ENABLED is non-zero the catchpoint is
8174    created in an enabled state.  */
8175
8176 void
8177 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8178 {
8179   struct solib_catchpoint *c;
8180   struct gdbarch *gdbarch = get_current_arch ();
8181   struct cleanup *cleanup;
8182
8183   if (!arg)
8184     arg = "";
8185   arg = skip_spaces (arg);
8186
8187   c = XCNEW (struct solib_catchpoint);
8188   cleanup = make_cleanup (xfree, c);
8189
8190   if (*arg != '\0')
8191     {
8192       int errcode;
8193
8194       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8195       if (errcode != 0)
8196         {
8197           char *err = get_regcomp_error (errcode, &c->compiled);
8198
8199           make_cleanup (xfree, err);
8200           error (_("Invalid regexp (%s): %s"), err, arg);
8201         }
8202       c->regex = xstrdup (arg);
8203     }
8204
8205   c->is_load = is_load;
8206   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8207                    &catch_solib_breakpoint_ops);
8208
8209   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8210
8211   discard_cleanups (cleanup);
8212   install_breakpoint (0, &c->base, 1);
8213 }
8214
8215 /* A helper function that does all the work for "catch load" and
8216    "catch unload".  */
8217
8218 static void
8219 catch_load_or_unload (char *arg, int from_tty, int is_load,
8220                       struct cmd_list_element *command)
8221 {
8222   int tempflag;
8223   const int enabled = 1;
8224
8225   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8226
8227   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8228 }
8229
8230 static void
8231 catch_load_command_1 (char *arg, int from_tty,
8232                       struct cmd_list_element *command)
8233 {
8234   catch_load_or_unload (arg, from_tty, 1, command);
8235 }
8236
8237 static void
8238 catch_unload_command_1 (char *arg, int from_tty,
8239                         struct cmd_list_element *command)
8240 {
8241   catch_load_or_unload (arg, from_tty, 0, command);
8242 }
8243
8244 /* An instance of this type is used to represent a syscall catchpoint.
8245    It includes a "struct breakpoint" as a kind of base class; users
8246    downcast to "struct breakpoint *" when needed.  A breakpoint is
8247    really of this type iff its ops pointer points to
8248    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8249
8250 struct syscall_catchpoint
8251 {
8252   /* The base class.  */
8253   struct breakpoint base;
8254
8255   /* Syscall numbers used for the 'catch syscall' feature.  If no
8256      syscall has been specified for filtering, its value is NULL.
8257      Otherwise, it holds a list of all syscalls to be caught.  The
8258      list elements are allocated with xmalloc.  */
8259   VEC(int) *syscalls_to_be_caught;
8260 };
8261
8262 /* Implement the "dtor" breakpoint_ops method for syscall
8263    catchpoints.  */
8264
8265 static void
8266 dtor_catch_syscall (struct breakpoint *b)
8267 {
8268   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8269
8270   VEC_free (int, c->syscalls_to_be_caught);
8271
8272   base_breakpoint_ops.dtor (b);
8273 }
8274
8275 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8276
8277 struct catch_syscall_inferior_data
8278 {
8279   /* We keep a count of the number of times the user has requested a
8280      particular syscall to be tracked, and pass this information to the
8281      target.  This lets capable targets implement filtering directly.  */
8282
8283   /* Number of times that "any" syscall is requested.  */
8284   int any_syscall_count;
8285
8286   /* Count of each system call.  */
8287   VEC(int) *syscalls_counts;
8288
8289   /* This counts all syscall catch requests, so we can readily determine
8290      if any catching is necessary.  */
8291   int total_syscalls_count;
8292 };
8293
8294 static struct catch_syscall_inferior_data*
8295 get_catch_syscall_inferior_data (struct inferior *inf)
8296 {
8297   struct catch_syscall_inferior_data *inf_data;
8298
8299   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8300   if (inf_data == NULL)
8301     {
8302       inf_data = XCNEW (struct catch_syscall_inferior_data);
8303       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8304     }
8305
8306   return inf_data;
8307 }
8308
8309 static void
8310 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8311 {
8312   xfree (arg);
8313 }
8314
8315
8316 /* Implement the "insert" breakpoint_ops method for syscall
8317    catchpoints.  */
8318
8319 static int
8320 insert_catch_syscall (struct bp_location *bl)
8321 {
8322   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8323   struct inferior *inf = current_inferior ();
8324   struct catch_syscall_inferior_data *inf_data
8325     = get_catch_syscall_inferior_data (inf);
8326
8327   ++inf_data->total_syscalls_count;
8328   if (!c->syscalls_to_be_caught)
8329     ++inf_data->any_syscall_count;
8330   else
8331     {
8332       int i, iter;
8333
8334       for (i = 0;
8335            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8336            i++)
8337         {
8338           int elem;
8339
8340           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8341             {
8342               int old_size = VEC_length (int, inf_data->syscalls_counts);
8343               uintptr_t vec_addr_offset
8344                 = old_size * ((uintptr_t) sizeof (int));
8345               uintptr_t vec_addr;
8346               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8347               vec_addr = ((uintptr_t) VEC_address (int,
8348                                                   inf_data->syscalls_counts)
8349                           + vec_addr_offset);
8350               memset ((void *) vec_addr, 0,
8351                       (iter + 1 - old_size) * sizeof (int));
8352             }
8353           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8354           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8355         }
8356     }
8357
8358   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8359                                         inf_data->total_syscalls_count != 0,
8360                                         inf_data->any_syscall_count,
8361                                         VEC_length (int,
8362                                                     inf_data->syscalls_counts),
8363                                         VEC_address (int,
8364                                                      inf_data->syscalls_counts));
8365 }
8366
8367 /* Implement the "remove" breakpoint_ops method for syscall
8368    catchpoints.  */
8369
8370 static int
8371 remove_catch_syscall (struct bp_location *bl)
8372 {
8373   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8374   struct inferior *inf = current_inferior ();
8375   struct catch_syscall_inferior_data *inf_data
8376     = get_catch_syscall_inferior_data (inf);
8377
8378   --inf_data->total_syscalls_count;
8379   if (!c->syscalls_to_be_caught)
8380     --inf_data->any_syscall_count;
8381   else
8382     {
8383       int i, iter;
8384
8385       for (i = 0;
8386            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8387            i++)
8388         {
8389           int elem;
8390           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8391             /* Shouldn't happen.  */
8392             continue;
8393           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8394           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8395         }
8396     }
8397
8398   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8399                                         inf_data->total_syscalls_count != 0,
8400                                         inf_data->any_syscall_count,
8401                                         VEC_length (int,
8402                                                     inf_data->syscalls_counts),
8403                                         VEC_address (int,
8404                                                      inf_data->syscalls_counts));
8405 }
8406
8407 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8408    catchpoints.  */
8409
8410 static int
8411 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8412                               struct address_space *aspace, CORE_ADDR bp_addr,
8413                               const struct target_waitstatus *ws)
8414 {
8415   /* We must check if we are catching specific syscalls in this
8416      breakpoint.  If we are, then we must guarantee that the called
8417      syscall is the same syscall we are catching.  */
8418   int syscall_number = 0;
8419   const struct syscall_catchpoint *c
8420     = (const struct syscall_catchpoint *) bl->owner;
8421
8422   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8423       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8424     return 0;
8425
8426   syscall_number = ws->value.syscall_number;
8427
8428   /* Now, checking if the syscall is the same.  */
8429   if (c->syscalls_to_be_caught)
8430     {
8431       int i, iter;
8432
8433       for (i = 0;
8434            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8435            i++)
8436         if (syscall_number == iter)
8437           return 1;
8438
8439       return 0;
8440     }
8441
8442   return 1;
8443 }
8444
8445 /* Implement the "print_it" breakpoint_ops method for syscall
8446    catchpoints.  */
8447
8448 static enum print_stop_action
8449 print_it_catch_syscall (bpstat bs)
8450 {
8451   struct ui_out *uiout = current_uiout;
8452   struct breakpoint *b = bs->breakpoint_at;
8453   /* These are needed because we want to know in which state a
8454      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8455      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8456      must print "called syscall" or "returned from syscall".  */
8457   ptid_t ptid;
8458   struct target_waitstatus last;
8459   struct syscall s;
8460
8461   get_last_target_status (&ptid, &last);
8462
8463   get_syscall_by_number (last.value.syscall_number, &s);
8464
8465   annotate_catchpoint (b->number);
8466
8467   if (b->disposition == disp_del)
8468     ui_out_text (uiout, "\nTemporary catchpoint ");
8469   else
8470     ui_out_text (uiout, "\nCatchpoint ");
8471   if (ui_out_is_mi_like_p (uiout))
8472     {
8473       ui_out_field_string (uiout, "reason",
8474                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8475                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8476                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8477       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8478     }
8479   ui_out_field_int (uiout, "bkptno", b->number);
8480
8481   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8482     ui_out_text (uiout, " (call to syscall ");
8483   else
8484     ui_out_text (uiout, " (returned from syscall ");
8485
8486   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8487     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8488   if (s.name != NULL)
8489     ui_out_field_string (uiout, "syscall-name", s.name);
8490
8491   ui_out_text (uiout, "), ");
8492
8493   return PRINT_SRC_AND_LOC;
8494 }
8495
8496 /* Implement the "print_one" breakpoint_ops method for syscall
8497    catchpoints.  */
8498
8499 static void
8500 print_one_catch_syscall (struct breakpoint *b,
8501                          struct bp_location **last_loc)
8502 {
8503   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8504   struct value_print_options opts;
8505   struct ui_out *uiout = current_uiout;
8506
8507   get_user_print_options (&opts);
8508   /* Field 4, the address, is omitted (which makes the columns not
8509      line up too nicely with the headers, but the effect is relatively
8510      readable).  */
8511   if (opts.addressprint)
8512     ui_out_field_skip (uiout, "addr");
8513   annotate_field (5);
8514
8515   if (c->syscalls_to_be_caught
8516       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8517     ui_out_text (uiout, "syscalls \"");
8518   else
8519     ui_out_text (uiout, "syscall \"");
8520
8521   if (c->syscalls_to_be_caught)
8522     {
8523       int i, iter;
8524       char *text = xstrprintf ("%s", "");
8525
8526       for (i = 0;
8527            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8528            i++)
8529         {
8530           char *x = text;
8531           struct syscall s;
8532           get_syscall_by_number (iter, &s);
8533
8534           if (s.name != NULL)
8535             text = xstrprintf ("%s%s, ", text, s.name);
8536           else
8537             text = xstrprintf ("%s%d, ", text, iter);
8538
8539           /* We have to xfree the last 'text' (now stored at 'x')
8540              because xstrprintf dynamically allocates new space for it
8541              on every call.  */
8542           xfree (x);
8543         }
8544       /* Remove the last comma.  */
8545       text[strlen (text) - 2] = '\0';
8546       ui_out_field_string (uiout, "what", text);
8547     }
8548   else
8549     ui_out_field_string (uiout, "what", "<any syscall>");
8550   ui_out_text (uiout, "\" ");
8551
8552   if (ui_out_is_mi_like_p (uiout))
8553     ui_out_field_string (uiout, "catch-type", "syscall");
8554 }
8555
8556 /* Implement the "print_mention" breakpoint_ops method for syscall
8557    catchpoints.  */
8558
8559 static void
8560 print_mention_catch_syscall (struct breakpoint *b)
8561 {
8562   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8563
8564   if (c->syscalls_to_be_caught)
8565     {
8566       int i, iter;
8567
8568       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8569         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8570       else
8571         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8572
8573       for (i = 0;
8574            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8575            i++)
8576         {
8577           struct syscall s;
8578           get_syscall_by_number (iter, &s);
8579
8580           if (s.name)
8581             printf_filtered (" '%s' [%d]", s.name, s.number);
8582           else
8583             printf_filtered (" %d", s.number);
8584         }
8585       printf_filtered (")");
8586     }
8587   else
8588     printf_filtered (_("Catchpoint %d (any syscall)"),
8589                      b->number);
8590 }
8591
8592 /* Implement the "print_recreate" breakpoint_ops method for syscall
8593    catchpoints.  */
8594
8595 static void
8596 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8597 {
8598   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8599
8600   fprintf_unfiltered (fp, "catch syscall");
8601
8602   if (c->syscalls_to_be_caught)
8603     {
8604       int i, iter;
8605
8606       for (i = 0;
8607            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8608            i++)
8609         {
8610           struct syscall s;
8611
8612           get_syscall_by_number (iter, &s);
8613           if (s.name)
8614             fprintf_unfiltered (fp, " %s", s.name);
8615           else
8616             fprintf_unfiltered (fp, " %d", s.number);
8617         }
8618     }
8619   print_recreate_thread (b, fp);
8620 }
8621
8622 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8623
8624 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8625
8626 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8627
8628 static int
8629 syscall_catchpoint_p (struct breakpoint *b)
8630 {
8631   return (b->ops == &catch_syscall_breakpoint_ops);
8632 }
8633
8634 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8635    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8636    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8637    the breakpoint_ops structure associated to the catchpoint.  */
8638
8639 void
8640 init_catchpoint (struct breakpoint *b,
8641                  struct gdbarch *gdbarch, int tempflag,
8642                  char *cond_string,
8643                  const struct breakpoint_ops *ops)
8644 {
8645   struct symtab_and_line sal;
8646
8647   init_sal (&sal);
8648   sal.pspace = current_program_space;
8649
8650   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8651
8652   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8653   b->disposition = tempflag ? disp_del : disp_donttouch;
8654 }
8655
8656 void
8657 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8658 {
8659   add_to_breakpoint_chain (b);
8660   set_breakpoint_number (internal, b);
8661   if (is_tracepoint (b))
8662     set_tracepoint_count (breakpoint_count);
8663   if (!internal)
8664     mention (b);
8665   observer_notify_breakpoint_created (b);
8666
8667   if (update_gll)
8668     update_global_location_list (1);
8669 }
8670
8671 static void
8672 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8673                                     int tempflag, char *cond_string,
8674                                     const struct breakpoint_ops *ops)
8675 {
8676   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8677
8678   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8679
8680   c->forked_inferior_pid = null_ptid;
8681
8682   install_breakpoint (0, &c->base, 1);
8683 }
8684
8685 /* Exec catchpoints.  */
8686
8687 /* An instance of this type is used to represent an exec catchpoint.
8688    It includes a "struct breakpoint" as a kind of base class; users
8689    downcast to "struct breakpoint *" when needed.  A breakpoint is
8690    really of this type iff its ops pointer points to
8691    CATCH_EXEC_BREAKPOINT_OPS.  */
8692
8693 struct exec_catchpoint
8694 {
8695   /* The base class.  */
8696   struct breakpoint base;
8697
8698   /* Filename of a program whose exec triggered this catchpoint.
8699      This field is only valid immediately after this catchpoint has
8700      triggered.  */
8701   char *exec_pathname;
8702 };
8703
8704 /* Implement the "dtor" breakpoint_ops method for exec
8705    catchpoints.  */
8706
8707 static void
8708 dtor_catch_exec (struct breakpoint *b)
8709 {
8710   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8711
8712   xfree (c->exec_pathname);
8713
8714   base_breakpoint_ops.dtor (b);
8715 }
8716
8717 static int
8718 insert_catch_exec (struct bp_location *bl)
8719 {
8720   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8721 }
8722
8723 static int
8724 remove_catch_exec (struct bp_location *bl)
8725 {
8726   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8727 }
8728
8729 static int
8730 breakpoint_hit_catch_exec (const struct bp_location *bl,
8731                            struct address_space *aspace, CORE_ADDR bp_addr,
8732                            const struct target_waitstatus *ws)
8733 {
8734   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8735
8736   if (ws->kind != TARGET_WAITKIND_EXECD)
8737     return 0;
8738
8739   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8740   return 1;
8741 }
8742
8743 static enum print_stop_action
8744 print_it_catch_exec (bpstat bs)
8745 {
8746   struct ui_out *uiout = current_uiout;
8747   struct breakpoint *b = bs->breakpoint_at;
8748   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8749
8750   annotate_catchpoint (b->number);
8751   if (b->disposition == disp_del)
8752     ui_out_text (uiout, "\nTemporary catchpoint ");
8753   else
8754     ui_out_text (uiout, "\nCatchpoint ");
8755   if (ui_out_is_mi_like_p (uiout))
8756     {
8757       ui_out_field_string (uiout, "reason",
8758                            async_reason_lookup (EXEC_ASYNC_EXEC));
8759       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8760     }
8761   ui_out_field_int (uiout, "bkptno", b->number);
8762   ui_out_text (uiout, " (exec'd ");
8763   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8764   ui_out_text (uiout, "), ");
8765
8766   return PRINT_SRC_AND_LOC;
8767 }
8768
8769 static void
8770 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8771 {
8772   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8773   struct value_print_options opts;
8774   struct ui_out *uiout = current_uiout;
8775
8776   get_user_print_options (&opts);
8777
8778   /* Field 4, the address, is omitted (which makes the columns
8779      not line up too nicely with the headers, but the effect
8780      is relatively readable).  */
8781   if (opts.addressprint)
8782     ui_out_field_skip (uiout, "addr");
8783   annotate_field (5);
8784   ui_out_text (uiout, "exec");
8785   if (c->exec_pathname != NULL)
8786     {
8787       ui_out_text (uiout, ", program \"");
8788       ui_out_field_string (uiout, "what", c->exec_pathname);
8789       ui_out_text (uiout, "\" ");
8790     }
8791
8792   if (ui_out_is_mi_like_p (uiout))
8793     ui_out_field_string (uiout, "catch-type", "exec");
8794 }
8795
8796 static void
8797 print_mention_catch_exec (struct breakpoint *b)
8798 {
8799   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8800 }
8801
8802 /* Implement the "print_recreate" breakpoint_ops method for exec
8803    catchpoints.  */
8804
8805 static void
8806 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8807 {
8808   fprintf_unfiltered (fp, "catch exec");
8809   print_recreate_thread (b, fp);
8810 }
8811
8812 static struct breakpoint_ops catch_exec_breakpoint_ops;
8813
8814 static void
8815 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8816                                  const struct breakpoint_ops *ops)
8817 {
8818   struct syscall_catchpoint *c;
8819   struct gdbarch *gdbarch = get_current_arch ();
8820
8821   c = XNEW (struct syscall_catchpoint);
8822   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8823   c->syscalls_to_be_caught = filter;
8824
8825   install_breakpoint (0, &c->base, 1);
8826 }
8827
8828 static int
8829 hw_breakpoint_used_count (void)
8830 {
8831   int i = 0;
8832   struct breakpoint *b;
8833   struct bp_location *bl;
8834
8835   ALL_BREAKPOINTS (b)
8836   {
8837     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8838       for (bl = b->loc; bl; bl = bl->next)
8839         {
8840           /* Special types of hardware breakpoints may use more than
8841              one register.  */
8842           i += b->ops->resources_needed (bl);
8843         }
8844   }
8845
8846   return i;
8847 }
8848
8849 /* Returns the resources B would use if it were a hardware
8850    watchpoint.  */
8851
8852 static int
8853 hw_watchpoint_use_count (struct breakpoint *b)
8854 {
8855   int i = 0;
8856   struct bp_location *bl;
8857
8858   if (!breakpoint_enabled (b))
8859     return 0;
8860
8861   for (bl = b->loc; bl; bl = bl->next)
8862     {
8863       /* Special types of hardware watchpoints may use more than
8864          one register.  */
8865       i += b->ops->resources_needed (bl);
8866     }
8867
8868   return i;
8869 }
8870
8871 /* Returns the sum the used resources of all hardware watchpoints of
8872    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8873    the sum of the used resources of all hardware watchpoints of other
8874    types _not_ TYPE.  */
8875
8876 static int
8877 hw_watchpoint_used_count_others (struct breakpoint *except,
8878                                  enum bptype type, int *other_type_used)
8879 {
8880   int i = 0;
8881   struct breakpoint *b;
8882
8883   *other_type_used = 0;
8884   ALL_BREAKPOINTS (b)
8885     {
8886       if (b == except)
8887         continue;
8888       if (!breakpoint_enabled (b))
8889         continue;
8890
8891       if (b->type == type)
8892         i += hw_watchpoint_use_count (b);
8893       else if (is_hardware_watchpoint (b))
8894         *other_type_used = 1;
8895     }
8896
8897   return i;
8898 }
8899
8900 void
8901 disable_watchpoints_before_interactive_call_start (void)
8902 {
8903   struct breakpoint *b;
8904
8905   ALL_BREAKPOINTS (b)
8906   {
8907     if (is_watchpoint (b) && breakpoint_enabled (b))
8908       {
8909         b->enable_state = bp_call_disabled;
8910         update_global_location_list (0);
8911       }
8912   }
8913 }
8914
8915 void
8916 enable_watchpoints_after_interactive_call_stop (void)
8917 {
8918   struct breakpoint *b;
8919
8920   ALL_BREAKPOINTS (b)
8921   {
8922     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8923       {
8924         b->enable_state = bp_enabled;
8925         update_global_location_list (1);
8926       }
8927   }
8928 }
8929
8930 void
8931 disable_breakpoints_before_startup (void)
8932 {
8933   current_program_space->executing_startup = 1;
8934   update_global_location_list (0);
8935 }
8936
8937 void
8938 enable_breakpoints_after_startup (void)
8939 {
8940   current_program_space->executing_startup = 0;
8941   breakpoint_re_set ();
8942 }
8943
8944
8945 /* Set a breakpoint that will evaporate an end of command
8946    at address specified by SAL.
8947    Restrict it to frame FRAME if FRAME is nonzero.  */
8948
8949 struct breakpoint *
8950 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8951                           struct frame_id frame_id, enum bptype type)
8952 {
8953   struct breakpoint *b;
8954
8955   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
8956      tail-called one.  */
8957   gdb_assert (!frame_id_artificial_p (frame_id));
8958
8959   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8960   b->enable_state = bp_enabled;
8961   b->disposition = disp_donttouch;
8962   b->frame_id = frame_id;
8963
8964   /* If we're debugging a multi-threaded program, then we want
8965      momentary breakpoints to be active in only a single thread of
8966      control.  */
8967   if (in_thread_list (inferior_ptid))
8968     b->thread = pid_to_thread_id (inferior_ptid);
8969
8970   update_global_location_list_nothrow (1);
8971
8972   return b;
8973 }
8974
8975 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8976    The new breakpoint will have type TYPE, and use OPS as it
8977    breakpoint_ops.  */
8978
8979 static struct breakpoint *
8980 momentary_breakpoint_from_master (struct breakpoint *orig,
8981                                   enum bptype type,
8982                                   const struct breakpoint_ops *ops)
8983 {
8984   struct breakpoint *copy;
8985
8986   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8987   copy->loc = allocate_bp_location (copy);
8988   set_breakpoint_location_function (copy->loc, 1);
8989
8990   copy->loc->gdbarch = orig->loc->gdbarch;
8991   copy->loc->requested_address = orig->loc->requested_address;
8992   copy->loc->address = orig->loc->address;
8993   copy->loc->section = orig->loc->section;
8994   copy->loc->pspace = orig->loc->pspace;
8995   copy->loc->probe = orig->loc->probe;
8996   copy->loc->line_number = orig->loc->line_number;
8997   copy->loc->symtab = orig->loc->symtab;
8998   copy->frame_id = orig->frame_id;
8999   copy->thread = orig->thread;
9000   copy->pspace = orig->pspace;
9001
9002   copy->enable_state = bp_enabled;
9003   copy->disposition = disp_donttouch;
9004   copy->number = internal_breakpoint_number--;
9005
9006   update_global_location_list_nothrow (0);
9007   return copy;
9008 }
9009
9010 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9011    ORIG is NULL.  */
9012
9013 struct breakpoint *
9014 clone_momentary_breakpoint (struct breakpoint *orig)
9015 {
9016   /* If there's nothing to clone, then return nothing.  */
9017   if (orig == NULL)
9018     return NULL;
9019
9020   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
9021 }
9022
9023 struct breakpoint *
9024 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9025                                 enum bptype type)
9026 {
9027   struct symtab_and_line sal;
9028
9029   sal = find_pc_line (pc, 0);
9030   sal.pc = pc;
9031   sal.section = find_pc_overlay (pc);
9032   sal.explicit_pc = 1;
9033
9034   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9035 }
9036 \f
9037
9038 /* Tell the user we have just set a breakpoint B.  */
9039
9040 static void
9041 mention (struct breakpoint *b)
9042 {
9043   b->ops->print_mention (b);
9044   if (ui_out_is_mi_like_p (current_uiout))
9045     return;
9046   printf_filtered ("\n");
9047 }
9048 \f
9049
9050 static struct bp_location *
9051 add_location_to_breakpoint (struct breakpoint *b,
9052                             const struct symtab_and_line *sal)
9053 {
9054   struct bp_location *loc, **tmp;
9055   CORE_ADDR adjusted_address;
9056   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9057
9058   if (loc_gdbarch == NULL)
9059     loc_gdbarch = b->gdbarch;
9060
9061   /* Adjust the breakpoint's address prior to allocating a location.
9062      Once we call allocate_bp_location(), that mostly uninitialized
9063      location will be placed on the location chain.  Adjustment of the
9064      breakpoint may cause target_read_memory() to be called and we do
9065      not want its scan of the location chain to find a breakpoint and
9066      location that's only been partially initialized.  */
9067   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9068                                                 sal->pc, b->type);
9069
9070   /* Sort the locations by their ADDRESS.  */
9071   loc = allocate_bp_location (b);
9072   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9073        tmp = &((*tmp)->next))
9074     ;
9075   loc->next = *tmp;
9076   *tmp = loc;
9077
9078   loc->requested_address = sal->pc;
9079   loc->address = adjusted_address;
9080   loc->pspace = sal->pspace;
9081   loc->probe.probe = sal->probe;
9082   loc->probe.objfile = sal->objfile;
9083   gdb_assert (loc->pspace != NULL);
9084   loc->section = sal->section;
9085   loc->gdbarch = loc_gdbarch;
9086   loc->line_number = sal->line;
9087   loc->symtab = sal->symtab;
9088
9089   set_breakpoint_location_function (loc,
9090                                     sal->explicit_pc || sal->explicit_line);
9091   return loc;
9092 }
9093 \f
9094
9095 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9096    return 0 otherwise.  */
9097
9098 static int
9099 bp_loc_is_permanent (struct bp_location *loc)
9100 {
9101   int len;
9102   CORE_ADDR addr;
9103   const gdb_byte *bpoint;
9104   gdb_byte *target_mem;
9105   struct cleanup *cleanup;
9106   int retval = 0;
9107
9108   gdb_assert (loc != NULL);
9109
9110   addr = loc->address;
9111   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9112
9113   /* Software breakpoints unsupported?  */
9114   if (bpoint == NULL)
9115     return 0;
9116
9117   target_mem = alloca (len);
9118
9119   /* Enable the automatic memory restoration from breakpoints while
9120      we read the memory.  Otherwise we could say about our temporary
9121      breakpoints they are permanent.  */
9122   cleanup = save_current_space_and_thread ();
9123
9124   switch_to_program_space_and_thread (loc->pspace);
9125   make_show_memory_breakpoints_cleanup (0);
9126
9127   if (target_read_memory (loc->address, target_mem, len) == 0
9128       && memcmp (target_mem, bpoint, len) == 0)
9129     retval = 1;
9130
9131   do_cleanups (cleanup);
9132
9133   return retval;
9134 }
9135
9136 /* Build a command list for the dprintf corresponding to the current
9137    settings of the dprintf style options.  */
9138
9139 static void
9140 update_dprintf_command_list (struct breakpoint *b)
9141 {
9142   char *dprintf_args = b->extra_string;
9143   char *printf_line = NULL;
9144
9145   if (!dprintf_args)
9146     return;
9147
9148   dprintf_args = skip_spaces (dprintf_args);
9149
9150   /* Allow a comma, as it may have terminated a location, but don't
9151      insist on it.  */
9152   if (*dprintf_args == ',')
9153     ++dprintf_args;
9154   dprintf_args = skip_spaces (dprintf_args);
9155
9156   if (*dprintf_args != '"')
9157     error (_("Bad format string, missing '\"'."));
9158
9159   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9160     printf_line = xstrprintf ("printf %s", dprintf_args);
9161   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9162     {
9163       if (!dprintf_function)
9164         error (_("No function supplied for dprintf call"));
9165
9166       if (dprintf_channel && strlen (dprintf_channel) > 0)
9167         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9168                                   dprintf_function,
9169                                   dprintf_channel,
9170                                   dprintf_args);
9171       else
9172         printf_line = xstrprintf ("call (void) %s (%s)",
9173                                   dprintf_function,
9174                                   dprintf_args);
9175     }
9176   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9177     {
9178       if (target_can_run_breakpoint_commands ())
9179         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9180       else
9181         {
9182           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9183           printf_line = xstrprintf ("printf %s", dprintf_args);
9184         }
9185     }
9186   else
9187     internal_error (__FILE__, __LINE__,
9188                     _("Invalid dprintf style."));
9189
9190   gdb_assert (printf_line != NULL);
9191   /* Manufacture a printf sequence.  */
9192   {
9193     struct command_line *printf_cmd_line
9194       = xmalloc (sizeof (struct command_line));
9195
9196     printf_cmd_line = xmalloc (sizeof (struct command_line));
9197     printf_cmd_line->control_type = simple_control;
9198     printf_cmd_line->body_count = 0;
9199     printf_cmd_line->body_list = NULL;
9200     printf_cmd_line->next = NULL;
9201     printf_cmd_line->line = printf_line;
9202
9203     breakpoint_set_commands (b, printf_cmd_line);
9204   }
9205 }
9206
9207 /* Update all dprintf commands, making their command lists reflect
9208    current style settings.  */
9209
9210 static void
9211 update_dprintf_commands (char *args, int from_tty,
9212                          struct cmd_list_element *c)
9213 {
9214   struct breakpoint *b;
9215
9216   ALL_BREAKPOINTS (b)
9217     {
9218       if (b->type == bp_dprintf)
9219         update_dprintf_command_list (b);
9220     }
9221 }
9222
9223 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9224    as textual description of the location, and COND_STRING
9225    as condition expression.  */
9226
9227 static void
9228 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9229                      struct symtabs_and_lines sals, char *addr_string,
9230                      char *filter, char *cond_string,
9231                      char *extra_string,
9232                      enum bptype type, enum bpdisp disposition,
9233                      int thread, int task, int ignore_count,
9234                      const struct breakpoint_ops *ops, int from_tty,
9235                      int enabled, int internal, unsigned flags,
9236                      int display_canonical)
9237 {
9238   int i;
9239
9240   if (type == bp_hardware_breakpoint)
9241     {
9242       int target_resources_ok;
9243
9244       i = hw_breakpoint_used_count ();
9245       target_resources_ok =
9246         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9247                                             i + 1, 0);
9248       if (target_resources_ok == 0)
9249         error (_("No hardware breakpoint support in the target."));
9250       else if (target_resources_ok < 0)
9251         error (_("Hardware breakpoints used exceeds limit."));
9252     }
9253
9254   gdb_assert (sals.nelts > 0);
9255
9256   for (i = 0; i < sals.nelts; ++i)
9257     {
9258       struct symtab_and_line sal = sals.sals[i];
9259       struct bp_location *loc;
9260
9261       if (from_tty)
9262         {
9263           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9264           if (!loc_gdbarch)
9265             loc_gdbarch = gdbarch;
9266
9267           describe_other_breakpoints (loc_gdbarch,
9268                                       sal.pspace, sal.pc, sal.section, thread);
9269         }
9270
9271       if (i == 0)
9272         {
9273           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9274           b->thread = thread;
9275           b->task = task;
9276
9277           b->cond_string = cond_string;
9278           b->extra_string = extra_string;
9279           b->ignore_count = ignore_count;
9280           b->enable_state = enabled ? bp_enabled : bp_disabled;
9281           b->disposition = disposition;
9282
9283           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9284             b->loc->inserted = 1;
9285
9286           if (type == bp_static_tracepoint)
9287             {
9288               struct tracepoint *t = (struct tracepoint *) b;
9289               struct static_tracepoint_marker marker;
9290
9291               if (strace_marker_p (b))
9292                 {
9293                   /* We already know the marker exists, otherwise, we
9294                      wouldn't see a sal for it.  */
9295                   char *p = &addr_string[3];
9296                   char *endp;
9297                   char *marker_str;
9298
9299                   p = skip_spaces (p);
9300
9301                   endp = skip_to_space (p);
9302
9303                   marker_str = savestring (p, endp - p);
9304                   t->static_trace_marker_id = marker_str;
9305
9306                   printf_filtered (_("Probed static tracepoint "
9307                                      "marker \"%s\"\n"),
9308                                    t->static_trace_marker_id);
9309                 }
9310               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9311                 {
9312                   t->static_trace_marker_id = xstrdup (marker.str_id);
9313                   release_static_tracepoint_marker (&marker);
9314
9315                   printf_filtered (_("Probed static tracepoint "
9316                                      "marker \"%s\"\n"),
9317                                    t->static_trace_marker_id);
9318                 }
9319               else
9320                 warning (_("Couldn't determine the static "
9321                            "tracepoint marker to probe"));
9322             }
9323
9324           loc = b->loc;
9325         }
9326       else
9327         {
9328           loc = add_location_to_breakpoint (b, &sal);
9329           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9330             loc->inserted = 1;
9331         }
9332
9333       if (bp_loc_is_permanent (loc))
9334         make_breakpoint_permanent (b);
9335
9336       if (b->cond_string)
9337         {
9338           const char *arg = b->cond_string;
9339
9340           loc->cond = parse_exp_1 (&arg, loc->address,
9341                                    block_for_pc (loc->address), 0);
9342           if (*arg)
9343               error (_("Garbage '%s' follows condition"), arg);
9344         }
9345
9346       /* Dynamic printf requires and uses additional arguments on the
9347          command line, otherwise it's an error.  */
9348       if (type == bp_dprintf)
9349         {
9350           if (b->extra_string)
9351             update_dprintf_command_list (b);
9352           else
9353             error (_("Format string required"));
9354         }
9355       else if (b->extra_string)
9356         error (_("Garbage '%s' at end of command"), b->extra_string);
9357     }
9358
9359   b->display_canonical = display_canonical;
9360   if (addr_string)
9361     b->addr_string = addr_string;
9362   else
9363     /* addr_string has to be used or breakpoint_re_set will delete
9364        me.  */
9365     b->addr_string
9366       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9367   b->filter = filter;
9368 }
9369
9370 static void
9371 create_breakpoint_sal (struct gdbarch *gdbarch,
9372                        struct symtabs_and_lines sals, char *addr_string,
9373                        char *filter, char *cond_string,
9374                        char *extra_string,
9375                        enum bptype type, enum bpdisp disposition,
9376                        int thread, int task, int ignore_count,
9377                        const struct breakpoint_ops *ops, int from_tty,
9378                        int enabled, int internal, unsigned flags,
9379                        int display_canonical)
9380 {
9381   struct breakpoint *b;
9382   struct cleanup *old_chain;
9383
9384   if (is_tracepoint_type (type))
9385     {
9386       struct tracepoint *t;
9387
9388       t = XCNEW (struct tracepoint);
9389       b = &t->base;
9390     }
9391   else
9392     b = XNEW (struct breakpoint);
9393
9394   old_chain = make_cleanup (xfree, b);
9395
9396   init_breakpoint_sal (b, gdbarch,
9397                        sals, addr_string,
9398                        filter, cond_string, extra_string,
9399                        type, disposition,
9400                        thread, task, ignore_count,
9401                        ops, from_tty,
9402                        enabled, internal, flags,
9403                        display_canonical);
9404   discard_cleanups (old_chain);
9405
9406   install_breakpoint (internal, b, 0);
9407 }
9408
9409 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9410    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9411    value.  COND_STRING, if not NULL, specified the condition to be
9412    used for all breakpoints.  Essentially the only case where
9413    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9414    function.  In that case, it's still not possible to specify
9415    separate conditions for different overloaded functions, so
9416    we take just a single condition string.
9417    
9418    NOTE: If the function succeeds, the caller is expected to cleanup
9419    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9420    array contents).  If the function fails (error() is called), the
9421    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9422    COND and SALS arrays and each of those arrays contents.  */
9423
9424 static void
9425 create_breakpoints_sal (struct gdbarch *gdbarch,
9426                         struct linespec_result *canonical,
9427                         char *cond_string, char *extra_string,
9428                         enum bptype type, enum bpdisp disposition,
9429                         int thread, int task, int ignore_count,
9430                         const struct breakpoint_ops *ops, int from_tty,
9431                         int enabled, int internal, unsigned flags)
9432 {
9433   int i;
9434   struct linespec_sals *lsal;
9435
9436   if (canonical->pre_expanded)
9437     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9438
9439   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9440     {
9441       /* Note that 'addr_string' can be NULL in the case of a plain
9442          'break', without arguments.  */
9443       char *addr_string = (canonical->addr_string
9444                            ? xstrdup (canonical->addr_string)
9445                            : NULL);
9446       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9447       struct cleanup *inner = make_cleanup (xfree, addr_string);
9448
9449       make_cleanup (xfree, filter_string);
9450       create_breakpoint_sal (gdbarch, lsal->sals,
9451                              addr_string,
9452                              filter_string,
9453                              cond_string, extra_string,
9454                              type, disposition,
9455                              thread, task, ignore_count, ops,
9456                              from_tty, enabled, internal, flags,
9457                              canonical->special_display);
9458       discard_cleanups (inner);
9459     }
9460 }
9461
9462 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9463    followed by conditionals.  On return, SALS contains an array of SAL
9464    addresses found.  ADDR_STRING contains a vector of (canonical)
9465    address strings.  ADDRESS points to the end of the SAL.
9466
9467    The array and the line spec strings are allocated on the heap, it is
9468    the caller's responsibility to free them.  */
9469
9470 static void
9471 parse_breakpoint_sals (char **address,
9472                        struct linespec_result *canonical)
9473 {
9474   /* If no arg given, or if first arg is 'if ', use the default
9475      breakpoint.  */
9476   if ((*address) == NULL
9477       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9478     {
9479       /* The last displayed codepoint, if it's valid, is our default breakpoint
9480          address.  */
9481       if (last_displayed_sal_is_valid ())
9482         {
9483           struct linespec_sals lsal;
9484           struct symtab_and_line sal;
9485           CORE_ADDR pc;
9486
9487           init_sal (&sal);              /* Initialize to zeroes.  */
9488           lsal.sals.sals = (struct symtab_and_line *)
9489             xmalloc (sizeof (struct symtab_and_line));
9490
9491           /* Set sal's pspace, pc, symtab, and line to the values
9492              corresponding to the last call to print_frame_info.
9493              Be sure to reinitialize LINE with NOTCURRENT == 0
9494              as the breakpoint line number is inappropriate otherwise.
9495              find_pc_line would adjust PC, re-set it back.  */
9496           get_last_displayed_sal (&sal);
9497           pc = sal.pc;
9498           sal = find_pc_line (pc, 0);
9499
9500           /* "break" without arguments is equivalent to "break *PC"
9501              where PC is the last displayed codepoint's address.  So
9502              make sure to set sal.explicit_pc to prevent GDB from
9503              trying to expand the list of sals to include all other
9504              instances with the same symtab and line.  */
9505           sal.pc = pc;
9506           sal.explicit_pc = 1;
9507
9508           lsal.sals.sals[0] = sal;
9509           lsal.sals.nelts = 1;
9510           lsal.canonical = NULL;
9511
9512           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9513         }
9514       else
9515         error (_("No default breakpoint address now."));
9516     }
9517   else
9518     {
9519       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9520
9521       /* Force almost all breakpoints to be in terms of the
9522          current_source_symtab (which is decode_line_1's default).
9523          This should produce the results we want almost all of the
9524          time while leaving default_breakpoint_* alone.
9525
9526          ObjC: However, don't match an Objective-C method name which
9527          may have a '+' or '-' succeeded by a '['.  */
9528       if (last_displayed_sal_is_valid ()
9529           && (!cursal.symtab
9530               || ((strchr ("+-", (*address)[0]) != NULL)
9531                   && ((*address)[1] != '['))))
9532         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9533                           get_last_displayed_symtab (),
9534                           get_last_displayed_line (),
9535                           canonical, NULL, NULL);
9536       else
9537         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9538                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9539     }
9540 }
9541
9542
9543 /* Convert each SAL into a real PC.  Verify that the PC can be
9544    inserted as a breakpoint.  If it can't throw an error.  */
9545
9546 static void
9547 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9548 {    
9549   int i;
9550
9551   for (i = 0; i < sals->nelts; i++)
9552     resolve_sal_pc (&sals->sals[i]);
9553 }
9554
9555 /* Fast tracepoints may have restrictions on valid locations.  For
9556    instance, a fast tracepoint using a jump instead of a trap will
9557    likely have to overwrite more bytes than a trap would, and so can
9558    only be placed where the instruction is longer than the jump, or a
9559    multi-instruction sequence does not have a jump into the middle of
9560    it, etc.  */
9561
9562 static void
9563 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9564                             struct symtabs_and_lines *sals)
9565 {
9566   int i, rslt;
9567   struct symtab_and_line *sal;
9568   char *msg;
9569   struct cleanup *old_chain;
9570
9571   for (i = 0; i < sals->nelts; i++)
9572     {
9573       struct gdbarch *sarch;
9574
9575       sal = &sals->sals[i];
9576
9577       sarch = get_sal_arch (*sal);
9578       /* We fall back to GDBARCH if there is no architecture
9579          associated with SAL.  */
9580       if (sarch == NULL)
9581         sarch = gdbarch;
9582       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9583                                                NULL, &msg);
9584       old_chain = make_cleanup (xfree, msg);
9585
9586       if (!rslt)
9587         error (_("May not have a fast tracepoint at 0x%s%s"),
9588                paddress (sarch, sal->pc), (msg ? msg : ""));
9589
9590       do_cleanups (old_chain);
9591     }
9592 }
9593
9594 /* Issue an invalid thread ID error.  */
9595
9596 static void ATTRIBUTE_NORETURN
9597 invalid_thread_id_error (int id)
9598 {
9599   error (_("Unknown thread %d."), id);
9600 }
9601
9602 /* Given TOK, a string specification of condition and thread, as
9603    accepted by the 'break' command, extract the condition
9604    string and thread number and set *COND_STRING and *THREAD.
9605    PC identifies the context at which the condition should be parsed.
9606    If no condition is found, *COND_STRING is set to NULL.
9607    If no thread is found, *THREAD is set to -1.  */
9608
9609 static void
9610 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9611                            char **cond_string, int *thread, int *task,
9612                            char **rest)
9613 {
9614   *cond_string = NULL;
9615   *thread = -1;
9616   *task = 0;
9617   *rest = NULL;
9618
9619   while (tok && *tok)
9620     {
9621       const char *end_tok;
9622       int toklen;
9623       const char *cond_start = NULL;
9624       const char *cond_end = NULL;
9625
9626       tok = skip_spaces_const (tok);
9627
9628       if ((*tok == '"' || *tok == ',') && rest)
9629         {
9630           *rest = savestring (tok, strlen (tok));
9631           return;
9632         }
9633
9634       end_tok = skip_to_space_const (tok);
9635
9636       toklen = end_tok - tok;
9637
9638       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9639         {
9640           struct expression *expr;
9641
9642           tok = cond_start = end_tok + 1;
9643           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9644           xfree (expr);
9645           cond_end = tok;
9646           *cond_string = savestring (cond_start, cond_end - cond_start);
9647         }
9648       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9649         {
9650           char *tmptok;
9651
9652           tok = end_tok + 1;
9653           *thread = strtol (tok, &tmptok, 0);
9654           if (tok == tmptok)
9655             error (_("Junk after thread keyword."));
9656           if (!valid_thread_id (*thread))
9657             invalid_thread_id_error (*thread);
9658           tok = tmptok;
9659         }
9660       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9661         {
9662           char *tmptok;
9663
9664           tok = end_tok + 1;
9665           *task = strtol (tok, &tmptok, 0);
9666           if (tok == tmptok)
9667             error (_("Junk after task keyword."));
9668           if (!valid_task_id (*task))
9669             error (_("Unknown task %d."), *task);
9670           tok = tmptok;
9671         }
9672       else if (rest)
9673         {
9674           *rest = savestring (tok, strlen (tok));
9675           return;
9676         }
9677       else
9678         error (_("Junk at end of arguments."));
9679     }
9680 }
9681
9682 /* Decode a static tracepoint marker spec.  */
9683
9684 static struct symtabs_and_lines
9685 decode_static_tracepoint_spec (char **arg_p)
9686 {
9687   VEC(static_tracepoint_marker_p) *markers = NULL;
9688   struct symtabs_and_lines sals;
9689   struct cleanup *old_chain;
9690   char *p = &(*arg_p)[3];
9691   char *endp;
9692   char *marker_str;
9693   int i;
9694
9695   p = skip_spaces (p);
9696
9697   endp = skip_to_space (p);
9698
9699   marker_str = savestring (p, endp - p);
9700   old_chain = make_cleanup (xfree, marker_str);
9701
9702   markers = target_static_tracepoint_markers_by_strid (marker_str);
9703   if (VEC_empty(static_tracepoint_marker_p, markers))
9704     error (_("No known static tracepoint marker named %s"), marker_str);
9705
9706   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9707   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9708
9709   for (i = 0; i < sals.nelts; i++)
9710     {
9711       struct static_tracepoint_marker *marker;
9712
9713       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9714
9715       init_sal (&sals.sals[i]);
9716
9717       sals.sals[i] = find_pc_line (marker->address, 0);
9718       sals.sals[i].pc = marker->address;
9719
9720       release_static_tracepoint_marker (marker);
9721     }
9722
9723   do_cleanups (old_chain);
9724
9725   *arg_p = endp;
9726   return sals;
9727 }
9728
9729 /* Set a breakpoint.  This function is shared between CLI and MI
9730    functions for setting a breakpoint.  This function has two major
9731    modes of operations, selected by the PARSE_ARG parameter.  If
9732    non-zero, the function will parse ARG, extracting location,
9733    condition, thread and extra string.  Otherwise, ARG is just the
9734    breakpoint's location, with condition, thread, and extra string
9735    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9736    If INTERNAL is non-zero, the breakpoint number will be allocated
9737    from the internal breakpoint count.  Returns true if any breakpoint
9738    was created; false otherwise.  */
9739
9740 int
9741 create_breakpoint (struct gdbarch *gdbarch,
9742                    char *arg, char *cond_string,
9743                    int thread, char *extra_string,
9744                    int parse_arg,
9745                    int tempflag, enum bptype type_wanted,
9746                    int ignore_count,
9747                    enum auto_boolean pending_break_support,
9748                    const struct breakpoint_ops *ops,
9749                    int from_tty, int enabled, int internal,
9750                    unsigned flags)
9751 {
9752   volatile struct gdb_exception e;
9753   char *copy_arg = NULL;
9754   char *addr_start = arg;
9755   struct linespec_result canonical;
9756   struct cleanup *old_chain;
9757   struct cleanup *bkpt_chain = NULL;
9758   int pending = 0;
9759   int task = 0;
9760   int prev_bkpt_count = breakpoint_count;
9761
9762   gdb_assert (ops != NULL);
9763
9764   init_linespec_result (&canonical);
9765
9766   TRY_CATCH (e, RETURN_MASK_ALL)
9767     {
9768       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9769                                      addr_start, &copy_arg);
9770     }
9771
9772   /* If caller is interested in rc value from parse, set value.  */
9773   switch (e.reason)
9774     {
9775     case GDB_NO_ERROR:
9776       if (VEC_empty (linespec_sals, canonical.sals))
9777         return 0;
9778       break;
9779     case RETURN_ERROR:
9780       switch (e.error)
9781         {
9782         case NOT_FOUND_ERROR:
9783
9784           /* If pending breakpoint support is turned off, throw
9785              error.  */
9786
9787           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9788             throw_exception (e);
9789
9790           exception_print (gdb_stderr, e);
9791
9792           /* If pending breakpoint support is auto query and the user
9793              selects no, then simply return the error code.  */
9794           if (pending_break_support == AUTO_BOOLEAN_AUTO
9795               && !nquery (_("Make %s pending on future shared library load? "),
9796                           bptype_string (type_wanted)))
9797             return 0;
9798
9799           /* At this point, either the user was queried about setting
9800              a pending breakpoint and selected yes, or pending
9801              breakpoint behavior is on and thus a pending breakpoint
9802              is defaulted on behalf of the user.  */
9803           {
9804             struct linespec_sals lsal;
9805
9806             copy_arg = xstrdup (addr_start);
9807             lsal.canonical = xstrdup (copy_arg);
9808             lsal.sals.nelts = 1;
9809             lsal.sals.sals = XNEW (struct symtab_and_line);
9810             init_sal (&lsal.sals.sals[0]);
9811             pending = 1;
9812             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9813           }
9814           break;
9815         default:
9816           throw_exception (e);
9817         }
9818       break;
9819     default:
9820       throw_exception (e);
9821     }
9822
9823   /* Create a chain of things that always need to be cleaned up.  */
9824   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9825
9826   /* ----------------------------- SNIP -----------------------------
9827      Anything added to the cleanup chain beyond this point is assumed
9828      to be part of a breakpoint.  If the breakpoint create succeeds
9829      then the memory is not reclaimed.  */
9830   bkpt_chain = make_cleanup (null_cleanup, 0);
9831
9832   /* Resolve all line numbers to PC's and verify that the addresses
9833      are ok for the target.  */
9834   if (!pending)
9835     {
9836       int ix;
9837       struct linespec_sals *iter;
9838
9839       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9840         breakpoint_sals_to_pc (&iter->sals);
9841     }
9842
9843   /* Fast tracepoints may have additional restrictions on location.  */
9844   if (!pending && type_wanted == bp_fast_tracepoint)
9845     {
9846       int ix;
9847       struct linespec_sals *iter;
9848
9849       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9850         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9851     }
9852
9853   /* Verify that condition can be parsed, before setting any
9854      breakpoints.  Allocate a separate condition expression for each
9855      breakpoint.  */
9856   if (!pending)
9857     {
9858       if (parse_arg)
9859         {
9860           char *rest;
9861           struct linespec_sals *lsal;
9862
9863           lsal = VEC_index (linespec_sals, canonical.sals, 0);
9864
9865           /* Here we only parse 'arg' to separate condition
9866              from thread number, so parsing in context of first
9867              sal is OK.  When setting the breakpoint we'll
9868              re-parse it in context of each sal.  */
9869
9870           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9871                                      &thread, &task, &rest);
9872           if (cond_string)
9873             make_cleanup (xfree, cond_string);
9874           if (rest)
9875             make_cleanup (xfree, rest);
9876           if (rest)
9877             extra_string = rest;
9878         }
9879       else
9880         {
9881           if (*arg != '\0')
9882             error (_("Garbage '%s' at end of location"), arg);
9883
9884           /* Create a private copy of condition string.  */
9885           if (cond_string)
9886             {
9887               cond_string = xstrdup (cond_string);
9888               make_cleanup (xfree, cond_string);
9889             }
9890           /* Create a private copy of any extra string.  */
9891           if (extra_string)
9892             {
9893               extra_string = xstrdup (extra_string);
9894               make_cleanup (xfree, extra_string);
9895             }
9896         }
9897
9898       ops->create_breakpoints_sal (gdbarch, &canonical,
9899                                    cond_string, extra_string, type_wanted,
9900                                    tempflag ? disp_del : disp_donttouch,
9901                                    thread, task, ignore_count, ops,
9902                                    from_tty, enabled, internal, flags);
9903     }
9904   else
9905     {
9906       struct breakpoint *b;
9907
9908       make_cleanup (xfree, copy_arg);
9909
9910       if (is_tracepoint_type (type_wanted))
9911         {
9912           struct tracepoint *t;
9913
9914           t = XCNEW (struct tracepoint);
9915           b = &t->base;
9916         }
9917       else
9918         b = XNEW (struct breakpoint);
9919
9920       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9921
9922       b->addr_string = copy_arg;
9923       if (parse_arg)
9924         b->cond_string = NULL;
9925       else
9926         {
9927           /* Create a private copy of condition string.  */
9928           if (cond_string)
9929             {
9930               cond_string = xstrdup (cond_string);
9931               make_cleanup (xfree, cond_string);
9932             }
9933           b->cond_string = cond_string;
9934         }
9935       b->extra_string = NULL;
9936       b->ignore_count = ignore_count;
9937       b->disposition = tempflag ? disp_del : disp_donttouch;
9938       b->condition_not_parsed = 1;
9939       b->enable_state = enabled ? bp_enabled : bp_disabled;
9940       if ((type_wanted != bp_breakpoint
9941            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9942         b->pspace = current_program_space;
9943
9944       install_breakpoint (internal, b, 0);
9945     }
9946   
9947   if (VEC_length (linespec_sals, canonical.sals) > 1)
9948     {
9949       warning (_("Multiple breakpoints were set.\nUse the "
9950                  "\"delete\" command to delete unwanted breakpoints."));
9951       prev_breakpoint_count = prev_bkpt_count;
9952     }
9953
9954   /* That's it.  Discard the cleanups for data inserted into the
9955      breakpoint.  */
9956   discard_cleanups (bkpt_chain);
9957   /* But cleanup everything else.  */
9958   do_cleanups (old_chain);
9959
9960   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9961   update_global_location_list (1);
9962
9963   return 1;
9964 }
9965
9966 /* Set a breakpoint.
9967    ARG is a string describing breakpoint address,
9968    condition, and thread.
9969    FLAG specifies if a breakpoint is hardware on,
9970    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9971    and BP_TEMPFLAG.  */
9972
9973 static void
9974 break_command_1 (char *arg, int flag, int from_tty)
9975 {
9976   int tempflag = flag & BP_TEMPFLAG;
9977   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9978                              ? bp_hardware_breakpoint
9979                              : bp_breakpoint);
9980   struct breakpoint_ops *ops;
9981   const char *arg_cp = arg;
9982
9983   /* Matching breakpoints on probes.  */
9984   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9985     ops = &bkpt_probe_breakpoint_ops;
9986   else
9987     ops = &bkpt_breakpoint_ops;
9988
9989   create_breakpoint (get_current_arch (),
9990                      arg,
9991                      NULL, 0, NULL, 1 /* parse arg */,
9992                      tempflag, type_wanted,
9993                      0 /* Ignore count */,
9994                      pending_break_support,
9995                      ops,
9996                      from_tty,
9997                      1 /* enabled */,
9998                      0 /* internal */,
9999                      0);
10000 }
10001
10002 /* Helper function for break_command_1 and disassemble_command.  */
10003
10004 void
10005 resolve_sal_pc (struct symtab_and_line *sal)
10006 {
10007   CORE_ADDR pc;
10008
10009   if (sal->pc == 0 && sal->symtab != NULL)
10010     {
10011       if (!find_line_pc (sal->symtab, sal->line, &pc))
10012         error (_("No line %d in file \"%s\"."),
10013                sal->line, symtab_to_filename_for_display (sal->symtab));
10014       sal->pc = pc;
10015
10016       /* If this SAL corresponds to a breakpoint inserted using a line
10017          number, then skip the function prologue if necessary.  */
10018       if (sal->explicit_line)
10019         skip_prologue_sal (sal);
10020     }
10021
10022   if (sal->section == 0 && sal->symtab != NULL)
10023     {
10024       struct blockvector *bv;
10025       struct block *b;
10026       struct symbol *sym;
10027
10028       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10029       if (bv != NULL)
10030         {
10031           sym = block_linkage_function (b);
10032           if (sym != NULL)
10033             {
10034               fixup_symbol_section (sym, sal->symtab->objfile);
10035               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10036             }
10037           else
10038             {
10039               /* It really is worthwhile to have the section, so we'll
10040                  just have to look harder. This case can be executed
10041                  if we have line numbers but no functions (as can
10042                  happen in assembly source).  */
10043
10044               struct bound_minimal_symbol msym;
10045               struct cleanup *old_chain = save_current_space_and_thread ();
10046
10047               switch_to_program_space_and_thread (sal->pspace);
10048
10049               msym = lookup_minimal_symbol_by_pc (sal->pc);
10050               if (msym.minsym)
10051                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10052
10053               do_cleanups (old_chain);
10054             }
10055         }
10056     }
10057 }
10058
10059 void
10060 break_command (char *arg, int from_tty)
10061 {
10062   break_command_1 (arg, 0, from_tty);
10063 }
10064
10065 void
10066 tbreak_command (char *arg, int from_tty)
10067 {
10068   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10069 }
10070
10071 static void
10072 hbreak_command (char *arg, int from_tty)
10073 {
10074   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10075 }
10076
10077 static void
10078 thbreak_command (char *arg, int from_tty)
10079 {
10080   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10081 }
10082
10083 static void
10084 stop_command (char *arg, int from_tty)
10085 {
10086   printf_filtered (_("Specify the type of breakpoint to set.\n\
10087 Usage: stop in <function | address>\n\
10088        stop at <line>\n"));
10089 }
10090
10091 static void
10092 stopin_command (char *arg, int from_tty)
10093 {
10094   int badInput = 0;
10095
10096   if (arg == (char *) NULL)
10097     badInput = 1;
10098   else if (*arg != '*')
10099     {
10100       char *argptr = arg;
10101       int hasColon = 0;
10102
10103       /* Look for a ':'.  If this is a line number specification, then
10104          say it is bad, otherwise, it should be an address or
10105          function/method name.  */
10106       while (*argptr && !hasColon)
10107         {
10108           hasColon = (*argptr == ':');
10109           argptr++;
10110         }
10111
10112       if (hasColon)
10113         badInput = (*argptr != ':');    /* Not a class::method */
10114       else
10115         badInput = isdigit (*arg);      /* a simple line number */
10116     }
10117
10118   if (badInput)
10119     printf_filtered (_("Usage: stop in <function | address>\n"));
10120   else
10121     break_command_1 (arg, 0, from_tty);
10122 }
10123
10124 static void
10125 stopat_command (char *arg, int from_tty)
10126 {
10127   int badInput = 0;
10128
10129   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10130     badInput = 1;
10131   else
10132     {
10133       char *argptr = arg;
10134       int hasColon = 0;
10135
10136       /* Look for a ':'.  If there is a '::' then get out, otherwise
10137          it is probably a line number.  */
10138       while (*argptr && !hasColon)
10139         {
10140           hasColon = (*argptr == ':');
10141           argptr++;
10142         }
10143
10144       if (hasColon)
10145         badInput = (*argptr == ':');    /* we have class::method */
10146       else
10147         badInput = !isdigit (*arg);     /* not a line number */
10148     }
10149
10150   if (badInput)
10151     printf_filtered (_("Usage: stop at <line>\n"));
10152   else
10153     break_command_1 (arg, 0, from_tty);
10154 }
10155
10156 /* The dynamic printf command is mostly like a regular breakpoint, but
10157    with a prewired command list consisting of a single output command,
10158    built from extra arguments supplied on the dprintf command
10159    line.  */
10160
10161 static void
10162 dprintf_command (char *arg, int from_tty)
10163 {
10164   create_breakpoint (get_current_arch (),
10165                      arg,
10166                      NULL, 0, NULL, 1 /* parse arg */,
10167                      0, bp_dprintf,
10168                      0 /* Ignore count */,
10169                      pending_break_support,
10170                      &dprintf_breakpoint_ops,
10171                      from_tty,
10172                      1 /* enabled */,
10173                      0 /* internal */,
10174                      0);
10175 }
10176
10177 static void
10178 agent_printf_command (char *arg, int from_tty)
10179 {
10180   error (_("May only run agent-printf on the target"));
10181 }
10182
10183 /* Implement the "breakpoint_hit" breakpoint_ops method for
10184    ranged breakpoints.  */
10185
10186 static int
10187 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10188                                   struct address_space *aspace,
10189                                   CORE_ADDR bp_addr,
10190                                   const struct target_waitstatus *ws)
10191 {
10192   if (ws->kind != TARGET_WAITKIND_STOPPED
10193       || ws->value.sig != GDB_SIGNAL_TRAP)
10194     return 0;
10195
10196   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10197                                          bl->length, aspace, bp_addr);
10198 }
10199
10200 /* Implement the "resources_needed" breakpoint_ops method for
10201    ranged breakpoints.  */
10202
10203 static int
10204 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10205 {
10206   return target_ranged_break_num_registers ();
10207 }
10208
10209 /* Implement the "print_it" breakpoint_ops method for
10210    ranged breakpoints.  */
10211
10212 static enum print_stop_action
10213 print_it_ranged_breakpoint (bpstat bs)
10214 {
10215   struct breakpoint *b = bs->breakpoint_at;
10216   struct bp_location *bl = b->loc;
10217   struct ui_out *uiout = current_uiout;
10218
10219   gdb_assert (b->type == bp_hardware_breakpoint);
10220
10221   /* Ranged breakpoints have only one location.  */
10222   gdb_assert (bl && bl->next == NULL);
10223
10224   annotate_breakpoint (b->number);
10225   if (b->disposition == disp_del)
10226     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10227   else
10228     ui_out_text (uiout, "\nRanged breakpoint ");
10229   if (ui_out_is_mi_like_p (uiout))
10230     {
10231       ui_out_field_string (uiout, "reason",
10232                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10233       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10234     }
10235   ui_out_field_int (uiout, "bkptno", b->number);
10236   ui_out_text (uiout, ", ");
10237
10238   return PRINT_SRC_AND_LOC;
10239 }
10240
10241 /* Implement the "print_one" breakpoint_ops method for
10242    ranged breakpoints.  */
10243
10244 static void
10245 print_one_ranged_breakpoint (struct breakpoint *b,
10246                              struct bp_location **last_loc)
10247 {
10248   struct bp_location *bl = b->loc;
10249   struct value_print_options opts;
10250   struct ui_out *uiout = current_uiout;
10251
10252   /* Ranged breakpoints have only one location.  */
10253   gdb_assert (bl && bl->next == NULL);
10254
10255   get_user_print_options (&opts);
10256
10257   if (opts.addressprint)
10258     /* We don't print the address range here, it will be printed later
10259        by print_one_detail_ranged_breakpoint.  */
10260     ui_out_field_skip (uiout, "addr");
10261   annotate_field (5);
10262   print_breakpoint_location (b, bl);
10263   *last_loc = bl;
10264 }
10265
10266 /* Implement the "print_one_detail" breakpoint_ops method for
10267    ranged breakpoints.  */
10268
10269 static void
10270 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10271                                     struct ui_out *uiout)
10272 {
10273   CORE_ADDR address_start, address_end;
10274   struct bp_location *bl = b->loc;
10275   struct ui_file *stb = mem_fileopen ();
10276   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10277
10278   gdb_assert (bl);
10279
10280   address_start = bl->address;
10281   address_end = address_start + bl->length - 1;
10282
10283   ui_out_text (uiout, "\taddress range: ");
10284   fprintf_unfiltered (stb, "[%s, %s]",
10285                       print_core_address (bl->gdbarch, address_start),
10286                       print_core_address (bl->gdbarch, address_end));
10287   ui_out_field_stream (uiout, "addr", stb);
10288   ui_out_text (uiout, "\n");
10289
10290   do_cleanups (cleanup);
10291 }
10292
10293 /* Implement the "print_mention" breakpoint_ops method for
10294    ranged breakpoints.  */
10295
10296 static void
10297 print_mention_ranged_breakpoint (struct breakpoint *b)
10298 {
10299   struct bp_location *bl = b->loc;
10300   struct ui_out *uiout = current_uiout;
10301
10302   gdb_assert (bl);
10303   gdb_assert (b->type == bp_hardware_breakpoint);
10304
10305   if (ui_out_is_mi_like_p (uiout))
10306     return;
10307
10308   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10309                    b->number, paddress (bl->gdbarch, bl->address),
10310                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10311 }
10312
10313 /* Implement the "print_recreate" breakpoint_ops method for
10314    ranged breakpoints.  */
10315
10316 static void
10317 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10318 {
10319   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10320                       b->addr_string_range_end);
10321   print_recreate_thread (b, fp);
10322 }
10323
10324 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10325
10326 static struct breakpoint_ops ranged_breakpoint_ops;
10327
10328 /* Find the address where the end of the breakpoint range should be
10329    placed, given the SAL of the end of the range.  This is so that if
10330    the user provides a line number, the end of the range is set to the
10331    last instruction of the given line.  */
10332
10333 static CORE_ADDR
10334 find_breakpoint_range_end (struct symtab_and_line sal)
10335 {
10336   CORE_ADDR end;
10337
10338   /* If the user provided a PC value, use it.  Otherwise,
10339      find the address of the end of the given location.  */
10340   if (sal.explicit_pc)
10341     end = sal.pc;
10342   else
10343     {
10344       int ret;
10345       CORE_ADDR start;
10346
10347       ret = find_line_pc_range (sal, &start, &end);
10348       if (!ret)
10349         error (_("Could not find location of the end of the range."));
10350
10351       /* find_line_pc_range returns the start of the next line.  */
10352       end--;
10353     }
10354
10355   return end;
10356 }
10357
10358 /* Implement the "break-range" CLI command.  */
10359
10360 static void
10361 break_range_command (char *arg, int from_tty)
10362 {
10363   char *arg_start, *addr_string_start, *addr_string_end;
10364   struct linespec_result canonical_start, canonical_end;
10365   int bp_count, can_use_bp, length;
10366   CORE_ADDR end;
10367   struct breakpoint *b;
10368   struct symtab_and_line sal_start, sal_end;
10369   struct cleanup *cleanup_bkpt;
10370   struct linespec_sals *lsal_start, *lsal_end;
10371
10372   /* We don't support software ranged breakpoints.  */
10373   if (target_ranged_break_num_registers () < 0)
10374     error (_("This target does not support hardware ranged breakpoints."));
10375
10376   bp_count = hw_breakpoint_used_count ();
10377   bp_count += target_ranged_break_num_registers ();
10378   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10379                                                    bp_count, 0);
10380   if (can_use_bp < 0)
10381     error (_("Hardware breakpoints used exceeds limit."));
10382
10383   arg = skip_spaces (arg);
10384   if (arg == NULL || arg[0] == '\0')
10385     error(_("No address range specified."));
10386
10387   init_linespec_result (&canonical_start);
10388
10389   arg_start = arg;
10390   parse_breakpoint_sals (&arg, &canonical_start);
10391
10392   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10393
10394   if (arg[0] != ',')
10395     error (_("Too few arguments."));
10396   else if (VEC_empty (linespec_sals, canonical_start.sals))
10397     error (_("Could not find location of the beginning of the range."));
10398
10399   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10400
10401   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10402       || lsal_start->sals.nelts != 1)
10403     error (_("Cannot create a ranged breakpoint with multiple locations."));
10404
10405   sal_start = lsal_start->sals.sals[0];
10406   addr_string_start = savestring (arg_start, arg - arg_start);
10407   make_cleanup (xfree, addr_string_start);
10408
10409   arg++;        /* Skip the comma.  */
10410   arg = skip_spaces (arg);
10411
10412   /* Parse the end location.  */
10413
10414   init_linespec_result (&canonical_end);
10415   arg_start = arg;
10416
10417   /* We call decode_line_full directly here instead of using
10418      parse_breakpoint_sals because we need to specify the start location's
10419      symtab and line as the default symtab and line for the end of the
10420      range.  This makes it possible to have ranges like "foo.c:27, +14",
10421      where +14 means 14 lines from the start location.  */
10422   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10423                     sal_start.symtab, sal_start.line,
10424                     &canonical_end, NULL, NULL);
10425
10426   make_cleanup_destroy_linespec_result (&canonical_end);
10427
10428   if (VEC_empty (linespec_sals, canonical_end.sals))
10429     error (_("Could not find location of the end of the range."));
10430
10431   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10432   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10433       || lsal_end->sals.nelts != 1)
10434     error (_("Cannot create a ranged breakpoint with multiple locations."));
10435
10436   sal_end = lsal_end->sals.sals[0];
10437   addr_string_end = savestring (arg_start, arg - arg_start);
10438   make_cleanup (xfree, addr_string_end);
10439
10440   end = find_breakpoint_range_end (sal_end);
10441   if (sal_start.pc > end)
10442     error (_("Invalid address range, end precedes start."));
10443
10444   length = end - sal_start.pc + 1;
10445   if (length < 0)
10446     /* Length overflowed.  */
10447     error (_("Address range too large."));
10448   else if (length == 1)
10449     {
10450       /* This range is simple enough to be handled by
10451          the `hbreak' command.  */
10452       hbreak_command (addr_string_start, 1);
10453
10454       do_cleanups (cleanup_bkpt);
10455
10456       return;
10457     }
10458
10459   /* Now set up the breakpoint.  */
10460   b = set_raw_breakpoint (get_current_arch (), sal_start,
10461                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10462   set_breakpoint_count (breakpoint_count + 1);
10463   b->number = breakpoint_count;
10464   b->disposition = disp_donttouch;
10465   b->addr_string = xstrdup (addr_string_start);
10466   b->addr_string_range_end = xstrdup (addr_string_end);
10467   b->loc->length = length;
10468
10469   do_cleanups (cleanup_bkpt);
10470
10471   mention (b);
10472   observer_notify_breakpoint_created (b);
10473   update_global_location_list (1);
10474 }
10475
10476 /*  Return non-zero if EXP is verified as constant.  Returned zero
10477     means EXP is variable.  Also the constant detection may fail for
10478     some constant expressions and in such case still falsely return
10479     zero.  */
10480
10481 static int
10482 watchpoint_exp_is_const (const struct expression *exp)
10483 {
10484   int i = exp->nelts;
10485
10486   while (i > 0)
10487     {
10488       int oplenp, argsp;
10489
10490       /* We are only interested in the descriptor of each element.  */
10491       operator_length (exp, i, &oplenp, &argsp);
10492       i -= oplenp;
10493
10494       switch (exp->elts[i].opcode)
10495         {
10496         case BINOP_ADD:
10497         case BINOP_SUB:
10498         case BINOP_MUL:
10499         case BINOP_DIV:
10500         case BINOP_REM:
10501         case BINOP_MOD:
10502         case BINOP_LSH:
10503         case BINOP_RSH:
10504         case BINOP_LOGICAL_AND:
10505         case BINOP_LOGICAL_OR:
10506         case BINOP_BITWISE_AND:
10507         case BINOP_BITWISE_IOR:
10508         case BINOP_BITWISE_XOR:
10509         case BINOP_EQUAL:
10510         case BINOP_NOTEQUAL:
10511         case BINOP_LESS:
10512         case BINOP_GTR:
10513         case BINOP_LEQ:
10514         case BINOP_GEQ:
10515         case BINOP_REPEAT:
10516         case BINOP_COMMA:
10517         case BINOP_EXP:
10518         case BINOP_MIN:
10519         case BINOP_MAX:
10520         case BINOP_INTDIV:
10521         case BINOP_CONCAT:
10522         case BINOP_IN:
10523         case BINOP_RANGE:
10524         case TERNOP_COND:
10525         case TERNOP_SLICE:
10526
10527         case OP_LONG:
10528         case OP_DOUBLE:
10529         case OP_DECFLOAT:
10530         case OP_LAST:
10531         case OP_COMPLEX:
10532         case OP_STRING:
10533         case OP_ARRAY:
10534         case OP_TYPE:
10535         case OP_TYPEOF:
10536         case OP_DECLTYPE:
10537         case OP_TYPEID:
10538         case OP_NAME:
10539         case OP_OBJC_NSSTRING:
10540
10541         case UNOP_NEG:
10542         case UNOP_LOGICAL_NOT:
10543         case UNOP_COMPLEMENT:
10544         case UNOP_ADDR:
10545         case UNOP_HIGH:
10546         case UNOP_CAST:
10547
10548         case UNOP_CAST_TYPE:
10549         case UNOP_REINTERPRET_CAST:
10550         case UNOP_DYNAMIC_CAST:
10551           /* Unary, binary and ternary operators: We have to check
10552              their operands.  If they are constant, then so is the
10553              result of that operation.  For instance, if A and B are
10554              determined to be constants, then so is "A + B".
10555
10556              UNOP_IND is one exception to the rule above, because the
10557              value of *ADDR is not necessarily a constant, even when
10558              ADDR is.  */
10559           break;
10560
10561         case OP_VAR_VALUE:
10562           /* Check whether the associated symbol is a constant.
10563
10564              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10565              possible that a buggy compiler could mark a variable as
10566              constant even when it is not, and TYPE_CONST would return
10567              true in this case, while SYMBOL_CLASS wouldn't.
10568
10569              We also have to check for function symbols because they
10570              are always constant.  */
10571           {
10572             struct symbol *s = exp->elts[i + 2].symbol;
10573
10574             if (SYMBOL_CLASS (s) != LOC_BLOCK
10575                 && SYMBOL_CLASS (s) != LOC_CONST
10576                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10577               return 0;
10578             break;
10579           }
10580
10581         /* The default action is to return 0 because we are using
10582            the optimistic approach here: If we don't know something,
10583            then it is not a constant.  */
10584         default:
10585           return 0;
10586         }
10587     }
10588
10589   return 1;
10590 }
10591
10592 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10593
10594 static void
10595 dtor_watchpoint (struct breakpoint *self)
10596 {
10597   struct watchpoint *w = (struct watchpoint *) self;
10598
10599   xfree (w->cond_exp);
10600   xfree (w->exp);
10601   xfree (w->exp_string);
10602   xfree (w->exp_string_reparse);
10603   value_free (w->val);
10604
10605   base_breakpoint_ops.dtor (self);
10606 }
10607
10608 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10609
10610 static void
10611 re_set_watchpoint (struct breakpoint *b)
10612 {
10613   struct watchpoint *w = (struct watchpoint *) b;
10614
10615   /* Watchpoint can be either on expression using entirely global
10616      variables, or it can be on local variables.
10617
10618      Watchpoints of the first kind are never auto-deleted, and even
10619      persist across program restarts.  Since they can use variables
10620      from shared libraries, we need to reparse expression as libraries
10621      are loaded and unloaded.
10622
10623      Watchpoints on local variables can also change meaning as result
10624      of solib event.  For example, if a watchpoint uses both a local
10625      and a global variables in expression, it's a local watchpoint,
10626      but unloading of a shared library will make the expression
10627      invalid.  This is not a very common use case, but we still
10628      re-evaluate expression, to avoid surprises to the user.
10629
10630      Note that for local watchpoints, we re-evaluate it only if
10631      watchpoints frame id is still valid.  If it's not, it means the
10632      watchpoint is out of scope and will be deleted soon.  In fact,
10633      I'm not sure we'll ever be called in this case.
10634
10635      If a local watchpoint's frame id is still valid, then
10636      w->exp_valid_block is likewise valid, and we can safely use it.
10637
10638      Don't do anything about disabled watchpoints, since they will be
10639      reevaluated again when enabled.  */
10640   update_watchpoint (w, 1 /* reparse */);
10641 }
10642
10643 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10644
10645 static int
10646 insert_watchpoint (struct bp_location *bl)
10647 {
10648   struct watchpoint *w = (struct watchpoint *) bl->owner;
10649   int length = w->exact ? 1 : bl->length;
10650
10651   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10652                                    w->cond_exp);
10653 }
10654
10655 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10656
10657 static int
10658 remove_watchpoint (struct bp_location *bl)
10659 {
10660   struct watchpoint *w = (struct watchpoint *) bl->owner;
10661   int length = w->exact ? 1 : bl->length;
10662
10663   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10664                                    w->cond_exp);
10665 }
10666
10667 static int
10668 breakpoint_hit_watchpoint (const struct bp_location *bl,
10669                            struct address_space *aspace, CORE_ADDR bp_addr,
10670                            const struct target_waitstatus *ws)
10671 {
10672   struct breakpoint *b = bl->owner;
10673   struct watchpoint *w = (struct watchpoint *) b;
10674
10675   /* Continuable hardware watchpoints are treated as non-existent if the
10676      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10677      some data address).  Otherwise gdb won't stop on a break instruction
10678      in the code (not from a breakpoint) when a hardware watchpoint has
10679      been defined.  Also skip watchpoints which we know did not trigger
10680      (did not match the data address).  */
10681   if (is_hardware_watchpoint (b)
10682       && w->watchpoint_triggered == watch_triggered_no)
10683     return 0;
10684
10685   return 1;
10686 }
10687
10688 static void
10689 check_status_watchpoint (bpstat bs)
10690 {
10691   gdb_assert (is_watchpoint (bs->breakpoint_at));
10692
10693   bpstat_check_watchpoint (bs);
10694 }
10695
10696 /* Implement the "resources_needed" breakpoint_ops method for
10697    hardware watchpoints.  */
10698
10699 static int
10700 resources_needed_watchpoint (const struct bp_location *bl)
10701 {
10702   struct watchpoint *w = (struct watchpoint *) bl->owner;
10703   int length = w->exact? 1 : bl->length;
10704
10705   return target_region_ok_for_hw_watchpoint (bl->address, length);
10706 }
10707
10708 /* Implement the "works_in_software_mode" breakpoint_ops method for
10709    hardware watchpoints.  */
10710
10711 static int
10712 works_in_software_mode_watchpoint (const struct breakpoint *b)
10713 {
10714   /* Read and access watchpoints only work with hardware support.  */
10715   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10716 }
10717
10718 static enum print_stop_action
10719 print_it_watchpoint (bpstat bs)
10720 {
10721   struct cleanup *old_chain;
10722   struct breakpoint *b;
10723   struct ui_file *stb;
10724   enum print_stop_action result;
10725   struct watchpoint *w;
10726   struct ui_out *uiout = current_uiout;
10727
10728   gdb_assert (bs->bp_location_at != NULL);
10729
10730   b = bs->breakpoint_at;
10731   w = (struct watchpoint *) b;
10732
10733   stb = mem_fileopen ();
10734   old_chain = make_cleanup_ui_file_delete (stb);
10735
10736   switch (b->type)
10737     {
10738     case bp_watchpoint:
10739     case bp_hardware_watchpoint:
10740       annotate_watchpoint (b->number);
10741       if (ui_out_is_mi_like_p (uiout))
10742         ui_out_field_string
10743           (uiout, "reason",
10744            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10745       mention (b);
10746       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10747       ui_out_text (uiout, "\nOld value = ");
10748       watchpoint_value_print (bs->old_val, stb);
10749       ui_out_field_stream (uiout, "old", stb);
10750       ui_out_text (uiout, "\nNew value = ");
10751       watchpoint_value_print (w->val, stb);
10752       ui_out_field_stream (uiout, "new", stb);
10753       ui_out_text (uiout, "\n");
10754       /* More than one watchpoint may have been triggered.  */
10755       result = PRINT_UNKNOWN;
10756       break;
10757
10758     case bp_read_watchpoint:
10759       if (ui_out_is_mi_like_p (uiout))
10760         ui_out_field_string
10761           (uiout, "reason",
10762            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10763       mention (b);
10764       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10765       ui_out_text (uiout, "\nValue = ");
10766       watchpoint_value_print (w->val, stb);
10767       ui_out_field_stream (uiout, "value", stb);
10768       ui_out_text (uiout, "\n");
10769       result = PRINT_UNKNOWN;
10770       break;
10771
10772     case bp_access_watchpoint:
10773       if (bs->old_val != NULL)
10774         {
10775           annotate_watchpoint (b->number);
10776           if (ui_out_is_mi_like_p (uiout))
10777             ui_out_field_string
10778               (uiout, "reason",
10779                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10780           mention (b);
10781           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10782           ui_out_text (uiout, "\nOld value = ");
10783           watchpoint_value_print (bs->old_val, stb);
10784           ui_out_field_stream (uiout, "old", stb);
10785           ui_out_text (uiout, "\nNew value = ");
10786         }
10787       else
10788         {
10789           mention (b);
10790           if (ui_out_is_mi_like_p (uiout))
10791             ui_out_field_string
10792               (uiout, "reason",
10793                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10794           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10795           ui_out_text (uiout, "\nValue = ");
10796         }
10797       watchpoint_value_print (w->val, stb);
10798       ui_out_field_stream (uiout, "new", stb);
10799       ui_out_text (uiout, "\n");
10800       result = PRINT_UNKNOWN;
10801       break;
10802     default:
10803       result = PRINT_UNKNOWN;
10804     }
10805
10806   do_cleanups (old_chain);
10807   return result;
10808 }
10809
10810 /* Implement the "print_mention" breakpoint_ops method for hardware
10811    watchpoints.  */
10812
10813 static void
10814 print_mention_watchpoint (struct breakpoint *b)
10815 {
10816   struct cleanup *ui_out_chain;
10817   struct watchpoint *w = (struct watchpoint *) b;
10818   struct ui_out *uiout = current_uiout;
10819
10820   switch (b->type)
10821     {
10822     case bp_watchpoint:
10823       ui_out_text (uiout, "Watchpoint ");
10824       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10825       break;
10826     case bp_hardware_watchpoint:
10827       ui_out_text (uiout, "Hardware watchpoint ");
10828       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10829       break;
10830     case bp_read_watchpoint:
10831       ui_out_text (uiout, "Hardware read watchpoint ");
10832       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10833       break;
10834     case bp_access_watchpoint:
10835       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10836       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10837       break;
10838     default:
10839       internal_error (__FILE__, __LINE__,
10840                       _("Invalid hardware watchpoint type."));
10841     }
10842
10843   ui_out_field_int (uiout, "number", b->number);
10844   ui_out_text (uiout, ": ");
10845   ui_out_field_string (uiout, "exp", w->exp_string);
10846   do_cleanups (ui_out_chain);
10847 }
10848
10849 /* Implement the "print_recreate" breakpoint_ops method for
10850    watchpoints.  */
10851
10852 static void
10853 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10854 {
10855   struct watchpoint *w = (struct watchpoint *) b;
10856
10857   switch (b->type)
10858     {
10859     case bp_watchpoint:
10860     case bp_hardware_watchpoint:
10861       fprintf_unfiltered (fp, "watch");
10862       break;
10863     case bp_read_watchpoint:
10864       fprintf_unfiltered (fp, "rwatch");
10865       break;
10866     case bp_access_watchpoint:
10867       fprintf_unfiltered (fp, "awatch");
10868       break;
10869     default:
10870       internal_error (__FILE__, __LINE__,
10871                       _("Invalid watchpoint type."));
10872     }
10873
10874   fprintf_unfiltered (fp, " %s", w->exp_string);
10875   print_recreate_thread (b, fp);
10876 }
10877
10878 /* Implement the "explains_signal" breakpoint_ops method for
10879    watchpoints.  */
10880
10881 static int
10882 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
10883 {
10884   /* A software watchpoint cannot cause a signal other than
10885      GDB_SIGNAL_TRAP.  */
10886   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
10887     return 0;
10888
10889   return 1;
10890 }
10891
10892 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10893
10894 static struct breakpoint_ops watchpoint_breakpoint_ops;
10895
10896 /* Implement the "insert" breakpoint_ops method for
10897    masked hardware watchpoints.  */
10898
10899 static int
10900 insert_masked_watchpoint (struct bp_location *bl)
10901 {
10902   struct watchpoint *w = (struct watchpoint *) bl->owner;
10903
10904   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10905                                         bl->watchpoint_type);
10906 }
10907
10908 /* Implement the "remove" breakpoint_ops method for
10909    masked hardware watchpoints.  */
10910
10911 static int
10912 remove_masked_watchpoint (struct bp_location *bl)
10913 {
10914   struct watchpoint *w = (struct watchpoint *) bl->owner;
10915
10916   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10917                                         bl->watchpoint_type);
10918 }
10919
10920 /* Implement the "resources_needed" breakpoint_ops method for
10921    masked hardware watchpoints.  */
10922
10923 static int
10924 resources_needed_masked_watchpoint (const struct bp_location *bl)
10925 {
10926   struct watchpoint *w = (struct watchpoint *) bl->owner;
10927
10928   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10929 }
10930
10931 /* Implement the "works_in_software_mode" breakpoint_ops method for
10932    masked hardware watchpoints.  */
10933
10934 static int
10935 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10936 {
10937   return 0;
10938 }
10939
10940 /* Implement the "print_it" breakpoint_ops method for
10941    masked hardware watchpoints.  */
10942
10943 static enum print_stop_action
10944 print_it_masked_watchpoint (bpstat bs)
10945 {
10946   struct breakpoint *b = bs->breakpoint_at;
10947   struct ui_out *uiout = current_uiout;
10948
10949   /* Masked watchpoints have only one location.  */
10950   gdb_assert (b->loc && b->loc->next == NULL);
10951
10952   switch (b->type)
10953     {
10954     case bp_hardware_watchpoint:
10955       annotate_watchpoint (b->number);
10956       if (ui_out_is_mi_like_p (uiout))
10957         ui_out_field_string
10958           (uiout, "reason",
10959            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10960       break;
10961
10962     case bp_read_watchpoint:
10963       if (ui_out_is_mi_like_p (uiout))
10964         ui_out_field_string
10965           (uiout, "reason",
10966            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10967       break;
10968
10969     case bp_access_watchpoint:
10970       if (ui_out_is_mi_like_p (uiout))
10971         ui_out_field_string
10972           (uiout, "reason",
10973            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10974       break;
10975     default:
10976       internal_error (__FILE__, __LINE__,
10977                       _("Invalid hardware watchpoint type."));
10978     }
10979
10980   mention (b);
10981   ui_out_text (uiout, _("\n\
10982 Check the underlying instruction at PC for the memory\n\
10983 address and value which triggered this watchpoint.\n"));
10984   ui_out_text (uiout, "\n");
10985
10986   /* More than one watchpoint may have been triggered.  */
10987   return PRINT_UNKNOWN;
10988 }
10989
10990 /* Implement the "print_one_detail" breakpoint_ops method for
10991    masked hardware watchpoints.  */
10992
10993 static void
10994 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10995                                     struct ui_out *uiout)
10996 {
10997   struct watchpoint *w = (struct watchpoint *) b;
10998
10999   /* Masked watchpoints have only one location.  */
11000   gdb_assert (b->loc && b->loc->next == NULL);
11001
11002   ui_out_text (uiout, "\tmask ");
11003   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11004   ui_out_text (uiout, "\n");
11005 }
11006
11007 /* Implement the "print_mention" breakpoint_ops method for
11008    masked hardware watchpoints.  */
11009
11010 static void
11011 print_mention_masked_watchpoint (struct breakpoint *b)
11012 {
11013   struct watchpoint *w = (struct watchpoint *) b;
11014   struct ui_out *uiout = current_uiout;
11015   struct cleanup *ui_out_chain;
11016
11017   switch (b->type)
11018     {
11019     case bp_hardware_watchpoint:
11020       ui_out_text (uiout, "Masked hardware watchpoint ");
11021       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11022       break;
11023     case bp_read_watchpoint:
11024       ui_out_text (uiout, "Masked hardware read watchpoint ");
11025       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11026       break;
11027     case bp_access_watchpoint:
11028       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11029       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11030       break;
11031     default:
11032       internal_error (__FILE__, __LINE__,
11033                       _("Invalid hardware watchpoint type."));
11034     }
11035
11036   ui_out_field_int (uiout, "number", b->number);
11037   ui_out_text (uiout, ": ");
11038   ui_out_field_string (uiout, "exp", w->exp_string);
11039   do_cleanups (ui_out_chain);
11040 }
11041
11042 /* Implement the "print_recreate" breakpoint_ops method for
11043    masked hardware watchpoints.  */
11044
11045 static void
11046 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11047 {
11048   struct watchpoint *w = (struct watchpoint *) b;
11049   char tmp[40];
11050
11051   switch (b->type)
11052     {
11053     case bp_hardware_watchpoint:
11054       fprintf_unfiltered (fp, "watch");
11055       break;
11056     case bp_read_watchpoint:
11057       fprintf_unfiltered (fp, "rwatch");
11058       break;
11059     case bp_access_watchpoint:
11060       fprintf_unfiltered (fp, "awatch");
11061       break;
11062     default:
11063       internal_error (__FILE__, __LINE__,
11064                       _("Invalid hardware watchpoint type."));
11065     }
11066
11067   sprintf_vma (tmp, w->hw_wp_mask);
11068   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11069   print_recreate_thread (b, fp);
11070 }
11071
11072 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11073
11074 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11075
11076 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11077
11078 static int
11079 is_masked_watchpoint (const struct breakpoint *b)
11080 {
11081   return b->ops == &masked_watchpoint_breakpoint_ops;
11082 }
11083
11084 /* accessflag:  hw_write:  watch write, 
11085                 hw_read:   watch read, 
11086                 hw_access: watch access (read or write) */
11087 static void
11088 watch_command_1 (const char *arg, int accessflag, int from_tty,
11089                  int just_location, int internal)
11090 {
11091   volatile struct gdb_exception e;
11092   struct breakpoint *b, *scope_breakpoint = NULL;
11093   struct expression *exp;
11094   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11095   struct value *val, *mark, *result;
11096   struct frame_info *frame;
11097   const char *exp_start = NULL;
11098   const char *exp_end = NULL;
11099   const char *tok, *end_tok;
11100   int toklen = -1;
11101   const char *cond_start = NULL;
11102   const char *cond_end = NULL;
11103   enum bptype bp_type;
11104   int thread = -1;
11105   int pc = 0;
11106   /* Flag to indicate whether we are going to use masks for
11107      the hardware watchpoint.  */
11108   int use_mask = 0;
11109   CORE_ADDR mask = 0;
11110   struct watchpoint *w;
11111   char *expression;
11112   struct cleanup *back_to;
11113
11114   /* Make sure that we actually have parameters to parse.  */
11115   if (arg != NULL && arg[0] != '\0')
11116     {
11117       const char *value_start;
11118
11119       exp_end = arg + strlen (arg);
11120
11121       /* Look for "parameter value" pairs at the end
11122          of the arguments string.  */
11123       for (tok = exp_end - 1; tok > arg; tok--)
11124         {
11125           /* Skip whitespace at the end of the argument list.  */
11126           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11127             tok--;
11128
11129           /* Find the beginning of the last token.
11130              This is the value of the parameter.  */
11131           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11132             tok--;
11133           value_start = tok + 1;
11134
11135           /* Skip whitespace.  */
11136           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11137             tok--;
11138
11139           end_tok = tok;
11140
11141           /* Find the beginning of the second to last token.
11142              This is the parameter itself.  */
11143           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11144             tok--;
11145           tok++;
11146           toklen = end_tok - tok + 1;
11147
11148           if (toklen == 6 && !strncmp (tok, "thread", 6))
11149             {
11150               /* At this point we've found a "thread" token, which means
11151                  the user is trying to set a watchpoint that triggers
11152                  only in a specific thread.  */
11153               char *endp;
11154
11155               if (thread != -1)
11156                 error(_("You can specify only one thread."));
11157
11158               /* Extract the thread ID from the next token.  */
11159               thread = strtol (value_start, &endp, 0);
11160
11161               /* Check if the user provided a valid numeric value for the
11162                  thread ID.  */
11163               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11164                 error (_("Invalid thread ID specification %s."), value_start);
11165
11166               /* Check if the thread actually exists.  */
11167               if (!valid_thread_id (thread))
11168                 invalid_thread_id_error (thread);
11169             }
11170           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11171             {
11172               /* We've found a "mask" token, which means the user wants to
11173                  create a hardware watchpoint that is going to have the mask
11174                  facility.  */
11175               struct value *mask_value, *mark;
11176
11177               if (use_mask)
11178                 error(_("You can specify only one mask."));
11179
11180               use_mask = just_location = 1;
11181
11182               mark = value_mark ();
11183               mask_value = parse_to_comma_and_eval (&value_start);
11184               mask = value_as_address (mask_value);
11185               value_free_to_mark (mark);
11186             }
11187           else
11188             /* We didn't recognize what we found.  We should stop here.  */
11189             break;
11190
11191           /* Truncate the string and get rid of the "parameter value" pair before
11192              the arguments string is parsed by the parse_exp_1 function.  */
11193           exp_end = tok;
11194         }
11195     }
11196   else
11197     exp_end = arg;
11198
11199   /* Parse the rest of the arguments.  From here on out, everything
11200      is in terms of a newly allocated string instead of the original
11201      ARG.  */
11202   innermost_block = NULL;
11203   expression = savestring (arg, exp_end - arg);
11204   back_to = make_cleanup (xfree, expression);
11205   exp_start = arg = expression;
11206   exp = parse_exp_1 (&arg, 0, 0, 0);
11207   exp_end = arg;
11208   /* Remove trailing whitespace from the expression before saving it.
11209      This makes the eventual display of the expression string a bit
11210      prettier.  */
11211   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11212     --exp_end;
11213
11214   /* Checking if the expression is not constant.  */
11215   if (watchpoint_exp_is_const (exp))
11216     {
11217       int len;
11218
11219       len = exp_end - exp_start;
11220       while (len > 0 && isspace (exp_start[len - 1]))
11221         len--;
11222       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11223     }
11224
11225   exp_valid_block = innermost_block;
11226   mark = value_mark ();
11227   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11228
11229   if (just_location)
11230     {
11231       int ret;
11232
11233       exp_valid_block = NULL;
11234       val = value_addr (result);
11235       release_value (val);
11236       value_free_to_mark (mark);
11237
11238       if (use_mask)
11239         {
11240           ret = target_masked_watch_num_registers (value_as_address (val),
11241                                                    mask);
11242           if (ret == -1)
11243             error (_("This target does not support masked watchpoints."));
11244           else if (ret == -2)
11245             error (_("Invalid mask or memory region."));
11246         }
11247     }
11248   else if (val != NULL)
11249     release_value (val);
11250
11251   tok = skip_spaces_const (arg);
11252   end_tok = skip_to_space_const (tok);
11253
11254   toklen = end_tok - tok;
11255   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11256     {
11257       struct expression *cond;
11258
11259       innermost_block = NULL;
11260       tok = cond_start = end_tok + 1;
11261       cond = parse_exp_1 (&tok, 0, 0, 0);
11262
11263       /* The watchpoint expression may not be local, but the condition
11264          may still be.  E.g.: `watch global if local > 0'.  */
11265       cond_exp_valid_block = innermost_block;
11266
11267       xfree (cond);
11268       cond_end = tok;
11269     }
11270   if (*tok)
11271     error (_("Junk at end of command."));
11272
11273   frame = block_innermost_frame (exp_valid_block);
11274
11275   /* If the expression is "local", then set up a "watchpoint scope"
11276      breakpoint at the point where we've left the scope of the watchpoint
11277      expression.  Create the scope breakpoint before the watchpoint, so
11278      that we will encounter it first in bpstat_stop_status.  */
11279   if (exp_valid_block && frame)
11280     {
11281       if (frame_id_p (frame_unwind_caller_id (frame)))
11282         {
11283           scope_breakpoint
11284             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11285                                           frame_unwind_caller_pc (frame),
11286                                           bp_watchpoint_scope,
11287                                           &momentary_breakpoint_ops);
11288
11289           scope_breakpoint->enable_state = bp_enabled;
11290
11291           /* Automatically delete the breakpoint when it hits.  */
11292           scope_breakpoint->disposition = disp_del;
11293
11294           /* Only break in the proper frame (help with recursion).  */
11295           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11296
11297           /* Set the address at which we will stop.  */
11298           scope_breakpoint->loc->gdbarch
11299             = frame_unwind_caller_arch (frame);
11300           scope_breakpoint->loc->requested_address
11301             = frame_unwind_caller_pc (frame);
11302           scope_breakpoint->loc->address
11303             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11304                                          scope_breakpoint->loc->requested_address,
11305                                          scope_breakpoint->type);
11306         }
11307     }
11308
11309   /* Now set up the breakpoint.  We create all watchpoints as hardware
11310      watchpoints here even if hardware watchpoints are turned off, a call
11311      to update_watchpoint later in this function will cause the type to
11312      drop back to bp_watchpoint (software watchpoint) if required.  */
11313
11314   if (accessflag == hw_read)
11315     bp_type = bp_read_watchpoint;
11316   else if (accessflag == hw_access)
11317     bp_type = bp_access_watchpoint;
11318   else
11319     bp_type = bp_hardware_watchpoint;
11320
11321   w = XCNEW (struct watchpoint);
11322   b = &w->base;
11323   if (use_mask)
11324     init_raw_breakpoint_without_location (b, NULL, bp_type,
11325                                           &masked_watchpoint_breakpoint_ops);
11326   else
11327     init_raw_breakpoint_without_location (b, NULL, bp_type,
11328                                           &watchpoint_breakpoint_ops);
11329   b->thread = thread;
11330   b->disposition = disp_donttouch;
11331   b->pspace = current_program_space;
11332   w->exp = exp;
11333   w->exp_valid_block = exp_valid_block;
11334   w->cond_exp_valid_block = cond_exp_valid_block;
11335   if (just_location)
11336     {
11337       struct type *t = value_type (val);
11338       CORE_ADDR addr = value_as_address (val);
11339       char *name;
11340
11341       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11342       name = type_to_string (t);
11343
11344       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11345                                           core_addr_to_string (addr));
11346       xfree (name);
11347
11348       w->exp_string = xstrprintf ("-location %.*s",
11349                                   (int) (exp_end - exp_start), exp_start);
11350
11351       /* The above expression is in C.  */
11352       b->language = language_c;
11353     }
11354   else
11355     w->exp_string = savestring (exp_start, exp_end - exp_start);
11356
11357   if (use_mask)
11358     {
11359       w->hw_wp_mask = mask;
11360     }
11361   else
11362     {
11363       w->val = val;
11364       w->val_valid = 1;
11365     }
11366
11367   if (cond_start)
11368     b->cond_string = savestring (cond_start, cond_end - cond_start);
11369   else
11370     b->cond_string = 0;
11371
11372   if (frame)
11373     {
11374       w->watchpoint_frame = get_frame_id (frame);
11375       w->watchpoint_thread = inferior_ptid;
11376     }
11377   else
11378     {
11379       w->watchpoint_frame = null_frame_id;
11380       w->watchpoint_thread = null_ptid;
11381     }
11382
11383   if (scope_breakpoint != NULL)
11384     {
11385       /* The scope breakpoint is related to the watchpoint.  We will
11386          need to act on them together.  */
11387       b->related_breakpoint = scope_breakpoint;
11388       scope_breakpoint->related_breakpoint = b;
11389     }
11390
11391   if (!just_location)
11392     value_free_to_mark (mark);
11393
11394   TRY_CATCH (e, RETURN_MASK_ALL)
11395     {
11396       /* Finally update the new watchpoint.  This creates the locations
11397          that should be inserted.  */
11398       update_watchpoint (w, 1);
11399     }
11400   if (e.reason < 0)
11401     {
11402       delete_breakpoint (b);
11403       throw_exception (e);
11404     }
11405
11406   install_breakpoint (internal, b, 1);
11407   do_cleanups (back_to);
11408 }
11409
11410 /* Return count of debug registers needed to watch the given expression.
11411    If the watchpoint cannot be handled in hardware return zero.  */
11412
11413 static int
11414 can_use_hardware_watchpoint (struct value *v)
11415 {
11416   int found_memory_cnt = 0;
11417   struct value *head = v;
11418
11419   /* Did the user specifically forbid us to use hardware watchpoints? */
11420   if (!can_use_hw_watchpoints)
11421     return 0;
11422
11423   /* Make sure that the value of the expression depends only upon
11424      memory contents, and values computed from them within GDB.  If we
11425      find any register references or function calls, we can't use a
11426      hardware watchpoint.
11427
11428      The idea here is that evaluating an expression generates a series
11429      of values, one holding the value of every subexpression.  (The
11430      expression a*b+c has five subexpressions: a, b, a*b, c, and
11431      a*b+c.)  GDB's values hold almost enough information to establish
11432      the criteria given above --- they identify memory lvalues,
11433      register lvalues, computed values, etcetera.  So we can evaluate
11434      the expression, and then scan the chain of values that leaves
11435      behind to decide whether we can detect any possible change to the
11436      expression's final value using only hardware watchpoints.
11437
11438      However, I don't think that the values returned by inferior
11439      function calls are special in any way.  So this function may not
11440      notice that an expression involving an inferior function call
11441      can't be watched with hardware watchpoints.  FIXME.  */
11442   for (; v; v = value_next (v))
11443     {
11444       if (VALUE_LVAL (v) == lval_memory)
11445         {
11446           if (v != head && value_lazy (v))
11447             /* A lazy memory lvalue in the chain is one that GDB never
11448                needed to fetch; we either just used its address (e.g.,
11449                `a' in `a.b') or we never needed it at all (e.g., `a'
11450                in `a,b').  This doesn't apply to HEAD; if that is
11451                lazy then it was not readable, but watch it anyway.  */
11452             ;
11453           else
11454             {
11455               /* Ahh, memory we actually used!  Check if we can cover
11456                  it with hardware watchpoints.  */
11457               struct type *vtype = check_typedef (value_type (v));
11458
11459               /* We only watch structs and arrays if user asked for it
11460                  explicitly, never if they just happen to appear in a
11461                  middle of some value chain.  */
11462               if (v == head
11463                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11464                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11465                 {
11466                   CORE_ADDR vaddr = value_address (v);
11467                   int len;
11468                   int num_regs;
11469
11470                   len = (target_exact_watchpoints
11471                          && is_scalar_type_recursive (vtype))?
11472                     1 : TYPE_LENGTH (value_type (v));
11473
11474                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11475                   if (!num_regs)
11476                     return 0;
11477                   else
11478                     found_memory_cnt += num_regs;
11479                 }
11480             }
11481         }
11482       else if (VALUE_LVAL (v) != not_lval
11483                && deprecated_value_modifiable (v) == 0)
11484         return 0;       /* These are values from the history (e.g., $1).  */
11485       else if (VALUE_LVAL (v) == lval_register)
11486         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11487     }
11488
11489   /* The expression itself looks suitable for using a hardware
11490      watchpoint, but give the target machine a chance to reject it.  */
11491   return found_memory_cnt;
11492 }
11493
11494 void
11495 watch_command_wrapper (char *arg, int from_tty, int internal)
11496 {
11497   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11498 }
11499
11500 /* A helper function that looks for the "-location" argument and then
11501    calls watch_command_1.  */
11502
11503 static void
11504 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11505 {
11506   int just_location = 0;
11507
11508   if (arg
11509       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11510           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11511     {
11512       arg = skip_spaces (arg);
11513       just_location = 1;
11514     }
11515
11516   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11517 }
11518
11519 static void
11520 watch_command (char *arg, int from_tty)
11521 {
11522   watch_maybe_just_location (arg, hw_write, from_tty);
11523 }
11524
11525 void
11526 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11527 {
11528   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11529 }
11530
11531 static void
11532 rwatch_command (char *arg, int from_tty)
11533 {
11534   watch_maybe_just_location (arg, hw_read, from_tty);
11535 }
11536
11537 void
11538 awatch_command_wrapper (char *arg, int from_tty, int internal)
11539 {
11540   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11541 }
11542
11543 static void
11544 awatch_command (char *arg, int from_tty)
11545 {
11546   watch_maybe_just_location (arg, hw_access, from_tty);
11547 }
11548 \f
11549
11550 /* Helper routines for the until_command routine in infcmd.c.  Here
11551    because it uses the mechanisms of breakpoints.  */
11552
11553 struct until_break_command_continuation_args
11554 {
11555   struct breakpoint *breakpoint;
11556   struct breakpoint *breakpoint2;
11557   int thread_num;
11558 };
11559
11560 /* This function is called by fetch_inferior_event via the
11561    cmd_continuation pointer, to complete the until command.  It takes
11562    care of cleaning up the temporary breakpoints set up by the until
11563    command.  */
11564 static void
11565 until_break_command_continuation (void *arg, int err)
11566 {
11567   struct until_break_command_continuation_args *a = arg;
11568
11569   delete_breakpoint (a->breakpoint);
11570   if (a->breakpoint2)
11571     delete_breakpoint (a->breakpoint2);
11572   delete_longjmp_breakpoint (a->thread_num);
11573 }
11574
11575 void
11576 until_break_command (char *arg, int from_tty, int anywhere)
11577 {
11578   struct symtabs_and_lines sals;
11579   struct symtab_and_line sal;
11580   struct frame_info *frame;
11581   struct gdbarch *frame_gdbarch;
11582   struct frame_id stack_frame_id;
11583   struct frame_id caller_frame_id;
11584   struct breakpoint *breakpoint;
11585   struct breakpoint *breakpoint2 = NULL;
11586   struct cleanup *old_chain;
11587   int thread;
11588   struct thread_info *tp;
11589
11590   clear_proceed_status ();
11591
11592   /* Set a breakpoint where the user wants it and at return from
11593      this function.  */
11594
11595   if (last_displayed_sal_is_valid ())
11596     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11597                           get_last_displayed_symtab (),
11598                           get_last_displayed_line ());
11599   else
11600     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11601                           (struct symtab *) NULL, 0);
11602
11603   if (sals.nelts != 1)
11604     error (_("Couldn't get information on specified line."));
11605
11606   sal = sals.sals[0];
11607   xfree (sals.sals);    /* malloc'd, so freed.  */
11608
11609   if (*arg)
11610     error (_("Junk at end of arguments."));
11611
11612   resolve_sal_pc (&sal);
11613
11614   tp = inferior_thread ();
11615   thread = tp->num;
11616
11617   old_chain = make_cleanup (null_cleanup, NULL);
11618
11619   /* Note linespec handling above invalidates the frame chain.
11620      Installing a breakpoint also invalidates the frame chain (as it
11621      may need to switch threads), so do any frame handling before
11622      that.  */
11623
11624   frame = get_selected_frame (NULL);
11625   frame_gdbarch = get_frame_arch (frame);
11626   stack_frame_id = get_stack_frame_id (frame);
11627   caller_frame_id = frame_unwind_caller_id (frame);
11628
11629   /* Keep within the current frame, or in frames called by the current
11630      one.  */
11631
11632   if (frame_id_p (caller_frame_id))
11633     {
11634       struct symtab_and_line sal2;
11635
11636       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11637       sal2.pc = frame_unwind_caller_pc (frame);
11638       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11639                                               sal2,
11640                                               caller_frame_id,
11641                                               bp_until);
11642       make_cleanup_delete_breakpoint (breakpoint2);
11643
11644       set_longjmp_breakpoint (tp, caller_frame_id);
11645       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11646     }
11647
11648   /* set_momentary_breakpoint could invalidate FRAME.  */
11649   frame = NULL;
11650
11651   if (anywhere)
11652     /* If the user told us to continue until a specified location,
11653        we don't specify a frame at which we need to stop.  */
11654     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11655                                            null_frame_id, bp_until);
11656   else
11657     /* Otherwise, specify the selected frame, because we want to stop
11658        only at the very same frame.  */
11659     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11660                                            stack_frame_id, bp_until);
11661   make_cleanup_delete_breakpoint (breakpoint);
11662
11663   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11664
11665   /* If we are running asynchronously, and proceed call above has
11666      actually managed to start the target, arrange for breakpoints to
11667      be deleted when the target stops.  Otherwise, we're already
11668      stopped and delete breakpoints via cleanup chain.  */
11669
11670   if (target_can_async_p () && is_running (inferior_ptid))
11671     {
11672       struct until_break_command_continuation_args *args;
11673       args = xmalloc (sizeof (*args));
11674
11675       args->breakpoint = breakpoint;
11676       args->breakpoint2 = breakpoint2;
11677       args->thread_num = thread;
11678
11679       discard_cleanups (old_chain);
11680       add_continuation (inferior_thread (),
11681                         until_break_command_continuation, args,
11682                         xfree);
11683     }
11684   else
11685     do_cleanups (old_chain);
11686 }
11687
11688 /* This function attempts to parse an optional "if <cond>" clause
11689    from the arg string.  If one is not found, it returns NULL.
11690
11691    Else, it returns a pointer to the condition string.  (It does not
11692    attempt to evaluate the string against a particular block.)  And,
11693    it updates arg to point to the first character following the parsed
11694    if clause in the arg string.  */
11695
11696 char *
11697 ep_parse_optional_if_clause (char **arg)
11698 {
11699   char *cond_string;
11700
11701   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11702     return NULL;
11703
11704   /* Skip the "if" keyword.  */
11705   (*arg) += 2;
11706
11707   /* Skip any extra leading whitespace, and record the start of the
11708      condition string.  */
11709   *arg = skip_spaces (*arg);
11710   cond_string = *arg;
11711
11712   /* Assume that the condition occupies the remainder of the arg
11713      string.  */
11714   (*arg) += strlen (cond_string);
11715
11716   return cond_string;
11717 }
11718
11719 /* Commands to deal with catching events, such as signals, exceptions,
11720    process start/exit, etc.  */
11721
11722 typedef enum
11723 {
11724   catch_fork_temporary, catch_vfork_temporary,
11725   catch_fork_permanent, catch_vfork_permanent
11726 }
11727 catch_fork_kind;
11728
11729 static void
11730 catch_fork_command_1 (char *arg, int from_tty, 
11731                       struct cmd_list_element *command)
11732 {
11733   struct gdbarch *gdbarch = get_current_arch ();
11734   char *cond_string = NULL;
11735   catch_fork_kind fork_kind;
11736   int tempflag;
11737
11738   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11739   tempflag = (fork_kind == catch_fork_temporary
11740               || fork_kind == catch_vfork_temporary);
11741
11742   if (!arg)
11743     arg = "";
11744   arg = skip_spaces (arg);
11745
11746   /* The allowed syntax is:
11747      catch [v]fork
11748      catch [v]fork if <cond>
11749
11750      First, check if there's an if clause.  */
11751   cond_string = ep_parse_optional_if_clause (&arg);
11752
11753   if ((*arg != '\0') && !isspace (*arg))
11754     error (_("Junk at end of arguments."));
11755
11756   /* If this target supports it, create a fork or vfork catchpoint
11757      and enable reporting of such events.  */
11758   switch (fork_kind)
11759     {
11760     case catch_fork_temporary:
11761     case catch_fork_permanent:
11762       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11763                                           &catch_fork_breakpoint_ops);
11764       break;
11765     case catch_vfork_temporary:
11766     case catch_vfork_permanent:
11767       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11768                                           &catch_vfork_breakpoint_ops);
11769       break;
11770     default:
11771       error (_("unsupported or unknown fork kind; cannot catch it"));
11772       break;
11773     }
11774 }
11775
11776 static void
11777 catch_exec_command_1 (char *arg, int from_tty, 
11778                       struct cmd_list_element *command)
11779 {
11780   struct exec_catchpoint *c;
11781   struct gdbarch *gdbarch = get_current_arch ();
11782   int tempflag;
11783   char *cond_string = NULL;
11784
11785   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11786
11787   if (!arg)
11788     arg = "";
11789   arg = skip_spaces (arg);
11790
11791   /* The allowed syntax is:
11792      catch exec
11793      catch exec if <cond>
11794
11795      First, check if there's an if clause.  */
11796   cond_string = ep_parse_optional_if_clause (&arg);
11797
11798   if ((*arg != '\0') && !isspace (*arg))
11799     error (_("Junk at end of arguments."));
11800
11801   c = XNEW (struct exec_catchpoint);
11802   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11803                    &catch_exec_breakpoint_ops);
11804   c->exec_pathname = NULL;
11805
11806   install_breakpoint (0, &c->base, 1);
11807 }
11808
11809 void
11810 init_ada_exception_breakpoint (struct breakpoint *b,
11811                                struct gdbarch *gdbarch,
11812                                struct symtab_and_line sal,
11813                                char *addr_string,
11814                                const struct breakpoint_ops *ops,
11815                                int tempflag,
11816                                int enabled,
11817                                int from_tty)
11818 {
11819   if (from_tty)
11820     {
11821       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11822       if (!loc_gdbarch)
11823         loc_gdbarch = gdbarch;
11824
11825       describe_other_breakpoints (loc_gdbarch,
11826                                   sal.pspace, sal.pc, sal.section, -1);
11827       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11828          version for exception catchpoints, because two catchpoints
11829          used for different exception names will use the same address.
11830          In this case, a "breakpoint ... also set at..." warning is
11831          unproductive.  Besides, the warning phrasing is also a bit
11832          inappropriate, we should use the word catchpoint, and tell
11833          the user what type of catchpoint it is.  The above is good
11834          enough for now, though.  */
11835     }
11836
11837   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11838
11839   b->enable_state = enabled ? bp_enabled : bp_disabled;
11840   b->disposition = tempflag ? disp_del : disp_donttouch;
11841   b->addr_string = addr_string;
11842   b->language = language_ada;
11843 }
11844
11845 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11846    filter list, or NULL if no filtering is required.  */
11847 static VEC(int) *
11848 catch_syscall_split_args (char *arg)
11849 {
11850   VEC(int) *result = NULL;
11851   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11852
11853   while (*arg != '\0')
11854     {
11855       int i, syscall_number;
11856       char *endptr;
11857       char cur_name[128];
11858       struct syscall s;
11859
11860       /* Skip whitespace.  */
11861       arg = skip_spaces (arg);
11862
11863       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11864         cur_name[i] = arg[i];
11865       cur_name[i] = '\0';
11866       arg += i;
11867
11868       /* Check if the user provided a syscall name or a number.  */
11869       syscall_number = (int) strtol (cur_name, &endptr, 0);
11870       if (*endptr == '\0')
11871         get_syscall_by_number (syscall_number, &s);
11872       else
11873         {
11874           /* We have a name.  Let's check if it's valid and convert it
11875              to a number.  */
11876           get_syscall_by_name (cur_name, &s);
11877
11878           if (s.number == UNKNOWN_SYSCALL)
11879             /* Here we have to issue an error instead of a warning,
11880                because GDB cannot do anything useful if there's no
11881                syscall number to be caught.  */
11882             error (_("Unknown syscall name '%s'."), cur_name);
11883         }
11884
11885       /* Ok, it's valid.  */
11886       VEC_safe_push (int, result, s.number);
11887     }
11888
11889   discard_cleanups (cleanup);
11890   return result;
11891 }
11892
11893 /* Implement the "catch syscall" command.  */
11894
11895 static void
11896 catch_syscall_command_1 (char *arg, int from_tty, 
11897                          struct cmd_list_element *command)
11898 {
11899   int tempflag;
11900   VEC(int) *filter;
11901   struct syscall s;
11902   struct gdbarch *gdbarch = get_current_arch ();
11903
11904   /* Checking if the feature if supported.  */
11905   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11906     error (_("The feature 'catch syscall' is not supported on \
11907 this architecture yet."));
11908
11909   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11910
11911   arg = skip_spaces (arg);
11912
11913   /* We need to do this first "dummy" translation in order
11914      to get the syscall XML file loaded or, most important,
11915      to display a warning to the user if there's no XML file
11916      for his/her architecture.  */
11917   get_syscall_by_number (0, &s);
11918
11919   /* The allowed syntax is:
11920      catch syscall
11921      catch syscall <name | number> [<name | number> ... <name | number>]
11922
11923      Let's check if there's a syscall name.  */
11924
11925   if (arg != NULL)
11926     filter = catch_syscall_split_args (arg);
11927   else
11928     filter = NULL;
11929
11930   create_syscall_event_catchpoint (tempflag, filter,
11931                                    &catch_syscall_breakpoint_ops);
11932 }
11933
11934 static void
11935 catch_command (char *arg, int from_tty)
11936 {
11937   error (_("Catch requires an event name."));
11938 }
11939 \f
11940
11941 static void
11942 tcatch_command (char *arg, int from_tty)
11943 {
11944   error (_("Catch requires an event name."));
11945 }
11946
11947 /* A qsort comparison function that sorts breakpoints in order.  */
11948
11949 static int
11950 compare_breakpoints (const void *a, const void *b)
11951 {
11952   const breakpoint_p *ba = a;
11953   uintptr_t ua = (uintptr_t) *ba;
11954   const breakpoint_p *bb = b;
11955   uintptr_t ub = (uintptr_t) *bb;
11956
11957   if ((*ba)->number < (*bb)->number)
11958     return -1;
11959   else if ((*ba)->number > (*bb)->number)
11960     return 1;
11961
11962   /* Now sort by address, in case we see, e..g, two breakpoints with
11963      the number 0.  */
11964   if (ua < ub)
11965     return -1;
11966   return ua > ub ? 1 : 0;
11967 }
11968
11969 /* Delete breakpoints by address or line.  */
11970
11971 static void
11972 clear_command (char *arg, int from_tty)
11973 {
11974   struct breakpoint *b, *prev;
11975   VEC(breakpoint_p) *found = 0;
11976   int ix;
11977   int default_match;
11978   struct symtabs_and_lines sals;
11979   struct symtab_and_line sal;
11980   int i;
11981   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11982
11983   if (arg)
11984     {
11985       sals = decode_line_with_current_source (arg,
11986                                               (DECODE_LINE_FUNFIRSTLINE
11987                                                | DECODE_LINE_LIST_MODE));
11988       make_cleanup (xfree, sals.sals);
11989       default_match = 0;
11990     }
11991   else
11992     {
11993       sals.sals = (struct symtab_and_line *)
11994         xmalloc (sizeof (struct symtab_and_line));
11995       make_cleanup (xfree, sals.sals);
11996       init_sal (&sal);          /* Initialize to zeroes.  */
11997
11998       /* Set sal's line, symtab, pc, and pspace to the values
11999          corresponding to the last call to print_frame_info.  If the
12000          codepoint is not valid, this will set all the fields to 0.  */
12001       get_last_displayed_sal (&sal);
12002       if (sal.symtab == 0)
12003         error (_("No source file specified."));
12004
12005       sals.sals[0] = sal;
12006       sals.nelts = 1;
12007
12008       default_match = 1;
12009     }
12010
12011   /* We don't call resolve_sal_pc here.  That's not as bad as it
12012      seems, because all existing breakpoints typically have both
12013      file/line and pc set.  So, if clear is given file/line, we can
12014      match this to existing breakpoint without obtaining pc at all.
12015
12016      We only support clearing given the address explicitly 
12017      present in breakpoint table.  Say, we've set breakpoint 
12018      at file:line.  There were several PC values for that file:line,
12019      due to optimization, all in one block.
12020
12021      We've picked one PC value.  If "clear" is issued with another
12022      PC corresponding to the same file:line, the breakpoint won't
12023      be cleared.  We probably can still clear the breakpoint, but 
12024      since the other PC value is never presented to user, user
12025      can only find it by guessing, and it does not seem important
12026      to support that.  */
12027
12028   /* For each line spec given, delete bps which correspond to it.  Do
12029      it in two passes, solely to preserve the current behavior that
12030      from_tty is forced true if we delete more than one
12031      breakpoint.  */
12032
12033   found = NULL;
12034   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12035   for (i = 0; i < sals.nelts; i++)
12036     {
12037       const char *sal_fullname;
12038
12039       /* If exact pc given, clear bpts at that pc.
12040          If line given (pc == 0), clear all bpts on specified line.
12041          If defaulting, clear all bpts on default line
12042          or at default pc.
12043
12044          defaulting    sal.pc != 0    tests to do
12045
12046          0              1             pc
12047          1              1             pc _and_ line
12048          0              0             line
12049          1              0             <can't happen> */
12050
12051       sal = sals.sals[i];
12052       sal_fullname = (sal.symtab == NULL
12053                       ? NULL : symtab_to_fullname (sal.symtab));
12054
12055       /* Find all matching breakpoints and add them to 'found'.  */
12056       ALL_BREAKPOINTS (b)
12057         {
12058           int match = 0;
12059           /* Are we going to delete b?  */
12060           if (b->type != bp_none && !is_watchpoint (b))
12061             {
12062               struct bp_location *loc = b->loc;
12063               for (; loc; loc = loc->next)
12064                 {
12065                   /* If the user specified file:line, don't allow a PC
12066                      match.  This matches historical gdb behavior.  */
12067                   int pc_match = (!sal.explicit_line
12068                                   && sal.pc
12069                                   && (loc->pspace == sal.pspace)
12070                                   && (loc->address == sal.pc)
12071                                   && (!section_is_overlay (loc->section)
12072                                       || loc->section == sal.section));
12073                   int line_match = 0;
12074
12075                   if ((default_match || sal.explicit_line)
12076                       && loc->symtab != NULL
12077                       && sal_fullname != NULL
12078                       && sal.pspace == loc->pspace
12079                       && loc->line_number == sal.line
12080                       && filename_cmp (symtab_to_fullname (loc->symtab),
12081                                        sal_fullname) == 0)
12082                     line_match = 1;
12083
12084                   if (pc_match || line_match)
12085                     {
12086                       match = 1;
12087                       break;
12088                     }
12089                 }
12090             }
12091
12092           if (match)
12093             VEC_safe_push(breakpoint_p, found, b);
12094         }
12095     }
12096
12097   /* Now go thru the 'found' chain and delete them.  */
12098   if (VEC_empty(breakpoint_p, found))
12099     {
12100       if (arg)
12101         error (_("No breakpoint at %s."), arg);
12102       else
12103         error (_("No breakpoint at this line."));
12104     }
12105
12106   /* Remove duplicates from the vec.  */
12107   qsort (VEC_address (breakpoint_p, found),
12108          VEC_length (breakpoint_p, found),
12109          sizeof (breakpoint_p),
12110          compare_breakpoints);
12111   prev = VEC_index (breakpoint_p, found, 0);
12112   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12113     {
12114       if (b == prev)
12115         {
12116           VEC_ordered_remove (breakpoint_p, found, ix);
12117           --ix;
12118         }
12119     }
12120
12121   if (VEC_length(breakpoint_p, found) > 1)
12122     from_tty = 1;       /* Always report if deleted more than one.  */
12123   if (from_tty)
12124     {
12125       if (VEC_length(breakpoint_p, found) == 1)
12126         printf_unfiltered (_("Deleted breakpoint "));
12127       else
12128         printf_unfiltered (_("Deleted breakpoints "));
12129     }
12130
12131   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12132     {
12133       if (from_tty)
12134         printf_unfiltered ("%d ", b->number);
12135       delete_breakpoint (b);
12136     }
12137   if (from_tty)
12138     putchar_unfiltered ('\n');
12139
12140   do_cleanups (cleanups);
12141 }
12142 \f
12143 /* Delete breakpoint in BS if they are `delete' breakpoints and
12144    all breakpoints that are marked for deletion, whether hit or not.
12145    This is called after any breakpoint is hit, or after errors.  */
12146
12147 void
12148 breakpoint_auto_delete (bpstat bs)
12149 {
12150   struct breakpoint *b, *b_tmp;
12151
12152   for (; bs; bs = bs->next)
12153     if (bs->breakpoint_at
12154         && bs->breakpoint_at->disposition == disp_del
12155         && bs->stop)
12156       delete_breakpoint (bs->breakpoint_at);
12157
12158   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12159   {
12160     if (b->disposition == disp_del_at_next_stop)
12161       delete_breakpoint (b);
12162   }
12163 }
12164
12165 /* A comparison function for bp_location AP and BP being interfaced to
12166    qsort.  Sort elements primarily by their ADDRESS (no matter what
12167    does breakpoint_address_is_meaningful say for its OWNER),
12168    secondarily by ordering first bp_permanent OWNERed elements and
12169    terciarily just ensuring the array is sorted stable way despite
12170    qsort being an unstable algorithm.  */
12171
12172 static int
12173 bp_location_compare (const void *ap, const void *bp)
12174 {
12175   struct bp_location *a = *(void **) ap;
12176   struct bp_location *b = *(void **) bp;
12177   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12178   int a_perm = a->owner->enable_state == bp_permanent;
12179   int b_perm = b->owner->enable_state == bp_permanent;
12180
12181   if (a->address != b->address)
12182     return (a->address > b->address) - (a->address < b->address);
12183
12184   /* Sort locations at the same address by their pspace number, keeping
12185      locations of the same inferior (in a multi-inferior environment)
12186      grouped.  */
12187
12188   if (a->pspace->num != b->pspace->num)
12189     return ((a->pspace->num > b->pspace->num)
12190             - (a->pspace->num < b->pspace->num));
12191
12192   /* Sort permanent breakpoints first.  */
12193   if (a_perm != b_perm)
12194     return (a_perm < b_perm) - (a_perm > b_perm);
12195
12196   /* Make the internal GDB representation stable across GDB runs
12197      where A and B memory inside GDB can differ.  Breakpoint locations of
12198      the same type at the same address can be sorted in arbitrary order.  */
12199
12200   if (a->owner->number != b->owner->number)
12201     return ((a->owner->number > b->owner->number)
12202             - (a->owner->number < b->owner->number));
12203
12204   return (a > b) - (a < b);
12205 }
12206
12207 /* Set bp_location_placed_address_before_address_max and
12208    bp_location_shadow_len_after_address_max according to the current
12209    content of the bp_location array.  */
12210
12211 static void
12212 bp_location_target_extensions_update (void)
12213 {
12214   struct bp_location *bl, **blp_tmp;
12215
12216   bp_location_placed_address_before_address_max = 0;
12217   bp_location_shadow_len_after_address_max = 0;
12218
12219   ALL_BP_LOCATIONS (bl, blp_tmp)
12220     {
12221       CORE_ADDR start, end, addr;
12222
12223       if (!bp_location_has_shadow (bl))
12224         continue;
12225
12226       start = bl->target_info.placed_address;
12227       end = start + bl->target_info.shadow_len;
12228
12229       gdb_assert (bl->address >= start);
12230       addr = bl->address - start;
12231       if (addr > bp_location_placed_address_before_address_max)
12232         bp_location_placed_address_before_address_max = addr;
12233
12234       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12235
12236       gdb_assert (bl->address < end);
12237       addr = end - bl->address;
12238       if (addr > bp_location_shadow_len_after_address_max)
12239         bp_location_shadow_len_after_address_max = addr;
12240     }
12241 }
12242
12243 /* Download tracepoint locations if they haven't been.  */
12244
12245 static void
12246 download_tracepoint_locations (void)
12247 {
12248   struct breakpoint *b;
12249   struct cleanup *old_chain;
12250
12251   if (!target_can_download_tracepoint ())
12252     return;
12253
12254   old_chain = save_current_space_and_thread ();
12255
12256   ALL_TRACEPOINTS (b)
12257     {
12258       struct bp_location *bl;
12259       struct tracepoint *t;
12260       int bp_location_downloaded = 0;
12261
12262       if ((b->type == bp_fast_tracepoint
12263            ? !may_insert_fast_tracepoints
12264            : !may_insert_tracepoints))
12265         continue;
12266
12267       for (bl = b->loc; bl; bl = bl->next)
12268         {
12269           /* In tracepoint, locations are _never_ duplicated, so
12270              should_be_inserted is equivalent to
12271              unduplicated_should_be_inserted.  */
12272           if (!should_be_inserted (bl) || bl->inserted)
12273             continue;
12274
12275           switch_to_program_space_and_thread (bl->pspace);
12276
12277           target_download_tracepoint (bl);
12278
12279           bl->inserted = 1;
12280           bp_location_downloaded = 1;
12281         }
12282       t = (struct tracepoint *) b;
12283       t->number_on_target = b->number;
12284       if (bp_location_downloaded)
12285         observer_notify_breakpoint_modified (b);
12286     }
12287
12288   do_cleanups (old_chain);
12289 }
12290
12291 /* Swap the insertion/duplication state between two locations.  */
12292
12293 static void
12294 swap_insertion (struct bp_location *left, struct bp_location *right)
12295 {
12296   const int left_inserted = left->inserted;
12297   const int left_duplicate = left->duplicate;
12298   const int left_needs_update = left->needs_update;
12299   const struct bp_target_info left_target_info = left->target_info;
12300
12301   /* Locations of tracepoints can never be duplicated.  */
12302   if (is_tracepoint (left->owner))
12303     gdb_assert (!left->duplicate);
12304   if (is_tracepoint (right->owner))
12305     gdb_assert (!right->duplicate);
12306
12307   left->inserted = right->inserted;
12308   left->duplicate = right->duplicate;
12309   left->needs_update = right->needs_update;
12310   left->target_info = right->target_info;
12311   right->inserted = left_inserted;
12312   right->duplicate = left_duplicate;
12313   right->needs_update = left_needs_update;
12314   right->target_info = left_target_info;
12315 }
12316
12317 /* Force the re-insertion of the locations at ADDRESS.  This is called
12318    once a new/deleted/modified duplicate location is found and we are evaluating
12319    conditions on the target's side.  Such conditions need to be updated on
12320    the target.  */
12321
12322 static void
12323 force_breakpoint_reinsertion (struct bp_location *bl)
12324 {
12325   struct bp_location **locp = NULL, **loc2p;
12326   struct bp_location *loc;
12327   CORE_ADDR address = 0;
12328   int pspace_num;
12329
12330   address = bl->address;
12331   pspace_num = bl->pspace->num;
12332
12333   /* This is only meaningful if the target is
12334      evaluating conditions and if the user has
12335      opted for condition evaluation on the target's
12336      side.  */
12337   if (gdb_evaluates_breakpoint_condition_p ()
12338       || !target_supports_evaluation_of_breakpoint_conditions ())
12339     return;
12340
12341   /* Flag all breakpoint locations with this address and
12342      the same program space as the location
12343      as "its condition has changed".  We need to
12344      update the conditions on the target's side.  */
12345   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12346     {
12347       loc = *loc2p;
12348
12349       if (!is_breakpoint (loc->owner)
12350           || pspace_num != loc->pspace->num)
12351         continue;
12352
12353       /* Flag the location appropriately.  We use a different state to
12354          let everyone know that we already updated the set of locations
12355          with addr bl->address and program space bl->pspace.  This is so
12356          we don't have to keep calling these functions just to mark locations
12357          that have already been marked.  */
12358       loc->condition_changed = condition_updated;
12359
12360       /* Free the agent expression bytecode as well.  We will compute
12361          it later on.  */
12362       if (loc->cond_bytecode)
12363         {
12364           free_agent_expr (loc->cond_bytecode);
12365           loc->cond_bytecode = NULL;
12366         }
12367     }
12368 }
12369
12370 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
12371    into the inferior, only remove already-inserted locations that no
12372    longer should be inserted.  Functions that delete a breakpoint or
12373    breakpoints should pass false, so that deleting a breakpoint
12374    doesn't have the side effect of inserting the locations of other
12375    breakpoints that are marked not-inserted, but should_be_inserted
12376    returns true on them.
12377
12378    This behaviour is useful is situations close to tear-down -- e.g.,
12379    after an exec, while the target still has execution, but breakpoint
12380    shadows of the previous executable image should *NOT* be restored
12381    to the new image; or before detaching, where the target still has
12382    execution and wants to delete breakpoints from GDB's lists, and all
12383    breakpoints had already been removed from the inferior.  */
12384
12385 static void
12386 update_global_location_list (int should_insert)
12387 {
12388   struct breakpoint *b;
12389   struct bp_location **locp, *loc;
12390   struct cleanup *cleanups;
12391   /* Last breakpoint location address that was marked for update.  */
12392   CORE_ADDR last_addr = 0;
12393   /* Last breakpoint location program space that was marked for update.  */
12394   int last_pspace_num = -1;
12395
12396   /* Used in the duplicates detection below.  When iterating over all
12397      bp_locations, points to the first bp_location of a given address.
12398      Breakpoints and watchpoints of different types are never
12399      duplicates of each other.  Keep one pointer for each type of
12400      breakpoint/watchpoint, so we only need to loop over all locations
12401      once.  */
12402   struct bp_location *bp_loc_first;  /* breakpoint */
12403   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12404   struct bp_location *awp_loc_first; /* access watchpoint */
12405   struct bp_location *rwp_loc_first; /* read watchpoint */
12406
12407   /* Saved former bp_location array which we compare against the newly
12408      built bp_location from the current state of ALL_BREAKPOINTS.  */
12409   struct bp_location **old_location, **old_locp;
12410   unsigned old_location_count;
12411
12412   old_location = bp_location;
12413   old_location_count = bp_location_count;
12414   bp_location = NULL;
12415   bp_location_count = 0;
12416   cleanups = make_cleanup (xfree, old_location);
12417
12418   ALL_BREAKPOINTS (b)
12419     for (loc = b->loc; loc; loc = loc->next)
12420       bp_location_count++;
12421
12422   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12423   locp = bp_location;
12424   ALL_BREAKPOINTS (b)
12425     for (loc = b->loc; loc; loc = loc->next)
12426       *locp++ = loc;
12427   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12428          bp_location_compare);
12429
12430   bp_location_target_extensions_update ();
12431
12432   /* Identify bp_location instances that are no longer present in the
12433      new list, and therefore should be freed.  Note that it's not
12434      necessary that those locations should be removed from inferior --
12435      if there's another location at the same address (previously
12436      marked as duplicate), we don't need to remove/insert the
12437      location.
12438      
12439      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12440      and former bp_location array state respectively.  */
12441
12442   locp = bp_location;
12443   for (old_locp = old_location; old_locp < old_location + old_location_count;
12444        old_locp++)
12445     {
12446       struct bp_location *old_loc = *old_locp;
12447       struct bp_location **loc2p;
12448
12449       /* Tells if 'old_loc' is found among the new locations.  If
12450          not, we have to free it.  */
12451       int found_object = 0;
12452       /* Tells if the location should remain inserted in the target.  */
12453       int keep_in_target = 0;
12454       int removed = 0;
12455
12456       /* Skip LOCP entries which will definitely never be needed.
12457          Stop either at or being the one matching OLD_LOC.  */
12458       while (locp < bp_location + bp_location_count
12459              && (*locp)->address < old_loc->address)
12460         locp++;
12461
12462       for (loc2p = locp;
12463            (loc2p < bp_location + bp_location_count
12464             && (*loc2p)->address == old_loc->address);
12465            loc2p++)
12466         {
12467           /* Check if this is a new/duplicated location or a duplicated
12468              location that had its condition modified.  If so, we want to send
12469              its condition to the target if evaluation of conditions is taking
12470              place there.  */
12471           if ((*loc2p)->condition_changed == condition_modified
12472               && (last_addr != old_loc->address
12473                   || last_pspace_num != old_loc->pspace->num))
12474             {
12475               force_breakpoint_reinsertion (*loc2p);
12476               last_pspace_num = old_loc->pspace->num;
12477             }
12478
12479           if (*loc2p == old_loc)
12480             found_object = 1;
12481         }
12482
12483       /* We have already handled this address, update it so that we don't
12484          have to go through updates again.  */
12485       last_addr = old_loc->address;
12486
12487       /* Target-side condition evaluation: Handle deleted locations.  */
12488       if (!found_object)
12489         force_breakpoint_reinsertion (old_loc);
12490
12491       /* If this location is no longer present, and inserted, look if
12492          there's maybe a new location at the same address.  If so,
12493          mark that one inserted, and don't remove this one.  This is
12494          needed so that we don't have a time window where a breakpoint
12495          at certain location is not inserted.  */
12496
12497       if (old_loc->inserted)
12498         {
12499           /* If the location is inserted now, we might have to remove
12500              it.  */
12501
12502           if (found_object && should_be_inserted (old_loc))
12503             {
12504               /* The location is still present in the location list,
12505                  and still should be inserted.  Don't do anything.  */
12506               keep_in_target = 1;
12507             }
12508           else
12509             {
12510               /* This location still exists, but it won't be kept in the
12511                  target since it may have been disabled.  We proceed to
12512                  remove its target-side condition.  */
12513
12514               /* The location is either no longer present, or got
12515                  disabled.  See if there's another location at the
12516                  same address, in which case we don't need to remove
12517                  this one from the target.  */
12518
12519               /* OLD_LOC comes from existing struct breakpoint.  */
12520               if (breakpoint_address_is_meaningful (old_loc->owner))
12521                 {
12522                   for (loc2p = locp;
12523                        (loc2p < bp_location + bp_location_count
12524                         && (*loc2p)->address == old_loc->address);
12525                        loc2p++)
12526                     {
12527                       struct bp_location *loc2 = *loc2p;
12528
12529                       if (breakpoint_locations_match (loc2, old_loc))
12530                         {
12531                           /* Read watchpoint locations are switched to
12532                              access watchpoints, if the former are not
12533                              supported, but the latter are.  */
12534                           if (is_hardware_watchpoint (old_loc->owner))
12535                             {
12536                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12537                               loc2->watchpoint_type = old_loc->watchpoint_type;
12538                             }
12539
12540                           /* loc2 is a duplicated location. We need to check
12541                              if it should be inserted in case it will be
12542                              unduplicated.  */
12543                           if (loc2 != old_loc
12544                               && unduplicated_should_be_inserted (loc2))
12545                             {
12546                               swap_insertion (old_loc, loc2);
12547                               keep_in_target = 1;
12548                               break;
12549                             }
12550                         }
12551                     }
12552                 }
12553             }
12554
12555           if (!keep_in_target)
12556             {
12557               if (remove_breakpoint (old_loc, mark_uninserted))
12558                 {
12559                   /* This is just about all we can do.  We could keep
12560                      this location on the global list, and try to
12561                      remove it next time, but there's no particular
12562                      reason why we will succeed next time.
12563                      
12564                      Note that at this point, old_loc->owner is still
12565                      valid, as delete_breakpoint frees the breakpoint
12566                      only after calling us.  */
12567                   printf_filtered (_("warning: Error removing "
12568                                      "breakpoint %d\n"), 
12569                                    old_loc->owner->number);
12570                 }
12571               removed = 1;
12572             }
12573         }
12574
12575       if (!found_object)
12576         {
12577           if (removed && non_stop
12578               && breakpoint_address_is_meaningful (old_loc->owner)
12579               && !is_hardware_watchpoint (old_loc->owner))
12580             {
12581               /* This location was removed from the target.  In
12582                  non-stop mode, a race condition is possible where
12583                  we've removed a breakpoint, but stop events for that
12584                  breakpoint are already queued and will arrive later.
12585                  We apply an heuristic to be able to distinguish such
12586                  SIGTRAPs from other random SIGTRAPs: we keep this
12587                  breakpoint location for a bit, and will retire it
12588                  after we see some number of events.  The theory here
12589                  is that reporting of events should, "on the average",
12590                  be fair, so after a while we'll see events from all
12591                  threads that have anything of interest, and no longer
12592                  need to keep this breakpoint location around.  We
12593                  don't hold locations forever so to reduce chances of
12594                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12595                  SIGTRAP.
12596
12597                  The heuristic failing can be disastrous on
12598                  decr_pc_after_break targets.
12599
12600                  On decr_pc_after_break targets, like e.g., x86-linux,
12601                  if we fail to recognize a late breakpoint SIGTRAP,
12602                  because events_till_retirement has reached 0 too
12603                  soon, we'll fail to do the PC adjustment, and report
12604                  a random SIGTRAP to the user.  When the user resumes
12605                  the inferior, it will most likely immediately crash
12606                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12607                  corrupted, because of being resumed e.g., in the
12608                  middle of a multi-byte instruction, or skipped a
12609                  one-byte instruction.  This was actually seen happen
12610                  on native x86-linux, and should be less rare on
12611                  targets that do not support new thread events, like
12612                  remote, due to the heuristic depending on
12613                  thread_count.
12614
12615                  Mistaking a random SIGTRAP for a breakpoint trap
12616                  causes similar symptoms (PC adjustment applied when
12617                  it shouldn't), but then again, playing with SIGTRAPs
12618                  behind the debugger's back is asking for trouble.
12619
12620                  Since hardware watchpoint traps are always
12621                  distinguishable from other traps, so we don't need to
12622                  apply keep hardware watchpoint moribund locations
12623                  around.  We simply always ignore hardware watchpoint
12624                  traps we can no longer explain.  */
12625
12626               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12627               old_loc->owner = NULL;
12628
12629               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12630             }
12631           else
12632             {
12633               old_loc->owner = NULL;
12634               decref_bp_location (&old_loc);
12635             }
12636         }
12637     }
12638
12639   /* Rescan breakpoints at the same address and section, marking the
12640      first one as "first" and any others as "duplicates".  This is so
12641      that the bpt instruction is only inserted once.  If we have a
12642      permanent breakpoint at the same place as BPT, make that one the
12643      official one, and the rest as duplicates.  Permanent breakpoints
12644      are sorted first for the same address.
12645
12646      Do the same for hardware watchpoints, but also considering the
12647      watchpoint's type (regular/access/read) and length.  */
12648
12649   bp_loc_first = NULL;
12650   wp_loc_first = NULL;
12651   awp_loc_first = NULL;
12652   rwp_loc_first = NULL;
12653   ALL_BP_LOCATIONS (loc, locp)
12654     {
12655       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12656          non-NULL.  */
12657       struct bp_location **loc_first_p;
12658       b = loc->owner;
12659
12660       if (!unduplicated_should_be_inserted (loc)
12661           || !breakpoint_address_is_meaningful (b)
12662           /* Don't detect duplicate for tracepoint locations because they are
12663            never duplicated.  See the comments in field `duplicate' of
12664            `struct bp_location'.  */
12665           || is_tracepoint (b))
12666         {
12667           /* Clear the condition modification flag.  */
12668           loc->condition_changed = condition_unchanged;
12669           continue;
12670         }
12671
12672       /* Permanent breakpoint should always be inserted.  */
12673       if (b->enable_state == bp_permanent && ! loc->inserted)
12674         internal_error (__FILE__, __LINE__,
12675                         _("allegedly permanent breakpoint is not "
12676                         "actually inserted"));
12677
12678       if (b->type == bp_hardware_watchpoint)
12679         loc_first_p = &wp_loc_first;
12680       else if (b->type == bp_read_watchpoint)
12681         loc_first_p = &rwp_loc_first;
12682       else if (b->type == bp_access_watchpoint)
12683         loc_first_p = &awp_loc_first;
12684       else
12685         loc_first_p = &bp_loc_first;
12686
12687       if (*loc_first_p == NULL
12688           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12689           || !breakpoint_locations_match (loc, *loc_first_p))
12690         {
12691           *loc_first_p = loc;
12692           loc->duplicate = 0;
12693
12694           if (is_breakpoint (loc->owner) && loc->condition_changed)
12695             {
12696               loc->needs_update = 1;
12697               /* Clear the condition modification flag.  */
12698               loc->condition_changed = condition_unchanged;
12699             }
12700           continue;
12701         }
12702
12703
12704       /* This and the above ensure the invariant that the first location
12705          is not duplicated, and is the inserted one.
12706          All following are marked as duplicated, and are not inserted.  */
12707       if (loc->inserted)
12708         swap_insertion (loc, *loc_first_p);
12709       loc->duplicate = 1;
12710
12711       /* Clear the condition modification flag.  */
12712       loc->condition_changed = condition_unchanged;
12713
12714       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12715           && b->enable_state != bp_permanent)
12716         internal_error (__FILE__, __LINE__,
12717                         _("another breakpoint was inserted on top of "
12718                         "a permanent breakpoint"));
12719     }
12720
12721   if (breakpoints_always_inserted_mode ()
12722       && (have_live_inferiors ()
12723           || (gdbarch_has_global_breakpoints (target_gdbarch ()))))
12724     {
12725       if (should_insert)
12726         insert_breakpoint_locations ();
12727       else
12728         {
12729           /* Though should_insert is false, we may need to update conditions
12730              on the target's side if it is evaluating such conditions.  We
12731              only update conditions for locations that are marked
12732              "needs_update".  */
12733           update_inserted_breakpoint_locations ();
12734         }
12735     }
12736
12737   if (should_insert)
12738     download_tracepoint_locations ();
12739
12740   do_cleanups (cleanups);
12741 }
12742
12743 void
12744 breakpoint_retire_moribund (void)
12745 {
12746   struct bp_location *loc;
12747   int ix;
12748
12749   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12750     if (--(loc->events_till_retirement) == 0)
12751       {
12752         decref_bp_location (&loc);
12753         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12754         --ix;
12755       }
12756 }
12757
12758 static void
12759 update_global_location_list_nothrow (int inserting)
12760 {
12761   volatile struct gdb_exception e;
12762
12763   TRY_CATCH (e, RETURN_MASK_ERROR)
12764     update_global_location_list (inserting);
12765 }
12766
12767 /* Clear BKP from a BPS.  */
12768
12769 static void
12770 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12771 {
12772   bpstat bs;
12773
12774   for (bs = bps; bs; bs = bs->next)
12775     if (bs->breakpoint_at == bpt)
12776       {
12777         bs->breakpoint_at = NULL;
12778         bs->old_val = NULL;
12779         /* bs->commands will be freed later.  */
12780       }
12781 }
12782
12783 /* Callback for iterate_over_threads.  */
12784 static int
12785 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12786 {
12787   struct breakpoint *bpt = data;
12788
12789   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12790   return 0;
12791 }
12792
12793 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12794    callbacks.  */
12795
12796 static void
12797 say_where (struct breakpoint *b)
12798 {
12799   struct value_print_options opts;
12800
12801   get_user_print_options (&opts);
12802
12803   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12804      single string.  */
12805   if (b->loc == NULL)
12806     {
12807       printf_filtered (_(" (%s) pending."), b->addr_string);
12808     }
12809   else
12810     {
12811       if (opts.addressprint || b->loc->symtab == NULL)
12812         {
12813           printf_filtered (" at ");
12814           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12815                           gdb_stdout);
12816         }
12817       if (b->loc->symtab != NULL)
12818         {
12819           /* If there is a single location, we can print the location
12820              more nicely.  */
12821           if (b->loc->next == NULL)
12822             printf_filtered (": file %s, line %d.",
12823                              symtab_to_filename_for_display (b->loc->symtab),
12824                              b->loc->line_number);
12825           else
12826             /* This is not ideal, but each location may have a
12827                different file name, and this at least reflects the
12828                real situation somewhat.  */
12829             printf_filtered (": %s.", b->addr_string);
12830         }
12831
12832       if (b->loc->next)
12833         {
12834           struct bp_location *loc = b->loc;
12835           int n = 0;
12836           for (; loc; loc = loc->next)
12837             ++n;
12838           printf_filtered (" (%d locations)", n);
12839         }
12840     }
12841 }
12842
12843 /* Default bp_location_ops methods.  */
12844
12845 static void
12846 bp_location_dtor (struct bp_location *self)
12847 {
12848   xfree (self->cond);
12849   if (self->cond_bytecode)
12850     free_agent_expr (self->cond_bytecode);
12851   xfree (self->function_name);
12852
12853   VEC_free (agent_expr_p, self->target_info.conditions);
12854   VEC_free (agent_expr_p, self->target_info.tcommands);
12855 }
12856
12857 static const struct bp_location_ops bp_location_ops =
12858 {
12859   bp_location_dtor
12860 };
12861
12862 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12863    inherit from.  */
12864
12865 static void
12866 base_breakpoint_dtor (struct breakpoint *self)
12867 {
12868   decref_counted_command_line (&self->commands);
12869   xfree (self->cond_string);
12870   xfree (self->extra_string);
12871   xfree (self->addr_string);
12872   xfree (self->filter);
12873   xfree (self->addr_string_range_end);
12874 }
12875
12876 static struct bp_location *
12877 base_breakpoint_allocate_location (struct breakpoint *self)
12878 {
12879   struct bp_location *loc;
12880
12881   loc = XNEW (struct bp_location);
12882   init_bp_location (loc, &bp_location_ops, self);
12883   return loc;
12884 }
12885
12886 static void
12887 base_breakpoint_re_set (struct breakpoint *b)
12888 {
12889   /* Nothing to re-set. */
12890 }
12891
12892 #define internal_error_pure_virtual_called() \
12893   gdb_assert_not_reached ("pure virtual function called")
12894
12895 static int
12896 base_breakpoint_insert_location (struct bp_location *bl)
12897 {
12898   internal_error_pure_virtual_called ();
12899 }
12900
12901 static int
12902 base_breakpoint_remove_location (struct bp_location *bl)
12903 {
12904   internal_error_pure_virtual_called ();
12905 }
12906
12907 static int
12908 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12909                                 struct address_space *aspace,
12910                                 CORE_ADDR bp_addr,
12911                                 const struct target_waitstatus *ws)
12912 {
12913   internal_error_pure_virtual_called ();
12914 }
12915
12916 static void
12917 base_breakpoint_check_status (bpstat bs)
12918 {
12919   /* Always stop.   */
12920 }
12921
12922 /* A "works_in_software_mode" breakpoint_ops method that just internal
12923    errors.  */
12924
12925 static int
12926 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12927 {
12928   internal_error_pure_virtual_called ();
12929 }
12930
12931 /* A "resources_needed" breakpoint_ops method that just internal
12932    errors.  */
12933
12934 static int
12935 base_breakpoint_resources_needed (const struct bp_location *bl)
12936 {
12937   internal_error_pure_virtual_called ();
12938 }
12939
12940 static enum print_stop_action
12941 base_breakpoint_print_it (bpstat bs)
12942 {
12943   internal_error_pure_virtual_called ();
12944 }
12945
12946 static void
12947 base_breakpoint_print_one_detail (const struct breakpoint *self,
12948                                   struct ui_out *uiout)
12949 {
12950   /* nothing */
12951 }
12952
12953 static void
12954 base_breakpoint_print_mention (struct breakpoint *b)
12955 {
12956   internal_error_pure_virtual_called ();
12957 }
12958
12959 static void
12960 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12961 {
12962   internal_error_pure_virtual_called ();
12963 }
12964
12965 static void
12966 base_breakpoint_create_sals_from_address (char **arg,
12967                                           struct linespec_result *canonical,
12968                                           enum bptype type_wanted,
12969                                           char *addr_start,
12970                                           char **copy_arg)
12971 {
12972   internal_error_pure_virtual_called ();
12973 }
12974
12975 static void
12976 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12977                                         struct linespec_result *c,
12978                                         char *cond_string,
12979                                         char *extra_string,
12980                                         enum bptype type_wanted,
12981                                         enum bpdisp disposition,
12982                                         int thread,
12983                                         int task, int ignore_count,
12984                                         const struct breakpoint_ops *o,
12985                                         int from_tty, int enabled,
12986                                         int internal, unsigned flags)
12987 {
12988   internal_error_pure_virtual_called ();
12989 }
12990
12991 static void
12992 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12993                                  struct symtabs_and_lines *sals)
12994 {
12995   internal_error_pure_virtual_called ();
12996 }
12997
12998 /* The default 'explains_signal' method.  */
12999
13000 static int
13001 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13002 {
13003   return 1;
13004 }
13005
13006 /* The default "after_condition_true" method.  */
13007
13008 static void
13009 base_breakpoint_after_condition_true (struct bpstats *bs)
13010 {
13011   /* Nothing to do.   */
13012 }
13013
13014 struct breakpoint_ops base_breakpoint_ops =
13015 {
13016   base_breakpoint_dtor,
13017   base_breakpoint_allocate_location,
13018   base_breakpoint_re_set,
13019   base_breakpoint_insert_location,
13020   base_breakpoint_remove_location,
13021   base_breakpoint_breakpoint_hit,
13022   base_breakpoint_check_status,
13023   base_breakpoint_resources_needed,
13024   base_breakpoint_works_in_software_mode,
13025   base_breakpoint_print_it,
13026   NULL,
13027   base_breakpoint_print_one_detail,
13028   base_breakpoint_print_mention,
13029   base_breakpoint_print_recreate,
13030   base_breakpoint_create_sals_from_address,
13031   base_breakpoint_create_breakpoints_sal,
13032   base_breakpoint_decode_linespec,
13033   base_breakpoint_explains_signal,
13034   base_breakpoint_after_condition_true,
13035 };
13036
13037 /* Default breakpoint_ops methods.  */
13038
13039 static void
13040 bkpt_re_set (struct breakpoint *b)
13041 {
13042   /* FIXME: is this still reachable?  */
13043   if (b->addr_string == NULL)
13044     {
13045       /* Anything without a string can't be re-set.  */
13046       delete_breakpoint (b);
13047       return;
13048     }
13049
13050   breakpoint_re_set_default (b);
13051 }
13052
13053 static int
13054 bkpt_insert_location (struct bp_location *bl)
13055 {
13056   if (bl->loc_type == bp_loc_hardware_breakpoint)
13057     return target_insert_hw_breakpoint (bl->gdbarch,
13058                                         &bl->target_info);
13059   else
13060     return target_insert_breakpoint (bl->gdbarch,
13061                                      &bl->target_info);
13062 }
13063
13064 static int
13065 bkpt_remove_location (struct bp_location *bl)
13066 {
13067   if (bl->loc_type == bp_loc_hardware_breakpoint)
13068     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13069   else
13070     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
13071 }
13072
13073 static int
13074 bkpt_breakpoint_hit (const struct bp_location *bl,
13075                      struct address_space *aspace, CORE_ADDR bp_addr,
13076                      const struct target_waitstatus *ws)
13077 {
13078   if (ws->kind != TARGET_WAITKIND_STOPPED
13079       || ws->value.sig != GDB_SIGNAL_TRAP)
13080     return 0;
13081
13082   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13083                                  aspace, bp_addr))
13084     return 0;
13085
13086   if (overlay_debugging         /* unmapped overlay section */
13087       && section_is_overlay (bl->section)
13088       && !section_is_mapped (bl->section))
13089     return 0;
13090
13091   return 1;
13092 }
13093
13094 static int
13095 bkpt_resources_needed (const struct bp_location *bl)
13096 {
13097   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13098
13099   return 1;
13100 }
13101
13102 static enum print_stop_action
13103 bkpt_print_it (bpstat bs)
13104 {
13105   struct breakpoint *b;
13106   const struct bp_location *bl;
13107   int bp_temp;
13108   struct ui_out *uiout = current_uiout;
13109
13110   gdb_assert (bs->bp_location_at != NULL);
13111
13112   bl = bs->bp_location_at;
13113   b = bs->breakpoint_at;
13114
13115   bp_temp = b->disposition == disp_del;
13116   if (bl->address != bl->requested_address)
13117     breakpoint_adjustment_warning (bl->requested_address,
13118                                    bl->address,
13119                                    b->number, 1);
13120   annotate_breakpoint (b->number);
13121   if (bp_temp)
13122     ui_out_text (uiout, "\nTemporary breakpoint ");
13123   else
13124     ui_out_text (uiout, "\nBreakpoint ");
13125   if (ui_out_is_mi_like_p (uiout))
13126     {
13127       ui_out_field_string (uiout, "reason",
13128                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13129       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13130     }
13131   ui_out_field_int (uiout, "bkptno", b->number);
13132   ui_out_text (uiout, ", ");
13133
13134   return PRINT_SRC_AND_LOC;
13135 }
13136
13137 static void
13138 bkpt_print_mention (struct breakpoint *b)
13139 {
13140   if (ui_out_is_mi_like_p (current_uiout))
13141     return;
13142
13143   switch (b->type)
13144     {
13145     case bp_breakpoint:
13146     case bp_gnu_ifunc_resolver:
13147       if (b->disposition == disp_del)
13148         printf_filtered (_("Temporary breakpoint"));
13149       else
13150         printf_filtered (_("Breakpoint"));
13151       printf_filtered (_(" %d"), b->number);
13152       if (b->type == bp_gnu_ifunc_resolver)
13153         printf_filtered (_(" at gnu-indirect-function resolver"));
13154       break;
13155     case bp_hardware_breakpoint:
13156       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13157       break;
13158     case bp_dprintf:
13159       printf_filtered (_("Dprintf %d"), b->number);
13160       break;
13161     }
13162
13163   say_where (b);
13164 }
13165
13166 static void
13167 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13168 {
13169   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13170     fprintf_unfiltered (fp, "tbreak");
13171   else if (tp->type == bp_breakpoint)
13172     fprintf_unfiltered (fp, "break");
13173   else if (tp->type == bp_hardware_breakpoint
13174            && tp->disposition == disp_del)
13175     fprintf_unfiltered (fp, "thbreak");
13176   else if (tp->type == bp_hardware_breakpoint)
13177     fprintf_unfiltered (fp, "hbreak");
13178   else
13179     internal_error (__FILE__, __LINE__,
13180                     _("unhandled breakpoint type %d"), (int) tp->type);
13181
13182   fprintf_unfiltered (fp, " %s", tp->addr_string);
13183   print_recreate_thread (tp, fp);
13184 }
13185
13186 static void
13187 bkpt_create_sals_from_address (char **arg,
13188                                struct linespec_result *canonical,
13189                                enum bptype type_wanted,
13190                                char *addr_start, char **copy_arg)
13191 {
13192   create_sals_from_address_default (arg, canonical, type_wanted,
13193                                     addr_start, copy_arg);
13194 }
13195
13196 static void
13197 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13198                              struct linespec_result *canonical,
13199                              char *cond_string,
13200                              char *extra_string,
13201                              enum bptype type_wanted,
13202                              enum bpdisp disposition,
13203                              int thread,
13204                              int task, int ignore_count,
13205                              const struct breakpoint_ops *ops,
13206                              int from_tty, int enabled,
13207                              int internal, unsigned flags)
13208 {
13209   create_breakpoints_sal_default (gdbarch, canonical,
13210                                   cond_string, extra_string,
13211                                   type_wanted,
13212                                   disposition, thread, task,
13213                                   ignore_count, ops, from_tty,
13214                                   enabled, internal, flags);
13215 }
13216
13217 static void
13218 bkpt_decode_linespec (struct breakpoint *b, char **s,
13219                       struct symtabs_and_lines *sals)
13220 {
13221   decode_linespec_default (b, s, sals);
13222 }
13223
13224 /* Virtual table for internal breakpoints.  */
13225
13226 static void
13227 internal_bkpt_re_set (struct breakpoint *b)
13228 {
13229   switch (b->type)
13230     {
13231       /* Delete overlay event and longjmp master breakpoints; they
13232          will be reset later by breakpoint_re_set.  */
13233     case bp_overlay_event:
13234     case bp_longjmp_master:
13235     case bp_std_terminate_master:
13236     case bp_exception_master:
13237       delete_breakpoint (b);
13238       break;
13239
13240       /* This breakpoint is special, it's set up when the inferior
13241          starts and we really don't want to touch it.  */
13242     case bp_shlib_event:
13243
13244       /* Like bp_shlib_event, this breakpoint type is special.  Once
13245          it is set up, we do not want to touch it.  */
13246     case bp_thread_event:
13247       break;
13248     }
13249 }
13250
13251 static void
13252 internal_bkpt_check_status (bpstat bs)
13253 {
13254   if (bs->breakpoint_at->type == bp_shlib_event)
13255     {
13256       /* If requested, stop when the dynamic linker notifies GDB of
13257          events.  This allows the user to get control and place
13258          breakpoints in initializer routines for dynamically loaded
13259          objects (among other things).  */
13260       bs->stop = stop_on_solib_events;
13261       bs->print = stop_on_solib_events;
13262     }
13263   else
13264     bs->stop = 0;
13265 }
13266
13267 static enum print_stop_action
13268 internal_bkpt_print_it (bpstat bs)
13269 {
13270   struct breakpoint *b;
13271
13272   b = bs->breakpoint_at;
13273
13274   switch (b->type)
13275     {
13276     case bp_shlib_event:
13277       /* Did we stop because the user set the stop_on_solib_events
13278          variable?  (If so, we report this as a generic, "Stopped due
13279          to shlib event" message.) */
13280       print_solib_event (0);
13281       break;
13282
13283     case bp_thread_event:
13284       /* Not sure how we will get here.
13285          GDB should not stop for these breakpoints.  */
13286       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13287       break;
13288
13289     case bp_overlay_event:
13290       /* By analogy with the thread event, GDB should not stop for these.  */
13291       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13292       break;
13293
13294     case bp_longjmp_master:
13295       /* These should never be enabled.  */
13296       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13297       break;
13298
13299     case bp_std_terminate_master:
13300       /* These should never be enabled.  */
13301       printf_filtered (_("std::terminate Master Breakpoint: "
13302                          "gdb should not stop!\n"));
13303       break;
13304
13305     case bp_exception_master:
13306       /* These should never be enabled.  */
13307       printf_filtered (_("Exception Master Breakpoint: "
13308                          "gdb should not stop!\n"));
13309       break;
13310     }
13311
13312   return PRINT_NOTHING;
13313 }
13314
13315 static void
13316 internal_bkpt_print_mention (struct breakpoint *b)
13317 {
13318   /* Nothing to mention.  These breakpoints are internal.  */
13319 }
13320
13321 /* Virtual table for momentary breakpoints  */
13322
13323 static void
13324 momentary_bkpt_re_set (struct breakpoint *b)
13325 {
13326   /* Keep temporary breakpoints, which can be encountered when we step
13327      over a dlopen call and solib_add is resetting the breakpoints.
13328      Otherwise these should have been blown away via the cleanup chain
13329      or by breakpoint_init_inferior when we rerun the executable.  */
13330 }
13331
13332 static void
13333 momentary_bkpt_check_status (bpstat bs)
13334 {
13335   /* Nothing.  The point of these breakpoints is causing a stop.  */
13336 }
13337
13338 static enum print_stop_action
13339 momentary_bkpt_print_it (bpstat bs)
13340 {
13341   struct ui_out *uiout = current_uiout;
13342
13343   if (ui_out_is_mi_like_p (uiout))
13344     {
13345       struct breakpoint *b = bs->breakpoint_at;
13346
13347       switch (b->type)
13348         {
13349         case bp_finish:
13350           ui_out_field_string
13351             (uiout, "reason",
13352              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13353           break;
13354
13355         case bp_until:
13356           ui_out_field_string
13357             (uiout, "reason",
13358              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13359           break;
13360         }
13361     }
13362
13363   return PRINT_UNKNOWN;
13364 }
13365
13366 static void
13367 momentary_bkpt_print_mention (struct breakpoint *b)
13368 {
13369   /* Nothing to mention.  These breakpoints are internal.  */
13370 }
13371
13372 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13373
13374    It gets cleared already on the removal of the first one of such placed
13375    breakpoints.  This is OK as they get all removed altogether.  */
13376
13377 static void
13378 longjmp_bkpt_dtor (struct breakpoint *self)
13379 {
13380   struct thread_info *tp = find_thread_id (self->thread);
13381
13382   if (tp)
13383     tp->initiating_frame = null_frame_id;
13384
13385   momentary_breakpoint_ops.dtor (self);
13386 }
13387
13388 /* Specific methods for probe breakpoints.  */
13389
13390 static int
13391 bkpt_probe_insert_location (struct bp_location *bl)
13392 {
13393   int v = bkpt_insert_location (bl);
13394
13395   if (v == 0)
13396     {
13397       /* The insertion was successful, now let's set the probe's semaphore
13398          if needed.  */
13399       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13400                                             bl->probe.objfile,
13401                                             bl->gdbarch);
13402     }
13403
13404   return v;
13405 }
13406
13407 static int
13408 bkpt_probe_remove_location (struct bp_location *bl)
13409 {
13410   /* Let's clear the semaphore before removing the location.  */
13411   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13412                                           bl->probe.objfile,
13413                                           bl->gdbarch);
13414
13415   return bkpt_remove_location (bl);
13416 }
13417
13418 static void
13419 bkpt_probe_create_sals_from_address (char **arg,
13420                                      struct linespec_result *canonical,
13421                                      enum bptype type_wanted,
13422                                      char *addr_start, char **copy_arg)
13423 {
13424   struct linespec_sals lsal;
13425
13426   lsal.sals = parse_probes (arg, canonical);
13427
13428   *copy_arg = xstrdup (canonical->addr_string);
13429   lsal.canonical = xstrdup (*copy_arg);
13430
13431   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13432 }
13433
13434 static void
13435 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13436                             struct symtabs_and_lines *sals)
13437 {
13438   *sals = parse_probes (s, NULL);
13439   if (!sals->sals)
13440     error (_("probe not found"));
13441 }
13442
13443 /* The breakpoint_ops structure to be used in tracepoints.  */
13444
13445 static void
13446 tracepoint_re_set (struct breakpoint *b)
13447 {
13448   breakpoint_re_set_default (b);
13449 }
13450
13451 static int
13452 tracepoint_breakpoint_hit (const struct bp_location *bl,
13453                            struct address_space *aspace, CORE_ADDR bp_addr,
13454                            const struct target_waitstatus *ws)
13455 {
13456   /* By definition, the inferior does not report stops at
13457      tracepoints.  */
13458   return 0;
13459 }
13460
13461 static void
13462 tracepoint_print_one_detail (const struct breakpoint *self,
13463                              struct ui_out *uiout)
13464 {
13465   struct tracepoint *tp = (struct tracepoint *) self;
13466   if (tp->static_trace_marker_id)
13467     {
13468       gdb_assert (self->type == bp_static_tracepoint);
13469
13470       ui_out_text (uiout, "\tmarker id is ");
13471       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13472                            tp->static_trace_marker_id);
13473       ui_out_text (uiout, "\n");
13474     }
13475 }
13476
13477 static void
13478 tracepoint_print_mention (struct breakpoint *b)
13479 {
13480   if (ui_out_is_mi_like_p (current_uiout))
13481     return;
13482
13483   switch (b->type)
13484     {
13485     case bp_tracepoint:
13486       printf_filtered (_("Tracepoint"));
13487       printf_filtered (_(" %d"), b->number);
13488       break;
13489     case bp_fast_tracepoint:
13490       printf_filtered (_("Fast tracepoint"));
13491       printf_filtered (_(" %d"), b->number);
13492       break;
13493     case bp_static_tracepoint:
13494       printf_filtered (_("Static tracepoint"));
13495       printf_filtered (_(" %d"), b->number);
13496       break;
13497     default:
13498       internal_error (__FILE__, __LINE__,
13499                       _("unhandled tracepoint type %d"), (int) b->type);
13500     }
13501
13502   say_where (b);
13503 }
13504
13505 static void
13506 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13507 {
13508   struct tracepoint *tp = (struct tracepoint *) self;
13509
13510   if (self->type == bp_fast_tracepoint)
13511     fprintf_unfiltered (fp, "ftrace");
13512   if (self->type == bp_static_tracepoint)
13513     fprintf_unfiltered (fp, "strace");
13514   else if (self->type == bp_tracepoint)
13515     fprintf_unfiltered (fp, "trace");
13516   else
13517     internal_error (__FILE__, __LINE__,
13518                     _("unhandled tracepoint type %d"), (int) self->type);
13519
13520   fprintf_unfiltered (fp, " %s", self->addr_string);
13521   print_recreate_thread (self, fp);
13522
13523   if (tp->pass_count)
13524     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13525 }
13526
13527 static void
13528 tracepoint_create_sals_from_address (char **arg,
13529                                      struct linespec_result *canonical,
13530                                      enum bptype type_wanted,
13531                                      char *addr_start, char **copy_arg)
13532 {
13533   create_sals_from_address_default (arg, canonical, type_wanted,
13534                                     addr_start, copy_arg);
13535 }
13536
13537 static void
13538 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13539                                    struct linespec_result *canonical,
13540                                    char *cond_string,
13541                                    char *extra_string,
13542                                    enum bptype type_wanted,
13543                                    enum bpdisp disposition,
13544                                    int thread,
13545                                    int task, int ignore_count,
13546                                    const struct breakpoint_ops *ops,
13547                                    int from_tty, int enabled,
13548                                    int internal, unsigned flags)
13549 {
13550   create_breakpoints_sal_default (gdbarch, canonical,
13551                                   cond_string, extra_string,
13552                                   type_wanted,
13553                                   disposition, thread, task,
13554                                   ignore_count, ops, from_tty,
13555                                   enabled, internal, flags);
13556 }
13557
13558 static void
13559 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13560                             struct symtabs_and_lines *sals)
13561 {
13562   decode_linespec_default (b, s, sals);
13563 }
13564
13565 struct breakpoint_ops tracepoint_breakpoint_ops;
13566
13567 /* The breakpoint_ops structure to be use on tracepoints placed in a
13568    static probe.  */
13569
13570 static void
13571 tracepoint_probe_create_sals_from_address (char **arg,
13572                                            struct linespec_result *canonical,
13573                                            enum bptype type_wanted,
13574                                            char *addr_start, char **copy_arg)
13575 {
13576   /* We use the same method for breakpoint on probes.  */
13577   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13578                                        addr_start, copy_arg);
13579 }
13580
13581 static void
13582 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13583                                   struct symtabs_and_lines *sals)
13584 {
13585   /* We use the same method for breakpoint on probes.  */
13586   bkpt_probe_decode_linespec (b, s, sals);
13587 }
13588
13589 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13590
13591 /* Dprintf breakpoint_ops methods.  */
13592
13593 static void
13594 dprintf_re_set (struct breakpoint *b)
13595 {
13596   breakpoint_re_set_default (b);
13597
13598   /* This breakpoint could have been pending, and be resolved now, and
13599      if so, we should now have the extra string.  If we don't, the
13600      dprintf was malformed when created, but we couldn't tell because
13601      we can't extract the extra string until the location is
13602      resolved.  */
13603   if (b->loc != NULL && b->extra_string == NULL)
13604     error (_("Format string required"));
13605
13606   /* 1 - connect to target 1, that can run breakpoint commands.
13607      2 - create a dprintf, which resolves fine.
13608      3 - disconnect from target 1
13609      4 - connect to target 2, that can NOT run breakpoint commands.
13610
13611      After steps #3/#4, you'll want the dprintf command list to
13612      be updated, because target 1 and 2 may well return different
13613      answers for target_can_run_breakpoint_commands().
13614      Given absence of finer grained resetting, we get to do
13615      it all the time.  */
13616   if (b->extra_string != NULL)
13617     update_dprintf_command_list (b);
13618 }
13619
13620 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13621
13622 static void
13623 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13624 {
13625   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13626                       tp->extra_string);
13627   print_recreate_thread (tp, fp);
13628 }
13629
13630 /* Implement the "after_condition_true" breakpoint_ops method for
13631    dprintf.
13632
13633    dprintf's are implemented with regular commands in their command
13634    list, but we run the commands here instead of before presenting the
13635    stop to the user, as dprintf's don't actually cause a stop.  This
13636    also makes it so that the commands of multiple dprintfs at the same
13637    address are all handled.  */
13638
13639 static void
13640 dprintf_after_condition_true (struct bpstats *bs)
13641 {
13642   struct cleanup *old_chain;
13643   struct bpstats tmp_bs = { NULL };
13644   struct bpstats *tmp_bs_p = &tmp_bs;
13645
13646   /* dprintf's never cause a stop.  This wasn't set in the
13647      check_status hook instead because that would make the dprintf's
13648      condition not be evaluated.  */
13649   bs->stop = 0;
13650
13651   /* Run the command list here.  Take ownership of it instead of
13652      copying.  We never want these commands to run later in
13653      bpstat_do_actions, if a breakpoint that causes a stop happens to
13654      be set at same address as this dprintf, or even if running the
13655      commands here throws.  */
13656   tmp_bs.commands = bs->commands;
13657   bs->commands = NULL;
13658   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13659
13660   bpstat_do_actions_1 (&tmp_bs_p);
13661
13662   /* 'tmp_bs.commands' will usually be NULL by now, but
13663      bpstat_do_actions_1 may return early without processing the whole
13664      list.  */
13665   do_cleanups (old_chain);
13666 }
13667
13668 /* The breakpoint_ops structure to be used on static tracepoints with
13669    markers (`-m').  */
13670
13671 static void
13672 strace_marker_create_sals_from_address (char **arg,
13673                                         struct linespec_result *canonical,
13674                                         enum bptype type_wanted,
13675                                         char *addr_start, char **copy_arg)
13676 {
13677   struct linespec_sals lsal;
13678
13679   lsal.sals = decode_static_tracepoint_spec (arg);
13680
13681   *copy_arg = savestring (addr_start, *arg - addr_start);
13682
13683   canonical->addr_string = xstrdup (*copy_arg);
13684   lsal.canonical = xstrdup (*copy_arg);
13685   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13686 }
13687
13688 static void
13689 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13690                                       struct linespec_result *canonical,
13691                                       char *cond_string,
13692                                       char *extra_string,
13693                                       enum bptype type_wanted,
13694                                       enum bpdisp disposition,
13695                                       int thread,
13696                                       int task, int ignore_count,
13697                                       const struct breakpoint_ops *ops,
13698                                       int from_tty, int enabled,
13699                                       int internal, unsigned flags)
13700 {
13701   int i;
13702   struct linespec_sals *lsal = VEC_index (linespec_sals,
13703                                           canonical->sals, 0);
13704
13705   /* If the user is creating a static tracepoint by marker id
13706      (strace -m MARKER_ID), then store the sals index, so that
13707      breakpoint_re_set can try to match up which of the newly
13708      found markers corresponds to this one, and, don't try to
13709      expand multiple locations for each sal, given than SALS
13710      already should contain all sals for MARKER_ID.  */
13711
13712   for (i = 0; i < lsal->sals.nelts; ++i)
13713     {
13714       struct symtabs_and_lines expanded;
13715       struct tracepoint *tp;
13716       struct cleanup *old_chain;
13717       char *addr_string;
13718
13719       expanded.nelts = 1;
13720       expanded.sals = &lsal->sals.sals[i];
13721
13722       addr_string = xstrdup (canonical->addr_string);
13723       old_chain = make_cleanup (xfree, addr_string);
13724
13725       tp = XCNEW (struct tracepoint);
13726       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13727                            addr_string, NULL,
13728                            cond_string, extra_string,
13729                            type_wanted, disposition,
13730                            thread, task, ignore_count, ops,
13731                            from_tty, enabled, internal, flags,
13732                            canonical->special_display);
13733       /* Given that its possible to have multiple markers with
13734          the same string id, if the user is creating a static
13735          tracepoint by marker id ("strace -m MARKER_ID"), then
13736          store the sals index, so that breakpoint_re_set can
13737          try to match up which of the newly found markers
13738          corresponds to this one  */
13739       tp->static_trace_marker_id_idx = i;
13740
13741       install_breakpoint (internal, &tp->base, 0);
13742
13743       discard_cleanups (old_chain);
13744     }
13745 }
13746
13747 static void
13748 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13749                                struct symtabs_and_lines *sals)
13750 {
13751   struct tracepoint *tp = (struct tracepoint *) b;
13752
13753   *sals = decode_static_tracepoint_spec (s);
13754   if (sals->nelts > tp->static_trace_marker_id_idx)
13755     {
13756       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13757       sals->nelts = 1;
13758     }
13759   else
13760     error (_("marker %s not found"), tp->static_trace_marker_id);
13761 }
13762
13763 static struct breakpoint_ops strace_marker_breakpoint_ops;
13764
13765 static int
13766 strace_marker_p (struct breakpoint *b)
13767 {
13768   return b->ops == &strace_marker_breakpoint_ops;
13769 }
13770
13771 /* Delete a breakpoint and clean up all traces of it in the data
13772    structures.  */
13773
13774 void
13775 delete_breakpoint (struct breakpoint *bpt)
13776 {
13777   struct breakpoint *b;
13778
13779   gdb_assert (bpt != NULL);
13780
13781   /* Has this bp already been deleted?  This can happen because
13782      multiple lists can hold pointers to bp's.  bpstat lists are
13783      especial culprits.
13784
13785      One example of this happening is a watchpoint's scope bp.  When
13786      the scope bp triggers, we notice that the watchpoint is out of
13787      scope, and delete it.  We also delete its scope bp.  But the
13788      scope bp is marked "auto-deleting", and is already on a bpstat.
13789      That bpstat is then checked for auto-deleting bp's, which are
13790      deleted.
13791
13792      A real solution to this problem might involve reference counts in
13793      bp's, and/or giving them pointers back to their referencing
13794      bpstat's, and teaching delete_breakpoint to only free a bp's
13795      storage when no more references were extent.  A cheaper bandaid
13796      was chosen.  */
13797   if (bpt->type == bp_none)
13798     return;
13799
13800   /* At least avoid this stale reference until the reference counting
13801      of breakpoints gets resolved.  */
13802   if (bpt->related_breakpoint != bpt)
13803     {
13804       struct breakpoint *related;
13805       struct watchpoint *w;
13806
13807       if (bpt->type == bp_watchpoint_scope)
13808         w = (struct watchpoint *) bpt->related_breakpoint;
13809       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13810         w = (struct watchpoint *) bpt;
13811       else
13812         w = NULL;
13813       if (w != NULL)
13814         watchpoint_del_at_next_stop (w);
13815
13816       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13817       for (related = bpt; related->related_breakpoint != bpt;
13818            related = related->related_breakpoint);
13819       related->related_breakpoint = bpt->related_breakpoint;
13820       bpt->related_breakpoint = bpt;
13821     }
13822
13823   /* watch_command_1 creates a watchpoint but only sets its number if
13824      update_watchpoint succeeds in creating its bp_locations.  If there's
13825      a problem in that process, we'll be asked to delete the half-created
13826      watchpoint.  In that case, don't announce the deletion.  */
13827   if (bpt->number)
13828     observer_notify_breakpoint_deleted (bpt);
13829
13830   if (breakpoint_chain == bpt)
13831     breakpoint_chain = bpt->next;
13832
13833   ALL_BREAKPOINTS (b)
13834     if (b->next == bpt)
13835     {
13836       b->next = bpt->next;
13837       break;
13838     }
13839
13840   /* Be sure no bpstat's are pointing at the breakpoint after it's
13841      been freed.  */
13842   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13843      in all threads for now.  Note that we cannot just remove bpstats
13844      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13845      commands are associated with the bpstat; if we remove it here,
13846      then the later call to bpstat_do_actions (&stop_bpstat); in
13847      event-top.c won't do anything, and temporary breakpoints with
13848      commands won't work.  */
13849
13850   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13851
13852   /* Now that breakpoint is removed from breakpoint list, update the
13853      global location list.  This will remove locations that used to
13854      belong to this breakpoint.  Do this before freeing the breakpoint
13855      itself, since remove_breakpoint looks at location's owner.  It
13856      might be better design to have location completely
13857      self-contained, but it's not the case now.  */
13858   update_global_location_list (0);
13859
13860   bpt->ops->dtor (bpt);
13861   /* On the chance that someone will soon try again to delete this
13862      same bp, we mark it as deleted before freeing its storage.  */
13863   bpt->type = bp_none;
13864   xfree (bpt);
13865 }
13866
13867 static void
13868 do_delete_breakpoint_cleanup (void *b)
13869 {
13870   delete_breakpoint (b);
13871 }
13872
13873 struct cleanup *
13874 make_cleanup_delete_breakpoint (struct breakpoint *b)
13875 {
13876   return make_cleanup (do_delete_breakpoint_cleanup, b);
13877 }
13878
13879 /* Iterator function to call a user-provided callback function once
13880    for each of B and its related breakpoints.  */
13881
13882 static void
13883 iterate_over_related_breakpoints (struct breakpoint *b,
13884                                   void (*function) (struct breakpoint *,
13885                                                     void *),
13886                                   void *data)
13887 {
13888   struct breakpoint *related;
13889
13890   related = b;
13891   do
13892     {
13893       struct breakpoint *next;
13894
13895       /* FUNCTION may delete RELATED.  */
13896       next = related->related_breakpoint;
13897
13898       if (next == related)
13899         {
13900           /* RELATED is the last ring entry.  */
13901           function (related, data);
13902
13903           /* FUNCTION may have deleted it, so we'd never reach back to
13904              B.  There's nothing left to do anyway, so just break
13905              out.  */
13906           break;
13907         }
13908       else
13909         function (related, data);
13910
13911       related = next;
13912     }
13913   while (related != b);
13914 }
13915
13916 static void
13917 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13918 {
13919   delete_breakpoint (b);
13920 }
13921
13922 /* A callback for map_breakpoint_numbers that calls
13923    delete_breakpoint.  */
13924
13925 static void
13926 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13927 {
13928   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13929 }
13930
13931 void
13932 delete_command (char *arg, int from_tty)
13933 {
13934   struct breakpoint *b, *b_tmp;
13935
13936   dont_repeat ();
13937
13938   if (arg == 0)
13939     {
13940       int breaks_to_delete = 0;
13941
13942       /* Delete all breakpoints if no argument.  Do not delete
13943          internal breakpoints, these have to be deleted with an
13944          explicit breakpoint number argument.  */
13945       ALL_BREAKPOINTS (b)
13946         if (user_breakpoint_p (b))
13947           {
13948             breaks_to_delete = 1;
13949             break;
13950           }
13951
13952       /* Ask user only if there are some breakpoints to delete.  */
13953       if (!from_tty
13954           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13955         {
13956           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13957             if (user_breakpoint_p (b))
13958               delete_breakpoint (b);
13959         }
13960     }
13961   else
13962     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13963 }
13964
13965 static int
13966 all_locations_are_pending (struct bp_location *loc)
13967 {
13968   for (; loc; loc = loc->next)
13969     if (!loc->shlib_disabled
13970         && !loc->pspace->executing_startup)
13971       return 0;
13972   return 1;
13973 }
13974
13975 /* Subroutine of update_breakpoint_locations to simplify it.
13976    Return non-zero if multiple fns in list LOC have the same name.
13977    Null names are ignored.  */
13978
13979 static int
13980 ambiguous_names_p (struct bp_location *loc)
13981 {
13982   struct bp_location *l;
13983   htab_t htab = htab_create_alloc (13, htab_hash_string,
13984                                    (int (*) (const void *, 
13985                                              const void *)) streq,
13986                                    NULL, xcalloc, xfree);
13987
13988   for (l = loc; l != NULL; l = l->next)
13989     {
13990       const char **slot;
13991       const char *name = l->function_name;
13992
13993       /* Allow for some names to be NULL, ignore them.  */
13994       if (name == NULL)
13995         continue;
13996
13997       slot = (const char **) htab_find_slot (htab, (const void *) name,
13998                                              INSERT);
13999       /* NOTE: We can assume slot != NULL here because xcalloc never
14000          returns NULL.  */
14001       if (*slot != NULL)
14002         {
14003           htab_delete (htab);
14004           return 1;
14005         }
14006       *slot = name;
14007     }
14008
14009   htab_delete (htab);
14010   return 0;
14011 }
14012
14013 /* When symbols change, it probably means the sources changed as well,
14014    and it might mean the static tracepoint markers are no longer at
14015    the same address or line numbers they used to be at last we
14016    checked.  Losing your static tracepoints whenever you rebuild is
14017    undesirable.  This function tries to resync/rematch gdb static
14018    tracepoints with the markers on the target, for static tracepoints
14019    that have not been set by marker id.  Static tracepoint that have
14020    been set by marker id are reset by marker id in breakpoint_re_set.
14021    The heuristic is:
14022
14023    1) For a tracepoint set at a specific address, look for a marker at
14024    the old PC.  If one is found there, assume to be the same marker.
14025    If the name / string id of the marker found is different from the
14026    previous known name, assume that means the user renamed the marker
14027    in the sources, and output a warning.
14028
14029    2) For a tracepoint set at a given line number, look for a marker
14030    at the new address of the old line number.  If one is found there,
14031    assume to be the same marker.  If the name / string id of the
14032    marker found is different from the previous known name, assume that
14033    means the user renamed the marker in the sources, and output a
14034    warning.
14035
14036    3) If a marker is no longer found at the same address or line, it
14037    may mean the marker no longer exists.  But it may also just mean
14038    the code changed a bit.  Maybe the user added a few lines of code
14039    that made the marker move up or down (in line number terms).  Ask
14040    the target for info about the marker with the string id as we knew
14041    it.  If found, update line number and address in the matching
14042    static tracepoint.  This will get confused if there's more than one
14043    marker with the same ID (possible in UST, although unadvised
14044    precisely because it confuses tools).  */
14045
14046 static struct symtab_and_line
14047 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14048 {
14049   struct tracepoint *tp = (struct tracepoint *) b;
14050   struct static_tracepoint_marker marker;
14051   CORE_ADDR pc;
14052
14053   pc = sal.pc;
14054   if (sal.line)
14055     find_line_pc (sal.symtab, sal.line, &pc);
14056
14057   if (target_static_tracepoint_marker_at (pc, &marker))
14058     {
14059       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14060         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14061                  b->number,
14062                  tp->static_trace_marker_id, marker.str_id);
14063
14064       xfree (tp->static_trace_marker_id);
14065       tp->static_trace_marker_id = xstrdup (marker.str_id);
14066       release_static_tracepoint_marker (&marker);
14067
14068       return sal;
14069     }
14070
14071   /* Old marker wasn't found on target at lineno.  Try looking it up
14072      by string ID.  */
14073   if (!sal.explicit_pc
14074       && sal.line != 0
14075       && sal.symtab != NULL
14076       && tp->static_trace_marker_id != NULL)
14077     {
14078       VEC(static_tracepoint_marker_p) *markers;
14079
14080       markers
14081         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14082
14083       if (!VEC_empty(static_tracepoint_marker_p, markers))
14084         {
14085           struct symtab_and_line sal2;
14086           struct symbol *sym;
14087           struct static_tracepoint_marker *tpmarker;
14088           struct ui_out *uiout = current_uiout;
14089
14090           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14091
14092           xfree (tp->static_trace_marker_id);
14093           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14094
14095           warning (_("marker for static tracepoint %d (%s) not "
14096                      "found at previous line number"),
14097                    b->number, tp->static_trace_marker_id);
14098
14099           init_sal (&sal2);
14100
14101           sal2.pc = tpmarker->address;
14102
14103           sal2 = find_pc_line (tpmarker->address, 0);
14104           sym = find_pc_sect_function (tpmarker->address, NULL);
14105           ui_out_text (uiout, "Now in ");
14106           if (sym)
14107             {
14108               ui_out_field_string (uiout, "func",
14109                                    SYMBOL_PRINT_NAME (sym));
14110               ui_out_text (uiout, " at ");
14111             }
14112           ui_out_field_string (uiout, "file",
14113                                symtab_to_filename_for_display (sal2.symtab));
14114           ui_out_text (uiout, ":");
14115
14116           if (ui_out_is_mi_like_p (uiout))
14117             {
14118               const char *fullname = symtab_to_fullname (sal2.symtab);
14119
14120               ui_out_field_string (uiout, "fullname", fullname);
14121             }
14122
14123           ui_out_field_int (uiout, "line", sal2.line);
14124           ui_out_text (uiout, "\n");
14125
14126           b->loc->line_number = sal2.line;
14127           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14128
14129           xfree (b->addr_string);
14130           b->addr_string = xstrprintf ("%s:%d",
14131                                    symtab_to_filename_for_display (sal2.symtab),
14132                                        b->loc->line_number);
14133
14134           /* Might be nice to check if function changed, and warn if
14135              so.  */
14136
14137           release_static_tracepoint_marker (tpmarker);
14138         }
14139     }
14140   return sal;
14141 }
14142
14143 /* Returns 1 iff locations A and B are sufficiently same that
14144    we don't need to report breakpoint as changed.  */
14145
14146 static int
14147 locations_are_equal (struct bp_location *a, struct bp_location *b)
14148 {
14149   while (a && b)
14150     {
14151       if (a->address != b->address)
14152         return 0;
14153
14154       if (a->shlib_disabled != b->shlib_disabled)
14155         return 0;
14156
14157       if (a->enabled != b->enabled)
14158         return 0;
14159
14160       a = a->next;
14161       b = b->next;
14162     }
14163
14164   if ((a == NULL) != (b == NULL))
14165     return 0;
14166
14167   return 1;
14168 }
14169
14170 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14171    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14172    a ranged breakpoint.  */
14173
14174 void
14175 update_breakpoint_locations (struct breakpoint *b,
14176                              struct symtabs_and_lines sals,
14177                              struct symtabs_and_lines sals_end)
14178 {
14179   int i;
14180   struct bp_location *existing_locations = b->loc;
14181
14182   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14183     {
14184       /* Ranged breakpoints have only one start location and one end
14185          location.  */
14186       b->enable_state = bp_disabled;
14187       update_global_location_list (1);
14188       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14189                            "multiple locations found\n"),
14190                          b->number);
14191       return;
14192     }
14193
14194   /* If there's no new locations, and all existing locations are
14195      pending, don't do anything.  This optimizes the common case where
14196      all locations are in the same shared library, that was unloaded.
14197      We'd like to retain the location, so that when the library is
14198      loaded again, we don't loose the enabled/disabled status of the
14199      individual locations.  */
14200   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14201     return;
14202
14203   b->loc = NULL;
14204
14205   for (i = 0; i < sals.nelts; ++i)
14206     {
14207       struct bp_location *new_loc;
14208
14209       switch_to_program_space_and_thread (sals.sals[i].pspace);
14210
14211       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14212
14213       /* Reparse conditions, they might contain references to the
14214          old symtab.  */
14215       if (b->cond_string != NULL)
14216         {
14217           const char *s;
14218           volatile struct gdb_exception e;
14219
14220           s = b->cond_string;
14221           TRY_CATCH (e, RETURN_MASK_ERROR)
14222             {
14223               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14224                                            block_for_pc (sals.sals[i].pc), 
14225                                            0);
14226             }
14227           if (e.reason < 0)
14228             {
14229               warning (_("failed to reevaluate condition "
14230                          "for breakpoint %d: %s"), 
14231                        b->number, e.message);
14232               new_loc->enabled = 0;
14233             }
14234         }
14235
14236       if (sals_end.nelts)
14237         {
14238           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14239
14240           new_loc->length = end - sals.sals[0].pc + 1;
14241         }
14242     }
14243
14244   /* Update locations of permanent breakpoints.  */
14245   if (b->enable_state == bp_permanent)
14246     make_breakpoint_permanent (b);
14247
14248   /* If possible, carry over 'disable' status from existing
14249      breakpoints.  */
14250   {
14251     struct bp_location *e = existing_locations;
14252     /* If there are multiple breakpoints with the same function name,
14253        e.g. for inline functions, comparing function names won't work.
14254        Instead compare pc addresses; this is just a heuristic as things
14255        may have moved, but in practice it gives the correct answer
14256        often enough until a better solution is found.  */
14257     int have_ambiguous_names = ambiguous_names_p (b->loc);
14258
14259     for (; e; e = e->next)
14260       {
14261         if (!e->enabled && e->function_name)
14262           {
14263             struct bp_location *l = b->loc;
14264             if (have_ambiguous_names)
14265               {
14266                 for (; l; l = l->next)
14267                   if (breakpoint_locations_match (e, l))
14268                     {
14269                       l->enabled = 0;
14270                       break;
14271                     }
14272               }
14273             else
14274               {
14275                 for (; l; l = l->next)
14276                   if (l->function_name
14277                       && strcmp (e->function_name, l->function_name) == 0)
14278                     {
14279                       l->enabled = 0;
14280                       break;
14281                     }
14282               }
14283           }
14284       }
14285   }
14286
14287   if (!locations_are_equal (existing_locations, b->loc))
14288     observer_notify_breakpoint_modified (b);
14289
14290   update_global_location_list (1);
14291 }
14292
14293 /* Find the SaL locations corresponding to the given ADDR_STRING.
14294    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14295
14296 static struct symtabs_and_lines
14297 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14298 {
14299   char *s;
14300   struct symtabs_and_lines sals = {0};
14301   volatile struct gdb_exception e;
14302
14303   gdb_assert (b->ops != NULL);
14304   s = addr_string;
14305
14306   TRY_CATCH (e, RETURN_MASK_ERROR)
14307     {
14308       b->ops->decode_linespec (b, &s, &sals);
14309     }
14310   if (e.reason < 0)
14311     {
14312       int not_found_and_ok = 0;
14313       /* For pending breakpoints, it's expected that parsing will
14314          fail until the right shared library is loaded.  User has
14315          already told to create pending breakpoints and don't need
14316          extra messages.  If breakpoint is in bp_shlib_disabled
14317          state, then user already saw the message about that
14318          breakpoint being disabled, and don't want to see more
14319          errors.  */
14320       if (e.error == NOT_FOUND_ERROR
14321           && (b->condition_not_parsed 
14322               || (b->loc && b->loc->shlib_disabled)
14323               || (b->loc && b->loc->pspace->executing_startup)
14324               || b->enable_state == bp_disabled))
14325         not_found_and_ok = 1;
14326
14327       if (!not_found_and_ok)
14328         {
14329           /* We surely don't want to warn about the same breakpoint
14330              10 times.  One solution, implemented here, is disable
14331              the breakpoint on error.  Another solution would be to
14332              have separate 'warning emitted' flag.  Since this
14333              happens only when a binary has changed, I don't know
14334              which approach is better.  */
14335           b->enable_state = bp_disabled;
14336           throw_exception (e);
14337         }
14338     }
14339
14340   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14341     {
14342       int i;
14343
14344       for (i = 0; i < sals.nelts; ++i)
14345         resolve_sal_pc (&sals.sals[i]);
14346       if (b->condition_not_parsed && s && s[0])
14347         {
14348           char *cond_string, *extra_string;
14349           int thread, task;
14350
14351           find_condition_and_thread (s, sals.sals[0].pc,
14352                                      &cond_string, &thread, &task,
14353                                      &extra_string);
14354           if (cond_string)
14355             b->cond_string = cond_string;
14356           b->thread = thread;
14357           b->task = task;
14358           if (extra_string)
14359             b->extra_string = extra_string;
14360           b->condition_not_parsed = 0;
14361         }
14362
14363       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14364         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14365
14366       *found = 1;
14367     }
14368   else
14369     *found = 0;
14370
14371   return sals;
14372 }
14373
14374 /* The default re_set method, for typical hardware or software
14375    breakpoints.  Reevaluate the breakpoint and recreate its
14376    locations.  */
14377
14378 static void
14379 breakpoint_re_set_default (struct breakpoint *b)
14380 {
14381   int found;
14382   struct symtabs_and_lines sals, sals_end;
14383   struct symtabs_and_lines expanded = {0};
14384   struct symtabs_and_lines expanded_end = {0};
14385
14386   sals = addr_string_to_sals (b, b->addr_string, &found);
14387   if (found)
14388     {
14389       make_cleanup (xfree, sals.sals);
14390       expanded = sals;
14391     }
14392
14393   if (b->addr_string_range_end)
14394     {
14395       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14396       if (found)
14397         {
14398           make_cleanup (xfree, sals_end.sals);
14399           expanded_end = sals_end;
14400         }
14401     }
14402
14403   update_breakpoint_locations (b, expanded, expanded_end);
14404 }
14405
14406 /* Default method for creating SALs from an address string.  It basically
14407    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14408
14409 static void
14410 create_sals_from_address_default (char **arg,
14411                                   struct linespec_result *canonical,
14412                                   enum bptype type_wanted,
14413                                   char *addr_start, char **copy_arg)
14414 {
14415   parse_breakpoint_sals (arg, canonical);
14416 }
14417
14418 /* Call create_breakpoints_sal for the given arguments.  This is the default
14419    function for the `create_breakpoints_sal' method of
14420    breakpoint_ops.  */
14421
14422 static void
14423 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14424                                 struct linespec_result *canonical,
14425                                 char *cond_string,
14426                                 char *extra_string,
14427                                 enum bptype type_wanted,
14428                                 enum bpdisp disposition,
14429                                 int thread,
14430                                 int task, int ignore_count,
14431                                 const struct breakpoint_ops *ops,
14432                                 int from_tty, int enabled,
14433                                 int internal, unsigned flags)
14434 {
14435   create_breakpoints_sal (gdbarch, canonical, cond_string,
14436                           extra_string,
14437                           type_wanted, disposition,
14438                           thread, task, ignore_count, ops, from_tty,
14439                           enabled, internal, flags);
14440 }
14441
14442 /* Decode the line represented by S by calling decode_line_full.  This is the
14443    default function for the `decode_linespec' method of breakpoint_ops.  */
14444
14445 static void
14446 decode_linespec_default (struct breakpoint *b, char **s,
14447                          struct symtabs_and_lines *sals)
14448 {
14449   struct linespec_result canonical;
14450
14451   init_linespec_result (&canonical);
14452   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14453                     (struct symtab *) NULL, 0,
14454                     &canonical, multiple_symbols_all,
14455                     b->filter);
14456
14457   /* We should get 0 or 1 resulting SALs.  */
14458   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14459
14460   if (VEC_length (linespec_sals, canonical.sals) > 0)
14461     {
14462       struct linespec_sals *lsal;
14463
14464       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14465       *sals = lsal->sals;
14466       /* Arrange it so the destructor does not free the
14467          contents.  */
14468       lsal->sals.sals = NULL;
14469     }
14470
14471   destroy_linespec_result (&canonical);
14472 }
14473
14474 /* Prepare the global context for a re-set of breakpoint B.  */
14475
14476 static struct cleanup *
14477 prepare_re_set_context (struct breakpoint *b)
14478 {
14479   struct cleanup *cleanups;
14480
14481   input_radix = b->input_radix;
14482   cleanups = save_current_space_and_thread ();
14483   if (b->pspace != NULL)
14484     switch_to_program_space_and_thread (b->pspace);
14485   set_language (b->language);
14486
14487   return cleanups;
14488 }
14489
14490 /* Reset a breakpoint given it's struct breakpoint * BINT.
14491    The value we return ends up being the return value from catch_errors.
14492    Unused in this case.  */
14493
14494 static int
14495 breakpoint_re_set_one (void *bint)
14496 {
14497   /* Get past catch_errs.  */
14498   struct breakpoint *b = (struct breakpoint *) bint;
14499   struct cleanup *cleanups;
14500
14501   cleanups = prepare_re_set_context (b);
14502   b->ops->re_set (b);
14503   do_cleanups (cleanups);
14504   return 0;
14505 }
14506
14507 /* Re-set all breakpoints after symbols have been re-loaded.  */
14508 void
14509 breakpoint_re_set (void)
14510 {
14511   struct breakpoint *b, *b_tmp;
14512   enum language save_language;
14513   int save_input_radix;
14514   struct cleanup *old_chain;
14515
14516   save_language = current_language->la_language;
14517   save_input_radix = input_radix;
14518   old_chain = save_current_program_space ();
14519
14520   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14521   {
14522     /* Format possible error msg.  */
14523     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14524                                 b->number);
14525     struct cleanup *cleanups = make_cleanup (xfree, message);
14526     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14527     do_cleanups (cleanups);
14528   }
14529   set_language (save_language);
14530   input_radix = save_input_radix;
14531
14532   jit_breakpoint_re_set ();
14533
14534   do_cleanups (old_chain);
14535
14536   create_overlay_event_breakpoint ();
14537   create_longjmp_master_breakpoint ();
14538   create_std_terminate_master_breakpoint ();
14539   create_exception_master_breakpoint ();
14540 }
14541 \f
14542 /* Reset the thread number of this breakpoint:
14543
14544    - If the breakpoint is for all threads, leave it as-is.
14545    - Else, reset it to the current thread for inferior_ptid.  */
14546 void
14547 breakpoint_re_set_thread (struct breakpoint *b)
14548 {
14549   if (b->thread != -1)
14550     {
14551       if (in_thread_list (inferior_ptid))
14552         b->thread = pid_to_thread_id (inferior_ptid);
14553
14554       /* We're being called after following a fork.  The new fork is
14555          selected as current, and unless this was a vfork will have a
14556          different program space from the original thread.  Reset that
14557          as well.  */
14558       b->loc->pspace = current_program_space;
14559     }
14560 }
14561
14562 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14563    If from_tty is nonzero, it prints a message to that effect,
14564    which ends with a period (no newline).  */
14565
14566 void
14567 set_ignore_count (int bptnum, int count, int from_tty)
14568 {
14569   struct breakpoint *b;
14570
14571   if (count < 0)
14572     count = 0;
14573
14574   ALL_BREAKPOINTS (b)
14575     if (b->number == bptnum)
14576     {
14577       if (is_tracepoint (b))
14578         {
14579           if (from_tty && count != 0)
14580             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14581                              bptnum);
14582           return;
14583         }
14584       
14585       b->ignore_count = count;
14586       if (from_tty)
14587         {
14588           if (count == 0)
14589             printf_filtered (_("Will stop next time "
14590                                "breakpoint %d is reached."),
14591                              bptnum);
14592           else if (count == 1)
14593             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14594                              bptnum);
14595           else
14596             printf_filtered (_("Will ignore next %d "
14597                                "crossings of breakpoint %d."),
14598                              count, bptnum);
14599         }
14600       observer_notify_breakpoint_modified (b);
14601       return;
14602     }
14603
14604   error (_("No breakpoint number %d."), bptnum);
14605 }
14606
14607 /* Command to set ignore-count of breakpoint N to COUNT.  */
14608
14609 static void
14610 ignore_command (char *args, int from_tty)
14611 {
14612   char *p = args;
14613   int num;
14614
14615   if (p == 0)
14616     error_no_arg (_("a breakpoint number"));
14617
14618   num = get_number (&p);
14619   if (num == 0)
14620     error (_("bad breakpoint number: '%s'"), args);
14621   if (*p == 0)
14622     error (_("Second argument (specified ignore-count) is missing."));
14623
14624   set_ignore_count (num,
14625                     longest_to_int (value_as_long (parse_and_eval (p))),
14626                     from_tty);
14627   if (from_tty)
14628     printf_filtered ("\n");
14629 }
14630 \f
14631 /* Call FUNCTION on each of the breakpoints
14632    whose numbers are given in ARGS.  */
14633
14634 static void
14635 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14636                                                       void *),
14637                         void *data)
14638 {
14639   int num;
14640   struct breakpoint *b, *tmp;
14641   int match;
14642   struct get_number_or_range_state state;
14643
14644   if (args == 0)
14645     error_no_arg (_("one or more breakpoint numbers"));
14646
14647   init_number_or_range (&state, args);
14648
14649   while (!state.finished)
14650     {
14651       char *p = state.string;
14652
14653       match = 0;
14654
14655       num = get_number_or_range (&state);
14656       if (num == 0)
14657         {
14658           warning (_("bad breakpoint number at or near '%s'"), p);
14659         }
14660       else
14661         {
14662           ALL_BREAKPOINTS_SAFE (b, tmp)
14663             if (b->number == num)
14664               {
14665                 match = 1;
14666                 function (b, data);
14667                 break;
14668               }
14669           if (match == 0)
14670             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14671         }
14672     }
14673 }
14674
14675 static struct bp_location *
14676 find_location_by_number (char *number)
14677 {
14678   char *dot = strchr (number, '.');
14679   char *p1;
14680   int bp_num;
14681   int loc_num;
14682   struct breakpoint *b;
14683   struct bp_location *loc;  
14684
14685   *dot = '\0';
14686
14687   p1 = number;
14688   bp_num = get_number (&p1);
14689   if (bp_num == 0)
14690     error (_("Bad breakpoint number '%s'"), number);
14691
14692   ALL_BREAKPOINTS (b)
14693     if (b->number == bp_num)
14694       {
14695         break;
14696       }
14697
14698   if (!b || b->number != bp_num)
14699     error (_("Bad breakpoint number '%s'"), number);
14700   
14701   p1 = dot+1;
14702   loc_num = get_number (&p1);
14703   if (loc_num == 0)
14704     error (_("Bad breakpoint location number '%s'"), number);
14705
14706   --loc_num;
14707   loc = b->loc;
14708   for (;loc_num && loc; --loc_num, loc = loc->next)
14709     ;
14710   if (!loc)
14711     error (_("Bad breakpoint location number '%s'"), dot+1);
14712     
14713   return loc;  
14714 }
14715
14716
14717 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14718    If from_tty is nonzero, it prints a message to that effect,
14719    which ends with a period (no newline).  */
14720
14721 void
14722 disable_breakpoint (struct breakpoint *bpt)
14723 {
14724   /* Never disable a watchpoint scope breakpoint; we want to
14725      hit them when we leave scope so we can delete both the
14726      watchpoint and its scope breakpoint at that time.  */
14727   if (bpt->type == bp_watchpoint_scope)
14728     return;
14729
14730   /* You can't disable permanent breakpoints.  */
14731   if (bpt->enable_state == bp_permanent)
14732     return;
14733
14734   bpt->enable_state = bp_disabled;
14735
14736   /* Mark breakpoint locations modified.  */
14737   mark_breakpoint_modified (bpt);
14738
14739   if (target_supports_enable_disable_tracepoint ()
14740       && current_trace_status ()->running && is_tracepoint (bpt))
14741     {
14742       struct bp_location *location;
14743      
14744       for (location = bpt->loc; location; location = location->next)
14745         target_disable_tracepoint (location);
14746     }
14747
14748   update_global_location_list (0);
14749
14750   observer_notify_breakpoint_modified (bpt);
14751 }
14752
14753 /* A callback for iterate_over_related_breakpoints.  */
14754
14755 static void
14756 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14757 {
14758   disable_breakpoint (b);
14759 }
14760
14761 /* A callback for map_breakpoint_numbers that calls
14762    disable_breakpoint.  */
14763
14764 static void
14765 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14766 {
14767   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14768 }
14769
14770 static void
14771 disable_command (char *args, int from_tty)
14772 {
14773   if (args == 0)
14774     {
14775       struct breakpoint *bpt;
14776
14777       ALL_BREAKPOINTS (bpt)
14778         if (user_breakpoint_p (bpt))
14779           disable_breakpoint (bpt);
14780     }
14781   else
14782     {
14783       char *num = extract_arg (&args);
14784
14785       while (num)
14786         {
14787           if (strchr (num, '.'))
14788             {
14789               struct bp_location *loc = find_location_by_number (num);
14790
14791               if (loc)
14792                 {
14793                   if (loc->enabled)
14794                     {
14795                       loc->enabled = 0;
14796                       mark_breakpoint_location_modified (loc);
14797                     }
14798                   if (target_supports_enable_disable_tracepoint ()
14799                       && current_trace_status ()->running && loc->owner
14800                       && is_tracepoint (loc->owner))
14801                     target_disable_tracepoint (loc);
14802                 }
14803               update_global_location_list (0);
14804             }
14805           else
14806             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
14807           num = extract_arg (&args);
14808         }
14809     }
14810 }
14811
14812 static void
14813 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14814                         int count)
14815 {
14816   int target_resources_ok;
14817
14818   if (bpt->type == bp_hardware_breakpoint)
14819     {
14820       int i;
14821       i = hw_breakpoint_used_count ();
14822       target_resources_ok = 
14823         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14824                                             i + 1, 0);
14825       if (target_resources_ok == 0)
14826         error (_("No hardware breakpoint support in the target."));
14827       else if (target_resources_ok < 0)
14828         error (_("Hardware breakpoints used exceeds limit."));
14829     }
14830
14831   if (is_watchpoint (bpt))
14832     {
14833       /* Initialize it just to avoid a GCC false warning.  */
14834       enum enable_state orig_enable_state = 0;
14835       volatile struct gdb_exception e;
14836
14837       TRY_CATCH (e, RETURN_MASK_ALL)
14838         {
14839           struct watchpoint *w = (struct watchpoint *) bpt;
14840
14841           orig_enable_state = bpt->enable_state;
14842           bpt->enable_state = bp_enabled;
14843           update_watchpoint (w, 1 /* reparse */);
14844         }
14845       if (e.reason < 0)
14846         {
14847           bpt->enable_state = orig_enable_state;
14848           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14849                              bpt->number);
14850           return;
14851         }
14852     }
14853
14854   if (bpt->enable_state != bp_permanent)
14855     bpt->enable_state = bp_enabled;
14856
14857   bpt->enable_state = bp_enabled;
14858
14859   /* Mark breakpoint locations modified.  */
14860   mark_breakpoint_modified (bpt);
14861
14862   if (target_supports_enable_disable_tracepoint ()
14863       && current_trace_status ()->running && is_tracepoint (bpt))
14864     {
14865       struct bp_location *location;
14866
14867       for (location = bpt->loc; location; location = location->next)
14868         target_enable_tracepoint (location);
14869     }
14870
14871   bpt->disposition = disposition;
14872   bpt->enable_count = count;
14873   update_global_location_list (1);
14874
14875   observer_notify_breakpoint_modified (bpt);
14876 }
14877
14878
14879 void
14880 enable_breakpoint (struct breakpoint *bpt)
14881 {
14882   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14883 }
14884
14885 static void
14886 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14887 {
14888   enable_breakpoint (bpt);
14889 }
14890
14891 /* A callback for map_breakpoint_numbers that calls
14892    enable_breakpoint.  */
14893
14894 static void
14895 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14896 {
14897   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14898 }
14899
14900 /* The enable command enables the specified breakpoints (or all defined
14901    breakpoints) so they once again become (or continue to be) effective
14902    in stopping the inferior.  */
14903
14904 static void
14905 enable_command (char *args, int from_tty)
14906 {
14907   if (args == 0)
14908     {
14909       struct breakpoint *bpt;
14910
14911       ALL_BREAKPOINTS (bpt)
14912         if (user_breakpoint_p (bpt))
14913           enable_breakpoint (bpt);
14914     }
14915   else
14916     {
14917       char *num = extract_arg (&args);
14918
14919       while (num)
14920         {
14921           if (strchr (num, '.'))
14922             {
14923               struct bp_location *loc = find_location_by_number (num);
14924
14925               if (loc)
14926                 {
14927                   if (!loc->enabled)
14928                     {
14929                       loc->enabled = 1;
14930                       mark_breakpoint_location_modified (loc);
14931                     }
14932                   if (target_supports_enable_disable_tracepoint ()
14933                       && current_trace_status ()->running && loc->owner
14934                       && is_tracepoint (loc->owner))
14935                     target_enable_tracepoint (loc);
14936                 }
14937               update_global_location_list (1);
14938             }
14939           else
14940             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
14941           num = extract_arg (&args);
14942         }
14943     }
14944 }
14945
14946 /* This struct packages up disposition data for application to multiple
14947    breakpoints.  */
14948
14949 struct disp_data
14950 {
14951   enum bpdisp disp;
14952   int count;
14953 };
14954
14955 static void
14956 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14957 {
14958   struct disp_data disp_data = *(struct disp_data *) arg;
14959
14960   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14961 }
14962
14963 static void
14964 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14965 {
14966   struct disp_data disp = { disp_disable, 1 };
14967
14968   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14969 }
14970
14971 static void
14972 enable_once_command (char *args, int from_tty)
14973 {
14974   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14975 }
14976
14977 static void
14978 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14979 {
14980   struct disp_data disp = { disp_disable, *(int *) countptr };
14981
14982   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14983 }
14984
14985 static void
14986 enable_count_command (char *args, int from_tty)
14987 {
14988   int count = get_number (&args);
14989
14990   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14991 }
14992
14993 static void
14994 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14995 {
14996   struct disp_data disp = { disp_del, 1 };
14997
14998   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14999 }
15000
15001 static void
15002 enable_delete_command (char *args, int from_tty)
15003 {
15004   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15005 }
15006 \f
15007 static void
15008 set_breakpoint_cmd (char *args, int from_tty)
15009 {
15010 }
15011
15012 static void
15013 show_breakpoint_cmd (char *args, int from_tty)
15014 {
15015 }
15016
15017 /* Invalidate last known value of any hardware watchpoint if
15018    the memory which that value represents has been written to by
15019    GDB itself.  */
15020
15021 static void
15022 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15023                                       CORE_ADDR addr, ssize_t len,
15024                                       const bfd_byte *data)
15025 {
15026   struct breakpoint *bp;
15027
15028   ALL_BREAKPOINTS (bp)
15029     if (bp->enable_state == bp_enabled
15030         && bp->type == bp_hardware_watchpoint)
15031       {
15032         struct watchpoint *wp = (struct watchpoint *) bp;
15033
15034         if (wp->val_valid && wp->val)
15035           {
15036             struct bp_location *loc;
15037
15038             for (loc = bp->loc; loc != NULL; loc = loc->next)
15039               if (loc->loc_type == bp_loc_hardware_watchpoint
15040                   && loc->address + loc->length > addr
15041                   && addr + len > loc->address)
15042                 {
15043                   value_free (wp->val);
15044                   wp->val = NULL;
15045                   wp->val_valid = 0;
15046                 }
15047           }
15048       }
15049 }
15050
15051 /* Create and insert a raw software breakpoint at PC.  Return an
15052    identifier, which should be used to remove the breakpoint later.
15053    In general, places which call this should be using something on the
15054    breakpoint chain instead; this function should be eliminated
15055    someday.  */
15056
15057 void *
15058 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15059                                   struct address_space *aspace, CORE_ADDR pc)
15060 {
15061   struct bp_target_info *bp_tgt;
15062
15063   bp_tgt = XCNEW (struct bp_target_info);
15064
15065   bp_tgt->placed_address_space = aspace;
15066   bp_tgt->placed_address = pc;
15067
15068   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15069     {
15070       /* Could not insert the breakpoint.  */
15071       xfree (bp_tgt);
15072       return NULL;
15073     }
15074
15075   return bp_tgt;
15076 }
15077
15078 /* Remove a breakpoint BP inserted by
15079    deprecated_insert_raw_breakpoint.  */
15080
15081 int
15082 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15083 {
15084   struct bp_target_info *bp_tgt = bp;
15085   int ret;
15086
15087   ret = target_remove_breakpoint (gdbarch, bp_tgt);
15088   xfree (bp_tgt);
15089
15090   return ret;
15091 }
15092
15093 /* Create and insert a breakpoint for software single step.  */
15094
15095 void
15096 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15097                                struct address_space *aspace, 
15098                                CORE_ADDR next_pc)
15099 {
15100   void **bpt_p;
15101
15102   if (single_step_breakpoints[0] == NULL)
15103     {
15104       bpt_p = &single_step_breakpoints[0];
15105       single_step_gdbarch[0] = gdbarch;
15106     }
15107   else
15108     {
15109       gdb_assert (single_step_breakpoints[1] == NULL);
15110       bpt_p = &single_step_breakpoints[1];
15111       single_step_gdbarch[1] = gdbarch;
15112     }
15113
15114   /* NOTE drow/2006-04-11: A future improvement to this function would
15115      be to only create the breakpoints once, and actually put them on
15116      the breakpoint chain.  That would let us use set_raw_breakpoint.
15117      We could adjust the addresses each time they were needed.  Doing
15118      this requires corresponding changes elsewhere where single step
15119      breakpoints are handled, however.  So, for now, we use this.  */
15120
15121   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15122   if (*bpt_p == NULL)
15123     error (_("Could not insert single-step breakpoint at %s"),
15124              paddress (gdbarch, next_pc));
15125 }
15126
15127 /* Check if the breakpoints used for software single stepping
15128    were inserted or not.  */
15129
15130 int
15131 single_step_breakpoints_inserted (void)
15132 {
15133   return (single_step_breakpoints[0] != NULL
15134           || single_step_breakpoints[1] != NULL);
15135 }
15136
15137 /* Remove and delete any breakpoints used for software single step.  */
15138
15139 void
15140 remove_single_step_breakpoints (void)
15141 {
15142   gdb_assert (single_step_breakpoints[0] != NULL);
15143
15144   /* See insert_single_step_breakpoint for more about this deprecated
15145      call.  */
15146   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15147                                     single_step_breakpoints[0]);
15148   single_step_gdbarch[0] = NULL;
15149   single_step_breakpoints[0] = NULL;
15150
15151   if (single_step_breakpoints[1] != NULL)
15152     {
15153       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15154                                         single_step_breakpoints[1]);
15155       single_step_gdbarch[1] = NULL;
15156       single_step_breakpoints[1] = NULL;
15157     }
15158 }
15159
15160 /* Delete software single step breakpoints without removing them from
15161    the inferior.  This is intended to be used if the inferior's address
15162    space where they were inserted is already gone, e.g. after exit or
15163    exec.  */
15164
15165 void
15166 cancel_single_step_breakpoints (void)
15167 {
15168   int i;
15169
15170   for (i = 0; i < 2; i++)
15171     if (single_step_breakpoints[i])
15172       {
15173         xfree (single_step_breakpoints[i]);
15174         single_step_breakpoints[i] = NULL;
15175         single_step_gdbarch[i] = NULL;
15176       }
15177 }
15178
15179 /* Detach software single-step breakpoints from INFERIOR_PTID without
15180    removing them.  */
15181
15182 static void
15183 detach_single_step_breakpoints (void)
15184 {
15185   int i;
15186
15187   for (i = 0; i < 2; i++)
15188     if (single_step_breakpoints[i])
15189       target_remove_breakpoint (single_step_gdbarch[i],
15190                                 single_step_breakpoints[i]);
15191 }
15192
15193 /* Check whether a software single-step breakpoint is inserted at
15194    PC.  */
15195
15196 int
15197 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
15198                                         CORE_ADDR pc)
15199 {
15200   int i;
15201
15202   for (i = 0; i < 2; i++)
15203     {
15204       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15205       if (bp_tgt
15206           && breakpoint_address_match (bp_tgt->placed_address_space,
15207                                        bp_tgt->placed_address,
15208                                        aspace, pc))
15209         return 1;
15210     }
15211
15212   return 0;
15213 }
15214
15215 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15216    non-zero otherwise.  */
15217 static int
15218 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15219 {
15220   if (syscall_catchpoint_p (bp)
15221       && bp->enable_state != bp_disabled
15222       && bp->enable_state != bp_call_disabled)
15223     return 1;
15224   else
15225     return 0;
15226 }
15227
15228 int
15229 catch_syscall_enabled (void)
15230 {
15231   struct catch_syscall_inferior_data *inf_data
15232     = get_catch_syscall_inferior_data (current_inferior ());
15233
15234   return inf_data->total_syscalls_count != 0;
15235 }
15236
15237 int
15238 catching_syscall_number (int syscall_number)
15239 {
15240   struct breakpoint *bp;
15241
15242   ALL_BREAKPOINTS (bp)
15243     if (is_syscall_catchpoint_enabled (bp))
15244       {
15245         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15246
15247         if (c->syscalls_to_be_caught)
15248           {
15249             int i, iter;
15250             for (i = 0;
15251                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15252                  i++)
15253               if (syscall_number == iter)
15254                 return 1;
15255           }
15256         else
15257           return 1;
15258       }
15259
15260   return 0;
15261 }
15262
15263 /* Complete syscall names.  Used by "catch syscall".  */
15264 static VEC (char_ptr) *
15265 catch_syscall_completer (struct cmd_list_element *cmd,
15266                          const char *text, const char *word)
15267 {
15268   const char **list = get_syscall_names ();
15269   VEC (char_ptr) *retlist
15270     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15271
15272   xfree (list);
15273   return retlist;
15274 }
15275
15276 /* Tracepoint-specific operations.  */
15277
15278 /* Set tracepoint count to NUM.  */
15279 static void
15280 set_tracepoint_count (int num)
15281 {
15282   tracepoint_count = num;
15283   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15284 }
15285
15286 static void
15287 trace_command (char *arg, int from_tty)
15288 {
15289   struct breakpoint_ops *ops;
15290   const char *arg_cp = arg;
15291
15292   if (arg && probe_linespec_to_ops (&arg_cp))
15293     ops = &tracepoint_probe_breakpoint_ops;
15294   else
15295     ops = &tracepoint_breakpoint_ops;
15296
15297   create_breakpoint (get_current_arch (),
15298                      arg,
15299                      NULL, 0, NULL, 1 /* parse arg */,
15300                      0 /* tempflag */,
15301                      bp_tracepoint /* type_wanted */,
15302                      0 /* Ignore count */,
15303                      pending_break_support,
15304                      ops,
15305                      from_tty,
15306                      1 /* enabled */,
15307                      0 /* internal */, 0);
15308 }
15309
15310 static void
15311 ftrace_command (char *arg, int from_tty)
15312 {
15313   create_breakpoint (get_current_arch (),
15314                      arg,
15315                      NULL, 0, NULL, 1 /* parse arg */,
15316                      0 /* tempflag */,
15317                      bp_fast_tracepoint /* type_wanted */,
15318                      0 /* Ignore count */,
15319                      pending_break_support,
15320                      &tracepoint_breakpoint_ops,
15321                      from_tty,
15322                      1 /* enabled */,
15323                      0 /* internal */, 0);
15324 }
15325
15326 /* strace command implementation.  Creates a static tracepoint.  */
15327
15328 static void
15329 strace_command (char *arg, int from_tty)
15330 {
15331   struct breakpoint_ops *ops;
15332
15333   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15334      or with a normal static tracepoint.  */
15335   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15336     ops = &strace_marker_breakpoint_ops;
15337   else
15338     ops = &tracepoint_breakpoint_ops;
15339
15340   create_breakpoint (get_current_arch (),
15341                      arg,
15342                      NULL, 0, NULL, 1 /* parse arg */,
15343                      0 /* tempflag */,
15344                      bp_static_tracepoint /* type_wanted */,
15345                      0 /* Ignore count */,
15346                      pending_break_support,
15347                      ops,
15348                      from_tty,
15349                      1 /* enabled */,
15350                      0 /* internal */, 0);
15351 }
15352
15353 /* Set up a fake reader function that gets command lines from a linked
15354    list that was acquired during tracepoint uploading.  */
15355
15356 static struct uploaded_tp *this_utp;
15357 static int next_cmd;
15358
15359 static char *
15360 read_uploaded_action (void)
15361 {
15362   char *rslt;
15363
15364   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15365
15366   next_cmd++;
15367
15368   return rslt;
15369 }
15370
15371 /* Given information about a tracepoint as recorded on a target (which
15372    can be either a live system or a trace file), attempt to create an
15373    equivalent GDB tracepoint.  This is not a reliable process, since
15374    the target does not necessarily have all the information used when
15375    the tracepoint was originally defined.  */
15376   
15377 struct tracepoint *
15378 create_tracepoint_from_upload (struct uploaded_tp *utp)
15379 {
15380   char *addr_str, small_buf[100];
15381   struct tracepoint *tp;
15382
15383   if (utp->at_string)
15384     addr_str = utp->at_string;
15385   else
15386     {
15387       /* In the absence of a source location, fall back to raw
15388          address.  Since there is no way to confirm that the address
15389          means the same thing as when the trace was started, warn the
15390          user.  */
15391       warning (_("Uploaded tracepoint %d has no "
15392                  "source location, using raw address"),
15393                utp->number);
15394       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15395       addr_str = small_buf;
15396     }
15397
15398   /* There's not much we can do with a sequence of bytecodes.  */
15399   if (utp->cond && !utp->cond_string)
15400     warning (_("Uploaded tracepoint %d condition "
15401                "has no source form, ignoring it"),
15402              utp->number);
15403
15404   if (!create_breakpoint (get_current_arch (),
15405                           addr_str,
15406                           utp->cond_string, -1, NULL,
15407                           0 /* parse cond/thread */,
15408                           0 /* tempflag */,
15409                           utp->type /* type_wanted */,
15410                           0 /* Ignore count */,
15411                           pending_break_support,
15412                           &tracepoint_breakpoint_ops,
15413                           0 /* from_tty */,
15414                           utp->enabled /* enabled */,
15415                           0 /* internal */,
15416                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15417     return NULL;
15418
15419   /* Get the tracepoint we just created.  */
15420   tp = get_tracepoint (tracepoint_count);
15421   gdb_assert (tp != NULL);
15422
15423   if (utp->pass > 0)
15424     {
15425       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15426                  tp->base.number);
15427
15428       trace_pass_command (small_buf, 0);
15429     }
15430
15431   /* If we have uploaded versions of the original commands, set up a
15432      special-purpose "reader" function and call the usual command line
15433      reader, then pass the result to the breakpoint command-setting
15434      function.  */
15435   if (!VEC_empty (char_ptr, utp->cmd_strings))
15436     {
15437       struct command_line *cmd_list;
15438
15439       this_utp = utp;
15440       next_cmd = 0;
15441
15442       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15443
15444       breakpoint_set_commands (&tp->base, cmd_list);
15445     }
15446   else if (!VEC_empty (char_ptr, utp->actions)
15447            || !VEC_empty (char_ptr, utp->step_actions))
15448     warning (_("Uploaded tracepoint %d actions "
15449                "have no source form, ignoring them"),
15450              utp->number);
15451
15452   /* Copy any status information that might be available.  */
15453   tp->base.hit_count = utp->hit_count;
15454   tp->traceframe_usage = utp->traceframe_usage;
15455
15456   return tp;
15457 }
15458   
15459 /* Print information on tracepoint number TPNUM_EXP, or all if
15460    omitted.  */
15461
15462 static void
15463 tracepoints_info (char *args, int from_tty)
15464 {
15465   struct ui_out *uiout = current_uiout;
15466   int num_printed;
15467
15468   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15469
15470   if (num_printed == 0)
15471     {
15472       if (args == NULL || *args == '\0')
15473         ui_out_message (uiout, 0, "No tracepoints.\n");
15474       else
15475         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15476     }
15477
15478   default_collect_info ();
15479 }
15480
15481 /* The 'enable trace' command enables tracepoints.
15482    Not supported by all targets.  */
15483 static void
15484 enable_trace_command (char *args, int from_tty)
15485 {
15486   enable_command (args, from_tty);
15487 }
15488
15489 /* The 'disable trace' command disables tracepoints.
15490    Not supported by all targets.  */
15491 static void
15492 disable_trace_command (char *args, int from_tty)
15493 {
15494   disable_command (args, from_tty);
15495 }
15496
15497 /* Remove a tracepoint (or all if no argument).  */
15498 static void
15499 delete_trace_command (char *arg, int from_tty)
15500 {
15501   struct breakpoint *b, *b_tmp;
15502
15503   dont_repeat ();
15504
15505   if (arg == 0)
15506     {
15507       int breaks_to_delete = 0;
15508
15509       /* Delete all breakpoints if no argument.
15510          Do not delete internal or call-dummy breakpoints, these
15511          have to be deleted with an explicit breakpoint number 
15512          argument.  */
15513       ALL_TRACEPOINTS (b)
15514         if (is_tracepoint (b) && user_breakpoint_p (b))
15515           {
15516             breaks_to_delete = 1;
15517             break;
15518           }
15519
15520       /* Ask user only if there are some breakpoints to delete.  */
15521       if (!from_tty
15522           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15523         {
15524           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15525             if (is_tracepoint (b) && user_breakpoint_p (b))
15526               delete_breakpoint (b);
15527         }
15528     }
15529   else
15530     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15531 }
15532
15533 /* Helper function for trace_pass_command.  */
15534
15535 static void
15536 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15537 {
15538   tp->pass_count = count;
15539   observer_notify_breakpoint_modified (&tp->base);
15540   if (from_tty)
15541     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15542                      tp->base.number, count);
15543 }
15544
15545 /* Set passcount for tracepoint.
15546
15547    First command argument is passcount, second is tracepoint number.
15548    If tracepoint number omitted, apply to most recently defined.
15549    Also accepts special argument "all".  */
15550
15551 static void
15552 trace_pass_command (char *args, int from_tty)
15553 {
15554   struct tracepoint *t1;
15555   unsigned int count;
15556
15557   if (args == 0 || *args == 0)
15558     error (_("passcount command requires an "
15559              "argument (count + optional TP num)"));
15560
15561   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15562
15563   args = skip_spaces (args);
15564   if (*args && strncasecmp (args, "all", 3) == 0)
15565     {
15566       struct breakpoint *b;
15567
15568       args += 3;                        /* Skip special argument "all".  */
15569       if (*args)
15570         error (_("Junk at end of arguments."));
15571
15572       ALL_TRACEPOINTS (b)
15573       {
15574         t1 = (struct tracepoint *) b;
15575         trace_pass_set_count (t1, count, from_tty);
15576       }
15577     }
15578   else if (*args == '\0')
15579     {
15580       t1 = get_tracepoint_by_number (&args, NULL);
15581       if (t1)
15582         trace_pass_set_count (t1, count, from_tty);
15583     }
15584   else
15585     {
15586       struct get_number_or_range_state state;
15587
15588       init_number_or_range (&state, args);
15589       while (!state.finished)
15590         {
15591           t1 = get_tracepoint_by_number (&args, &state);
15592           if (t1)
15593             trace_pass_set_count (t1, count, from_tty);
15594         }
15595     }
15596 }
15597
15598 struct tracepoint *
15599 get_tracepoint (int num)
15600 {
15601   struct breakpoint *t;
15602
15603   ALL_TRACEPOINTS (t)
15604     if (t->number == num)
15605       return (struct tracepoint *) t;
15606
15607   return NULL;
15608 }
15609
15610 /* Find the tracepoint with the given target-side number (which may be
15611    different from the tracepoint number after disconnecting and
15612    reconnecting).  */
15613
15614 struct tracepoint *
15615 get_tracepoint_by_number_on_target (int num)
15616 {
15617   struct breakpoint *b;
15618
15619   ALL_TRACEPOINTS (b)
15620     {
15621       struct tracepoint *t = (struct tracepoint *) b;
15622
15623       if (t->number_on_target == num)
15624         return t;
15625     }
15626
15627   return NULL;
15628 }
15629
15630 /* Utility: parse a tracepoint number and look it up in the list.
15631    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15632    If the argument is missing, the most recent tracepoint
15633    (tracepoint_count) is returned.  */
15634
15635 struct tracepoint *
15636 get_tracepoint_by_number (char **arg,
15637                           struct get_number_or_range_state *state)
15638 {
15639   struct breakpoint *t;
15640   int tpnum;
15641   char *instring = arg == NULL ? NULL : *arg;
15642
15643   if (state)
15644     {
15645       gdb_assert (!state->finished);
15646       tpnum = get_number_or_range (state);
15647     }
15648   else if (arg == NULL || *arg == NULL || ! **arg)
15649     tpnum = tracepoint_count;
15650   else
15651     tpnum = get_number (arg);
15652
15653   if (tpnum <= 0)
15654     {
15655       if (instring && *instring)
15656         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15657                          instring);
15658       else
15659         printf_filtered (_("No previous tracepoint\n"));
15660       return NULL;
15661     }
15662
15663   ALL_TRACEPOINTS (t)
15664     if (t->number == tpnum)
15665     {
15666       return (struct tracepoint *) t;
15667     }
15668
15669   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15670   return NULL;
15671 }
15672
15673 void
15674 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15675 {
15676   if (b->thread != -1)
15677     fprintf_unfiltered (fp, " thread %d", b->thread);
15678
15679   if (b->task != 0)
15680     fprintf_unfiltered (fp, " task %d", b->task);
15681
15682   fprintf_unfiltered (fp, "\n");
15683 }
15684
15685 /* Save information on user settable breakpoints (watchpoints, etc) to
15686    a new script file named FILENAME.  If FILTER is non-NULL, call it
15687    on each breakpoint and only include the ones for which it returns
15688    non-zero.  */
15689
15690 static void
15691 save_breakpoints (char *filename, int from_tty,
15692                   int (*filter) (const struct breakpoint *))
15693 {
15694   struct breakpoint *tp;
15695   int any = 0;
15696   struct cleanup *cleanup;
15697   struct ui_file *fp;
15698   int extra_trace_bits = 0;
15699
15700   if (filename == 0 || *filename == 0)
15701     error (_("Argument required (file name in which to save)"));
15702
15703   /* See if we have anything to save.  */
15704   ALL_BREAKPOINTS (tp)
15705   {
15706     /* Skip internal and momentary breakpoints.  */
15707     if (!user_breakpoint_p (tp))
15708       continue;
15709
15710     /* If we have a filter, only save the breakpoints it accepts.  */
15711     if (filter && !filter (tp))
15712       continue;
15713
15714     any = 1;
15715
15716     if (is_tracepoint (tp))
15717       {
15718         extra_trace_bits = 1;
15719
15720         /* We can stop searching.  */
15721         break;
15722       }
15723   }
15724
15725   if (!any)
15726     {
15727       warning (_("Nothing to save."));
15728       return;
15729     }
15730
15731   filename = tilde_expand (filename);
15732   cleanup = make_cleanup (xfree, filename);
15733   fp = gdb_fopen (filename, "w");
15734   if (!fp)
15735     error (_("Unable to open file '%s' for saving (%s)"),
15736            filename, safe_strerror (errno));
15737   make_cleanup_ui_file_delete (fp);
15738
15739   if (extra_trace_bits)
15740     save_trace_state_variables (fp);
15741
15742   ALL_BREAKPOINTS (tp)
15743   {
15744     /* Skip internal and momentary breakpoints.  */
15745     if (!user_breakpoint_p (tp))
15746       continue;
15747
15748     /* If we have a filter, only save the breakpoints it accepts.  */
15749     if (filter && !filter (tp))
15750       continue;
15751
15752     tp->ops->print_recreate (tp, fp);
15753
15754     /* Note, we can't rely on tp->number for anything, as we can't
15755        assume the recreated breakpoint numbers will match.  Use $bpnum
15756        instead.  */
15757
15758     if (tp->cond_string)
15759       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15760
15761     if (tp->ignore_count)
15762       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15763
15764     if (tp->type != bp_dprintf && tp->commands)
15765       {
15766         volatile struct gdb_exception ex;       
15767
15768         fprintf_unfiltered (fp, "  commands\n");
15769         
15770         ui_out_redirect (current_uiout, fp);
15771         TRY_CATCH (ex, RETURN_MASK_ALL)
15772           {
15773             print_command_lines (current_uiout, tp->commands->commands, 2);
15774           }
15775         ui_out_redirect (current_uiout, NULL);
15776
15777         if (ex.reason < 0)
15778           throw_exception (ex);
15779
15780         fprintf_unfiltered (fp, "  end\n");
15781       }
15782
15783     if (tp->enable_state == bp_disabled)
15784       fprintf_unfiltered (fp, "disable\n");
15785
15786     /* If this is a multi-location breakpoint, check if the locations
15787        should be individually disabled.  Watchpoint locations are
15788        special, and not user visible.  */
15789     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15790       {
15791         struct bp_location *loc;
15792         int n = 1;
15793
15794         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15795           if (!loc->enabled)
15796             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15797       }
15798   }
15799
15800   if (extra_trace_bits && *default_collect)
15801     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15802
15803   if (from_tty)
15804     printf_filtered (_("Saved to file '%s'.\n"), filename);
15805   do_cleanups (cleanup);
15806 }
15807
15808 /* The `save breakpoints' command.  */
15809
15810 static void
15811 save_breakpoints_command (char *args, int from_tty)
15812 {
15813   save_breakpoints (args, from_tty, NULL);
15814 }
15815
15816 /* The `save tracepoints' command.  */
15817
15818 static void
15819 save_tracepoints_command (char *args, int from_tty)
15820 {
15821   save_breakpoints (args, from_tty, is_tracepoint);
15822 }
15823
15824 /* Create a vector of all tracepoints.  */
15825
15826 VEC(breakpoint_p) *
15827 all_tracepoints (void)
15828 {
15829   VEC(breakpoint_p) *tp_vec = 0;
15830   struct breakpoint *tp;
15831
15832   ALL_TRACEPOINTS (tp)
15833   {
15834     VEC_safe_push (breakpoint_p, tp_vec, tp);
15835   }
15836
15837   return tp_vec;
15838 }
15839
15840 \f
15841 /* This help string is used for the break, hbreak, tbreak and thbreak
15842    commands.  It is defined as a macro to prevent duplication.
15843    COMMAND should be a string constant containing the name of the
15844    command.  */
15845 #define BREAK_ARGS_HELP(command) \
15846 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15847 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
15848 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
15849 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
15850 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15851 If a line number is specified, break at start of code for that line.\n\
15852 If a function is specified, break at start of code for that function.\n\
15853 If an address is specified, break at that exact address.\n\
15854 With no LOCATION, uses current execution address of the selected\n\
15855 stack frame.  This is useful for breaking on return to a stack frame.\n\
15856 \n\
15857 THREADNUM is the number from \"info threads\".\n\
15858 CONDITION is a boolean expression.\n\
15859 \n\
15860 Multiple breakpoints at one place are permitted, and useful if their\n\
15861 conditions are different.\n\
15862 \n\
15863 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15864
15865 /* List of subcommands for "catch".  */
15866 static struct cmd_list_element *catch_cmdlist;
15867
15868 /* List of subcommands for "tcatch".  */
15869 static struct cmd_list_element *tcatch_cmdlist;
15870
15871 void
15872 add_catch_command (char *name, char *docstring,
15873                    void (*sfunc) (char *args, int from_tty,
15874                                   struct cmd_list_element *command),
15875                    completer_ftype *completer,
15876                    void *user_data_catch,
15877                    void *user_data_tcatch)
15878 {
15879   struct cmd_list_element *command;
15880
15881   command = add_cmd (name, class_breakpoint, NULL, docstring,
15882                      &catch_cmdlist);
15883   set_cmd_sfunc (command, sfunc);
15884   set_cmd_context (command, user_data_catch);
15885   set_cmd_completer (command, completer);
15886
15887   command = add_cmd (name, class_breakpoint, NULL, docstring,
15888                      &tcatch_cmdlist);
15889   set_cmd_sfunc (command, sfunc);
15890   set_cmd_context (command, user_data_tcatch);
15891   set_cmd_completer (command, completer);
15892 }
15893
15894 static void
15895 clear_syscall_counts (struct inferior *inf)
15896 {
15897   struct catch_syscall_inferior_data *inf_data
15898     = get_catch_syscall_inferior_data (inf);
15899
15900   inf_data->total_syscalls_count = 0;
15901   inf_data->any_syscall_count = 0;
15902   VEC_free (int, inf_data->syscalls_counts);
15903 }
15904
15905 static void
15906 save_command (char *arg, int from_tty)
15907 {
15908   printf_unfiltered (_("\"save\" must be followed by "
15909                        "the name of a save subcommand.\n"));
15910   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15911 }
15912
15913 struct breakpoint *
15914 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15915                           void *data)
15916 {
15917   struct breakpoint *b, *b_tmp;
15918
15919   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15920     {
15921       if ((*callback) (b, data))
15922         return b;
15923     }
15924
15925   return NULL;
15926 }
15927
15928 /* Zero if any of the breakpoint's locations could be a location where
15929    functions have been inlined, nonzero otherwise.  */
15930
15931 static int
15932 is_non_inline_function (struct breakpoint *b)
15933 {
15934   /* The shared library event breakpoint is set on the address of a
15935      non-inline function.  */
15936   if (b->type == bp_shlib_event)
15937     return 1;
15938
15939   return 0;
15940 }
15941
15942 /* Nonzero if the specified PC cannot be a location where functions
15943    have been inlined.  */
15944
15945 int
15946 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15947                            const struct target_waitstatus *ws)
15948 {
15949   struct breakpoint *b;
15950   struct bp_location *bl;
15951
15952   ALL_BREAKPOINTS (b)
15953     {
15954       if (!is_non_inline_function (b))
15955         continue;
15956
15957       for (bl = b->loc; bl != NULL; bl = bl->next)
15958         {
15959           if (!bl->shlib_disabled
15960               && bpstat_check_location (bl, aspace, pc, ws))
15961             return 1;
15962         }
15963     }
15964
15965   return 0;
15966 }
15967
15968 /* Remove any references to OBJFILE which is going to be freed.  */
15969
15970 void
15971 breakpoint_free_objfile (struct objfile *objfile)
15972 {
15973   struct bp_location **locp, *loc;
15974
15975   ALL_BP_LOCATIONS (loc, locp)
15976     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
15977       loc->symtab = NULL;
15978 }
15979
15980 void
15981 initialize_breakpoint_ops (void)
15982 {
15983   static int initialized = 0;
15984
15985   struct breakpoint_ops *ops;
15986
15987   if (initialized)
15988     return;
15989   initialized = 1;
15990
15991   /* The breakpoint_ops structure to be inherit by all kinds of
15992      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15993      internal and momentary breakpoints, etc.).  */
15994   ops = &bkpt_base_breakpoint_ops;
15995   *ops = base_breakpoint_ops;
15996   ops->re_set = bkpt_re_set;
15997   ops->insert_location = bkpt_insert_location;
15998   ops->remove_location = bkpt_remove_location;
15999   ops->breakpoint_hit = bkpt_breakpoint_hit;
16000   ops->create_sals_from_address = bkpt_create_sals_from_address;
16001   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16002   ops->decode_linespec = bkpt_decode_linespec;
16003
16004   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16005   ops = &bkpt_breakpoint_ops;
16006   *ops = bkpt_base_breakpoint_ops;
16007   ops->re_set = bkpt_re_set;
16008   ops->resources_needed = bkpt_resources_needed;
16009   ops->print_it = bkpt_print_it;
16010   ops->print_mention = bkpt_print_mention;
16011   ops->print_recreate = bkpt_print_recreate;
16012
16013   /* Ranged breakpoints.  */
16014   ops = &ranged_breakpoint_ops;
16015   *ops = bkpt_breakpoint_ops;
16016   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16017   ops->resources_needed = resources_needed_ranged_breakpoint;
16018   ops->print_it = print_it_ranged_breakpoint;
16019   ops->print_one = print_one_ranged_breakpoint;
16020   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16021   ops->print_mention = print_mention_ranged_breakpoint;
16022   ops->print_recreate = print_recreate_ranged_breakpoint;
16023
16024   /* Internal breakpoints.  */
16025   ops = &internal_breakpoint_ops;
16026   *ops = bkpt_base_breakpoint_ops;
16027   ops->re_set = internal_bkpt_re_set;
16028   ops->check_status = internal_bkpt_check_status;
16029   ops->print_it = internal_bkpt_print_it;
16030   ops->print_mention = internal_bkpt_print_mention;
16031
16032   /* Momentary breakpoints.  */
16033   ops = &momentary_breakpoint_ops;
16034   *ops = bkpt_base_breakpoint_ops;
16035   ops->re_set = momentary_bkpt_re_set;
16036   ops->check_status = momentary_bkpt_check_status;
16037   ops->print_it = momentary_bkpt_print_it;
16038   ops->print_mention = momentary_bkpt_print_mention;
16039
16040   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16041   ops = &longjmp_breakpoint_ops;
16042   *ops = momentary_breakpoint_ops;
16043   ops->dtor = longjmp_bkpt_dtor;
16044
16045   /* Probe breakpoints.  */
16046   ops = &bkpt_probe_breakpoint_ops;
16047   *ops = bkpt_breakpoint_ops;
16048   ops->insert_location = bkpt_probe_insert_location;
16049   ops->remove_location = bkpt_probe_remove_location;
16050   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16051   ops->decode_linespec = bkpt_probe_decode_linespec;
16052
16053   /* Watchpoints.  */
16054   ops = &watchpoint_breakpoint_ops;
16055   *ops = base_breakpoint_ops;
16056   ops->dtor = dtor_watchpoint;
16057   ops->re_set = re_set_watchpoint;
16058   ops->insert_location = insert_watchpoint;
16059   ops->remove_location = remove_watchpoint;
16060   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16061   ops->check_status = check_status_watchpoint;
16062   ops->resources_needed = resources_needed_watchpoint;
16063   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16064   ops->print_it = print_it_watchpoint;
16065   ops->print_mention = print_mention_watchpoint;
16066   ops->print_recreate = print_recreate_watchpoint;
16067   ops->explains_signal = explains_signal_watchpoint;
16068
16069   /* Masked watchpoints.  */
16070   ops = &masked_watchpoint_breakpoint_ops;
16071   *ops = watchpoint_breakpoint_ops;
16072   ops->insert_location = insert_masked_watchpoint;
16073   ops->remove_location = remove_masked_watchpoint;
16074   ops->resources_needed = resources_needed_masked_watchpoint;
16075   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16076   ops->print_it = print_it_masked_watchpoint;
16077   ops->print_one_detail = print_one_detail_masked_watchpoint;
16078   ops->print_mention = print_mention_masked_watchpoint;
16079   ops->print_recreate = print_recreate_masked_watchpoint;
16080
16081   /* Tracepoints.  */
16082   ops = &tracepoint_breakpoint_ops;
16083   *ops = base_breakpoint_ops;
16084   ops->re_set = tracepoint_re_set;
16085   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16086   ops->print_one_detail = tracepoint_print_one_detail;
16087   ops->print_mention = tracepoint_print_mention;
16088   ops->print_recreate = tracepoint_print_recreate;
16089   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16090   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16091   ops->decode_linespec = tracepoint_decode_linespec;
16092
16093   /* Probe tracepoints.  */
16094   ops = &tracepoint_probe_breakpoint_ops;
16095   *ops = tracepoint_breakpoint_ops;
16096   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16097   ops->decode_linespec = tracepoint_probe_decode_linespec;
16098
16099   /* Static tracepoints with marker (`-m').  */
16100   ops = &strace_marker_breakpoint_ops;
16101   *ops = tracepoint_breakpoint_ops;
16102   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16103   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16104   ops->decode_linespec = strace_marker_decode_linespec;
16105
16106   /* Fork catchpoints.  */
16107   ops = &catch_fork_breakpoint_ops;
16108   *ops = base_breakpoint_ops;
16109   ops->insert_location = insert_catch_fork;
16110   ops->remove_location = remove_catch_fork;
16111   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16112   ops->print_it = print_it_catch_fork;
16113   ops->print_one = print_one_catch_fork;
16114   ops->print_mention = print_mention_catch_fork;
16115   ops->print_recreate = print_recreate_catch_fork;
16116
16117   /* Vfork catchpoints.  */
16118   ops = &catch_vfork_breakpoint_ops;
16119   *ops = base_breakpoint_ops;
16120   ops->insert_location = insert_catch_vfork;
16121   ops->remove_location = remove_catch_vfork;
16122   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16123   ops->print_it = print_it_catch_vfork;
16124   ops->print_one = print_one_catch_vfork;
16125   ops->print_mention = print_mention_catch_vfork;
16126   ops->print_recreate = print_recreate_catch_vfork;
16127
16128   /* Exec catchpoints.  */
16129   ops = &catch_exec_breakpoint_ops;
16130   *ops = base_breakpoint_ops;
16131   ops->dtor = dtor_catch_exec;
16132   ops->insert_location = insert_catch_exec;
16133   ops->remove_location = remove_catch_exec;
16134   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16135   ops->print_it = print_it_catch_exec;
16136   ops->print_one = print_one_catch_exec;
16137   ops->print_mention = print_mention_catch_exec;
16138   ops->print_recreate = print_recreate_catch_exec;
16139
16140   /* Syscall catchpoints.  */
16141   ops = &catch_syscall_breakpoint_ops;
16142   *ops = base_breakpoint_ops;
16143   ops->dtor = dtor_catch_syscall;
16144   ops->insert_location = insert_catch_syscall;
16145   ops->remove_location = remove_catch_syscall;
16146   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16147   ops->print_it = print_it_catch_syscall;
16148   ops->print_one = print_one_catch_syscall;
16149   ops->print_mention = print_mention_catch_syscall;
16150   ops->print_recreate = print_recreate_catch_syscall;
16151
16152   /* Solib-related catchpoints.  */
16153   ops = &catch_solib_breakpoint_ops;
16154   *ops = base_breakpoint_ops;
16155   ops->dtor = dtor_catch_solib;
16156   ops->insert_location = insert_catch_solib;
16157   ops->remove_location = remove_catch_solib;
16158   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16159   ops->check_status = check_status_catch_solib;
16160   ops->print_it = print_it_catch_solib;
16161   ops->print_one = print_one_catch_solib;
16162   ops->print_mention = print_mention_catch_solib;
16163   ops->print_recreate = print_recreate_catch_solib;
16164
16165   ops = &dprintf_breakpoint_ops;
16166   *ops = bkpt_base_breakpoint_ops;
16167   ops->re_set = dprintf_re_set;
16168   ops->resources_needed = bkpt_resources_needed;
16169   ops->print_it = bkpt_print_it;
16170   ops->print_mention = bkpt_print_mention;
16171   ops->print_recreate = dprintf_print_recreate;
16172   ops->after_condition_true = dprintf_after_condition_true;
16173 }
16174
16175 /* Chain containing all defined "enable breakpoint" subcommands.  */
16176
16177 static struct cmd_list_element *enablebreaklist = NULL;
16178
16179 void
16180 _initialize_breakpoint (void)
16181 {
16182   struct cmd_list_element *c;
16183
16184   initialize_breakpoint_ops ();
16185
16186   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16187   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16188   observer_attach_inferior_exit (clear_syscall_counts);
16189   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16190
16191   breakpoint_objfile_key
16192     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16193
16194   catch_syscall_inferior_data
16195     = register_inferior_data_with_cleanup (NULL,
16196                                            catch_syscall_inferior_data_cleanup);
16197
16198   breakpoint_chain = 0;
16199   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16200      before a breakpoint is set.  */
16201   breakpoint_count = 0;
16202
16203   tracepoint_count = 0;
16204
16205   add_com ("ignore", class_breakpoint, ignore_command, _("\
16206 Set ignore-count of breakpoint number N to COUNT.\n\
16207 Usage is `ignore N COUNT'."));
16208   if (xdb_commands)
16209     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16210
16211   add_com ("commands", class_breakpoint, commands_command, _("\
16212 Set commands to be executed when a breakpoint is hit.\n\
16213 Give breakpoint number as argument after \"commands\".\n\
16214 With no argument, the targeted breakpoint is the last one set.\n\
16215 The commands themselves follow starting on the next line.\n\
16216 Type a line containing \"end\" to indicate the end of them.\n\
16217 Give \"silent\" as the first line to make the breakpoint silent;\n\
16218 then no output is printed when it is hit, except what the commands print."));
16219
16220   c = add_com ("condition", class_breakpoint, condition_command, _("\
16221 Specify breakpoint number N to break only if COND is true.\n\
16222 Usage is `condition N COND', where N is an integer and COND is an\n\
16223 expression to be evaluated whenever breakpoint N is reached."));
16224   set_cmd_completer (c, condition_completer);
16225
16226   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16227 Set a temporary breakpoint.\n\
16228 Like \"break\" except the breakpoint is only temporary,\n\
16229 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16230 by using \"enable delete\" on the breakpoint number.\n\
16231 \n"
16232 BREAK_ARGS_HELP ("tbreak")));
16233   set_cmd_completer (c, location_completer);
16234
16235   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16236 Set a hardware assisted breakpoint.\n\
16237 Like \"break\" except the breakpoint requires hardware support,\n\
16238 some target hardware may not have this support.\n\
16239 \n"
16240 BREAK_ARGS_HELP ("hbreak")));
16241   set_cmd_completer (c, location_completer);
16242
16243   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16244 Set a temporary hardware assisted breakpoint.\n\
16245 Like \"hbreak\" except the breakpoint is only temporary,\n\
16246 so it will be deleted when hit.\n\
16247 \n"
16248 BREAK_ARGS_HELP ("thbreak")));
16249   set_cmd_completer (c, location_completer);
16250
16251   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16252 Enable some breakpoints.\n\
16253 Give breakpoint numbers (separated by spaces) as arguments.\n\
16254 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16255 This is used to cancel the effect of the \"disable\" command.\n\
16256 With a subcommand you can enable temporarily."),
16257                   &enablelist, "enable ", 1, &cmdlist);
16258   if (xdb_commands)
16259     add_com ("ab", class_breakpoint, enable_command, _("\
16260 Enable some breakpoints.\n\
16261 Give breakpoint numbers (separated by spaces) as arguments.\n\
16262 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16263 This is used to cancel the effect of the \"disable\" command.\n\
16264 With a subcommand you can enable temporarily."));
16265
16266   add_com_alias ("en", "enable", class_breakpoint, 1);
16267
16268   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16269 Enable some breakpoints.\n\
16270 Give breakpoint numbers (separated by spaces) as arguments.\n\
16271 This is used to cancel the effect of the \"disable\" command.\n\
16272 May be abbreviated to simply \"enable\".\n"),
16273                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16274
16275   add_cmd ("once", no_class, enable_once_command, _("\
16276 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16277 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16278            &enablebreaklist);
16279
16280   add_cmd ("delete", no_class, enable_delete_command, _("\
16281 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16282 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16283            &enablebreaklist);
16284
16285   add_cmd ("count", no_class, enable_count_command, _("\
16286 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16287 If a breakpoint is hit while enabled in this fashion,\n\
16288 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16289            &enablebreaklist);
16290
16291   add_cmd ("delete", no_class, enable_delete_command, _("\
16292 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16293 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16294            &enablelist);
16295
16296   add_cmd ("once", no_class, enable_once_command, _("\
16297 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16298 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16299            &enablelist);
16300
16301   add_cmd ("count", no_class, enable_count_command, _("\
16302 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16303 If a breakpoint is hit while enabled in this fashion,\n\
16304 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16305            &enablelist);
16306
16307   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16308 Disable some breakpoints.\n\
16309 Arguments are breakpoint numbers with spaces in between.\n\
16310 To disable all breakpoints, give no argument.\n\
16311 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16312                   &disablelist, "disable ", 1, &cmdlist);
16313   add_com_alias ("dis", "disable", class_breakpoint, 1);
16314   add_com_alias ("disa", "disable", class_breakpoint, 1);
16315   if (xdb_commands)
16316     add_com ("sb", class_breakpoint, disable_command, _("\
16317 Disable some breakpoints.\n\
16318 Arguments are breakpoint numbers with spaces in between.\n\
16319 To disable all breakpoints, give no argument.\n\
16320 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16321
16322   add_cmd ("breakpoints", class_alias, disable_command, _("\
16323 Disable some breakpoints.\n\
16324 Arguments are breakpoint numbers with spaces in between.\n\
16325 To disable all breakpoints, give no argument.\n\
16326 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16327 This command may be abbreviated \"disable\"."),
16328            &disablelist);
16329
16330   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16331 Delete some breakpoints or auto-display expressions.\n\
16332 Arguments are breakpoint numbers with spaces in between.\n\
16333 To delete all breakpoints, give no argument.\n\
16334 \n\
16335 Also a prefix command for deletion of other GDB objects.\n\
16336 The \"unset\" command is also an alias for \"delete\"."),
16337                   &deletelist, "delete ", 1, &cmdlist);
16338   add_com_alias ("d", "delete", class_breakpoint, 1);
16339   add_com_alias ("del", "delete", class_breakpoint, 1);
16340   if (xdb_commands)
16341     add_com ("db", class_breakpoint, delete_command, _("\
16342 Delete some breakpoints.\n\
16343 Arguments are breakpoint numbers with spaces in between.\n\
16344 To delete all breakpoints, give no argument.\n"));
16345
16346   add_cmd ("breakpoints", class_alias, delete_command, _("\
16347 Delete some breakpoints or auto-display expressions.\n\
16348 Arguments are breakpoint numbers with spaces in between.\n\
16349 To delete all breakpoints, give no argument.\n\
16350 This command may be abbreviated \"delete\"."),
16351            &deletelist);
16352
16353   add_com ("clear", class_breakpoint, clear_command, _("\
16354 Clear breakpoint at specified line or function.\n\
16355 Argument may be line number, function name, or \"*\" and an address.\n\
16356 If line number is specified, all breakpoints in that line are cleared.\n\
16357 If function is specified, breakpoints at beginning of function are cleared.\n\
16358 If an address is specified, breakpoints at that address are cleared.\n\
16359 \n\
16360 With no argument, clears all breakpoints in the line that the selected frame\n\
16361 is executing in.\n\
16362 \n\
16363 See also the \"delete\" command which clears breakpoints by number."));
16364   add_com_alias ("cl", "clear", class_breakpoint, 1);
16365
16366   c = add_com ("break", class_breakpoint, break_command, _("\
16367 Set breakpoint at specified line or function.\n"
16368 BREAK_ARGS_HELP ("break")));
16369   set_cmd_completer (c, location_completer);
16370
16371   add_com_alias ("b", "break", class_run, 1);
16372   add_com_alias ("br", "break", class_run, 1);
16373   add_com_alias ("bre", "break", class_run, 1);
16374   add_com_alias ("brea", "break", class_run, 1);
16375
16376   if (xdb_commands)
16377    add_com_alias ("ba", "break", class_breakpoint, 1);
16378
16379   if (dbx_commands)
16380     {
16381       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16382 Break in function/address or break at a line in the current file."),
16383                              &stoplist, "stop ", 1, &cmdlist);
16384       add_cmd ("in", class_breakpoint, stopin_command,
16385                _("Break in function or address."), &stoplist);
16386       add_cmd ("at", class_breakpoint, stopat_command,
16387                _("Break at a line in the current file."), &stoplist);
16388       add_com ("status", class_info, breakpoints_info, _("\
16389 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16390 The \"Type\" column indicates one of:\n\
16391 \tbreakpoint     - normal breakpoint\n\
16392 \twatchpoint     - watchpoint\n\
16393 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16394 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16395 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16396 address and file/line number respectively.\n\
16397 \n\
16398 Convenience variable \"$_\" and default examine address for \"x\"\n\
16399 are set to the address of the last breakpoint listed unless the command\n\
16400 is prefixed with \"server \".\n\n\
16401 Convenience variable \"$bpnum\" contains the number of the last\n\
16402 breakpoint set."));
16403     }
16404
16405   add_info ("breakpoints", breakpoints_info, _("\
16406 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16407 The \"Type\" column indicates one of:\n\
16408 \tbreakpoint     - normal breakpoint\n\
16409 \twatchpoint     - watchpoint\n\
16410 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16411 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16412 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16413 address and file/line number respectively.\n\
16414 \n\
16415 Convenience variable \"$_\" and default examine address for \"x\"\n\
16416 are set to the address of the last breakpoint listed unless the command\n\
16417 is prefixed with \"server \".\n\n\
16418 Convenience variable \"$bpnum\" contains the number of the last\n\
16419 breakpoint set."));
16420
16421   add_info_alias ("b", "breakpoints", 1);
16422
16423   if (xdb_commands)
16424     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16425 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16426 The \"Type\" column indicates one of:\n\
16427 \tbreakpoint     - normal breakpoint\n\
16428 \twatchpoint     - watchpoint\n\
16429 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16430 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16431 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16432 address and file/line number respectively.\n\
16433 \n\
16434 Convenience variable \"$_\" and default examine address for \"x\"\n\
16435 are set to the address of the last breakpoint listed unless the command\n\
16436 is prefixed with \"server \".\n\n\
16437 Convenience variable \"$bpnum\" contains the number of the last\n\
16438 breakpoint set."));
16439
16440   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16441 Status of all breakpoints, or breakpoint number NUMBER.\n\
16442 The \"Type\" column indicates one of:\n\
16443 \tbreakpoint     - normal breakpoint\n\
16444 \twatchpoint     - watchpoint\n\
16445 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16446 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16447 \tuntil          - internal breakpoint used by the \"until\" command\n\
16448 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16449 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16450 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16451 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16452 address and file/line number respectively.\n\
16453 \n\
16454 Convenience variable \"$_\" and default examine address for \"x\"\n\
16455 are set to the address of the last breakpoint listed unless the command\n\
16456 is prefixed with \"server \".\n\n\
16457 Convenience variable \"$bpnum\" contains the number of the last\n\
16458 breakpoint set."),
16459            &maintenanceinfolist);
16460
16461   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16462 Set catchpoints to catch events."),
16463                   &catch_cmdlist, "catch ",
16464                   0/*allow-unknown*/, &cmdlist);
16465
16466   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16467 Set temporary catchpoints to catch events."),
16468                   &tcatch_cmdlist, "tcatch ",
16469                   0/*allow-unknown*/, &cmdlist);
16470
16471   add_catch_command ("fork", _("Catch calls to fork."),
16472                      catch_fork_command_1,
16473                      NULL,
16474                      (void *) (uintptr_t) catch_fork_permanent,
16475                      (void *) (uintptr_t) catch_fork_temporary);
16476   add_catch_command ("vfork", _("Catch calls to vfork."),
16477                      catch_fork_command_1,
16478                      NULL,
16479                      (void *) (uintptr_t) catch_vfork_permanent,
16480                      (void *) (uintptr_t) catch_vfork_temporary);
16481   add_catch_command ("exec", _("Catch calls to exec."),
16482                      catch_exec_command_1,
16483                      NULL,
16484                      CATCH_PERMANENT,
16485                      CATCH_TEMPORARY);
16486   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16487 Usage: catch load [REGEX]\n\
16488 If REGEX is given, only stop for libraries matching the regular expression."),
16489                      catch_load_command_1,
16490                      NULL,
16491                      CATCH_PERMANENT,
16492                      CATCH_TEMPORARY);
16493   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16494 Usage: catch unload [REGEX]\n\
16495 If REGEX is given, only stop for libraries matching the regular expression."),
16496                      catch_unload_command_1,
16497                      NULL,
16498                      CATCH_PERMANENT,
16499                      CATCH_TEMPORARY);
16500   add_catch_command ("syscall", _("\
16501 Catch system calls by their names and/or numbers.\n\
16502 Arguments say which system calls to catch.  If no arguments\n\
16503 are given, every system call will be caught.\n\
16504 Arguments, if given, should be one or more system call names\n\
16505 (if your system supports that), or system call numbers."),
16506                      catch_syscall_command_1,
16507                      catch_syscall_completer,
16508                      CATCH_PERMANENT,
16509                      CATCH_TEMPORARY);
16510
16511   c = add_com ("watch", class_breakpoint, watch_command, _("\
16512 Set a watchpoint for an expression.\n\
16513 Usage: watch [-l|-location] EXPRESSION\n\
16514 A watchpoint stops execution of your program whenever the value of\n\
16515 an expression changes.\n\
16516 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16517 the memory to which it refers."));
16518   set_cmd_completer (c, expression_completer);
16519
16520   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16521 Set a read watchpoint for an expression.\n\
16522 Usage: rwatch [-l|-location] EXPRESSION\n\
16523 A watchpoint stops execution of your program whenever the value of\n\
16524 an expression is read.\n\
16525 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16526 the memory to which it refers."));
16527   set_cmd_completer (c, expression_completer);
16528
16529   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16530 Set a watchpoint for an expression.\n\
16531 Usage: awatch [-l|-location] EXPRESSION\n\
16532 A watchpoint stops execution of your program whenever the value of\n\
16533 an expression is either read or written.\n\
16534 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16535 the memory to which it refers."));
16536   set_cmd_completer (c, expression_completer);
16537
16538   add_info ("watchpoints", watchpoints_info, _("\
16539 Status of specified watchpoints (all watchpoints if no argument)."));
16540
16541   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16542      respond to changes - contrary to the description.  */
16543   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16544                             &can_use_hw_watchpoints, _("\
16545 Set debugger's willingness to use watchpoint hardware."), _("\
16546 Show debugger's willingness to use watchpoint hardware."), _("\
16547 If zero, gdb will not use hardware for new watchpoints, even if\n\
16548 such is available.  (However, any hardware watchpoints that were\n\
16549 created before setting this to nonzero, will continue to use watchpoint\n\
16550 hardware.)"),
16551                             NULL,
16552                             show_can_use_hw_watchpoints,
16553                             &setlist, &showlist);
16554
16555   can_use_hw_watchpoints = 1;
16556
16557   /* Tracepoint manipulation commands.  */
16558
16559   c = add_com ("trace", class_breakpoint, trace_command, _("\
16560 Set a tracepoint at specified line or function.\n\
16561 \n"
16562 BREAK_ARGS_HELP ("trace") "\n\
16563 Do \"help tracepoints\" for info on other tracepoint commands."));
16564   set_cmd_completer (c, location_completer);
16565
16566   add_com_alias ("tp", "trace", class_alias, 0);
16567   add_com_alias ("tr", "trace", class_alias, 1);
16568   add_com_alias ("tra", "trace", class_alias, 1);
16569   add_com_alias ("trac", "trace", class_alias, 1);
16570
16571   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16572 Set a fast tracepoint at specified line or function.\n\
16573 \n"
16574 BREAK_ARGS_HELP ("ftrace") "\n\
16575 Do \"help tracepoints\" for info on other tracepoint commands."));
16576   set_cmd_completer (c, location_completer);
16577
16578   c = add_com ("strace", class_breakpoint, strace_command, _("\
16579 Set a static tracepoint at specified line, function or marker.\n\
16580 \n\
16581 strace [LOCATION] [if CONDITION]\n\
16582 LOCATION may be a line number, function name, \"*\" and an address,\n\
16583 or -m MARKER_ID.\n\
16584 If a line number is specified, probe the marker at start of code\n\
16585 for that line.  If a function is specified, probe the marker at start\n\
16586 of code for that function.  If an address is specified, probe the marker\n\
16587 at that exact address.  If a marker id is specified, probe the marker\n\
16588 with that name.  With no LOCATION, uses current execution address of\n\
16589 the selected stack frame.\n\
16590 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16591 This collects arbitrary user data passed in the probe point call to the\n\
16592 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16593 by printing the $_sdata variable like any other convenience variable.\n\
16594 \n\
16595 CONDITION is a boolean expression.\n\
16596 \n\
16597 Multiple tracepoints at one place are permitted, and useful if their\n\
16598 conditions are different.\n\
16599 \n\
16600 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16601 Do \"help tracepoints\" for info on other tracepoint commands."));
16602   set_cmd_completer (c, location_completer);
16603
16604   add_info ("tracepoints", tracepoints_info, _("\
16605 Status of specified tracepoints (all tracepoints if no argument).\n\
16606 Convenience variable \"$tpnum\" contains the number of the\n\
16607 last tracepoint set."));
16608
16609   add_info_alias ("tp", "tracepoints", 1);
16610
16611   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16612 Delete specified tracepoints.\n\
16613 Arguments are tracepoint numbers, separated by spaces.\n\
16614 No argument means delete all tracepoints."),
16615            &deletelist);
16616   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16617
16618   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16619 Disable specified tracepoints.\n\
16620 Arguments are tracepoint numbers, separated by spaces.\n\
16621 No argument means disable all tracepoints."),
16622            &disablelist);
16623   deprecate_cmd (c, "disable");
16624
16625   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16626 Enable specified tracepoints.\n\
16627 Arguments are tracepoint numbers, separated by spaces.\n\
16628 No argument means enable all tracepoints."),
16629            &enablelist);
16630   deprecate_cmd (c, "enable");
16631
16632   add_com ("passcount", class_trace, trace_pass_command, _("\
16633 Set the passcount for a tracepoint.\n\
16634 The trace will end when the tracepoint has been passed 'count' times.\n\
16635 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16636 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16637
16638   add_prefix_cmd ("save", class_breakpoint, save_command,
16639                   _("Save breakpoint definitions as a script."),
16640                   &save_cmdlist, "save ",
16641                   0/*allow-unknown*/, &cmdlist);
16642
16643   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16644 Save current breakpoint definitions as a script.\n\
16645 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16646 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16647 session to restore them."),
16648                &save_cmdlist);
16649   set_cmd_completer (c, filename_completer);
16650
16651   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16652 Save current tracepoint definitions as a script.\n\
16653 Use the 'source' command in another debug session to restore them."),
16654                &save_cmdlist);
16655   set_cmd_completer (c, filename_completer);
16656
16657   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16658   deprecate_cmd (c, "save tracepoints");
16659
16660   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16661 Breakpoint specific settings\n\
16662 Configure various breakpoint-specific variables such as\n\
16663 pending breakpoint behavior"),
16664                   &breakpoint_set_cmdlist, "set breakpoint ",
16665                   0/*allow-unknown*/, &setlist);
16666   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16667 Breakpoint specific settings\n\
16668 Configure various breakpoint-specific variables such as\n\
16669 pending breakpoint behavior"),
16670                   &breakpoint_show_cmdlist, "show breakpoint ",
16671                   0/*allow-unknown*/, &showlist);
16672
16673   add_setshow_auto_boolean_cmd ("pending", no_class,
16674                                 &pending_break_support, _("\
16675 Set debugger's behavior regarding pending breakpoints."), _("\
16676 Show debugger's behavior regarding pending breakpoints."), _("\
16677 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16678 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16679 an error.  If auto, an unrecognized breakpoint location results in a\n\
16680 user-query to see if a pending breakpoint should be created."),
16681                                 NULL,
16682                                 show_pending_break_support,
16683                                 &breakpoint_set_cmdlist,
16684                                 &breakpoint_show_cmdlist);
16685
16686   pending_break_support = AUTO_BOOLEAN_AUTO;
16687
16688   add_setshow_boolean_cmd ("auto-hw", no_class,
16689                            &automatic_hardware_breakpoints, _("\
16690 Set automatic usage of hardware breakpoints."), _("\
16691 Show automatic usage of hardware breakpoints."), _("\
16692 If set, the debugger will automatically use hardware breakpoints for\n\
16693 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16694 a warning will be emitted for such breakpoints."),
16695                            NULL,
16696                            show_automatic_hardware_breakpoints,
16697                            &breakpoint_set_cmdlist,
16698                            &breakpoint_show_cmdlist);
16699
16700   add_setshow_auto_boolean_cmd ("always-inserted", class_support,
16701                                 &always_inserted_mode, _("\
16702 Set mode for inserting breakpoints."), _("\
16703 Show mode for inserting breakpoints."), _("\
16704 When this mode is off, breakpoints are inserted in inferior when it is\n\
16705 resumed, and removed when execution stops.  When this mode is on,\n\
16706 breakpoints are inserted immediately and removed only when the user\n\
16707 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16708 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16709 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16710 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16711 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16712                                 NULL,
16713                                 &show_always_inserted_mode,
16714                                 &breakpoint_set_cmdlist,
16715                                 &breakpoint_show_cmdlist);
16716
16717   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16718                         condition_evaluation_enums,
16719                         &condition_evaluation_mode_1, _("\
16720 Set mode of breakpoint condition evaluation."), _("\
16721 Show mode of breakpoint condition evaluation."), _("\
16722 When this is set to \"host\", breakpoint conditions will be\n\
16723 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16724 breakpoint conditions will be downloaded to the target (if the target\n\
16725 supports such feature) and conditions will be evaluated on the target's side.\n\
16726 If this is set to \"auto\" (default), this will be automatically set to\n\
16727 \"target\" if it supports condition evaluation, otherwise it will\n\
16728 be set to \"gdb\""),
16729                            &set_condition_evaluation_mode,
16730                            &show_condition_evaluation_mode,
16731                            &breakpoint_set_cmdlist,
16732                            &breakpoint_show_cmdlist);
16733
16734   add_com ("break-range", class_breakpoint, break_range_command, _("\
16735 Set a breakpoint for an address range.\n\
16736 break-range START-LOCATION, END-LOCATION\n\
16737 where START-LOCATION and END-LOCATION can be one of the following:\n\
16738   LINENUM, for that line in the current file,\n\
16739   FILE:LINENUM, for that line in that file,\n\
16740   +OFFSET, for that number of lines after the current line\n\
16741            or the start of the range\n\
16742   FUNCTION, for the first line in that function,\n\
16743   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16744   *ADDRESS, for the instruction at that address.\n\
16745 \n\
16746 The breakpoint will stop execution of the inferior whenever it executes\n\
16747 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16748 range (including START-LOCATION and END-LOCATION)."));
16749
16750   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16751 Set a dynamic printf at specified line or function.\n\
16752 dprintf location,format string,arg1,arg2,...\n\
16753 location may be a line number, function name, or \"*\" and an address.\n\
16754 If a line number is specified, break at start of code for that line.\n\
16755 If a function is specified, break at start of code for that function."));
16756   set_cmd_completer (c, location_completer);
16757
16758   add_setshow_enum_cmd ("dprintf-style", class_support,
16759                         dprintf_style_enums, &dprintf_style, _("\
16760 Set the style of usage for dynamic printf."), _("\
16761 Show the style of usage for dynamic printf."), _("\
16762 This setting chooses how GDB will do a dynamic printf.\n\
16763 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16764 console, as with the \"printf\" command.\n\
16765 If the value is \"call\", the print is done by calling a function in your\n\
16766 program; by default printf(), but you can choose a different function or\n\
16767 output stream by setting dprintf-function and dprintf-channel."),
16768                         update_dprintf_commands, NULL,
16769                         &setlist, &showlist);
16770
16771   dprintf_function = xstrdup ("printf");
16772   add_setshow_string_cmd ("dprintf-function", class_support,
16773                           &dprintf_function, _("\
16774 Set the function to use for dynamic printf"), _("\
16775 Show the function to use for dynamic printf"), NULL,
16776                           update_dprintf_commands, NULL,
16777                           &setlist, &showlist);
16778
16779   dprintf_channel = xstrdup ("");
16780   add_setshow_string_cmd ("dprintf-channel", class_support,
16781                           &dprintf_channel, _("\
16782 Set the channel to use for dynamic printf"), _("\
16783 Show the channel to use for dynamic printf"), NULL,
16784                           update_dprintf_commands, NULL,
16785                           &setlist, &showlist);
16786
16787   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
16788                            &disconnected_dprintf, _("\
16789 Set whether dprintf continues after GDB disconnects."), _("\
16790 Show whether dprintf continues after GDB disconnects."), _("\
16791 Use this to let dprintf commands continue to hit and produce output\n\
16792 even if GDB disconnects or detaches from the target."),
16793                            NULL,
16794                            NULL,
16795                            &setlist, &showlist);
16796
16797   add_com ("agent-printf", class_vars, agent_printf_command, _("\
16798 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
16799 (target agent only) This is useful for formatted output in user-defined commands."));
16800
16801   automatic_hardware_breakpoints = 1;
16802
16803   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16804   observer_attach_thread_exit (remove_threaded_breakpoints);
16805 }