PR macros/7961:
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2012 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "gdb_regex.h"
64 #include "probe.h"
65 #include "cli/cli-utils.h"
66 #include "continuations.h"
67 #include "stack.h"
68 #include "skip.h"
69 #include "gdb_regex.h"
70 #include "ax-gdb.h"
71 #include "dummy-frame.h"
72
73 /* readline include files */
74 #include "readline/readline.h"
75 #include "readline/history.h"
76
77 /* readline defines this.  */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "python/python.h"
82
83 /* Prototypes for local functions.  */
84
85 static void enable_delete_command (char *, int);
86
87 static void enable_once_command (char *, int);
88
89 static void enable_count_command (char *, int);
90
91 static void disable_command (char *, int);
92
93 static void enable_command (char *, int);
94
95 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
96                                                       void *),
97                                     void *);
98
99 static void ignore_command (char *, int);
100
101 static int breakpoint_re_set_one (void *);
102
103 static void breakpoint_re_set_default (struct breakpoint *);
104
105 static void create_sals_from_address_default (char **,
106                                               struct linespec_result *,
107                                               enum bptype, char *,
108                                               char **);
109
110 static void create_breakpoints_sal_default (struct gdbarch *,
111                                             struct linespec_result *,
112                                             struct linespec_sals *,
113                                             char *, char *, enum bptype,
114                                             enum bpdisp, int, int,
115                                             int,
116                                             const struct breakpoint_ops *,
117                                             int, int, int, unsigned);
118
119 static void decode_linespec_default (struct breakpoint *, char **,
120                                      struct symtabs_and_lines *);
121
122 static void clear_command (char *, int);
123
124 static void catch_command (char *, int);
125
126 static int can_use_hardware_watchpoint (struct value *);
127
128 static void break_command_1 (char *, int, int);
129
130 static void mention (struct breakpoint *);
131
132 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
133                                                                enum bptype,
134                                                                const struct breakpoint_ops *);
135 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
136                                                        const struct symtab_and_line *);
137
138 /* This function is used in gdbtk sources and thus can not be made
139    static.  */
140 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
141                                        struct symtab_and_line,
142                                        enum bptype,
143                                        const struct breakpoint_ops *);
144
145 static struct breakpoint *
146   momentary_breakpoint_from_master (struct breakpoint *orig,
147                                     enum bptype type,
148                                     const struct breakpoint_ops *ops);
149
150 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
151
152 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
153                                             CORE_ADDR bpaddr,
154                                             enum bptype bptype);
155
156 static void describe_other_breakpoints (struct gdbarch *,
157                                         struct program_space *, CORE_ADDR,
158                                         struct obj_section *, int);
159
160 static int breakpoint_address_match (struct address_space *aspace1,
161                                      CORE_ADDR addr1,
162                                      struct address_space *aspace2,
163                                      CORE_ADDR addr2);
164
165 static int watchpoint_locations_match (struct bp_location *loc1,
166                                        struct bp_location *loc2);
167
168 static int breakpoint_location_address_match (struct bp_location *bl,
169                                               struct address_space *aspace,
170                                               CORE_ADDR addr);
171
172 static void breakpoints_info (char *, int);
173
174 static void watchpoints_info (char *, int);
175
176 static int breakpoint_1 (char *, int, 
177                          int (*) (const struct breakpoint *));
178
179 static int breakpoint_cond_eval (void *);
180
181 static void cleanup_executing_breakpoints (void *);
182
183 static void commands_command (char *, int);
184
185 static void condition_command (char *, int);
186
187 typedef enum
188   {
189     mark_inserted,
190     mark_uninserted
191   }
192 insertion_state_t;
193
194 static int remove_breakpoint (struct bp_location *, insertion_state_t);
195 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
196
197 static enum print_stop_action print_bp_stop_message (bpstat bs);
198
199 static int watchpoint_check (void *);
200
201 static void maintenance_info_breakpoints (char *, int);
202
203 static int hw_breakpoint_used_count (void);
204
205 static int hw_watchpoint_use_count (struct breakpoint *);
206
207 static int hw_watchpoint_used_count_others (struct breakpoint *except,
208                                             enum bptype type,
209                                             int *other_type_used);
210
211 static void hbreak_command (char *, int);
212
213 static void thbreak_command (char *, int);
214
215 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
216                                     int count);
217
218 static void stop_command (char *arg, int from_tty);
219
220 static void stopin_command (char *arg, int from_tty);
221
222 static void stopat_command (char *arg, int from_tty);
223
224 static char *ep_parse_optional_if_clause (char **arg);
225
226 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
227                                        char *arg, int tempflag, int from_tty);
228
229 static void tcatch_command (char *arg, int from_tty);
230
231 static void detach_single_step_breakpoints (void);
232
233 static int single_step_breakpoint_inserted_here_p (struct address_space *,
234                                                    CORE_ADDR pc);
235
236 static void free_bp_location (struct bp_location *loc);
237 static void incref_bp_location (struct bp_location *loc);
238 static void decref_bp_location (struct bp_location **loc);
239
240 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
241
242 static void update_global_location_list (int);
243
244 static void update_global_location_list_nothrow (int);
245
246 static int is_hardware_watchpoint (const struct breakpoint *bpt);
247
248 static void insert_breakpoint_locations (void);
249
250 static int syscall_catchpoint_p (struct breakpoint *b);
251
252 static void tracepoints_info (char *, int);
253
254 static void delete_trace_command (char *, int);
255
256 static void enable_trace_command (char *, int);
257
258 static void disable_trace_command (char *, int);
259
260 static void trace_pass_command (char *, int);
261
262 static int is_masked_watchpoint (const struct breakpoint *b);
263
264 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
265
266 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
267    otherwise.  */
268
269 static int strace_marker_p (struct breakpoint *b);
270
271 static void init_catchpoint (struct breakpoint *b,
272                              struct gdbarch *gdbarch, int tempflag,
273                              char *cond_string,
274                              const struct breakpoint_ops *ops);
275
276 /* The abstract base class all breakpoint_ops structures inherit
277    from.  */
278 static struct breakpoint_ops base_breakpoint_ops;
279
280 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
281    that are implemented on top of software or hardware breakpoints
282    (user breakpoints, internal and momentary breakpoints, etc.).  */
283 static struct breakpoint_ops bkpt_base_breakpoint_ops;
284
285 /* Internal breakpoints class type.  */
286 static struct breakpoint_ops internal_breakpoint_ops;
287
288 /* Momentary breakpoints class type.  */
289 static struct breakpoint_ops momentary_breakpoint_ops;
290
291 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
292 static struct breakpoint_ops longjmp_breakpoint_ops;
293
294 /* The breakpoint_ops structure to be used in regular user created
295    breakpoints.  */
296 struct breakpoint_ops bkpt_breakpoint_ops;
297
298 /* Breakpoints set on probes.  */
299 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
300
301 /* Dynamic printf class type.  */
302 static struct breakpoint_ops dprintf_breakpoint_ops;
303
304 /* A reference-counted struct command_line.  This lets multiple
305    breakpoints share a single command list.  */
306 struct counted_command_line
307 {
308   /* The reference count.  */
309   int refc;
310
311   /* The command list.  */
312   struct command_line *commands;
313 };
314
315 struct command_line *
316 breakpoint_commands (struct breakpoint *b)
317 {
318   return b->commands ? b->commands->commands : NULL;
319 }
320
321 /* Flag indicating that a command has proceeded the inferior past the
322    current breakpoint.  */
323
324 static int breakpoint_proceeded;
325
326 const char *
327 bpdisp_text (enum bpdisp disp)
328 {
329   /* NOTE: the following values are a part of MI protocol and
330      represent values of 'disp' field returned when inferior stops at
331      a breakpoint.  */
332   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
333
334   return bpdisps[(int) disp];
335 }
336
337 /* Prototypes for exported functions.  */
338 /* If FALSE, gdb will not use hardware support for watchpoints, even
339    if such is available.  */
340 static int can_use_hw_watchpoints;
341
342 static void
343 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
344                              struct cmd_list_element *c,
345                              const char *value)
346 {
347   fprintf_filtered (file,
348                     _("Debugger's willingness to use "
349                       "watchpoint hardware is %s.\n"),
350                     value);
351 }
352
353 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
354    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
355    for unrecognized breakpoint locations.
356    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
357 static enum auto_boolean pending_break_support;
358 static void
359 show_pending_break_support (struct ui_file *file, int from_tty,
360                             struct cmd_list_element *c,
361                             const char *value)
362 {
363   fprintf_filtered (file,
364                     _("Debugger's behavior regarding "
365                       "pending breakpoints is %s.\n"),
366                     value);
367 }
368
369 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
370    set with "break" but falling in read-only memory.
371    If 0, gdb will warn about such breakpoints, but won't automatically
372    use hardware breakpoints.  */
373 static int automatic_hardware_breakpoints;
374 static void
375 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
376                                      struct cmd_list_element *c,
377                                      const char *value)
378 {
379   fprintf_filtered (file,
380                     _("Automatic usage of hardware breakpoints is %s.\n"),
381                     value);
382 }
383
384 /* If on, gdb will keep breakpoints inserted even as inferior is
385    stopped, and immediately insert any new breakpoints.  If off, gdb
386    will insert breakpoints into inferior only when resuming it, and
387    will remove breakpoints upon stop.  If auto, GDB will behave as ON
388    if in non-stop mode, and as OFF if all-stop mode.*/
389
390 static const char always_inserted_auto[] = "auto";
391 static const char always_inserted_on[] = "on";
392 static const char always_inserted_off[] = "off";
393 static const char *const always_inserted_enums[] = {
394   always_inserted_auto,
395   always_inserted_off,
396   always_inserted_on,
397   NULL
398 };
399 static const char *always_inserted_mode = always_inserted_auto;
400 static void
401 show_always_inserted_mode (struct ui_file *file, int from_tty,
402                      struct cmd_list_element *c, const char *value)
403 {
404   if (always_inserted_mode == always_inserted_auto)
405     fprintf_filtered (file,
406                       _("Always inserted breakpoint "
407                         "mode is %s (currently %s).\n"),
408                       value,
409                       breakpoints_always_inserted_mode () ? "on" : "off");
410   else
411     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
412                       value);
413 }
414
415 int
416 breakpoints_always_inserted_mode (void)
417 {
418   return (always_inserted_mode == always_inserted_on
419           || (always_inserted_mode == always_inserted_auto && non_stop));
420 }
421
422 static const char condition_evaluation_both[] = "host or target";
423
424 /* Modes for breakpoint condition evaluation.  */
425 static const char condition_evaluation_auto[] = "auto";
426 static const char condition_evaluation_host[] = "host";
427 static const char condition_evaluation_target[] = "target";
428 static const char *const condition_evaluation_enums[] = {
429   condition_evaluation_auto,
430   condition_evaluation_host,
431   condition_evaluation_target,
432   NULL
433 };
434
435 /* Global that holds the current mode for breakpoint condition evaluation.  */
436 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
437
438 /* Global that we use to display information to the user (gets its value from
439    condition_evaluation_mode_1.  */
440 static const char *condition_evaluation_mode = condition_evaluation_auto;
441
442 /* Translate a condition evaluation mode MODE into either "host"
443    or "target".  This is used mostly to translate from "auto" to the
444    real setting that is being used.  It returns the translated
445    evaluation mode.  */
446
447 static const char *
448 translate_condition_evaluation_mode (const char *mode)
449 {
450   if (mode == condition_evaluation_auto)
451     {
452       if (target_supports_evaluation_of_breakpoint_conditions ())
453         return condition_evaluation_target;
454       else
455         return condition_evaluation_host;
456     }
457   else
458     return mode;
459 }
460
461 /* Discovers what condition_evaluation_auto translates to.  */
462
463 static const char *
464 breakpoint_condition_evaluation_mode (void)
465 {
466   return translate_condition_evaluation_mode (condition_evaluation_mode);
467 }
468
469 /* Return true if GDB should evaluate breakpoint conditions or false
470    otherwise.  */
471
472 static int
473 gdb_evaluates_breakpoint_condition_p (void)
474 {
475   const char *mode = breakpoint_condition_evaluation_mode ();
476
477   return (mode == condition_evaluation_host);
478 }
479
480 void _initialize_breakpoint (void);
481
482 /* Are we executing breakpoint commands?  */
483 static int executing_breakpoint_commands;
484
485 /* Are overlay event breakpoints enabled? */
486 static int overlay_events_enabled;
487
488 /* See description in breakpoint.h. */
489 int target_exact_watchpoints = 0;
490
491 /* Walk the following statement or block through all breakpoints.
492    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
493    current breakpoint.  */
494
495 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
496
497 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
498         for (B = breakpoint_chain;      \
499              B ? (TMP=B->next, 1): 0;   \
500              B = TMP)
501
502 /* Similar iterator for the low-level breakpoints.  SAFE variant is
503    not provided so update_global_location_list must not be called
504    while executing the block of ALL_BP_LOCATIONS.  */
505
506 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
507         for (BP_TMP = bp_location;                                      \
508              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
509              BP_TMP++)
510
511 /* Iterates through locations with address ADDRESS for the currently selected
512    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
513    to where the loop should start from.
514    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
515    appropriate location to start with.  */
516
517 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
518         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
519              BP_LOCP_TMP = BP_LOCP_START;                               \
520              BP_LOCP_START                                              \
521              && (BP_LOCP_TMP < bp_location + bp_location_count          \
522              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
523              BP_LOCP_TMP++)
524
525 /* Iterator for tracepoints only.  */
526
527 #define ALL_TRACEPOINTS(B)  \
528   for (B = breakpoint_chain; B; B = B->next)  \
529     if (is_tracepoint (B))
530
531 /* Chains of all breakpoints defined.  */
532
533 struct breakpoint *breakpoint_chain;
534
535 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
536
537 static struct bp_location **bp_location;
538
539 /* Number of elements of BP_LOCATION.  */
540
541 static unsigned bp_location_count;
542
543 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
544    ADDRESS for the current elements of BP_LOCATION which get a valid
545    result from bp_location_has_shadow.  You can use it for roughly
546    limiting the subrange of BP_LOCATION to scan for shadow bytes for
547    an address you need to read.  */
548
549 static CORE_ADDR bp_location_placed_address_before_address_max;
550
551 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
552    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
553    BP_LOCATION which get a valid result from bp_location_has_shadow.
554    You can use it for roughly limiting the subrange of BP_LOCATION to
555    scan for shadow bytes for an address you need to read.  */
556
557 static CORE_ADDR bp_location_shadow_len_after_address_max;
558
559 /* The locations that no longer correspond to any breakpoint, unlinked
560    from bp_location array, but for which a hit may still be reported
561    by a target.  */
562 VEC(bp_location_p) *moribund_locations = NULL;
563
564 /* Number of last breakpoint made.  */
565
566 static int breakpoint_count;
567
568 /* The value of `breakpoint_count' before the last command that
569    created breakpoints.  If the last (break-like) command created more
570    than one breakpoint, then the difference between BREAKPOINT_COUNT
571    and PREV_BREAKPOINT_COUNT is more than one.  */
572 static int prev_breakpoint_count;
573
574 /* Number of last tracepoint made.  */
575
576 static int tracepoint_count;
577
578 static struct cmd_list_element *breakpoint_set_cmdlist;
579 static struct cmd_list_element *breakpoint_show_cmdlist;
580 struct cmd_list_element *save_cmdlist;
581
582 /* Return whether a breakpoint is an active enabled breakpoint.  */
583 static int
584 breakpoint_enabled (struct breakpoint *b)
585 {
586   return (b->enable_state == bp_enabled);
587 }
588
589 /* Set breakpoint count to NUM.  */
590
591 static void
592 set_breakpoint_count (int num)
593 {
594   prev_breakpoint_count = breakpoint_count;
595   breakpoint_count = num;
596   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
597 }
598
599 /* Used by `start_rbreak_breakpoints' below, to record the current
600    breakpoint count before "rbreak" creates any breakpoint.  */
601 static int rbreak_start_breakpoint_count;
602
603 /* Called at the start an "rbreak" command to record the first
604    breakpoint made.  */
605
606 void
607 start_rbreak_breakpoints (void)
608 {
609   rbreak_start_breakpoint_count = breakpoint_count;
610 }
611
612 /* Called at the end of an "rbreak" command to record the last
613    breakpoint made.  */
614
615 void
616 end_rbreak_breakpoints (void)
617 {
618   prev_breakpoint_count = rbreak_start_breakpoint_count;
619 }
620
621 /* Used in run_command to zero the hit count when a new run starts.  */
622
623 void
624 clear_breakpoint_hit_counts (void)
625 {
626   struct breakpoint *b;
627
628   ALL_BREAKPOINTS (b)
629     b->hit_count = 0;
630 }
631
632 /* Allocate a new counted_command_line with reference count of 1.
633    The new structure owns COMMANDS.  */
634
635 static struct counted_command_line *
636 alloc_counted_command_line (struct command_line *commands)
637 {
638   struct counted_command_line *result
639     = xmalloc (sizeof (struct counted_command_line));
640
641   result->refc = 1;
642   result->commands = commands;
643   return result;
644 }
645
646 /* Increment reference count.  This does nothing if CMD is NULL.  */
647
648 static void
649 incref_counted_command_line (struct counted_command_line *cmd)
650 {
651   if (cmd)
652     ++cmd->refc;
653 }
654
655 /* Decrement reference count.  If the reference count reaches 0,
656    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
657    nothing if *CMDP is NULL.  */
658
659 static void
660 decref_counted_command_line (struct counted_command_line **cmdp)
661 {
662   if (*cmdp)
663     {
664       if (--(*cmdp)->refc == 0)
665         {
666           free_command_lines (&(*cmdp)->commands);
667           xfree (*cmdp);
668         }
669       *cmdp = NULL;
670     }
671 }
672
673 /* A cleanup function that calls decref_counted_command_line.  */
674
675 static void
676 do_cleanup_counted_command_line (void *arg)
677 {
678   decref_counted_command_line (arg);
679 }
680
681 /* Create a cleanup that calls decref_counted_command_line on the
682    argument.  */
683
684 static struct cleanup *
685 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
686 {
687   return make_cleanup (do_cleanup_counted_command_line, cmdp);
688 }
689
690 \f
691 /* Return the breakpoint with the specified number, or NULL
692    if the number does not refer to an existing breakpoint.  */
693
694 struct breakpoint *
695 get_breakpoint (int num)
696 {
697   struct breakpoint *b;
698
699   ALL_BREAKPOINTS (b)
700     if (b->number == num)
701       return b;
702   
703   return NULL;
704 }
705
706 \f
707
708 /* Mark locations as "conditions have changed" in case the target supports
709    evaluating conditions on its side.  */
710
711 static void
712 mark_breakpoint_modified (struct breakpoint *b)
713 {
714   struct bp_location *loc;
715
716   /* This is only meaningful if the target is
717      evaluating conditions and if the user has
718      opted for condition evaluation on the target's
719      side.  */
720   if (gdb_evaluates_breakpoint_condition_p ()
721       || !target_supports_evaluation_of_breakpoint_conditions ())
722     return;
723
724   if (!is_breakpoint (b))
725     return;
726
727   for (loc = b->loc; loc; loc = loc->next)
728     loc->condition_changed = condition_modified;
729 }
730
731 /* Mark location as "conditions have changed" in case the target supports
732    evaluating conditions on its side.  */
733
734 static void
735 mark_breakpoint_location_modified (struct bp_location *loc)
736 {
737   /* This is only meaningful if the target is
738      evaluating conditions and if the user has
739      opted for condition evaluation on the target's
740      side.  */
741   if (gdb_evaluates_breakpoint_condition_p ()
742       || !target_supports_evaluation_of_breakpoint_conditions ())
743
744     return;
745
746   if (!is_breakpoint (loc->owner))
747     return;
748
749   loc->condition_changed = condition_modified;
750 }
751
752 /* Sets the condition-evaluation mode using the static global
753    condition_evaluation_mode.  */
754
755 static void
756 set_condition_evaluation_mode (char *args, int from_tty,
757                                struct cmd_list_element *c)
758 {
759   const char *old_mode, *new_mode;
760
761   if ((condition_evaluation_mode_1 == condition_evaluation_target)
762       && !target_supports_evaluation_of_breakpoint_conditions ())
763     {
764       condition_evaluation_mode_1 = condition_evaluation_mode;
765       warning (_("Target does not support breakpoint condition evaluation.\n"
766                  "Using host evaluation mode instead."));
767       return;
768     }
769
770   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
771   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
772
773   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
774      settings was "auto".  */
775   condition_evaluation_mode = condition_evaluation_mode_1;
776
777   /* Only update the mode if the user picked a different one.  */
778   if (new_mode != old_mode)
779     {
780       struct bp_location *loc, **loc_tmp;
781       /* If the user switched to a different evaluation mode, we
782          need to synch the changes with the target as follows:
783
784          "host" -> "target": Send all (valid) conditions to the target.
785          "target" -> "host": Remove all the conditions from the target.
786       */
787
788       if (new_mode == condition_evaluation_target)
789         {
790           /* Mark everything modified and synch conditions with the
791              target.  */
792           ALL_BP_LOCATIONS (loc, loc_tmp)
793             mark_breakpoint_location_modified (loc);
794         }
795       else
796         {
797           /* Manually mark non-duplicate locations to synch conditions
798              with the target.  We do this to remove all the conditions the
799              target knows about.  */
800           ALL_BP_LOCATIONS (loc, loc_tmp)
801             if (is_breakpoint (loc->owner) && loc->inserted)
802               loc->needs_update = 1;
803         }
804
805       /* Do the update.  */
806       update_global_location_list (1);
807     }
808
809   return;
810 }
811
812 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
813    what "auto" is translating to.  */
814
815 static void
816 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
817                                 struct cmd_list_element *c, const char *value)
818 {
819   if (condition_evaluation_mode == condition_evaluation_auto)
820     fprintf_filtered (file,
821                       _("Breakpoint condition evaluation "
822                         "mode is %s (currently %s).\n"),
823                       value,
824                       breakpoint_condition_evaluation_mode ());
825   else
826     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
827                       value);
828 }
829
830 /* A comparison function for bp_location AP and BP that is used by
831    bsearch.  This comparison function only cares about addresses, unlike
832    the more general bp_location_compare function.  */
833
834 static int
835 bp_location_compare_addrs (const void *ap, const void *bp)
836 {
837   struct bp_location *a = *(void **) ap;
838   struct bp_location *b = *(void **) bp;
839
840   if (a->address == b->address)
841     return 0;
842   else
843     return ((a->address > b->address) - (a->address < b->address));
844 }
845
846 /* Helper function to skip all bp_locations with addresses
847    less than ADDRESS.  It returns the first bp_location that
848    is greater than or equal to ADDRESS.  If none is found, just
849    return NULL.  */
850
851 static struct bp_location **
852 get_first_locp_gte_addr (CORE_ADDR address)
853 {
854   struct bp_location dummy_loc;
855   struct bp_location *dummy_locp = &dummy_loc;
856   struct bp_location **locp_found = NULL;
857
858   /* Initialize the dummy location's address field.  */
859   memset (&dummy_loc, 0, sizeof (struct bp_location));
860   dummy_loc.address = address;
861
862   /* Find a close match to the first location at ADDRESS.  */
863   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
864                         sizeof (struct bp_location **),
865                         bp_location_compare_addrs);
866
867   /* Nothing was found, nothing left to do.  */
868   if (locp_found == NULL)
869     return NULL;
870
871   /* We may have found a location that is at ADDRESS but is not the first in the
872      location's list.  Go backwards (if possible) and locate the first one.  */
873   while ((locp_found - 1) >= bp_location
874          && (*(locp_found - 1))->address == address)
875     locp_found--;
876
877   return locp_found;
878 }
879
880 void
881 set_breakpoint_condition (struct breakpoint *b, char *exp,
882                           int from_tty)
883 {
884   xfree (b->cond_string);
885   b->cond_string = NULL;
886
887   if (is_watchpoint (b))
888     {
889       struct watchpoint *w = (struct watchpoint *) b;
890
891       xfree (w->cond_exp);
892       w->cond_exp = NULL;
893     }
894   else
895     {
896       struct bp_location *loc;
897
898       for (loc = b->loc; loc; loc = loc->next)
899         {
900           xfree (loc->cond);
901           loc->cond = NULL;
902
903           /* No need to free the condition agent expression
904              bytecode (if we have one).  We will handle this
905              when we go through update_global_location_list.  */
906         }
907     }
908
909   if (*exp == 0)
910     {
911       if (from_tty)
912         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
913     }
914   else
915     {
916       char *arg = exp;
917
918       /* I don't know if it matters whether this is the string the user
919          typed in or the decompiled expression.  */
920       b->cond_string = xstrdup (arg);
921       b->condition_not_parsed = 0;
922
923       if (is_watchpoint (b))
924         {
925           struct watchpoint *w = (struct watchpoint *) b;
926
927           innermost_block = NULL;
928           arg = exp;
929           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
930           if (*arg)
931             error (_("Junk at end of expression"));
932           w->cond_exp_valid_block = innermost_block;
933         }
934       else
935         {
936           struct bp_location *loc;
937
938           for (loc = b->loc; loc; loc = loc->next)
939             {
940               arg = exp;
941               loc->cond =
942                 parse_exp_1 (&arg, loc->address,
943                              block_for_pc (loc->address), 0);
944               if (*arg)
945                 error (_("Junk at end of expression"));
946             }
947         }
948     }
949   mark_breakpoint_modified (b);
950
951   breakpoints_changed ();
952   observer_notify_breakpoint_modified (b);
953 }
954
955 /* Completion for the "condition" command.  */
956
957 static VEC (char_ptr) *
958 condition_completer (struct cmd_list_element *cmd, char *text, char *word)
959 {
960   char *space;
961
962   text = skip_spaces (text);
963   space = skip_to_space (text);
964   if (*space == '\0')
965     {
966       int len;
967       struct breakpoint *b;
968       VEC (char_ptr) *result = NULL;
969
970       if (text[0] == '$')
971         {
972           /* We don't support completion of history indices.  */
973           if (isdigit (text[1]))
974             return NULL;
975           return complete_internalvar (&text[1]);
976         }
977
978       /* We're completing the breakpoint number.  */
979       len = strlen (text);
980
981       ALL_BREAKPOINTS (b)
982       {
983         int single = b->loc->next == NULL;
984         struct bp_location *loc;
985         int count = 1;
986
987         for (loc = b->loc; loc; loc = loc->next)
988           {
989             char location[50];
990
991             if (single)
992               sprintf (location, "%d", b->number);
993             else
994               sprintf (location, "%d.%d", b->number, count);
995
996             if (strncmp (location, text, len) == 0)
997               VEC_safe_push (char_ptr, result, xstrdup (location));
998
999             ++count;
1000           }
1001       }
1002
1003       return result;
1004     }
1005
1006   /* We're completing the expression part.  */
1007   text = skip_spaces (space);
1008   return expression_completer (cmd, text, word);
1009 }
1010
1011 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1012
1013 static void
1014 condition_command (char *arg, int from_tty)
1015 {
1016   struct breakpoint *b;
1017   char *p;
1018   int bnum;
1019
1020   if (arg == 0)
1021     error_no_arg (_("breakpoint number"));
1022
1023   p = arg;
1024   bnum = get_number (&p);
1025   if (bnum == 0)
1026     error (_("Bad breakpoint argument: '%s'"), arg);
1027
1028   ALL_BREAKPOINTS (b)
1029     if (b->number == bnum)
1030       {
1031         /* Check if this breakpoint has a Python object assigned to
1032            it, and if it has a definition of the "stop"
1033            method.  This method and conditions entered into GDB from
1034            the CLI are mutually exclusive.  */
1035         if (b->py_bp_object
1036             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
1037           error (_("Cannot set a condition where a Python 'stop' "
1038                    "method has been defined in the breakpoint."));
1039         set_breakpoint_condition (b, p, from_tty);
1040
1041         if (is_breakpoint (b))
1042           update_global_location_list (1);
1043
1044         return;
1045       }
1046
1047   error (_("No breakpoint number %d."), bnum);
1048 }
1049
1050 /* Check that COMMAND do not contain commands that are suitable
1051    only for tracepoints and not suitable for ordinary breakpoints.
1052    Throw if any such commands is found.  */
1053
1054 static void
1055 check_no_tracepoint_commands (struct command_line *commands)
1056 {
1057   struct command_line *c;
1058
1059   for (c = commands; c; c = c->next)
1060     {
1061       int i;
1062
1063       if (c->control_type == while_stepping_control)
1064         error (_("The 'while-stepping' command can "
1065                  "only be used for tracepoints"));
1066
1067       for (i = 0; i < c->body_count; ++i)
1068         check_no_tracepoint_commands ((c->body_list)[i]);
1069
1070       /* Not that command parsing removes leading whitespace and comment
1071          lines and also empty lines.  So, we only need to check for
1072          command directly.  */
1073       if (strstr (c->line, "collect ") == c->line)
1074         error (_("The 'collect' command can only be used for tracepoints"));
1075
1076       if (strstr (c->line, "teval ") == c->line)
1077         error (_("The 'teval' command can only be used for tracepoints"));
1078     }
1079 }
1080
1081 /* Encapsulate tests for different types of tracepoints.  */
1082
1083 static int
1084 is_tracepoint_type (enum bptype type)
1085 {
1086   return (type == bp_tracepoint
1087           || type == bp_fast_tracepoint
1088           || type == bp_static_tracepoint);
1089 }
1090
1091 int
1092 is_tracepoint (const struct breakpoint *b)
1093 {
1094   return is_tracepoint_type (b->type);
1095 }
1096
1097 /* A helper function that validates that COMMANDS are valid for a
1098    breakpoint.  This function will throw an exception if a problem is
1099    found.  */
1100
1101 static void
1102 validate_commands_for_breakpoint (struct breakpoint *b,
1103                                   struct command_line *commands)
1104 {
1105   if (is_tracepoint (b))
1106     {
1107       /* We need to verify that each top-level element of commands is
1108          valid for tracepoints, that there's at most one
1109          while-stepping element, and that while-stepping's body has
1110          valid tracing commands excluding nested while-stepping.  */
1111       struct command_line *c;
1112       struct command_line *while_stepping = 0;
1113       for (c = commands; c; c = c->next)
1114         {
1115           if (c->control_type == while_stepping_control)
1116             {
1117               if (b->type == bp_fast_tracepoint)
1118                 error (_("The 'while-stepping' command "
1119                          "cannot be used for fast tracepoint"));
1120               else if (b->type == bp_static_tracepoint)
1121                 error (_("The 'while-stepping' command "
1122                          "cannot be used for static tracepoint"));
1123
1124               if (while_stepping)
1125                 error (_("The 'while-stepping' command "
1126                          "can be used only once"));
1127               else
1128                 while_stepping = c;
1129             }
1130         }
1131       if (while_stepping)
1132         {
1133           struct command_line *c2;
1134
1135           gdb_assert (while_stepping->body_count == 1);
1136           c2 = while_stepping->body_list[0];
1137           for (; c2; c2 = c2->next)
1138             {
1139               if (c2->control_type == while_stepping_control)
1140                 error (_("The 'while-stepping' command cannot be nested"));
1141             }
1142         }
1143     }
1144   else
1145     {
1146       check_no_tracepoint_commands (commands);
1147     }
1148 }
1149
1150 /* Return a vector of all the static tracepoints set at ADDR.  The
1151    caller is responsible for releasing the vector.  */
1152
1153 VEC(breakpoint_p) *
1154 static_tracepoints_here (CORE_ADDR addr)
1155 {
1156   struct breakpoint *b;
1157   VEC(breakpoint_p) *found = 0;
1158   struct bp_location *loc;
1159
1160   ALL_BREAKPOINTS (b)
1161     if (b->type == bp_static_tracepoint)
1162       {
1163         for (loc = b->loc; loc; loc = loc->next)
1164           if (loc->address == addr)
1165             VEC_safe_push(breakpoint_p, found, b);
1166       }
1167
1168   return found;
1169 }
1170
1171 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1172    validate that only allowed commands are included.  */
1173
1174 void
1175 breakpoint_set_commands (struct breakpoint *b, 
1176                          struct command_line *commands)
1177 {
1178   validate_commands_for_breakpoint (b, commands);
1179
1180   decref_counted_command_line (&b->commands);
1181   b->commands = alloc_counted_command_line (commands);
1182   breakpoints_changed ();
1183   observer_notify_breakpoint_modified (b);
1184 }
1185
1186 /* Set the internal `silent' flag on the breakpoint.  Note that this
1187    is not the same as the "silent" that may appear in the breakpoint's
1188    commands.  */
1189
1190 void
1191 breakpoint_set_silent (struct breakpoint *b, int silent)
1192 {
1193   int old_silent = b->silent;
1194
1195   b->silent = silent;
1196   if (old_silent != silent)
1197     observer_notify_breakpoint_modified (b);
1198 }
1199
1200 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1201    breakpoint work for any thread.  */
1202
1203 void
1204 breakpoint_set_thread (struct breakpoint *b, int thread)
1205 {
1206   int old_thread = b->thread;
1207
1208   b->thread = thread;
1209   if (old_thread != thread)
1210     observer_notify_breakpoint_modified (b);
1211 }
1212
1213 /* Set the task for this breakpoint.  If TASK is 0, make the
1214    breakpoint work for any task.  */
1215
1216 void
1217 breakpoint_set_task (struct breakpoint *b, int task)
1218 {
1219   int old_task = b->task;
1220
1221   b->task = task;
1222   if (old_task != task)
1223     observer_notify_breakpoint_modified (b);
1224 }
1225
1226 void
1227 check_tracepoint_command (char *line, void *closure)
1228 {
1229   struct breakpoint *b = closure;
1230
1231   validate_actionline (&line, b);
1232 }
1233
1234 /* A structure used to pass information through
1235    map_breakpoint_numbers.  */
1236
1237 struct commands_info
1238 {
1239   /* True if the command was typed at a tty.  */
1240   int from_tty;
1241
1242   /* The breakpoint range spec.  */
1243   char *arg;
1244
1245   /* Non-NULL if the body of the commands are being read from this
1246      already-parsed command.  */
1247   struct command_line *control;
1248
1249   /* The command lines read from the user, or NULL if they have not
1250      yet been read.  */
1251   struct counted_command_line *cmd;
1252 };
1253
1254 /* A callback for map_breakpoint_numbers that sets the commands for
1255    commands_command.  */
1256
1257 static void
1258 do_map_commands_command (struct breakpoint *b, void *data)
1259 {
1260   struct commands_info *info = data;
1261
1262   if (info->cmd == NULL)
1263     {
1264       struct command_line *l;
1265
1266       if (info->control != NULL)
1267         l = copy_command_lines (info->control->body_list[0]);
1268       else
1269         {
1270           struct cleanup *old_chain;
1271           char *str;
1272
1273           str = xstrprintf (_("Type commands for breakpoint(s) "
1274                               "%s, one per line."),
1275                             info->arg);
1276
1277           old_chain = make_cleanup (xfree, str);
1278
1279           l = read_command_lines (str,
1280                                   info->from_tty, 1,
1281                                   (is_tracepoint (b)
1282                                    ? check_tracepoint_command : 0),
1283                                   b);
1284
1285           do_cleanups (old_chain);
1286         }
1287
1288       info->cmd = alloc_counted_command_line (l);
1289     }
1290
1291   /* If a breakpoint was on the list more than once, we don't need to
1292      do anything.  */
1293   if (b->commands != info->cmd)
1294     {
1295       validate_commands_for_breakpoint (b, info->cmd->commands);
1296       incref_counted_command_line (info->cmd);
1297       decref_counted_command_line (&b->commands);
1298       b->commands = info->cmd;
1299       breakpoints_changed ();
1300       observer_notify_breakpoint_modified (b);
1301     }
1302 }
1303
1304 static void
1305 commands_command_1 (char *arg, int from_tty, 
1306                     struct command_line *control)
1307 {
1308   struct cleanup *cleanups;
1309   struct commands_info info;
1310
1311   info.from_tty = from_tty;
1312   info.control = control;
1313   info.cmd = NULL;
1314   /* If we read command lines from the user, then `info' will hold an
1315      extra reference to the commands that we must clean up.  */
1316   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1317
1318   if (arg == NULL || !*arg)
1319     {
1320       if (breakpoint_count - prev_breakpoint_count > 1)
1321         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1322                           breakpoint_count);
1323       else if (breakpoint_count > 0)
1324         arg = xstrprintf ("%d", breakpoint_count);
1325       else
1326         {
1327           /* So that we don't try to free the incoming non-NULL
1328              argument in the cleanup below.  Mapping breakpoint
1329              numbers will fail in this case.  */
1330           arg = NULL;
1331         }
1332     }
1333   else
1334     /* The command loop has some static state, so we need to preserve
1335        our argument.  */
1336     arg = xstrdup (arg);
1337
1338   if (arg != NULL)
1339     make_cleanup (xfree, arg);
1340
1341   info.arg = arg;
1342
1343   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1344
1345   if (info.cmd == NULL)
1346     error (_("No breakpoints specified."));
1347
1348   do_cleanups (cleanups);
1349 }
1350
1351 static void
1352 commands_command (char *arg, int from_tty)
1353 {
1354   commands_command_1 (arg, from_tty, NULL);
1355 }
1356
1357 /* Like commands_command, but instead of reading the commands from
1358    input stream, takes them from an already parsed command structure.
1359
1360    This is used by cli-script.c to DTRT with breakpoint commands
1361    that are part of if and while bodies.  */
1362 enum command_control_type
1363 commands_from_control_command (char *arg, struct command_line *cmd)
1364 {
1365   commands_command_1 (arg, 0, cmd);
1366   return simple_control;
1367 }
1368
1369 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1370
1371 static int
1372 bp_location_has_shadow (struct bp_location *bl)
1373 {
1374   if (bl->loc_type != bp_loc_software_breakpoint)
1375     return 0;
1376   if (!bl->inserted)
1377     return 0;
1378   if (bl->target_info.shadow_len == 0)
1379     /* BL isn't valid, or doesn't shadow memory.  */
1380     return 0;
1381   return 1;
1382 }
1383
1384 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1385    by replacing any memory breakpoints with their shadowed contents.
1386
1387    If READBUF is not NULL, this buffer must not overlap with any of
1388    the breakpoint location's shadow_contents buffers.  Otherwise,
1389    a failed assertion internal error will be raised.
1390
1391    The range of shadowed area by each bp_location is:
1392      bl->address - bp_location_placed_address_before_address_max
1393      up to bl->address + bp_location_shadow_len_after_address_max
1394    The range we were requested to resolve shadows for is:
1395      memaddr ... memaddr + len
1396    Thus the safe cutoff boundaries for performance optimization are
1397      memaddr + len <= (bl->address
1398                        - bp_location_placed_address_before_address_max)
1399    and:
1400      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1401
1402 void
1403 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1404                         const gdb_byte *writebuf_org,
1405                         ULONGEST memaddr, LONGEST len)
1406 {
1407   /* Left boundary, right boundary and median element of our binary
1408      search.  */
1409   unsigned bc_l, bc_r, bc;
1410
1411   /* Find BC_L which is a leftmost element which may affect BUF
1412      content.  It is safe to report lower value but a failure to
1413      report higher one.  */
1414
1415   bc_l = 0;
1416   bc_r = bp_location_count;
1417   while (bc_l + 1 < bc_r)
1418     {
1419       struct bp_location *bl;
1420
1421       bc = (bc_l + bc_r) / 2;
1422       bl = bp_location[bc];
1423
1424       /* Check first BL->ADDRESS will not overflow due to the added
1425          constant.  Then advance the left boundary only if we are sure
1426          the BC element can in no way affect the BUF content (MEMADDR
1427          to MEMADDR + LEN range).
1428
1429          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1430          offset so that we cannot miss a breakpoint with its shadow
1431          range tail still reaching MEMADDR.  */
1432
1433       if ((bl->address + bp_location_shadow_len_after_address_max
1434            >= bl->address)
1435           && (bl->address + bp_location_shadow_len_after_address_max
1436               <= memaddr))
1437         bc_l = bc;
1438       else
1439         bc_r = bc;
1440     }
1441
1442   /* Due to the binary search above, we need to make sure we pick the
1443      first location that's at BC_L's address.  E.g., if there are
1444      multiple locations at the same address, BC_L may end up pointing
1445      at a duplicate location, and miss the "master"/"inserted"
1446      location.  Say, given locations L1, L2 and L3 at addresses A and
1447      B:
1448
1449       L1@A, L2@A, L3@B, ...
1450
1451      BC_L could end up pointing at location L2, while the "master"
1452      location could be L1.  Since the `loc->inserted' flag is only set
1453      on "master" locations, we'd forget to restore the shadow of L1
1454      and L2.  */
1455   while (bc_l > 0
1456          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1457     bc_l--;
1458
1459   /* Now do full processing of the found relevant range of elements.  */
1460
1461   for (bc = bc_l; bc < bp_location_count; bc++)
1462   {
1463     struct bp_location *bl = bp_location[bc];
1464     CORE_ADDR bp_addr = 0;
1465     int bp_size = 0;
1466     int bptoffset = 0;
1467
1468     /* bp_location array has BL->OWNER always non-NULL.  */
1469     if (bl->owner->type == bp_none)
1470       warning (_("reading through apparently deleted breakpoint #%d?"),
1471                bl->owner->number);
1472
1473     /* Performance optimization: any further element can no longer affect BUF
1474        content.  */
1475
1476     if (bl->address >= bp_location_placed_address_before_address_max
1477         && memaddr + len <= (bl->address
1478                              - bp_location_placed_address_before_address_max))
1479       break;
1480
1481     if (!bp_location_has_shadow (bl))
1482       continue;
1483     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1484                                    current_program_space->aspace, 0))
1485       continue;
1486
1487     /* Addresses and length of the part of the breakpoint that
1488        we need to copy.  */
1489     bp_addr = bl->target_info.placed_address;
1490     bp_size = bl->target_info.shadow_len;
1491
1492     if (bp_addr + bp_size <= memaddr)
1493       /* The breakpoint is entirely before the chunk of memory we
1494          are reading.  */
1495       continue;
1496
1497     if (bp_addr >= memaddr + len)
1498       /* The breakpoint is entirely after the chunk of memory we are
1499          reading.  */
1500       continue;
1501
1502     /* Offset within shadow_contents.  */
1503     if (bp_addr < memaddr)
1504       {
1505         /* Only copy the second part of the breakpoint.  */
1506         bp_size -= memaddr - bp_addr;
1507         bptoffset = memaddr - bp_addr;
1508         bp_addr = memaddr;
1509       }
1510
1511     if (bp_addr + bp_size > memaddr + len)
1512       {
1513         /* Only copy the first part of the breakpoint.  */
1514         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1515       }
1516
1517     if (readbuf != NULL)
1518       {
1519         /* Verify that the readbuf buffer does not overlap with
1520            the shadow_contents buffer.  */
1521         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1522                     || readbuf >= (bl->target_info.shadow_contents
1523                                    + bl->target_info.shadow_len));
1524
1525         /* Update the read buffer with this inserted breakpoint's
1526            shadow.  */
1527         memcpy (readbuf + bp_addr - memaddr,
1528                 bl->target_info.shadow_contents + bptoffset, bp_size);
1529       }
1530     else
1531       {
1532         struct gdbarch *gdbarch = bl->gdbarch;
1533         const unsigned char *bp;
1534         CORE_ADDR placed_address = bl->target_info.placed_address;
1535         unsigned placed_size = bl->target_info.placed_size;
1536
1537         /* Update the shadow with what we want to write to memory.  */
1538         memcpy (bl->target_info.shadow_contents + bptoffset,
1539                 writebuf_org + bp_addr - memaddr, bp_size);
1540
1541         /* Determine appropriate breakpoint contents and size for this
1542            address.  */
1543         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1544
1545         /* Update the final write buffer with this inserted
1546            breakpoint's INSN.  */
1547         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1548       }
1549   }
1550 }
1551 \f
1552
1553 /* Return true if BPT is either a software breakpoint or a hardware
1554    breakpoint.  */
1555
1556 int
1557 is_breakpoint (const struct breakpoint *bpt)
1558 {
1559   return (bpt->type == bp_breakpoint
1560           || bpt->type == bp_hardware_breakpoint
1561           || bpt->type == bp_dprintf);
1562 }
1563
1564 /* Return true if BPT is of any hardware watchpoint kind.  */
1565
1566 static int
1567 is_hardware_watchpoint (const struct breakpoint *bpt)
1568 {
1569   return (bpt->type == bp_hardware_watchpoint
1570           || bpt->type == bp_read_watchpoint
1571           || bpt->type == bp_access_watchpoint);
1572 }
1573
1574 /* Return true if BPT is of any watchpoint kind, hardware or
1575    software.  */
1576
1577 int
1578 is_watchpoint (const struct breakpoint *bpt)
1579 {
1580   return (is_hardware_watchpoint (bpt)
1581           || bpt->type == bp_watchpoint);
1582 }
1583
1584 /* Returns true if the current thread and its running state are safe
1585    to evaluate or update watchpoint B.  Watchpoints on local
1586    expressions need to be evaluated in the context of the thread that
1587    was current when the watchpoint was created, and, that thread needs
1588    to be stopped to be able to select the correct frame context.
1589    Watchpoints on global expressions can be evaluated on any thread,
1590    and in any state.  It is presently left to the target allowing
1591    memory accesses when threads are running.  */
1592
1593 static int
1594 watchpoint_in_thread_scope (struct watchpoint *b)
1595 {
1596   return (b->base.pspace == current_program_space
1597           && (ptid_equal (b->watchpoint_thread, null_ptid)
1598               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1599                   && !is_executing (inferior_ptid))));
1600 }
1601
1602 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1603    associated bp_watchpoint_scope breakpoint.  */
1604
1605 static void
1606 watchpoint_del_at_next_stop (struct watchpoint *w)
1607 {
1608   struct breakpoint *b = &w->base;
1609
1610   if (b->related_breakpoint != b)
1611     {
1612       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1613       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1614       b->related_breakpoint->disposition = disp_del_at_next_stop;
1615       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1616       b->related_breakpoint = b;
1617     }
1618   b->disposition = disp_del_at_next_stop;
1619 }
1620
1621 /* Assuming that B is a watchpoint:
1622    - Reparse watchpoint expression, if REPARSE is non-zero
1623    - Evaluate expression and store the result in B->val
1624    - Evaluate the condition if there is one, and store the result
1625      in b->loc->cond.
1626    - Update the list of values that must be watched in B->loc.
1627
1628    If the watchpoint disposition is disp_del_at_next_stop, then do
1629    nothing.  If this is local watchpoint that is out of scope, delete
1630    it.
1631
1632    Even with `set breakpoint always-inserted on' the watchpoints are
1633    removed + inserted on each stop here.  Normal breakpoints must
1634    never be removed because they might be missed by a running thread
1635    when debugging in non-stop mode.  On the other hand, hardware
1636    watchpoints (is_hardware_watchpoint; processed here) are specific
1637    to each LWP since they are stored in each LWP's hardware debug
1638    registers.  Therefore, such LWP must be stopped first in order to
1639    be able to modify its hardware watchpoints.
1640
1641    Hardware watchpoints must be reset exactly once after being
1642    presented to the user.  It cannot be done sooner, because it would
1643    reset the data used to present the watchpoint hit to the user.  And
1644    it must not be done later because it could display the same single
1645    watchpoint hit during multiple GDB stops.  Note that the latter is
1646    relevant only to the hardware watchpoint types bp_read_watchpoint
1647    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1648    not user-visible - its hit is suppressed if the memory content has
1649    not changed.
1650
1651    The following constraints influence the location where we can reset
1652    hardware watchpoints:
1653
1654    * target_stopped_by_watchpoint and target_stopped_data_address are
1655      called several times when GDB stops.
1656
1657    [linux] 
1658    * Multiple hardware watchpoints can be hit at the same time,
1659      causing GDB to stop.  GDB only presents one hardware watchpoint
1660      hit at a time as the reason for stopping, and all the other hits
1661      are presented later, one after the other, each time the user
1662      requests the execution to be resumed.  Execution is not resumed
1663      for the threads still having pending hit event stored in
1664      LWP_INFO->STATUS.  While the watchpoint is already removed from
1665      the inferior on the first stop the thread hit event is kept being
1666      reported from its cached value by linux_nat_stopped_data_address
1667      until the real thread resume happens after the watchpoint gets
1668      presented and thus its LWP_INFO->STATUS gets reset.
1669
1670    Therefore the hardware watchpoint hit can get safely reset on the
1671    watchpoint removal from inferior.  */
1672
1673 static void
1674 update_watchpoint (struct watchpoint *b, int reparse)
1675 {
1676   int within_current_scope;
1677   struct frame_id saved_frame_id;
1678   int frame_saved;
1679
1680   /* If this is a local watchpoint, we only want to check if the
1681      watchpoint frame is in scope if the current thread is the thread
1682      that was used to create the watchpoint.  */
1683   if (!watchpoint_in_thread_scope (b))
1684     return;
1685
1686   if (b->base.disposition == disp_del_at_next_stop)
1687     return;
1688  
1689   frame_saved = 0;
1690
1691   /* Determine if the watchpoint is within scope.  */
1692   if (b->exp_valid_block == NULL)
1693     within_current_scope = 1;
1694   else
1695     {
1696       struct frame_info *fi = get_current_frame ();
1697       struct gdbarch *frame_arch = get_frame_arch (fi);
1698       CORE_ADDR frame_pc = get_frame_pc (fi);
1699
1700       /* If we're in a function epilogue, unwinding may not work
1701          properly, so do not attempt to recreate locations at this
1702          point.  See similar comments in watchpoint_check.  */
1703       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1704         return;
1705
1706       /* Save the current frame's ID so we can restore it after
1707          evaluating the watchpoint expression on its own frame.  */
1708       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1709          took a frame parameter, so that we didn't have to change the
1710          selected frame.  */
1711       frame_saved = 1;
1712       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1713
1714       fi = frame_find_by_id (b->watchpoint_frame);
1715       within_current_scope = (fi != NULL);
1716       if (within_current_scope)
1717         select_frame (fi);
1718     }
1719
1720   /* We don't free locations.  They are stored in the bp_location array
1721      and update_global_location_list will eventually delete them and
1722      remove breakpoints if needed.  */
1723   b->base.loc = NULL;
1724
1725   if (within_current_scope && reparse)
1726     {
1727       char *s;
1728
1729       if (b->exp)
1730         {
1731           xfree (b->exp);
1732           b->exp = NULL;
1733         }
1734       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1735       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1736       /* If the meaning of expression itself changed, the old value is
1737          no longer relevant.  We don't want to report a watchpoint hit
1738          to the user when the old value and the new value may actually
1739          be completely different objects.  */
1740       value_free (b->val);
1741       b->val = NULL;
1742       b->val_valid = 0;
1743
1744       /* Note that unlike with breakpoints, the watchpoint's condition
1745          expression is stored in the breakpoint object, not in the
1746          locations (re)created below.  */
1747       if (b->base.cond_string != NULL)
1748         {
1749           if (b->cond_exp != NULL)
1750             {
1751               xfree (b->cond_exp);
1752               b->cond_exp = NULL;
1753             }
1754
1755           s = b->base.cond_string;
1756           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1757         }
1758     }
1759
1760   /* If we failed to parse the expression, for example because
1761      it refers to a global variable in a not-yet-loaded shared library,
1762      don't try to insert watchpoint.  We don't automatically delete
1763      such watchpoint, though, since failure to parse expression
1764      is different from out-of-scope watchpoint.  */
1765   if ( !target_has_execution)
1766     {
1767       /* Without execution, memory can't change.  No use to try and
1768          set watchpoint locations.  The watchpoint will be reset when
1769          the target gains execution, through breakpoint_re_set.  */
1770     }
1771   else if (within_current_scope && b->exp)
1772     {
1773       int pc = 0;
1774       struct value *val_chain, *v, *result, *next;
1775       struct program_space *frame_pspace;
1776
1777       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1778
1779       /* Avoid setting b->val if it's already set.  The meaning of
1780          b->val is 'the last value' user saw, and we should update
1781          it only if we reported that last value to user.  As it
1782          happens, the code that reports it updates b->val directly.
1783          We don't keep track of the memory value for masked
1784          watchpoints.  */
1785       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1786         {
1787           b->val = v;
1788           b->val_valid = 1;
1789         }
1790
1791       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1792
1793       /* Look at each value on the value chain.  */
1794       for (v = val_chain; v; v = value_next (v))
1795         {
1796           /* If it's a memory location, and GDB actually needed
1797              its contents to evaluate the expression, then we
1798              must watch it.  If the first value returned is
1799              still lazy, that means an error occurred reading it;
1800              watch it anyway in case it becomes readable.  */
1801           if (VALUE_LVAL (v) == lval_memory
1802               && (v == val_chain || ! value_lazy (v)))
1803             {
1804               struct type *vtype = check_typedef (value_type (v));
1805
1806               /* We only watch structs and arrays if user asked
1807                  for it explicitly, never if they just happen to
1808                  appear in the middle of some value chain.  */
1809               if (v == result
1810                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1811                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1812                 {
1813                   CORE_ADDR addr;
1814                   int len, type;
1815                   struct bp_location *loc, **tmp;
1816
1817                   addr = value_address (v);
1818                   len = TYPE_LENGTH (value_type (v));
1819                   type = hw_write;
1820                   if (b->base.type == bp_read_watchpoint)
1821                     type = hw_read;
1822                   else if (b->base.type == bp_access_watchpoint)
1823                     type = hw_access;
1824
1825                   loc = allocate_bp_location (&b->base);
1826                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1827                     ;
1828                   *tmp = loc;
1829                   loc->gdbarch = get_type_arch (value_type (v));
1830
1831                   loc->pspace = frame_pspace;
1832                   loc->address = addr;
1833                   loc->length = len;
1834                   loc->watchpoint_type = type;
1835                 }
1836             }
1837         }
1838
1839       /* Change the type of breakpoint between hardware assisted or
1840          an ordinary watchpoint depending on the hardware support
1841          and free hardware slots.  REPARSE is set when the inferior
1842          is started.  */
1843       if (reparse)
1844         {
1845           int reg_cnt;
1846           enum bp_loc_type loc_type;
1847           struct bp_location *bl;
1848
1849           reg_cnt = can_use_hardware_watchpoint (val_chain);
1850
1851           if (reg_cnt)
1852             {
1853               int i, target_resources_ok, other_type_used;
1854               enum bptype type;
1855
1856               /* Use an exact watchpoint when there's only one memory region to be
1857                  watched, and only one debug register is needed to watch it.  */
1858               b->exact = target_exact_watchpoints && reg_cnt == 1;
1859
1860               /* We need to determine how many resources are already
1861                  used for all other hardware watchpoints plus this one
1862                  to see if we still have enough resources to also fit
1863                  this watchpoint in as well.  */
1864
1865               /* If this is a software watchpoint, we try to turn it
1866                  to a hardware one -- count resources as if B was of
1867                  hardware watchpoint type.  */
1868               type = b->base.type;
1869               if (type == bp_watchpoint)
1870                 type = bp_hardware_watchpoint;
1871
1872               /* This watchpoint may or may not have been placed on
1873                  the list yet at this point (it won't be in the list
1874                  if we're trying to create it for the first time,
1875                  through watch_command), so always account for it
1876                  manually.  */
1877
1878               /* Count resources used by all watchpoints except B.  */
1879               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1880
1881               /* Add in the resources needed for B.  */
1882               i += hw_watchpoint_use_count (&b->base);
1883
1884               target_resources_ok
1885                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1886               if (target_resources_ok <= 0)
1887                 {
1888                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1889
1890                   if (target_resources_ok == 0 && !sw_mode)
1891                     error (_("Target does not support this type of "
1892                              "hardware watchpoint."));
1893                   else if (target_resources_ok < 0 && !sw_mode)
1894                     error (_("There are not enough available hardware "
1895                              "resources for this watchpoint."));
1896
1897                   /* Downgrade to software watchpoint.  */
1898                   b->base.type = bp_watchpoint;
1899                 }
1900               else
1901                 {
1902                   /* If this was a software watchpoint, we've just
1903                      found we have enough resources to turn it to a
1904                      hardware watchpoint.  Otherwise, this is a
1905                      nop.  */
1906                   b->base.type = type;
1907                 }
1908             }
1909           else if (!b->base.ops->works_in_software_mode (&b->base))
1910             error (_("Expression cannot be implemented with "
1911                      "read/access watchpoint."));
1912           else
1913             b->base.type = bp_watchpoint;
1914
1915           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1916                       : bp_loc_hardware_watchpoint);
1917           for (bl = b->base.loc; bl; bl = bl->next)
1918             bl->loc_type = loc_type;
1919         }
1920
1921       for (v = val_chain; v; v = next)
1922         {
1923           next = value_next (v);
1924           if (v != b->val)
1925             value_free (v);
1926         }
1927
1928       /* If a software watchpoint is not watching any memory, then the
1929          above left it without any location set up.  But,
1930          bpstat_stop_status requires a location to be able to report
1931          stops, so make sure there's at least a dummy one.  */
1932       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1933         {
1934           struct breakpoint *base = &b->base;
1935           base->loc = allocate_bp_location (base);
1936           base->loc->pspace = frame_pspace;
1937           base->loc->address = -1;
1938           base->loc->length = -1;
1939           base->loc->watchpoint_type = -1;
1940         }
1941     }
1942   else if (!within_current_scope)
1943     {
1944       printf_filtered (_("\
1945 Watchpoint %d deleted because the program has left the block\n\
1946 in which its expression is valid.\n"),
1947                        b->base.number);
1948       watchpoint_del_at_next_stop (b);
1949     }
1950
1951   /* Restore the selected frame.  */
1952   if (frame_saved)
1953     select_frame (frame_find_by_id (saved_frame_id));
1954 }
1955
1956
1957 /* Returns 1 iff breakpoint location should be
1958    inserted in the inferior.  We don't differentiate the type of BL's owner
1959    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1960    breakpoint_ops is not defined, because in insert_bp_location,
1961    tracepoint's insert_location will not be called.  */
1962 static int
1963 should_be_inserted (struct bp_location *bl)
1964 {
1965   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1966     return 0;
1967
1968   if (bl->owner->disposition == disp_del_at_next_stop)
1969     return 0;
1970
1971   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1972     return 0;
1973
1974   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1975     return 0;
1976
1977   /* This is set for example, when we're attached to the parent of a
1978      vfork, and have detached from the child.  The child is running
1979      free, and we expect it to do an exec or exit, at which point the
1980      OS makes the parent schedulable again (and the target reports
1981      that the vfork is done).  Until the child is done with the shared
1982      memory region, do not insert breakpoints in the parent, otherwise
1983      the child could still trip on the parent's breakpoints.  Since
1984      the parent is blocked anyway, it won't miss any breakpoint.  */
1985   if (bl->pspace->breakpoints_not_allowed)
1986     return 0;
1987
1988   return 1;
1989 }
1990
1991 /* Same as should_be_inserted but does the check assuming
1992    that the location is not duplicated.  */
1993
1994 static int
1995 unduplicated_should_be_inserted (struct bp_location *bl)
1996 {
1997   int result;
1998   const int save_duplicate = bl->duplicate;
1999
2000   bl->duplicate = 0;
2001   result = should_be_inserted (bl);
2002   bl->duplicate = save_duplicate;
2003   return result;
2004 }
2005
2006 /* Parses a conditional described by an expression COND into an
2007    agent expression bytecode suitable for evaluation
2008    by the bytecode interpreter.  Return NULL if there was
2009    any error during parsing.  */
2010
2011 static struct agent_expr *
2012 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2013 {
2014   struct agent_expr *aexpr = NULL;
2015   struct cleanup *old_chain = NULL;
2016   volatile struct gdb_exception ex;
2017
2018   if (!cond)
2019     return NULL;
2020
2021   /* We don't want to stop processing, so catch any errors
2022      that may show up.  */
2023   TRY_CATCH (ex, RETURN_MASK_ERROR)
2024     {
2025       aexpr = gen_eval_for_expr (scope, cond);
2026     }
2027
2028   if (ex.reason < 0)
2029     {
2030       /* If we got here, it means the condition could not be parsed to a valid
2031          bytecode expression and thus can't be evaluated on the target's side.
2032          It's no use iterating through the conditions.  */
2033       return NULL;
2034     }
2035
2036   /* We have a valid agent expression.  */
2037   return aexpr;
2038 }
2039
2040 /* Based on location BL, create a list of breakpoint conditions to be
2041    passed on to the target.  If we have duplicated locations with different
2042    conditions, we will add such conditions to the list.  The idea is that the
2043    target will evaluate the list of conditions and will only notify GDB when
2044    one of them is true.  */
2045
2046 static void
2047 build_target_condition_list (struct bp_location *bl)
2048 {
2049   struct bp_location **locp = NULL, **loc2p;
2050   int null_condition_or_parse_error = 0;
2051   int modified = bl->needs_update;
2052   struct bp_location *loc;
2053
2054   /* This is only meaningful if the target is
2055      evaluating conditions and if the user has
2056      opted for condition evaluation on the target's
2057      side.  */
2058   if (gdb_evaluates_breakpoint_condition_p ()
2059       || !target_supports_evaluation_of_breakpoint_conditions ())
2060     return;
2061
2062   /* Do a first pass to check for locations with no assigned
2063      conditions or conditions that fail to parse to a valid agent expression
2064      bytecode.  If any of these happen, then it's no use to send conditions
2065      to the target since this location will always trigger and generate a
2066      response back to GDB.  */
2067   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2068     {
2069       loc = (*loc2p);
2070       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2071         {
2072           if (modified)
2073             {
2074               struct agent_expr *aexpr;
2075
2076               /* Re-parse the conditions since something changed.  In that
2077                  case we already freed the condition bytecodes (see
2078                  force_breakpoint_reinsertion).  We just
2079                  need to parse the condition to bytecodes again.  */
2080               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2081               loc->cond_bytecode = aexpr;
2082
2083               /* Check if we managed to parse the conditional expression
2084                  correctly.  If not, we will not send this condition
2085                  to the target.  */
2086               if (aexpr)
2087                 continue;
2088             }
2089
2090           /* If we have a NULL bytecode expression, it means something
2091              went wrong or we have a null condition expression.  */
2092           if (!loc->cond_bytecode)
2093             {
2094               null_condition_or_parse_error = 1;
2095               break;
2096             }
2097         }
2098     }
2099
2100   /* If any of these happened, it means we will have to evaluate the conditions
2101      for the location's address on gdb's side.  It is no use keeping bytecodes
2102      for all the other duplicate locations, thus we free all of them here.
2103
2104      This is so we have a finer control over which locations' conditions are
2105      being evaluated by GDB or the remote stub.  */
2106   if (null_condition_or_parse_error)
2107     {
2108       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2109         {
2110           loc = (*loc2p);
2111           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2112             {
2113               /* Only go as far as the first NULL bytecode is
2114                  located.  */
2115               if (!loc->cond_bytecode)
2116                 return;
2117
2118               free_agent_expr (loc->cond_bytecode);
2119               loc->cond_bytecode = NULL;
2120             }
2121         }
2122     }
2123
2124   /* No NULL conditions or failed bytecode generation.  Build a condition list
2125      for this location's address.  */
2126   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2127     {
2128       loc = (*loc2p);
2129       if (loc->cond
2130           && is_breakpoint (loc->owner)
2131           && loc->pspace->num == bl->pspace->num
2132           && loc->owner->enable_state == bp_enabled
2133           && loc->enabled)
2134         /* Add the condition to the vector.  This will be used later to send the
2135            conditions to the target.  */
2136         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2137                        loc->cond_bytecode);
2138     }
2139
2140   return;
2141 }
2142
2143 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2144    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2145    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2146    Returns 0 for success, 1 if the bp_location type is not supported or
2147    -1 for failure.
2148
2149    NOTE drow/2003-09-09: This routine could be broken down to an
2150    object-style method for each breakpoint or catchpoint type.  */
2151 static int
2152 insert_bp_location (struct bp_location *bl,
2153                     struct ui_file *tmp_error_stream,
2154                     int *disabled_breaks,
2155                     int *hw_breakpoint_error)
2156 {
2157   int val = 0;
2158
2159   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2160     return 0;
2161
2162   /* Note we don't initialize bl->target_info, as that wipes out
2163      the breakpoint location's shadow_contents if the breakpoint
2164      is still inserted at that location.  This in turn breaks
2165      target_read_memory which depends on these buffers when
2166      a memory read is requested at the breakpoint location:
2167      Once the target_info has been wiped, we fail to see that
2168      we have a breakpoint inserted at that address and thus
2169      read the breakpoint instead of returning the data saved in
2170      the breakpoint location's shadow contents.  */
2171   bl->target_info.placed_address = bl->address;
2172   bl->target_info.placed_address_space = bl->pspace->aspace;
2173   bl->target_info.length = bl->length;
2174
2175   /* When working with target-side conditions, we must pass all the conditions
2176      for the same breakpoint address down to the target since GDB will not
2177      insert those locations.  With a list of breakpoint conditions, the target
2178      can decide when to stop and notify GDB.  */
2179
2180   if (is_breakpoint (bl->owner))
2181     {
2182       build_target_condition_list (bl);
2183       /* Reset the condition modification marker.  */
2184       bl->needs_update = 0;
2185     }
2186
2187   if (bl->loc_type == bp_loc_software_breakpoint
2188       || bl->loc_type == bp_loc_hardware_breakpoint)
2189     {
2190       if (bl->owner->type != bp_hardware_breakpoint)
2191         {
2192           /* If the explicitly specified breakpoint type
2193              is not hardware breakpoint, check the memory map to see
2194              if the breakpoint address is in read only memory or not.
2195
2196              Two important cases are:
2197              - location type is not hardware breakpoint, memory
2198              is readonly.  We change the type of the location to
2199              hardware breakpoint.
2200              - location type is hardware breakpoint, memory is
2201              read-write.  This means we've previously made the
2202              location hardware one, but then the memory map changed,
2203              so we undo.
2204              
2205              When breakpoints are removed, remove_breakpoints will use
2206              location types we've just set here, the only possible
2207              problem is that memory map has changed during running
2208              program, but it's not going to work anyway with current
2209              gdb.  */
2210           struct mem_region *mr 
2211             = lookup_mem_region (bl->target_info.placed_address);
2212           
2213           if (mr)
2214             {
2215               if (automatic_hardware_breakpoints)
2216                 {
2217                   enum bp_loc_type new_type;
2218                   
2219                   if (mr->attrib.mode != MEM_RW)
2220                     new_type = bp_loc_hardware_breakpoint;
2221                   else 
2222                     new_type = bp_loc_software_breakpoint;
2223                   
2224                   if (new_type != bl->loc_type)
2225                     {
2226                       static int said = 0;
2227
2228                       bl->loc_type = new_type;
2229                       if (!said)
2230                         {
2231                           fprintf_filtered (gdb_stdout,
2232                                             _("Note: automatically using "
2233                                               "hardware breakpoints for "
2234                                               "read-only addresses.\n"));
2235                           said = 1;
2236                         }
2237                     }
2238                 }
2239               else if (bl->loc_type == bp_loc_software_breakpoint
2240                        && mr->attrib.mode != MEM_RW)        
2241                 warning (_("cannot set software breakpoint "
2242                            "at readonly address %s"),
2243                          paddress (bl->gdbarch, bl->address));
2244             }
2245         }
2246         
2247       /* First check to see if we have to handle an overlay.  */
2248       if (overlay_debugging == ovly_off
2249           || bl->section == NULL
2250           || !(section_is_overlay (bl->section)))
2251         {
2252           /* No overlay handling: just set the breakpoint.  */
2253
2254           val = bl->owner->ops->insert_location (bl);
2255         }
2256       else
2257         {
2258           /* This breakpoint is in an overlay section.
2259              Shall we set a breakpoint at the LMA?  */
2260           if (!overlay_events_enabled)
2261             {
2262               /* Yes -- overlay event support is not active, 
2263                  so we must try to set a breakpoint at the LMA.
2264                  This will not work for a hardware breakpoint.  */
2265               if (bl->loc_type == bp_loc_hardware_breakpoint)
2266                 warning (_("hardware breakpoint %d not supported in overlay!"),
2267                          bl->owner->number);
2268               else
2269                 {
2270                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2271                                                              bl->section);
2272                   /* Set a software (trap) breakpoint at the LMA.  */
2273                   bl->overlay_target_info = bl->target_info;
2274                   bl->overlay_target_info.placed_address = addr;
2275                   val = target_insert_breakpoint (bl->gdbarch,
2276                                                   &bl->overlay_target_info);
2277                   if (val != 0)
2278                     fprintf_unfiltered (tmp_error_stream,
2279                                         "Overlay breakpoint %d "
2280                                         "failed: in ROM?\n",
2281                                         bl->owner->number);
2282                 }
2283             }
2284           /* Shall we set a breakpoint at the VMA? */
2285           if (section_is_mapped (bl->section))
2286             {
2287               /* Yes.  This overlay section is mapped into memory.  */
2288               val = bl->owner->ops->insert_location (bl);
2289             }
2290           else
2291             {
2292               /* No.  This breakpoint will not be inserted.  
2293                  No error, but do not mark the bp as 'inserted'.  */
2294               return 0;
2295             }
2296         }
2297
2298       if (val)
2299         {
2300           /* Can't set the breakpoint.  */
2301           if (solib_name_from_address (bl->pspace, bl->address))
2302             {
2303               /* See also: disable_breakpoints_in_shlibs.  */
2304               val = 0;
2305               bl->shlib_disabled = 1;
2306               observer_notify_breakpoint_modified (bl->owner);
2307               if (!*disabled_breaks)
2308                 {
2309                   fprintf_unfiltered (tmp_error_stream, 
2310                                       "Cannot insert breakpoint %d.\n", 
2311                                       bl->owner->number);
2312                   fprintf_unfiltered (tmp_error_stream, 
2313                                       "Temporarily disabling shared "
2314                                       "library breakpoints:\n");
2315                 }
2316               *disabled_breaks = 1;
2317               fprintf_unfiltered (tmp_error_stream,
2318                                   "breakpoint #%d\n", bl->owner->number);
2319             }
2320           else
2321             {
2322               if (bl->loc_type == bp_loc_hardware_breakpoint)
2323                 {
2324                   *hw_breakpoint_error = 1;
2325                   fprintf_unfiltered (tmp_error_stream,
2326                                       "Cannot insert hardware "
2327                                       "breakpoint %d.\n",
2328                                       bl->owner->number);
2329                 }
2330               else
2331                 {
2332                   fprintf_unfiltered (tmp_error_stream, 
2333                                       "Cannot insert breakpoint %d.\n", 
2334                                       bl->owner->number);
2335                   fprintf_filtered (tmp_error_stream, 
2336                                     "Error accessing memory address ");
2337                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2338                                   tmp_error_stream);
2339                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2340                                     safe_strerror (val));
2341                 }
2342
2343             }
2344         }
2345       else
2346         bl->inserted = 1;
2347
2348       return val;
2349     }
2350
2351   else if (bl->loc_type == bp_loc_hardware_watchpoint
2352            /* NOTE drow/2003-09-08: This state only exists for removing
2353               watchpoints.  It's not clear that it's necessary...  */
2354            && bl->owner->disposition != disp_del_at_next_stop)
2355     {
2356       gdb_assert (bl->owner->ops != NULL
2357                   && bl->owner->ops->insert_location != NULL);
2358
2359       val = bl->owner->ops->insert_location (bl);
2360
2361       /* If trying to set a read-watchpoint, and it turns out it's not
2362          supported, try emulating one with an access watchpoint.  */
2363       if (val == 1 && bl->watchpoint_type == hw_read)
2364         {
2365           struct bp_location *loc, **loc_temp;
2366
2367           /* But don't try to insert it, if there's already another
2368              hw_access location that would be considered a duplicate
2369              of this one.  */
2370           ALL_BP_LOCATIONS (loc, loc_temp)
2371             if (loc != bl
2372                 && loc->watchpoint_type == hw_access
2373                 && watchpoint_locations_match (bl, loc))
2374               {
2375                 bl->duplicate = 1;
2376                 bl->inserted = 1;
2377                 bl->target_info = loc->target_info;
2378                 bl->watchpoint_type = hw_access;
2379                 val = 0;
2380                 break;
2381               }
2382
2383           if (val == 1)
2384             {
2385               bl->watchpoint_type = hw_access;
2386               val = bl->owner->ops->insert_location (bl);
2387
2388               if (val)
2389                 /* Back to the original value.  */
2390                 bl->watchpoint_type = hw_read;
2391             }
2392         }
2393
2394       bl->inserted = (val == 0);
2395     }
2396
2397   else if (bl->owner->type == bp_catchpoint)
2398     {
2399       gdb_assert (bl->owner->ops != NULL
2400                   && bl->owner->ops->insert_location != NULL);
2401
2402       val = bl->owner->ops->insert_location (bl);
2403       if (val)
2404         {
2405           bl->owner->enable_state = bp_disabled;
2406
2407           if (val == 1)
2408             warning (_("\
2409 Error inserting catchpoint %d: Your system does not support this type\n\
2410 of catchpoint."), bl->owner->number);
2411           else
2412             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2413         }
2414
2415       bl->inserted = (val == 0);
2416
2417       /* We've already printed an error message if there was a problem
2418          inserting this catchpoint, and we've disabled the catchpoint,
2419          so just return success.  */
2420       return 0;
2421     }
2422
2423   return 0;
2424 }
2425
2426 /* This function is called when program space PSPACE is about to be
2427    deleted.  It takes care of updating breakpoints to not reference
2428    PSPACE anymore.  */
2429
2430 void
2431 breakpoint_program_space_exit (struct program_space *pspace)
2432 {
2433   struct breakpoint *b, *b_temp;
2434   struct bp_location *loc, **loc_temp;
2435
2436   /* Remove any breakpoint that was set through this program space.  */
2437   ALL_BREAKPOINTS_SAFE (b, b_temp)
2438     {
2439       if (b->pspace == pspace)
2440         delete_breakpoint (b);
2441     }
2442
2443   /* Breakpoints set through other program spaces could have locations
2444      bound to PSPACE as well.  Remove those.  */
2445   ALL_BP_LOCATIONS (loc, loc_temp)
2446     {
2447       struct bp_location *tmp;
2448
2449       if (loc->pspace == pspace)
2450         {
2451           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2452           if (loc->owner->loc == loc)
2453             loc->owner->loc = loc->next;
2454           else
2455             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2456               if (tmp->next == loc)
2457                 {
2458                   tmp->next = loc->next;
2459                   break;
2460                 }
2461         }
2462     }
2463
2464   /* Now update the global location list to permanently delete the
2465      removed locations above.  */
2466   update_global_location_list (0);
2467 }
2468
2469 /* Make sure all breakpoints are inserted in inferior.
2470    Throws exception on any error.
2471    A breakpoint that is already inserted won't be inserted
2472    again, so calling this function twice is safe.  */
2473 void
2474 insert_breakpoints (void)
2475 {
2476   struct breakpoint *bpt;
2477
2478   ALL_BREAKPOINTS (bpt)
2479     if (is_hardware_watchpoint (bpt))
2480       {
2481         struct watchpoint *w = (struct watchpoint *) bpt;
2482
2483         update_watchpoint (w, 0 /* don't reparse.  */);
2484       }
2485
2486   update_global_location_list (1);
2487
2488   /* update_global_location_list does not insert breakpoints when
2489      always_inserted_mode is not enabled.  Explicitly insert them
2490      now.  */
2491   if (!breakpoints_always_inserted_mode ())
2492     insert_breakpoint_locations ();
2493 }
2494
2495 /* Invoke CALLBACK for each of bp_location.  */
2496
2497 void
2498 iterate_over_bp_locations (walk_bp_location_callback callback)
2499 {
2500   struct bp_location *loc, **loc_tmp;
2501
2502   ALL_BP_LOCATIONS (loc, loc_tmp)
2503     {
2504       callback (loc, NULL);
2505     }
2506 }
2507
2508 /* This is used when we need to synch breakpoint conditions between GDB and the
2509    target.  It is the case with deleting and disabling of breakpoints when using
2510    always-inserted mode.  */
2511
2512 static void
2513 update_inserted_breakpoint_locations (void)
2514 {
2515   struct bp_location *bl, **blp_tmp;
2516   int error_flag = 0;
2517   int val = 0;
2518   int disabled_breaks = 0;
2519   int hw_breakpoint_error = 0;
2520
2521   struct ui_file *tmp_error_stream = mem_fileopen ();
2522   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2523
2524   /* Explicitly mark the warning -- this will only be printed if
2525      there was an error.  */
2526   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2527
2528   save_current_space_and_thread ();
2529
2530   ALL_BP_LOCATIONS (bl, blp_tmp)
2531     {
2532       /* We only want to update software breakpoints and hardware
2533          breakpoints.  */
2534       if (!is_breakpoint (bl->owner))
2535         continue;
2536
2537       /* We only want to update locations that are already inserted
2538          and need updating.  This is to avoid unwanted insertion during
2539          deletion of breakpoints.  */
2540       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2541         continue;
2542
2543       switch_to_program_space_and_thread (bl->pspace);
2544
2545       /* For targets that support global breakpoints, there's no need
2546          to select an inferior to insert breakpoint to.  In fact, even
2547          if we aren't attached to any process yet, we should still
2548          insert breakpoints.  */
2549       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2550           && ptid_equal (inferior_ptid, null_ptid))
2551         continue;
2552
2553       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2554                                     &hw_breakpoint_error);
2555       if (val)
2556         error_flag = val;
2557     }
2558
2559   if (error_flag)
2560     {
2561       target_terminal_ours_for_output ();
2562       error_stream (tmp_error_stream);
2563     }
2564
2565   do_cleanups (cleanups);
2566 }
2567
2568 /* Used when starting or continuing the program.  */
2569
2570 static void
2571 insert_breakpoint_locations (void)
2572 {
2573   struct breakpoint *bpt;
2574   struct bp_location *bl, **blp_tmp;
2575   int error_flag = 0;
2576   int val = 0;
2577   int disabled_breaks = 0;
2578   int hw_breakpoint_error = 0;
2579
2580   struct ui_file *tmp_error_stream = mem_fileopen ();
2581   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2582   
2583   /* Explicitly mark the warning -- this will only be printed if
2584      there was an error.  */
2585   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2586
2587   save_current_space_and_thread ();
2588
2589   ALL_BP_LOCATIONS (bl, blp_tmp)
2590     {
2591       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2592         continue;
2593
2594       /* There is no point inserting thread-specific breakpoints if
2595          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2596          has BL->OWNER always non-NULL.  */
2597       if (bl->owner->thread != -1
2598           && !valid_thread_id (bl->owner->thread))
2599         continue;
2600
2601       switch_to_program_space_and_thread (bl->pspace);
2602
2603       /* For targets that support global breakpoints, there's no need
2604          to select an inferior to insert breakpoint to.  In fact, even
2605          if we aren't attached to any process yet, we should still
2606          insert breakpoints.  */
2607       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2608           && ptid_equal (inferior_ptid, null_ptid))
2609         continue;
2610
2611       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2612                                     &hw_breakpoint_error);
2613       if (val)
2614         error_flag = val;
2615     }
2616
2617   /* If we failed to insert all locations of a watchpoint, remove
2618      them, as half-inserted watchpoint is of limited use.  */
2619   ALL_BREAKPOINTS (bpt)  
2620     {
2621       int some_failed = 0;
2622       struct bp_location *loc;
2623
2624       if (!is_hardware_watchpoint (bpt))
2625         continue;
2626
2627       if (!breakpoint_enabled (bpt))
2628         continue;
2629
2630       if (bpt->disposition == disp_del_at_next_stop)
2631         continue;
2632       
2633       for (loc = bpt->loc; loc; loc = loc->next)
2634         if (!loc->inserted && should_be_inserted (loc))
2635           {
2636             some_failed = 1;
2637             break;
2638           }
2639       if (some_failed)
2640         {
2641           for (loc = bpt->loc; loc; loc = loc->next)
2642             if (loc->inserted)
2643               remove_breakpoint (loc, mark_uninserted);
2644
2645           hw_breakpoint_error = 1;
2646           fprintf_unfiltered (tmp_error_stream,
2647                               "Could not insert hardware watchpoint %d.\n", 
2648                               bpt->number);
2649           error_flag = -1;
2650         }
2651     }
2652
2653   if (error_flag)
2654     {
2655       /* If a hardware breakpoint or watchpoint was inserted, add a
2656          message about possibly exhausted resources.  */
2657       if (hw_breakpoint_error)
2658         {
2659           fprintf_unfiltered (tmp_error_stream, 
2660                               "Could not insert hardware breakpoints:\n\
2661 You may have requested too many hardware breakpoints/watchpoints.\n");
2662         }
2663       target_terminal_ours_for_output ();
2664       error_stream (tmp_error_stream);
2665     }
2666
2667   do_cleanups (cleanups);
2668 }
2669
2670 /* Used when the program stops.
2671    Returns zero if successful, or non-zero if there was a problem
2672    removing a breakpoint location.  */
2673
2674 int
2675 remove_breakpoints (void)
2676 {
2677   struct bp_location *bl, **blp_tmp;
2678   int val = 0;
2679
2680   ALL_BP_LOCATIONS (bl, blp_tmp)
2681   {
2682     if (bl->inserted && !is_tracepoint (bl->owner))
2683       val |= remove_breakpoint (bl, mark_uninserted);
2684   }
2685   return val;
2686 }
2687
2688 /* Remove breakpoints of process PID.  */
2689
2690 int
2691 remove_breakpoints_pid (int pid)
2692 {
2693   struct bp_location *bl, **blp_tmp;
2694   int val;
2695   struct inferior *inf = find_inferior_pid (pid);
2696
2697   ALL_BP_LOCATIONS (bl, blp_tmp)
2698   {
2699     if (bl->pspace != inf->pspace)
2700       continue;
2701
2702     if (bl->inserted)
2703       {
2704         val = remove_breakpoint (bl, mark_uninserted);
2705         if (val != 0)
2706           return val;
2707       }
2708   }
2709   return 0;
2710 }
2711
2712 int
2713 reattach_breakpoints (int pid)
2714 {
2715   struct cleanup *old_chain;
2716   struct bp_location *bl, **blp_tmp;
2717   int val;
2718   struct ui_file *tmp_error_stream;
2719   int dummy1 = 0, dummy2 = 0;
2720   struct inferior *inf;
2721   struct thread_info *tp;
2722
2723   tp = any_live_thread_of_process (pid);
2724   if (tp == NULL)
2725     return 1;
2726
2727   inf = find_inferior_pid (pid);
2728   old_chain = save_inferior_ptid ();
2729
2730   inferior_ptid = tp->ptid;
2731
2732   tmp_error_stream = mem_fileopen ();
2733   make_cleanup_ui_file_delete (tmp_error_stream);
2734
2735   ALL_BP_LOCATIONS (bl, blp_tmp)
2736   {
2737     if (bl->pspace != inf->pspace)
2738       continue;
2739
2740     if (bl->inserted)
2741       {
2742         bl->inserted = 0;
2743         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2744         if (val != 0)
2745           {
2746             do_cleanups (old_chain);
2747             return val;
2748           }
2749       }
2750   }
2751   do_cleanups (old_chain);
2752   return 0;
2753 }
2754
2755 static int internal_breakpoint_number = -1;
2756
2757 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2758    If INTERNAL is non-zero, the breakpoint number will be populated
2759    from internal_breakpoint_number and that variable decremented.
2760    Otherwise the breakpoint number will be populated from
2761    breakpoint_count and that value incremented.  Internal breakpoints
2762    do not set the internal var bpnum.  */
2763 static void
2764 set_breakpoint_number (int internal, struct breakpoint *b)
2765 {
2766   if (internal)
2767     b->number = internal_breakpoint_number--;
2768   else
2769     {
2770       set_breakpoint_count (breakpoint_count + 1);
2771       b->number = breakpoint_count;
2772     }
2773 }
2774
2775 static struct breakpoint *
2776 create_internal_breakpoint (struct gdbarch *gdbarch,
2777                             CORE_ADDR address, enum bptype type,
2778                             const struct breakpoint_ops *ops)
2779 {
2780   struct symtab_and_line sal;
2781   struct breakpoint *b;
2782
2783   init_sal (&sal);              /* Initialize to zeroes.  */
2784
2785   sal.pc = address;
2786   sal.section = find_pc_overlay (sal.pc);
2787   sal.pspace = current_program_space;
2788
2789   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2790   b->number = internal_breakpoint_number--;
2791   b->disposition = disp_donttouch;
2792
2793   return b;
2794 }
2795
2796 static const char *const longjmp_names[] =
2797   {
2798     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2799   };
2800 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2801
2802 /* Per-objfile data private to breakpoint.c.  */
2803 struct breakpoint_objfile_data
2804 {
2805   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2806   struct minimal_symbol *overlay_msym;
2807
2808   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2809   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2810
2811   /* True if we have looked for longjmp probes.  */
2812   int longjmp_searched;
2813
2814   /* SystemTap probe points for longjmp (if any).  */
2815   VEC (probe_p) *longjmp_probes;
2816
2817   /* Minimal symbol for "std::terminate()" (if any).  */
2818   struct minimal_symbol *terminate_msym;
2819
2820   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2821   struct minimal_symbol *exception_msym;
2822
2823   /* True if we have looked for exception probes.  */
2824   int exception_searched;
2825
2826   /* SystemTap probe points for unwinding (if any).  */
2827   VEC (probe_p) *exception_probes;
2828 };
2829
2830 static const struct objfile_data *breakpoint_objfile_key;
2831
2832 /* Minimal symbol not found sentinel.  */
2833 static struct minimal_symbol msym_not_found;
2834
2835 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2836
2837 static int
2838 msym_not_found_p (const struct minimal_symbol *msym)
2839 {
2840   return msym == &msym_not_found;
2841 }
2842
2843 /* Return per-objfile data needed by breakpoint.c.
2844    Allocate the data if necessary.  */
2845
2846 static struct breakpoint_objfile_data *
2847 get_breakpoint_objfile_data (struct objfile *objfile)
2848 {
2849   struct breakpoint_objfile_data *bp_objfile_data;
2850
2851   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2852   if (bp_objfile_data == NULL)
2853     {
2854       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2855                                        sizeof (*bp_objfile_data));
2856
2857       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2858       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2859     }
2860   return bp_objfile_data;
2861 }
2862
2863 static void
2864 free_breakpoint_probes (struct objfile *obj, void *data)
2865 {
2866   struct breakpoint_objfile_data *bp_objfile_data = data;
2867
2868   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
2869   VEC_free (probe_p, bp_objfile_data->exception_probes);
2870 }
2871
2872 static void
2873 create_overlay_event_breakpoint (void)
2874 {
2875   struct objfile *objfile;
2876   const char *const func_name = "_ovly_debug_event";
2877
2878   ALL_OBJFILES (objfile)
2879     {
2880       struct breakpoint *b;
2881       struct breakpoint_objfile_data *bp_objfile_data;
2882       CORE_ADDR addr;
2883
2884       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2885
2886       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2887         continue;
2888
2889       if (bp_objfile_data->overlay_msym == NULL)
2890         {
2891           struct minimal_symbol *m;
2892
2893           m = lookup_minimal_symbol_text (func_name, objfile);
2894           if (m == NULL)
2895             {
2896               /* Avoid future lookups in this objfile.  */
2897               bp_objfile_data->overlay_msym = &msym_not_found;
2898               continue;
2899             }
2900           bp_objfile_data->overlay_msym = m;
2901         }
2902
2903       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2904       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2905                                       bp_overlay_event,
2906                                       &internal_breakpoint_ops);
2907       b->addr_string = xstrdup (func_name);
2908
2909       if (overlay_debugging == ovly_auto)
2910         {
2911           b->enable_state = bp_enabled;
2912           overlay_events_enabled = 1;
2913         }
2914       else
2915        {
2916          b->enable_state = bp_disabled;
2917          overlay_events_enabled = 0;
2918        }
2919     }
2920   update_global_location_list (1);
2921 }
2922
2923 static void
2924 create_longjmp_master_breakpoint (void)
2925 {
2926   struct program_space *pspace;
2927   struct cleanup *old_chain;
2928
2929   old_chain = save_current_program_space ();
2930
2931   ALL_PSPACES (pspace)
2932   {
2933     struct objfile *objfile;
2934
2935     set_current_program_space (pspace);
2936
2937     ALL_OBJFILES (objfile)
2938     {
2939       int i;
2940       struct gdbarch *gdbarch;
2941       struct breakpoint_objfile_data *bp_objfile_data;
2942
2943       gdbarch = get_objfile_arch (objfile);
2944       if (!gdbarch_get_longjmp_target_p (gdbarch))
2945         continue;
2946
2947       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2948
2949       if (!bp_objfile_data->longjmp_searched)
2950         {
2951           bp_objfile_data->longjmp_probes
2952             = find_probes_in_objfile (objfile, "libc", "longjmp");
2953           bp_objfile_data->longjmp_searched = 1;
2954         }
2955
2956       if (bp_objfile_data->longjmp_probes != NULL)
2957         {
2958           int i;
2959           struct probe *probe;
2960           struct gdbarch *gdbarch = get_objfile_arch (objfile);
2961
2962           for (i = 0;
2963                VEC_iterate (probe_p,
2964                             bp_objfile_data->longjmp_probes,
2965                             i, probe);
2966                ++i)
2967             {
2968               struct breakpoint *b;
2969
2970               b = create_internal_breakpoint (gdbarch, probe->address,
2971                                               bp_longjmp_master,
2972                                               &internal_breakpoint_ops);
2973               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
2974               b->enable_state = bp_disabled;
2975             }
2976
2977           continue;
2978         }
2979
2980       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2981         {
2982           struct breakpoint *b;
2983           const char *func_name;
2984           CORE_ADDR addr;
2985
2986           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2987             continue;
2988
2989           func_name = longjmp_names[i];
2990           if (bp_objfile_data->longjmp_msym[i] == NULL)
2991             {
2992               struct minimal_symbol *m;
2993
2994               m = lookup_minimal_symbol_text (func_name, objfile);
2995               if (m == NULL)
2996                 {
2997                   /* Prevent future lookups in this objfile.  */
2998                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2999                   continue;
3000                 }
3001               bp_objfile_data->longjmp_msym[i] = m;
3002             }
3003
3004           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3005           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3006                                           &internal_breakpoint_ops);
3007           b->addr_string = xstrdup (func_name);
3008           b->enable_state = bp_disabled;
3009         }
3010     }
3011   }
3012   update_global_location_list (1);
3013
3014   do_cleanups (old_chain);
3015 }
3016
3017 /* Create a master std::terminate breakpoint.  */
3018 static void
3019 create_std_terminate_master_breakpoint (void)
3020 {
3021   struct program_space *pspace;
3022   struct cleanup *old_chain;
3023   const char *const func_name = "std::terminate()";
3024
3025   old_chain = save_current_program_space ();
3026
3027   ALL_PSPACES (pspace)
3028   {
3029     struct objfile *objfile;
3030     CORE_ADDR addr;
3031
3032     set_current_program_space (pspace);
3033
3034     ALL_OBJFILES (objfile)
3035     {
3036       struct breakpoint *b;
3037       struct breakpoint_objfile_data *bp_objfile_data;
3038
3039       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3040
3041       if (msym_not_found_p (bp_objfile_data->terminate_msym))
3042         continue;
3043
3044       if (bp_objfile_data->terminate_msym == NULL)
3045         {
3046           struct minimal_symbol *m;
3047
3048           m = lookup_minimal_symbol (func_name, NULL, objfile);
3049           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
3050                             && MSYMBOL_TYPE (m) != mst_file_text))
3051             {
3052               /* Prevent future lookups in this objfile.  */
3053               bp_objfile_data->terminate_msym = &msym_not_found;
3054               continue;
3055             }
3056           bp_objfile_data->terminate_msym = m;
3057         }
3058
3059       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3060       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3061                                       bp_std_terminate_master,
3062                                       &internal_breakpoint_ops);
3063       b->addr_string = xstrdup (func_name);
3064       b->enable_state = bp_disabled;
3065     }
3066   }
3067
3068   update_global_location_list (1);
3069
3070   do_cleanups (old_chain);
3071 }
3072
3073 /* Install a master breakpoint on the unwinder's debug hook.  */
3074
3075 static void
3076 create_exception_master_breakpoint (void)
3077 {
3078   struct objfile *objfile;
3079   const char *const func_name = "_Unwind_DebugHook";
3080
3081   ALL_OBJFILES (objfile)
3082     {
3083       struct breakpoint *b;
3084       struct gdbarch *gdbarch;
3085       struct breakpoint_objfile_data *bp_objfile_data;
3086       CORE_ADDR addr;
3087
3088       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3089
3090       /* We prefer the SystemTap probe point if it exists.  */
3091       if (!bp_objfile_data->exception_searched)
3092         {
3093           bp_objfile_data->exception_probes
3094             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3095           bp_objfile_data->exception_searched = 1;
3096         }
3097
3098       if (bp_objfile_data->exception_probes != NULL)
3099         {
3100           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3101           int i;
3102           struct probe *probe;
3103
3104           for (i = 0;
3105                VEC_iterate (probe_p,
3106                             bp_objfile_data->exception_probes,
3107                             i, probe);
3108                ++i)
3109             {
3110               struct breakpoint *b;
3111
3112               b = create_internal_breakpoint (gdbarch, probe->address,
3113                                               bp_exception_master,
3114                                               &internal_breakpoint_ops);
3115               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3116               b->enable_state = bp_disabled;
3117             }
3118
3119           continue;
3120         }
3121
3122       /* Otherwise, try the hook function.  */
3123
3124       if (msym_not_found_p (bp_objfile_data->exception_msym))
3125         continue;
3126
3127       gdbarch = get_objfile_arch (objfile);
3128
3129       if (bp_objfile_data->exception_msym == NULL)
3130         {
3131           struct minimal_symbol *debug_hook;
3132
3133           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3134           if (debug_hook == NULL)
3135             {
3136               bp_objfile_data->exception_msym = &msym_not_found;
3137               continue;
3138             }
3139
3140           bp_objfile_data->exception_msym = debug_hook;
3141         }
3142
3143       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3144       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3145                                                  &current_target);
3146       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3147                                       &internal_breakpoint_ops);
3148       b->addr_string = xstrdup (func_name);
3149       b->enable_state = bp_disabled;
3150     }
3151
3152   update_global_location_list (1);
3153 }
3154
3155 void
3156 update_breakpoints_after_exec (void)
3157 {
3158   struct breakpoint *b, *b_tmp;
3159   struct bp_location *bploc, **bplocp_tmp;
3160
3161   /* We're about to delete breakpoints from GDB's lists.  If the
3162      INSERTED flag is true, GDB will try to lift the breakpoints by
3163      writing the breakpoints' "shadow contents" back into memory.  The
3164      "shadow contents" are NOT valid after an exec, so GDB should not
3165      do that.  Instead, the target is responsible from marking
3166      breakpoints out as soon as it detects an exec.  We don't do that
3167      here instead, because there may be other attempts to delete
3168      breakpoints after detecting an exec and before reaching here.  */
3169   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3170     if (bploc->pspace == current_program_space)
3171       gdb_assert (!bploc->inserted);
3172
3173   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3174   {
3175     if (b->pspace != current_program_space)
3176       continue;
3177
3178     /* Solib breakpoints must be explicitly reset after an exec().  */
3179     if (b->type == bp_shlib_event)
3180       {
3181         delete_breakpoint (b);
3182         continue;
3183       }
3184
3185     /* JIT breakpoints must be explicitly reset after an exec().  */
3186     if (b->type == bp_jit_event)
3187       {
3188         delete_breakpoint (b);
3189         continue;
3190       }
3191
3192     /* Thread event breakpoints must be set anew after an exec(),
3193        as must overlay event and longjmp master breakpoints.  */
3194     if (b->type == bp_thread_event || b->type == bp_overlay_event
3195         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3196         || b->type == bp_exception_master)
3197       {
3198         delete_breakpoint (b);
3199         continue;
3200       }
3201
3202     /* Step-resume breakpoints are meaningless after an exec().  */
3203     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3204       {
3205         delete_breakpoint (b);
3206         continue;
3207       }
3208
3209     /* Longjmp and longjmp-resume breakpoints are also meaningless
3210        after an exec.  */
3211     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3212         || b->type == bp_longjmp_call_dummy
3213         || b->type == bp_exception || b->type == bp_exception_resume)
3214       {
3215         delete_breakpoint (b);
3216         continue;
3217       }
3218
3219     if (b->type == bp_catchpoint)
3220       {
3221         /* For now, none of the bp_catchpoint breakpoints need to
3222            do anything at this point.  In the future, if some of
3223            the catchpoints need to something, we will need to add
3224            a new method, and call this method from here.  */
3225         continue;
3226       }
3227
3228     /* bp_finish is a special case.  The only way we ought to be able
3229        to see one of these when an exec() has happened, is if the user
3230        caught a vfork, and then said "finish".  Ordinarily a finish just
3231        carries them to the call-site of the current callee, by setting
3232        a temporary bp there and resuming.  But in this case, the finish
3233        will carry them entirely through the vfork & exec.
3234
3235        We don't want to allow a bp_finish to remain inserted now.  But
3236        we can't safely delete it, 'cause finish_command has a handle to
3237        the bp on a bpstat, and will later want to delete it.  There's a
3238        chance (and I've seen it happen) that if we delete the bp_finish
3239        here, that its storage will get reused by the time finish_command
3240        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3241        We really must allow finish_command to delete a bp_finish.
3242
3243        In the absence of a general solution for the "how do we know
3244        it's safe to delete something others may have handles to?"
3245        problem, what we'll do here is just uninsert the bp_finish, and
3246        let finish_command delete it.
3247
3248        (We know the bp_finish is "doomed" in the sense that it's
3249        momentary, and will be deleted as soon as finish_command sees
3250        the inferior stopped.  So it doesn't matter that the bp's
3251        address is probably bogus in the new a.out, unlike e.g., the
3252        solib breakpoints.)  */
3253
3254     if (b->type == bp_finish)
3255       {
3256         continue;
3257       }
3258
3259     /* Without a symbolic address, we have little hope of the
3260        pre-exec() address meaning the same thing in the post-exec()
3261        a.out.  */
3262     if (b->addr_string == NULL)
3263       {
3264         delete_breakpoint (b);
3265         continue;
3266       }
3267   }
3268   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3269   create_overlay_event_breakpoint ();
3270   create_longjmp_master_breakpoint ();
3271   create_std_terminate_master_breakpoint ();
3272   create_exception_master_breakpoint ();
3273 }
3274
3275 int
3276 detach_breakpoints (int pid)
3277 {
3278   struct bp_location *bl, **blp_tmp;
3279   int val = 0;
3280   struct cleanup *old_chain = save_inferior_ptid ();
3281   struct inferior *inf = current_inferior ();
3282
3283   if (pid == PIDGET (inferior_ptid))
3284     error (_("Cannot detach breakpoints of inferior_ptid"));
3285
3286   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3287   inferior_ptid = pid_to_ptid (pid);
3288   ALL_BP_LOCATIONS (bl, blp_tmp)
3289   {
3290     if (bl->pspace != inf->pspace)
3291       continue;
3292
3293     if (bl->inserted)
3294       val |= remove_breakpoint_1 (bl, mark_inserted);
3295   }
3296
3297   /* Detach single-step breakpoints as well.  */
3298   detach_single_step_breakpoints ();
3299
3300   do_cleanups (old_chain);
3301   return val;
3302 }
3303
3304 /* Remove the breakpoint location BL from the current address space.
3305    Note that this is used to detach breakpoints from a child fork.
3306    When we get here, the child isn't in the inferior list, and neither
3307    do we have objects to represent its address space --- we should
3308    *not* look at bl->pspace->aspace here.  */
3309
3310 static int
3311 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3312 {
3313   int val;
3314
3315   /* BL is never in moribund_locations by our callers.  */
3316   gdb_assert (bl->owner != NULL);
3317
3318   if (bl->owner->enable_state == bp_permanent)
3319     /* Permanent breakpoints cannot be inserted or removed.  */
3320     return 0;
3321
3322   /* The type of none suggests that owner is actually deleted.
3323      This should not ever happen.  */
3324   gdb_assert (bl->owner->type != bp_none);
3325
3326   if (bl->loc_type == bp_loc_software_breakpoint
3327       || bl->loc_type == bp_loc_hardware_breakpoint)
3328     {
3329       /* "Normal" instruction breakpoint: either the standard
3330          trap-instruction bp (bp_breakpoint), or a
3331          bp_hardware_breakpoint.  */
3332
3333       /* First check to see if we have to handle an overlay.  */
3334       if (overlay_debugging == ovly_off
3335           || bl->section == NULL
3336           || !(section_is_overlay (bl->section)))
3337         {
3338           /* No overlay handling: just remove the breakpoint.  */
3339           val = bl->owner->ops->remove_location (bl);
3340         }
3341       else
3342         {
3343           /* This breakpoint is in an overlay section.
3344              Did we set a breakpoint at the LMA?  */
3345           if (!overlay_events_enabled)
3346               {
3347                 /* Yes -- overlay event support is not active, so we
3348                    should have set a breakpoint at the LMA.  Remove it.  
3349                 */
3350                 /* Ignore any failures: if the LMA is in ROM, we will
3351                    have already warned when we failed to insert it.  */
3352                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3353                   target_remove_hw_breakpoint (bl->gdbarch,
3354                                                &bl->overlay_target_info);
3355                 else
3356                   target_remove_breakpoint (bl->gdbarch,
3357                                             &bl->overlay_target_info);
3358               }
3359           /* Did we set a breakpoint at the VMA? 
3360              If so, we will have marked the breakpoint 'inserted'.  */
3361           if (bl->inserted)
3362             {
3363               /* Yes -- remove it.  Previously we did not bother to
3364                  remove the breakpoint if the section had been
3365                  unmapped, but let's not rely on that being safe.  We
3366                  don't know what the overlay manager might do.  */
3367
3368               /* However, we should remove *software* breakpoints only
3369                  if the section is still mapped, or else we overwrite
3370                  wrong code with the saved shadow contents.  */
3371               if (bl->loc_type == bp_loc_hardware_breakpoint
3372                   || section_is_mapped (bl->section))
3373                 val = bl->owner->ops->remove_location (bl);
3374               else
3375                 val = 0;
3376             }
3377           else
3378             {
3379               /* No -- not inserted, so no need to remove.  No error.  */
3380               val = 0;
3381             }
3382         }
3383
3384       /* In some cases, we might not be able to remove a breakpoint
3385          in a shared library that has already been removed, but we
3386          have not yet processed the shlib unload event.  */
3387       if (val && solib_name_from_address (bl->pspace, bl->address))
3388         val = 0;
3389
3390       if (val)
3391         return val;
3392       bl->inserted = (is == mark_inserted);
3393     }
3394   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3395     {
3396       gdb_assert (bl->owner->ops != NULL
3397                   && bl->owner->ops->remove_location != NULL);
3398
3399       bl->inserted = (is == mark_inserted);
3400       bl->owner->ops->remove_location (bl);
3401
3402       /* Failure to remove any of the hardware watchpoints comes here.  */
3403       if ((is == mark_uninserted) && (bl->inserted))
3404         warning (_("Could not remove hardware watchpoint %d."),
3405                  bl->owner->number);
3406     }
3407   else if (bl->owner->type == bp_catchpoint
3408            && breakpoint_enabled (bl->owner)
3409            && !bl->duplicate)
3410     {
3411       gdb_assert (bl->owner->ops != NULL
3412                   && bl->owner->ops->remove_location != NULL);
3413
3414       val = bl->owner->ops->remove_location (bl);
3415       if (val)
3416         return val;
3417
3418       bl->inserted = (is == mark_inserted);
3419     }
3420
3421   return 0;
3422 }
3423
3424 static int
3425 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3426 {
3427   int ret;
3428   struct cleanup *old_chain;
3429
3430   /* BL is never in moribund_locations by our callers.  */
3431   gdb_assert (bl->owner != NULL);
3432
3433   if (bl->owner->enable_state == bp_permanent)
3434     /* Permanent breakpoints cannot be inserted or removed.  */
3435     return 0;
3436
3437   /* The type of none suggests that owner is actually deleted.
3438      This should not ever happen.  */
3439   gdb_assert (bl->owner->type != bp_none);
3440
3441   old_chain = save_current_space_and_thread ();
3442
3443   switch_to_program_space_and_thread (bl->pspace);
3444
3445   ret = remove_breakpoint_1 (bl, is);
3446
3447   do_cleanups (old_chain);
3448   return ret;
3449 }
3450
3451 /* Clear the "inserted" flag in all breakpoints.  */
3452
3453 void
3454 mark_breakpoints_out (void)
3455 {
3456   struct bp_location *bl, **blp_tmp;
3457
3458   ALL_BP_LOCATIONS (bl, blp_tmp)
3459     if (bl->pspace == current_program_space)
3460       bl->inserted = 0;
3461 }
3462
3463 /* Clear the "inserted" flag in all breakpoints and delete any
3464    breakpoints which should go away between runs of the program.
3465
3466    Plus other such housekeeping that has to be done for breakpoints
3467    between runs.
3468
3469    Note: this function gets called at the end of a run (by
3470    generic_mourn_inferior) and when a run begins (by
3471    init_wait_for_inferior).  */
3472
3473
3474
3475 void
3476 breakpoint_init_inferior (enum inf_context context)
3477 {
3478   struct breakpoint *b, *b_tmp;
3479   struct bp_location *bl, **blp_tmp;
3480   int ix;
3481   struct program_space *pspace = current_program_space;
3482
3483   /* If breakpoint locations are shared across processes, then there's
3484      nothing to do.  */
3485   if (gdbarch_has_global_breakpoints (target_gdbarch))
3486     return;
3487
3488   ALL_BP_LOCATIONS (bl, blp_tmp)
3489   {
3490     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3491     if (bl->pspace == pspace
3492         && bl->owner->enable_state != bp_permanent)
3493       bl->inserted = 0;
3494   }
3495
3496   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3497   {
3498     if (b->loc && b->loc->pspace != pspace)
3499       continue;
3500
3501     switch (b->type)
3502       {
3503       case bp_call_dummy:
3504       case bp_longjmp_call_dummy:
3505
3506         /* If the call dummy breakpoint is at the entry point it will
3507            cause problems when the inferior is rerun, so we better get
3508            rid of it.  */
3509
3510       case bp_watchpoint_scope:
3511
3512         /* Also get rid of scope breakpoints.  */
3513
3514       case bp_shlib_event:
3515
3516         /* Also remove solib event breakpoints.  Their addresses may
3517            have changed since the last time we ran the program.
3518            Actually we may now be debugging against different target;
3519            and so the solib backend that installed this breakpoint may
3520            not be used in by the target.  E.g.,
3521
3522            (gdb) file prog-linux
3523            (gdb) run               # native linux target
3524            ...
3525            (gdb) kill
3526            (gdb) file prog-win.exe
3527            (gdb) tar rem :9999     # remote Windows gdbserver.
3528         */
3529
3530       case bp_step_resume:
3531
3532         /* Also remove step-resume breakpoints.  */
3533
3534         delete_breakpoint (b);
3535         break;
3536
3537       case bp_watchpoint:
3538       case bp_hardware_watchpoint:
3539       case bp_read_watchpoint:
3540       case bp_access_watchpoint:
3541         {
3542           struct watchpoint *w = (struct watchpoint *) b;
3543
3544           /* Likewise for watchpoints on local expressions.  */
3545           if (w->exp_valid_block != NULL)
3546             delete_breakpoint (b);
3547           else if (context == inf_starting)
3548             {
3549               /* Reset val field to force reread of starting value in
3550                  insert_breakpoints.  */
3551               if (w->val)
3552                 value_free (w->val);
3553               w->val = NULL;
3554               w->val_valid = 0;
3555           }
3556         }
3557         break;
3558       default:
3559         break;
3560       }
3561   }
3562
3563   /* Get rid of the moribund locations.  */
3564   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3565     decref_bp_location (&bl);
3566   VEC_free (bp_location_p, moribund_locations);
3567 }
3568
3569 /* These functions concern about actual breakpoints inserted in the
3570    target --- to e.g. check if we need to do decr_pc adjustment or if
3571    we need to hop over the bkpt --- so we check for address space
3572    match, not program space.  */
3573
3574 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3575    exists at PC.  It returns ordinary_breakpoint_here if it's an
3576    ordinary breakpoint, or permanent_breakpoint_here if it's a
3577    permanent breakpoint.
3578    - When continuing from a location with an ordinary breakpoint, we
3579      actually single step once before calling insert_breakpoints.
3580    - When continuing from a location with a permanent breakpoint, we
3581      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3582      the target, to advance the PC past the breakpoint.  */
3583
3584 enum breakpoint_here
3585 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3586 {
3587   struct bp_location *bl, **blp_tmp;
3588   int any_breakpoint_here = 0;
3589
3590   ALL_BP_LOCATIONS (bl, blp_tmp)
3591     {
3592       if (bl->loc_type != bp_loc_software_breakpoint
3593           && bl->loc_type != bp_loc_hardware_breakpoint)
3594         continue;
3595
3596       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3597       if ((breakpoint_enabled (bl->owner)
3598            || bl->owner->enable_state == bp_permanent)
3599           && breakpoint_location_address_match (bl, aspace, pc))
3600         {
3601           if (overlay_debugging 
3602               && section_is_overlay (bl->section)
3603               && !section_is_mapped (bl->section))
3604             continue;           /* unmapped overlay -- can't be a match */
3605           else if (bl->owner->enable_state == bp_permanent)
3606             return permanent_breakpoint_here;
3607           else
3608             any_breakpoint_here = 1;
3609         }
3610     }
3611
3612   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3613 }
3614
3615 /* Return true if there's a moribund breakpoint at PC.  */
3616
3617 int
3618 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3619 {
3620   struct bp_location *loc;
3621   int ix;
3622
3623   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3624     if (breakpoint_location_address_match (loc, aspace, pc))
3625       return 1;
3626
3627   return 0;
3628 }
3629
3630 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3631    inserted using regular breakpoint_chain / bp_location array
3632    mechanism.  This does not check for single-step breakpoints, which
3633    are inserted and removed using direct target manipulation.  */
3634
3635 int
3636 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3637                                     CORE_ADDR pc)
3638 {
3639   struct bp_location *bl, **blp_tmp;
3640
3641   ALL_BP_LOCATIONS (bl, blp_tmp)
3642     {
3643       if (bl->loc_type != bp_loc_software_breakpoint
3644           && bl->loc_type != bp_loc_hardware_breakpoint)
3645         continue;
3646
3647       if (bl->inserted
3648           && breakpoint_location_address_match (bl, aspace, pc))
3649         {
3650           if (overlay_debugging 
3651               && section_is_overlay (bl->section)
3652               && !section_is_mapped (bl->section))
3653             continue;           /* unmapped overlay -- can't be a match */
3654           else
3655             return 1;
3656         }
3657     }
3658   return 0;
3659 }
3660
3661 /* Returns non-zero iff there's either regular breakpoint
3662    or a single step breakpoint inserted at PC.  */
3663
3664 int
3665 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3666 {
3667   if (regular_breakpoint_inserted_here_p (aspace, pc))
3668     return 1;
3669
3670   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3671     return 1;
3672
3673   return 0;
3674 }
3675
3676 /* This function returns non-zero iff there is a software breakpoint
3677    inserted at PC.  */
3678
3679 int
3680 software_breakpoint_inserted_here_p (struct address_space *aspace,
3681                                      CORE_ADDR pc)
3682 {
3683   struct bp_location *bl, **blp_tmp;
3684
3685   ALL_BP_LOCATIONS (bl, blp_tmp)
3686     {
3687       if (bl->loc_type != bp_loc_software_breakpoint)
3688         continue;
3689
3690       if (bl->inserted
3691           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3692                                        aspace, pc))
3693         {
3694           if (overlay_debugging 
3695               && section_is_overlay (bl->section)
3696               && !section_is_mapped (bl->section))
3697             continue;           /* unmapped overlay -- can't be a match */
3698           else
3699             return 1;
3700         }
3701     }
3702
3703   /* Also check for software single-step breakpoints.  */
3704   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3705     return 1;
3706
3707   return 0;
3708 }
3709
3710 int
3711 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3712                                        CORE_ADDR addr, ULONGEST len)
3713 {
3714   struct breakpoint *bpt;
3715
3716   ALL_BREAKPOINTS (bpt)
3717     {
3718       struct bp_location *loc;
3719
3720       if (bpt->type != bp_hardware_watchpoint
3721           && bpt->type != bp_access_watchpoint)
3722         continue;
3723
3724       if (!breakpoint_enabled (bpt))
3725         continue;
3726
3727       for (loc = bpt->loc; loc; loc = loc->next)
3728         if (loc->pspace->aspace == aspace && loc->inserted)
3729           {
3730             CORE_ADDR l, h;
3731
3732             /* Check for intersection.  */
3733             l = max (loc->address, addr);
3734             h = min (loc->address + loc->length, addr + len);
3735             if (l < h)
3736               return 1;
3737           }
3738     }
3739   return 0;
3740 }
3741
3742 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3743    PC is valid for process/thread PTID.  */
3744
3745 int
3746 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3747                          ptid_t ptid)
3748 {
3749   struct bp_location *bl, **blp_tmp;
3750   /* The thread and task IDs associated to PTID, computed lazily.  */
3751   int thread = -1;
3752   int task = 0;
3753   
3754   ALL_BP_LOCATIONS (bl, blp_tmp)
3755     {
3756       if (bl->loc_type != bp_loc_software_breakpoint
3757           && bl->loc_type != bp_loc_hardware_breakpoint)
3758         continue;
3759
3760       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3761       if (!breakpoint_enabled (bl->owner)
3762           && bl->owner->enable_state != bp_permanent)
3763         continue;
3764
3765       if (!breakpoint_location_address_match (bl, aspace, pc))
3766         continue;
3767
3768       if (bl->owner->thread != -1)
3769         {
3770           /* This is a thread-specific breakpoint.  Check that ptid
3771              matches that thread.  If thread hasn't been computed yet,
3772              it is now time to do so.  */
3773           if (thread == -1)
3774             thread = pid_to_thread_id (ptid);
3775           if (bl->owner->thread != thread)
3776             continue;
3777         }
3778
3779       if (bl->owner->task != 0)
3780         {
3781           /* This is a task-specific breakpoint.  Check that ptid
3782              matches that task.  If task hasn't been computed yet,
3783              it is now time to do so.  */
3784           if (task == 0)
3785             task = ada_get_task_number (ptid);
3786           if (bl->owner->task != task)
3787             continue;
3788         }
3789
3790       if (overlay_debugging 
3791           && section_is_overlay (bl->section)
3792           && !section_is_mapped (bl->section))
3793         continue;           /* unmapped overlay -- can't be a match */
3794
3795       return 1;
3796     }
3797
3798   return 0;
3799 }
3800 \f
3801
3802 /* bpstat stuff.  External routines' interfaces are documented
3803    in breakpoint.h.  */
3804
3805 int
3806 is_catchpoint (struct breakpoint *ep)
3807 {
3808   return (ep->type == bp_catchpoint);
3809 }
3810
3811 /* Frees any storage that is part of a bpstat.  Does not walk the
3812    'next' chain.  */
3813
3814 static void
3815 bpstat_free (bpstat bs)
3816 {
3817   if (bs->old_val != NULL)
3818     value_free (bs->old_val);
3819   decref_counted_command_line (&bs->commands);
3820   decref_bp_location (&bs->bp_location_at);
3821   xfree (bs);
3822 }
3823
3824 /* Clear a bpstat so that it says we are not at any breakpoint.
3825    Also free any storage that is part of a bpstat.  */
3826
3827 void
3828 bpstat_clear (bpstat *bsp)
3829 {
3830   bpstat p;
3831   bpstat q;
3832
3833   if (bsp == 0)
3834     return;
3835   p = *bsp;
3836   while (p != NULL)
3837     {
3838       q = p->next;
3839       bpstat_free (p);
3840       p = q;
3841     }
3842   *bsp = NULL;
3843 }
3844
3845 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3846    is part of the bpstat is copied as well.  */
3847
3848 bpstat
3849 bpstat_copy (bpstat bs)
3850 {
3851   bpstat p = NULL;
3852   bpstat tmp;
3853   bpstat retval = NULL;
3854
3855   if (bs == NULL)
3856     return bs;
3857
3858   for (; bs != NULL; bs = bs->next)
3859     {
3860       tmp = (bpstat) xmalloc (sizeof (*tmp));
3861       memcpy (tmp, bs, sizeof (*tmp));
3862       incref_counted_command_line (tmp->commands);
3863       incref_bp_location (tmp->bp_location_at);
3864       if (bs->old_val != NULL)
3865         {
3866           tmp->old_val = value_copy (bs->old_val);
3867           release_value (tmp->old_val);
3868         }
3869
3870       if (p == NULL)
3871         /* This is the first thing in the chain.  */
3872         retval = tmp;
3873       else
3874         p->next = tmp;
3875       p = tmp;
3876     }
3877   p->next = NULL;
3878   return retval;
3879 }
3880
3881 /* Find the bpstat associated with this breakpoint.  */
3882
3883 bpstat
3884 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3885 {
3886   if (bsp == NULL)
3887     return NULL;
3888
3889   for (; bsp != NULL; bsp = bsp->next)
3890     {
3891       if (bsp->breakpoint_at == breakpoint)
3892         return bsp;
3893     }
3894   return NULL;
3895 }
3896
3897 /* Put in *NUM the breakpoint number of the first breakpoint we are
3898    stopped at.  *BSP upon return is a bpstat which points to the
3899    remaining breakpoints stopped at (but which is not guaranteed to be
3900    good for anything but further calls to bpstat_num).
3901
3902    Return 0 if passed a bpstat which does not indicate any breakpoints.
3903    Return -1 if stopped at a breakpoint that has been deleted since
3904    we set it.
3905    Return 1 otherwise.  */
3906
3907 int
3908 bpstat_num (bpstat *bsp, int *num)
3909 {
3910   struct breakpoint *b;
3911
3912   if ((*bsp) == NULL)
3913     return 0;                   /* No more breakpoint values */
3914
3915   /* We assume we'll never have several bpstats that correspond to a
3916      single breakpoint -- otherwise, this function might return the
3917      same number more than once and this will look ugly.  */
3918   b = (*bsp)->breakpoint_at;
3919   *bsp = (*bsp)->next;
3920   if (b == NULL)
3921     return -1;                  /* breakpoint that's been deleted since */
3922
3923   *num = b->number;             /* We have its number */
3924   return 1;
3925 }
3926
3927 /* See breakpoint.h.  */
3928
3929 void
3930 bpstat_clear_actions (void)
3931 {
3932   struct thread_info *tp;
3933   bpstat bs;
3934
3935   if (ptid_equal (inferior_ptid, null_ptid))
3936     return;
3937
3938   tp = find_thread_ptid (inferior_ptid);
3939   if (tp == NULL)
3940     return;
3941
3942   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3943     {
3944       decref_counted_command_line (&bs->commands);
3945
3946       if (bs->old_val != NULL)
3947         {
3948           value_free (bs->old_val);
3949           bs->old_val = NULL;
3950         }
3951     }
3952 }
3953
3954 /* Called when a command is about to proceed the inferior.  */
3955
3956 static void
3957 breakpoint_about_to_proceed (void)
3958 {
3959   if (!ptid_equal (inferior_ptid, null_ptid))
3960     {
3961       struct thread_info *tp = inferior_thread ();
3962
3963       /* Allow inferior function calls in breakpoint commands to not
3964          interrupt the command list.  When the call finishes
3965          successfully, the inferior will be standing at the same
3966          breakpoint as if nothing happened.  */
3967       if (tp->control.in_infcall)
3968         return;
3969     }
3970
3971   breakpoint_proceeded = 1;
3972 }
3973
3974 /* Stub for cleaning up our state if we error-out of a breakpoint
3975    command.  */
3976 static void
3977 cleanup_executing_breakpoints (void *ignore)
3978 {
3979   executing_breakpoint_commands = 0;
3980 }
3981
3982 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3983    or its equivalent.  */
3984
3985 static int
3986 command_line_is_silent (struct command_line *cmd)
3987 {
3988   return cmd && (strcmp ("silent", cmd->line) == 0
3989                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3990 }
3991
3992 /* Execute all the commands associated with all the breakpoints at
3993    this location.  Any of these commands could cause the process to
3994    proceed beyond this point, etc.  We look out for such changes by
3995    checking the global "breakpoint_proceeded" after each command.
3996
3997    Returns true if a breakpoint command resumed the inferior.  In that
3998    case, it is the caller's responsibility to recall it again with the
3999    bpstat of the current thread.  */
4000
4001 static int
4002 bpstat_do_actions_1 (bpstat *bsp)
4003 {
4004   bpstat bs;
4005   struct cleanup *old_chain;
4006   int again = 0;
4007
4008   /* Avoid endless recursion if a `source' command is contained
4009      in bs->commands.  */
4010   if (executing_breakpoint_commands)
4011     return 0;
4012
4013   executing_breakpoint_commands = 1;
4014   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4015
4016   prevent_dont_repeat ();
4017
4018   /* This pointer will iterate over the list of bpstat's.  */
4019   bs = *bsp;
4020
4021   breakpoint_proceeded = 0;
4022   for (; bs != NULL; bs = bs->next)
4023     {
4024       struct counted_command_line *ccmd;
4025       struct command_line *cmd;
4026       struct cleanup *this_cmd_tree_chain;
4027
4028       /* Take ownership of the BSP's command tree, if it has one.
4029
4030          The command tree could legitimately contain commands like
4031          'step' and 'next', which call clear_proceed_status, which
4032          frees stop_bpstat's command tree.  To make sure this doesn't
4033          free the tree we're executing out from under us, we need to
4034          take ownership of the tree ourselves.  Since a given bpstat's
4035          commands are only executed once, we don't need to copy it; we
4036          can clear the pointer in the bpstat, and make sure we free
4037          the tree when we're done.  */
4038       ccmd = bs->commands;
4039       bs->commands = NULL;
4040       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4041       cmd = ccmd ? ccmd->commands : NULL;
4042       if (command_line_is_silent (cmd))
4043         {
4044           /* The action has been already done by bpstat_stop_status.  */
4045           cmd = cmd->next;
4046         }
4047
4048       while (cmd != NULL)
4049         {
4050           execute_control_command (cmd);
4051
4052           if (breakpoint_proceeded)
4053             break;
4054           else
4055             cmd = cmd->next;
4056         }
4057
4058       /* We can free this command tree now.  */
4059       do_cleanups (this_cmd_tree_chain);
4060
4061       if (breakpoint_proceeded)
4062         {
4063           if (target_can_async_p ())
4064             /* If we are in async mode, then the target might be still
4065                running, not stopped at any breakpoint, so nothing for
4066                us to do here -- just return to the event loop.  */
4067             ;
4068           else
4069             /* In sync mode, when execute_control_command returns
4070                we're already standing on the next breakpoint.
4071                Breakpoint commands for that stop were not run, since
4072                execute_command does not run breakpoint commands --
4073                only command_line_handler does, but that one is not
4074                involved in execution of breakpoint commands.  So, we
4075                can now execute breakpoint commands.  It should be
4076                noted that making execute_command do bpstat actions is
4077                not an option -- in this case we'll have recursive
4078                invocation of bpstat for each breakpoint with a
4079                command, and can easily blow up GDB stack.  Instead, we
4080                return true, which will trigger the caller to recall us
4081                with the new stop_bpstat.  */
4082             again = 1;
4083           break;
4084         }
4085     }
4086   do_cleanups (old_chain);
4087   return again;
4088 }
4089
4090 void
4091 bpstat_do_actions (void)
4092 {
4093   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4094
4095   /* Do any commands attached to breakpoint we are stopped at.  */
4096   while (!ptid_equal (inferior_ptid, null_ptid)
4097          && target_has_execution
4098          && !is_exited (inferior_ptid)
4099          && !is_executing (inferior_ptid))
4100     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4101        and only return when it is stopped at the next breakpoint, we
4102        keep doing breakpoint actions until it returns false to
4103        indicate the inferior was not resumed.  */
4104     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4105       break;
4106
4107   discard_cleanups (cleanup_if_error);
4108 }
4109
4110 /* Print out the (old or new) value associated with a watchpoint.  */
4111
4112 static void
4113 watchpoint_value_print (struct value *val, struct ui_file *stream)
4114 {
4115   if (val == NULL)
4116     fprintf_unfiltered (stream, _("<unreadable>"));
4117   else
4118     {
4119       struct value_print_options opts;
4120       get_user_print_options (&opts);
4121       value_print (val, stream, &opts);
4122     }
4123 }
4124
4125 /* Generic routine for printing messages indicating why we
4126    stopped.  The behavior of this function depends on the value
4127    'print_it' in the bpstat structure.  Under some circumstances we
4128    may decide not to print anything here and delegate the task to
4129    normal_stop().  */
4130
4131 static enum print_stop_action
4132 print_bp_stop_message (bpstat bs)
4133 {
4134   switch (bs->print_it)
4135     {
4136     case print_it_noop:
4137       /* Nothing should be printed for this bpstat entry.  */
4138       return PRINT_UNKNOWN;
4139       break;
4140
4141     case print_it_done:
4142       /* We still want to print the frame, but we already printed the
4143          relevant messages.  */
4144       return PRINT_SRC_AND_LOC;
4145       break;
4146
4147     case print_it_normal:
4148       {
4149         struct breakpoint *b = bs->breakpoint_at;
4150
4151         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4152            which has since been deleted.  */
4153         if (b == NULL)
4154           return PRINT_UNKNOWN;
4155
4156         /* Normal case.  Call the breakpoint's print_it method.  */
4157         return b->ops->print_it (bs);
4158       }
4159       break;
4160
4161     default:
4162       internal_error (__FILE__, __LINE__,
4163                       _("print_bp_stop_message: unrecognized enum value"));
4164       break;
4165     }
4166 }
4167
4168 /* A helper function that prints a shared library stopped event.  */
4169
4170 static void
4171 print_solib_event (int is_catchpoint)
4172 {
4173   int any_deleted
4174     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4175   int any_added
4176     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4177
4178   if (!is_catchpoint)
4179     {
4180       if (any_added || any_deleted)
4181         ui_out_text (current_uiout,
4182                      _("Stopped due to shared library event:\n"));
4183       else
4184         ui_out_text (current_uiout,
4185                      _("Stopped due to shared library event (no "
4186                        "libraries added or removed)\n"));
4187     }
4188
4189   if (ui_out_is_mi_like_p (current_uiout))
4190     ui_out_field_string (current_uiout, "reason",
4191                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4192
4193   if (any_deleted)
4194     {
4195       struct cleanup *cleanup;
4196       char *name;
4197       int ix;
4198
4199       ui_out_text (current_uiout, _("  Inferior unloaded "));
4200       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4201                                                     "removed");
4202       for (ix = 0;
4203            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4204                         ix, name);
4205            ++ix)
4206         {
4207           if (ix > 0)
4208             ui_out_text (current_uiout, "    ");
4209           ui_out_field_string (current_uiout, "library", name);
4210           ui_out_text (current_uiout, "\n");
4211         }
4212
4213       do_cleanups (cleanup);
4214     }
4215
4216   if (any_added)
4217     {
4218       struct so_list *iter;
4219       int ix;
4220       struct cleanup *cleanup;
4221
4222       ui_out_text (current_uiout, _("  Inferior loaded "));
4223       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4224                                                     "added");
4225       for (ix = 0;
4226            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4227                         ix, iter);
4228            ++ix)
4229         {
4230           if (ix > 0)
4231             ui_out_text (current_uiout, "    ");
4232           ui_out_field_string (current_uiout, "library", iter->so_name);
4233           ui_out_text (current_uiout, "\n");
4234         }
4235
4236       do_cleanups (cleanup);
4237     }
4238 }
4239
4240 /* Print a message indicating what happened.  This is called from
4241    normal_stop().  The input to this routine is the head of the bpstat
4242    list - a list of the eventpoints that caused this stop.  KIND is
4243    the target_waitkind for the stopping event.  This
4244    routine calls the generic print routine for printing a message
4245    about reasons for stopping.  This will print (for example) the
4246    "Breakpoint n," part of the output.  The return value of this
4247    routine is one of:
4248
4249    PRINT_UNKNOWN: Means we printed nothing.
4250    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4251    code to print the location.  An example is 
4252    "Breakpoint 1, " which should be followed by
4253    the location.
4254    PRINT_SRC_ONLY: Means we printed something, but there is no need
4255    to also print the location part of the message.
4256    An example is the catch/throw messages, which
4257    don't require a location appended to the end.
4258    PRINT_NOTHING: We have done some printing and we don't need any 
4259    further info to be printed.  */
4260
4261 enum print_stop_action
4262 bpstat_print (bpstat bs, int kind)
4263 {
4264   int val;
4265
4266   /* Maybe another breakpoint in the chain caused us to stop.
4267      (Currently all watchpoints go on the bpstat whether hit or not.
4268      That probably could (should) be changed, provided care is taken
4269      with respect to bpstat_explains_signal).  */
4270   for (; bs; bs = bs->next)
4271     {
4272       val = print_bp_stop_message (bs);
4273       if (val == PRINT_SRC_ONLY 
4274           || val == PRINT_SRC_AND_LOC 
4275           || val == PRINT_NOTHING)
4276         return val;
4277     }
4278
4279   /* If we had hit a shared library event breakpoint,
4280      print_bp_stop_message would print out this message.  If we hit an
4281      OS-level shared library event, do the same thing.  */
4282   if (kind == TARGET_WAITKIND_LOADED)
4283     {
4284       print_solib_event (0);
4285       return PRINT_NOTHING;
4286     }
4287
4288   /* We reached the end of the chain, or we got a null BS to start
4289      with and nothing was printed.  */
4290   return PRINT_UNKNOWN;
4291 }
4292
4293 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4294    used inside a catch_errors to evaluate the breakpoint condition.
4295    The argument is a "struct expression *" that has been cast to a
4296    "char *" to make it pass through catch_errors.  */
4297
4298 static int
4299 breakpoint_cond_eval (void *exp)
4300 {
4301   struct value *mark = value_mark ();
4302   int i = !value_true (evaluate_expression ((struct expression *) exp));
4303
4304   value_free_to_mark (mark);
4305   return i;
4306 }
4307
4308 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4309
4310 static bpstat
4311 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4312 {
4313   bpstat bs;
4314
4315   bs = (bpstat) xmalloc (sizeof (*bs));
4316   bs->next = NULL;
4317   **bs_link_pointer = bs;
4318   *bs_link_pointer = &bs->next;
4319   bs->breakpoint_at = bl->owner;
4320   bs->bp_location_at = bl;
4321   incref_bp_location (bl);
4322   /* If the condition is false, etc., don't do the commands.  */
4323   bs->commands = NULL;
4324   bs->old_val = NULL;
4325   bs->print_it = print_it_normal;
4326   return bs;
4327 }
4328 \f
4329 /* The target has stopped with waitstatus WS.  Check if any hardware
4330    watchpoints have triggered, according to the target.  */
4331
4332 int
4333 watchpoints_triggered (struct target_waitstatus *ws)
4334 {
4335   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4336   CORE_ADDR addr;
4337   struct breakpoint *b;
4338
4339   if (!stopped_by_watchpoint)
4340     {
4341       /* We were not stopped by a watchpoint.  Mark all watchpoints
4342          as not triggered.  */
4343       ALL_BREAKPOINTS (b)
4344         if (is_hardware_watchpoint (b))
4345           {
4346             struct watchpoint *w = (struct watchpoint *) b;
4347
4348             w->watchpoint_triggered = watch_triggered_no;
4349           }
4350
4351       return 0;
4352     }
4353
4354   if (!target_stopped_data_address (&current_target, &addr))
4355     {
4356       /* We were stopped by a watchpoint, but we don't know where.
4357          Mark all watchpoints as unknown.  */
4358       ALL_BREAKPOINTS (b)
4359         if (is_hardware_watchpoint (b))
4360           {
4361             struct watchpoint *w = (struct watchpoint *) b;
4362
4363             w->watchpoint_triggered = watch_triggered_unknown;
4364           }
4365
4366       return stopped_by_watchpoint;
4367     }
4368
4369   /* The target could report the data address.  Mark watchpoints
4370      affected by this data address as triggered, and all others as not
4371      triggered.  */
4372
4373   ALL_BREAKPOINTS (b)
4374     if (is_hardware_watchpoint (b))
4375       {
4376         struct watchpoint *w = (struct watchpoint *) b;
4377         struct bp_location *loc;
4378
4379         w->watchpoint_triggered = watch_triggered_no;
4380         for (loc = b->loc; loc; loc = loc->next)
4381           {
4382             if (is_masked_watchpoint (b))
4383               {
4384                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4385                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4386
4387                 if (newaddr == start)
4388                   {
4389                     w->watchpoint_triggered = watch_triggered_yes;
4390                     break;
4391                   }
4392               }
4393             /* Exact match not required.  Within range is sufficient.  */
4394             else if (target_watchpoint_addr_within_range (&current_target,
4395                                                          addr, loc->address,
4396                                                          loc->length))
4397               {
4398                 w->watchpoint_triggered = watch_triggered_yes;
4399                 break;
4400               }
4401           }
4402       }
4403
4404   return 1;
4405 }
4406
4407 /* Possible return values for watchpoint_check (this can't be an enum
4408    because of check_errors).  */
4409 /* The watchpoint has been deleted.  */
4410 #define WP_DELETED 1
4411 /* The value has changed.  */
4412 #define WP_VALUE_CHANGED 2
4413 /* The value has not changed.  */
4414 #define WP_VALUE_NOT_CHANGED 3
4415 /* Ignore this watchpoint, no matter if the value changed or not.  */
4416 #define WP_IGNORE 4
4417
4418 #define BP_TEMPFLAG 1
4419 #define BP_HARDWAREFLAG 2
4420
4421 /* Evaluate watchpoint condition expression and check if its value
4422    changed.
4423
4424    P should be a pointer to struct bpstat, but is defined as a void *
4425    in order for this function to be usable with catch_errors.  */
4426
4427 static int
4428 watchpoint_check (void *p)
4429 {
4430   bpstat bs = (bpstat) p;
4431   struct watchpoint *b;
4432   struct frame_info *fr;
4433   int within_current_scope;
4434
4435   /* BS is built from an existing struct breakpoint.  */
4436   gdb_assert (bs->breakpoint_at != NULL);
4437   b = (struct watchpoint *) bs->breakpoint_at;
4438
4439   /* If this is a local watchpoint, we only want to check if the
4440      watchpoint frame is in scope if the current thread is the thread
4441      that was used to create the watchpoint.  */
4442   if (!watchpoint_in_thread_scope (b))
4443     return WP_IGNORE;
4444
4445   if (b->exp_valid_block == NULL)
4446     within_current_scope = 1;
4447   else
4448     {
4449       struct frame_info *frame = get_current_frame ();
4450       struct gdbarch *frame_arch = get_frame_arch (frame);
4451       CORE_ADDR frame_pc = get_frame_pc (frame);
4452
4453       /* in_function_epilogue_p() returns a non-zero value if we're
4454          still in the function but the stack frame has already been
4455          invalidated.  Since we can't rely on the values of local
4456          variables after the stack has been destroyed, we are treating
4457          the watchpoint in that state as `not changed' without further
4458          checking.  Don't mark watchpoints as changed if the current
4459          frame is in an epilogue - even if they are in some other
4460          frame, our view of the stack is likely to be wrong and
4461          frame_find_by_id could error out.  */
4462       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4463         return WP_IGNORE;
4464
4465       fr = frame_find_by_id (b->watchpoint_frame);
4466       within_current_scope = (fr != NULL);
4467
4468       /* If we've gotten confused in the unwinder, we might have
4469          returned a frame that can't describe this variable.  */
4470       if (within_current_scope)
4471         {
4472           struct symbol *function;
4473
4474           function = get_frame_function (fr);
4475           if (function == NULL
4476               || !contained_in (b->exp_valid_block,
4477                                 SYMBOL_BLOCK_VALUE (function)))
4478             within_current_scope = 0;
4479         }
4480
4481       if (within_current_scope)
4482         /* If we end up stopping, the current frame will get selected
4483            in normal_stop.  So this call to select_frame won't affect
4484            the user.  */
4485         select_frame (fr);
4486     }
4487
4488   if (within_current_scope)
4489     {
4490       /* We use value_{,free_to_}mark because it could be a *long*
4491          time before we return to the command level and call
4492          free_all_values.  We can't call free_all_values because we
4493          might be in the middle of evaluating a function call.  */
4494
4495       int pc = 0;
4496       struct value *mark;
4497       struct value *new_val;
4498
4499       if (is_masked_watchpoint (&b->base))
4500         /* Since we don't know the exact trigger address (from
4501            stopped_data_address), just tell the user we've triggered
4502            a mask watchpoint.  */
4503         return WP_VALUE_CHANGED;
4504
4505       mark = value_mark ();
4506       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4507
4508       /* We use value_equal_contents instead of value_equal because
4509          the latter coerces an array to a pointer, thus comparing just
4510          the address of the array instead of its contents.  This is
4511          not what we want.  */
4512       if ((b->val != NULL) != (new_val != NULL)
4513           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4514         {
4515           if (new_val != NULL)
4516             {
4517               release_value (new_val);
4518               value_free_to_mark (mark);
4519             }
4520           bs->old_val = b->val;
4521           b->val = new_val;
4522           b->val_valid = 1;
4523           return WP_VALUE_CHANGED;
4524         }
4525       else
4526         {
4527           /* Nothing changed.  */
4528           value_free_to_mark (mark);
4529           return WP_VALUE_NOT_CHANGED;
4530         }
4531     }
4532   else
4533     {
4534       struct ui_out *uiout = current_uiout;
4535
4536       /* This seems like the only logical thing to do because
4537          if we temporarily ignored the watchpoint, then when
4538          we reenter the block in which it is valid it contains
4539          garbage (in the case of a function, it may have two
4540          garbage values, one before and one after the prologue).
4541          So we can't even detect the first assignment to it and
4542          watch after that (since the garbage may or may not equal
4543          the first value assigned).  */
4544       /* We print all the stop information in
4545          breakpoint_ops->print_it, but in this case, by the time we
4546          call breakpoint_ops->print_it this bp will be deleted
4547          already.  So we have no choice but print the information
4548          here.  */
4549       if (ui_out_is_mi_like_p (uiout))
4550         ui_out_field_string
4551           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4552       ui_out_text (uiout, "\nWatchpoint ");
4553       ui_out_field_int (uiout, "wpnum", b->base.number);
4554       ui_out_text (uiout,
4555                    " deleted because the program has left the block in\n\
4556 which its expression is valid.\n");     
4557
4558       /* Make sure the watchpoint's commands aren't executed.  */
4559       decref_counted_command_line (&b->base.commands);
4560       watchpoint_del_at_next_stop (b);
4561
4562       return WP_DELETED;
4563     }
4564 }
4565
4566 /* Return true if it looks like target has stopped due to hitting
4567    breakpoint location BL.  This function does not check if we should
4568    stop, only if BL explains the stop.  */
4569
4570 static int
4571 bpstat_check_location (const struct bp_location *bl,
4572                        struct address_space *aspace, CORE_ADDR bp_addr,
4573                        const struct target_waitstatus *ws)
4574 {
4575   struct breakpoint *b = bl->owner;
4576
4577   /* BL is from an existing breakpoint.  */
4578   gdb_assert (b != NULL);
4579
4580   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4581 }
4582
4583 /* Determine if the watched values have actually changed, and we
4584    should stop.  If not, set BS->stop to 0.  */
4585
4586 static void
4587 bpstat_check_watchpoint (bpstat bs)
4588 {
4589   const struct bp_location *bl;
4590   struct watchpoint *b;
4591
4592   /* BS is built for existing struct breakpoint.  */
4593   bl = bs->bp_location_at;
4594   gdb_assert (bl != NULL);
4595   b = (struct watchpoint *) bs->breakpoint_at;
4596   gdb_assert (b != NULL);
4597
4598     {
4599       int must_check_value = 0;
4600       
4601       if (b->base.type == bp_watchpoint)
4602         /* For a software watchpoint, we must always check the
4603            watched value.  */
4604         must_check_value = 1;
4605       else if (b->watchpoint_triggered == watch_triggered_yes)
4606         /* We have a hardware watchpoint (read, write, or access)
4607            and the target earlier reported an address watched by
4608            this watchpoint.  */
4609         must_check_value = 1;
4610       else if (b->watchpoint_triggered == watch_triggered_unknown
4611                && b->base.type == bp_hardware_watchpoint)
4612         /* We were stopped by a hardware watchpoint, but the target could
4613            not report the data address.  We must check the watchpoint's
4614            value.  Access and read watchpoints are out of luck; without
4615            a data address, we can't figure it out.  */
4616         must_check_value = 1;
4617
4618       if (must_check_value)
4619         {
4620           char *message
4621             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4622                           b->base.number);
4623           struct cleanup *cleanups = make_cleanup (xfree, message);
4624           int e = catch_errors (watchpoint_check, bs, message,
4625                                 RETURN_MASK_ALL);
4626           do_cleanups (cleanups);
4627           switch (e)
4628             {
4629             case WP_DELETED:
4630               /* We've already printed what needs to be printed.  */
4631               bs->print_it = print_it_done;
4632               /* Stop.  */
4633               break;
4634             case WP_IGNORE:
4635               bs->print_it = print_it_noop;
4636               bs->stop = 0;
4637               break;
4638             case WP_VALUE_CHANGED:
4639               if (b->base.type == bp_read_watchpoint)
4640                 {
4641                   /* There are two cases to consider here:
4642
4643                      1. We're watching the triggered memory for reads.
4644                      In that case, trust the target, and always report
4645                      the watchpoint hit to the user.  Even though
4646                      reads don't cause value changes, the value may
4647                      have changed since the last time it was read, and
4648                      since we're not trapping writes, we will not see
4649                      those, and as such we should ignore our notion of
4650                      old value.
4651
4652                      2. We're watching the triggered memory for both
4653                      reads and writes.  There are two ways this may
4654                      happen:
4655
4656                      2.1. This is a target that can't break on data
4657                      reads only, but can break on accesses (reads or
4658                      writes), such as e.g., x86.  We detect this case
4659                      at the time we try to insert read watchpoints.
4660
4661                      2.2. Otherwise, the target supports read
4662                      watchpoints, but, the user set an access or write
4663                      watchpoint watching the same memory as this read
4664                      watchpoint.
4665
4666                      If we're watching memory writes as well as reads,
4667                      ignore watchpoint hits when we find that the
4668                      value hasn't changed, as reads don't cause
4669                      changes.  This still gives false positives when
4670                      the program writes the same value to memory as
4671                      what there was already in memory (we will confuse
4672                      it for a read), but it's much better than
4673                      nothing.  */
4674
4675                   int other_write_watchpoint = 0;
4676
4677                   if (bl->watchpoint_type == hw_read)
4678                     {
4679                       struct breakpoint *other_b;
4680
4681                       ALL_BREAKPOINTS (other_b)
4682                         if (other_b->type == bp_hardware_watchpoint
4683                             || other_b->type == bp_access_watchpoint)
4684                           {
4685                             struct watchpoint *other_w =
4686                               (struct watchpoint *) other_b;
4687
4688                             if (other_w->watchpoint_triggered
4689                                 == watch_triggered_yes)
4690                               {
4691                                 other_write_watchpoint = 1;
4692                                 break;
4693                               }
4694                           }
4695                     }
4696
4697                   if (other_write_watchpoint
4698                       || bl->watchpoint_type == hw_access)
4699                     {
4700                       /* We're watching the same memory for writes,
4701                          and the value changed since the last time we
4702                          updated it, so this trap must be for a write.
4703                          Ignore it.  */
4704                       bs->print_it = print_it_noop;
4705                       bs->stop = 0;
4706                     }
4707                 }
4708               break;
4709             case WP_VALUE_NOT_CHANGED:
4710               if (b->base.type == bp_hardware_watchpoint
4711                   || b->base.type == bp_watchpoint)
4712                 {
4713                   /* Don't stop: write watchpoints shouldn't fire if
4714                      the value hasn't changed.  */
4715                   bs->print_it = print_it_noop;
4716                   bs->stop = 0;
4717                 }
4718               /* Stop.  */
4719               break;
4720             default:
4721               /* Can't happen.  */
4722             case 0:
4723               /* Error from catch_errors.  */
4724               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
4725               watchpoint_del_at_next_stop (b);
4726               /* We've already printed what needs to be printed.  */
4727               bs->print_it = print_it_done;
4728               break;
4729             }
4730         }
4731       else      /* must_check_value == 0 */
4732         {
4733           /* This is a case where some watchpoint(s) triggered, but
4734              not at the address of this watchpoint, or else no
4735              watchpoint triggered after all.  So don't print
4736              anything for this watchpoint.  */
4737           bs->print_it = print_it_noop;
4738           bs->stop = 0;
4739         }
4740     }
4741 }
4742
4743
4744 /* Check conditions (condition proper, frame, thread and ignore count)
4745    of breakpoint referred to by BS.  If we should not stop for this
4746    breakpoint, set BS->stop to 0.  */
4747
4748 static void
4749 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4750 {
4751   int thread_id = pid_to_thread_id (ptid);
4752   const struct bp_location *bl;
4753   struct breakpoint *b;
4754
4755   /* BS is built for existing struct breakpoint.  */
4756   bl = bs->bp_location_at;
4757   gdb_assert (bl != NULL);
4758   b = bs->breakpoint_at;
4759   gdb_assert (b != NULL);
4760
4761   /* Even if the target evaluated the condition on its end and notified GDB, we
4762      need to do so again since GDB does not know if we stopped due to a
4763      breakpoint or a single step breakpoint.  */
4764
4765   if (frame_id_p (b->frame_id)
4766       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4767     bs->stop = 0;
4768   else if (bs->stop)
4769     {
4770       int value_is_zero = 0;
4771       struct expression *cond;
4772
4773       /* Evaluate Python breakpoints that have a "stop"
4774          method implemented.  */
4775       if (b->py_bp_object)
4776         bs->stop = gdbpy_should_stop (b->py_bp_object);
4777
4778       if (is_watchpoint (b))
4779         {
4780           struct watchpoint *w = (struct watchpoint *) b;
4781
4782           cond = w->cond_exp;
4783         }
4784       else
4785         cond = bl->cond;
4786
4787       if (cond && b->disposition != disp_del_at_next_stop)
4788         {
4789           int within_current_scope = 1;
4790           struct watchpoint * w;
4791
4792           /* We use value_mark and value_free_to_mark because it could
4793              be a long time before we return to the command level and
4794              call free_all_values.  We can't call free_all_values
4795              because we might be in the middle of evaluating a
4796              function call.  */
4797           struct value *mark = value_mark ();
4798
4799           if (is_watchpoint (b))
4800             w = (struct watchpoint *) b;
4801           else
4802             w = NULL;
4803
4804           /* Need to select the frame, with all that implies so that
4805              the conditions will have the right context.  Because we
4806              use the frame, we will not see an inlined function's
4807              variables when we arrive at a breakpoint at the start
4808              of the inlined function; the current frame will be the
4809              call site.  */
4810           if (w == NULL || w->cond_exp_valid_block == NULL)
4811             select_frame (get_current_frame ());
4812           else
4813             {
4814               struct frame_info *frame;
4815
4816               /* For local watchpoint expressions, which particular
4817                  instance of a local is being watched matters, so we
4818                  keep track of the frame to evaluate the expression
4819                  in.  To evaluate the condition however, it doesn't
4820                  really matter which instantiation of the function
4821                  where the condition makes sense triggers the
4822                  watchpoint.  This allows an expression like "watch
4823                  global if q > 10" set in `func', catch writes to
4824                  global on all threads that call `func', or catch
4825                  writes on all recursive calls of `func' by a single
4826                  thread.  We simply always evaluate the condition in
4827                  the innermost frame that's executing where it makes
4828                  sense to evaluate the condition.  It seems
4829                  intuitive.  */
4830               frame = block_innermost_frame (w->cond_exp_valid_block);
4831               if (frame != NULL)
4832                 select_frame (frame);
4833               else
4834                 within_current_scope = 0;
4835             }
4836           if (within_current_scope)
4837             value_is_zero
4838               = catch_errors (breakpoint_cond_eval, cond,
4839                               "Error in testing breakpoint condition:\n",
4840                               RETURN_MASK_ALL);
4841           else
4842             {
4843               warning (_("Watchpoint condition cannot be tested "
4844                          "in the current scope"));
4845               /* If we failed to set the right context for this
4846                  watchpoint, unconditionally report it.  */
4847               value_is_zero = 0;
4848             }
4849           /* FIXME-someday, should give breakpoint #.  */
4850           value_free_to_mark (mark);
4851         }
4852
4853       if (cond && value_is_zero)
4854         {
4855           bs->stop = 0;
4856         }
4857       else if (b->thread != -1 && b->thread != thread_id)
4858         {
4859           bs->stop = 0;
4860         }
4861       else if (b->ignore_count > 0)
4862         {
4863           b->ignore_count--;
4864           annotate_ignore_count_change ();
4865           bs->stop = 0;
4866           /* Increase the hit count even though we don't stop.  */
4867           ++(b->hit_count);
4868           observer_notify_breakpoint_modified (b);
4869         }       
4870     }
4871 }
4872
4873
4874 /* Get a bpstat associated with having just stopped at address
4875    BP_ADDR in thread PTID.
4876
4877    Determine whether we stopped at a breakpoint, etc, or whether we
4878    don't understand this stop.  Result is a chain of bpstat's such
4879    that:
4880
4881    if we don't understand the stop, the result is a null pointer.
4882
4883    if we understand why we stopped, the result is not null.
4884
4885    Each element of the chain refers to a particular breakpoint or
4886    watchpoint at which we have stopped.  (We may have stopped for
4887    several reasons concurrently.)
4888
4889    Each element of the chain has valid next, breakpoint_at,
4890    commands, FIXME??? fields.  */
4891
4892 bpstat
4893 bpstat_stop_status (struct address_space *aspace,
4894                     CORE_ADDR bp_addr, ptid_t ptid,
4895                     const struct target_waitstatus *ws)
4896 {
4897   struct breakpoint *b = NULL;
4898   struct bp_location *bl;
4899   struct bp_location *loc;
4900   /* First item of allocated bpstat's.  */
4901   bpstat bs_head = NULL, *bs_link = &bs_head;
4902   /* Pointer to the last thing in the chain currently.  */
4903   bpstat bs;
4904   int ix;
4905   int need_remove_insert;
4906   int removed_any;
4907
4908   /* First, build the bpstat chain with locations that explain a
4909      target stop, while being careful to not set the target running,
4910      as that may invalidate locations (in particular watchpoint
4911      locations are recreated).  Resuming will happen here with
4912      breakpoint conditions or watchpoint expressions that include
4913      inferior function calls.  */
4914
4915   ALL_BREAKPOINTS (b)
4916     {
4917       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4918         continue;
4919
4920       for (bl = b->loc; bl != NULL; bl = bl->next)
4921         {
4922           /* For hardware watchpoints, we look only at the first
4923              location.  The watchpoint_check function will work on the
4924              entire expression, not the individual locations.  For
4925              read watchpoints, the watchpoints_triggered function has
4926              checked all locations already.  */
4927           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4928             break;
4929
4930           if (bl->shlib_disabled)
4931             continue;
4932
4933           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
4934             continue;
4935
4936           /* Come here if it's a watchpoint, or if the break address
4937              matches.  */
4938
4939           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4940                                                    explain stop.  */
4941
4942           /* Assume we stop.  Should we find a watchpoint that is not
4943              actually triggered, or if the condition of the breakpoint
4944              evaluates as false, we'll reset 'stop' to 0.  */
4945           bs->stop = 1;
4946           bs->print = 1;
4947
4948           /* If this is a scope breakpoint, mark the associated
4949              watchpoint as triggered so that we will handle the
4950              out-of-scope event.  We'll get to the watchpoint next
4951              iteration.  */
4952           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4953             {
4954               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4955
4956               w->watchpoint_triggered = watch_triggered_yes;
4957             }
4958         }
4959     }
4960
4961   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4962     {
4963       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4964         {
4965           bs = bpstat_alloc (loc, &bs_link);
4966           /* For hits of moribund locations, we should just proceed.  */
4967           bs->stop = 0;
4968           bs->print = 0;
4969           bs->print_it = print_it_noop;
4970         }
4971     }
4972
4973   /* A bit of special processing for shlib breakpoints.  We need to
4974      process solib loading here, so that the lists of loaded and
4975      unloaded libraries are correct before we handle "catch load" and
4976      "catch unload".  */
4977   for (bs = bs_head; bs != NULL; bs = bs->next)
4978     {
4979       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
4980         {
4981           handle_solib_event ();
4982           break;
4983         }
4984     }
4985
4986   /* Now go through the locations that caused the target to stop, and
4987      check whether we're interested in reporting this stop to higher
4988      layers, or whether we should resume the target transparently.  */
4989
4990   removed_any = 0;
4991
4992   for (bs = bs_head; bs != NULL; bs = bs->next)
4993     {
4994       if (!bs->stop)
4995         continue;
4996
4997       b = bs->breakpoint_at;
4998       b->ops->check_status (bs);
4999       if (bs->stop)
5000         {
5001           bpstat_check_breakpoint_conditions (bs, ptid);
5002
5003           if (bs->stop)
5004             {
5005               ++(b->hit_count);
5006               observer_notify_breakpoint_modified (b);
5007
5008               /* We will stop here.  */
5009               if (b->disposition == disp_disable)
5010                 {
5011                   --(b->enable_count);
5012                   if (b->enable_count <= 0
5013                       && b->enable_state != bp_permanent)
5014                     b->enable_state = bp_disabled;
5015                   removed_any = 1;
5016                 }
5017               if (b->silent)
5018                 bs->print = 0;
5019               bs->commands = b->commands;
5020               incref_counted_command_line (bs->commands);
5021               if (command_line_is_silent (bs->commands
5022                                           ? bs->commands->commands : NULL))
5023                 bs->print = 0;
5024             }
5025
5026         }
5027
5028       /* Print nothing for this entry if we don't stop or don't
5029          print.  */
5030       if (!bs->stop || !bs->print)
5031         bs->print_it = print_it_noop;
5032     }
5033
5034   /* If we aren't stopping, the value of some hardware watchpoint may
5035      not have changed, but the intermediate memory locations we are
5036      watching may have.  Don't bother if we're stopping; this will get
5037      done later.  */
5038   need_remove_insert = 0;
5039   if (! bpstat_causes_stop (bs_head))
5040     for (bs = bs_head; bs != NULL; bs = bs->next)
5041       if (!bs->stop
5042           && bs->breakpoint_at
5043           && is_hardware_watchpoint (bs->breakpoint_at))
5044         {
5045           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5046
5047           update_watchpoint (w, 0 /* don't reparse.  */);
5048           need_remove_insert = 1;
5049         }
5050
5051   if (need_remove_insert)
5052     update_global_location_list (1);
5053   else if (removed_any)
5054     update_global_location_list (0);
5055
5056   return bs_head;
5057 }
5058
5059 static void
5060 handle_jit_event (void)
5061 {
5062   struct frame_info *frame;
5063   struct gdbarch *gdbarch;
5064
5065   /* Switch terminal for any messages produced by
5066      breakpoint_re_set.  */
5067   target_terminal_ours_for_output ();
5068
5069   frame = get_current_frame ();
5070   gdbarch = get_frame_arch (frame);
5071
5072   jit_event_handler (gdbarch);
5073
5074   target_terminal_inferior ();
5075 }
5076
5077 /* Handle an solib event by calling solib_add.  */
5078
5079 void
5080 handle_solib_event (void)
5081 {
5082   clear_program_space_solib_cache (current_inferior ()->pspace);
5083
5084   /* Check for any newly added shared libraries if we're supposed to
5085      be adding them automatically.  Switch terminal for any messages
5086      produced by breakpoint_re_set.  */
5087   target_terminal_ours_for_output ();
5088 #ifdef SOLIB_ADD
5089   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
5090 #else
5091   solib_add (NULL, 0, &current_target, auto_solib_add);
5092 #endif
5093   target_terminal_inferior ();
5094 }
5095
5096 /* Prepare WHAT final decision for infrun.  */
5097
5098 /* Decide what infrun needs to do with this bpstat.  */
5099
5100 struct bpstat_what
5101 bpstat_what (bpstat bs_head)
5102 {
5103   struct bpstat_what retval;
5104   int jit_event = 0;
5105   bpstat bs;
5106
5107   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5108   retval.call_dummy = STOP_NONE;
5109   retval.is_longjmp = 0;
5110
5111   for (bs = bs_head; bs != NULL; bs = bs->next)
5112     {
5113       /* Extract this BS's action.  After processing each BS, we check
5114          if its action overrides all we've seem so far.  */
5115       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5116       enum bptype bptype;
5117
5118       if (bs->breakpoint_at == NULL)
5119         {
5120           /* I suspect this can happen if it was a momentary
5121              breakpoint which has since been deleted.  */
5122           bptype = bp_none;
5123         }
5124       else
5125         bptype = bs->breakpoint_at->type;
5126
5127       switch (bptype)
5128         {
5129         case bp_none:
5130           break;
5131         case bp_breakpoint:
5132         case bp_hardware_breakpoint:
5133         case bp_until:
5134         case bp_finish:
5135         case bp_shlib_event:
5136           if (bs->stop)
5137             {
5138               if (bs->print)
5139                 this_action = BPSTAT_WHAT_STOP_NOISY;
5140               else
5141                 this_action = BPSTAT_WHAT_STOP_SILENT;
5142             }
5143           else
5144             this_action = BPSTAT_WHAT_SINGLE;
5145           break;
5146         case bp_watchpoint:
5147         case bp_hardware_watchpoint:
5148         case bp_read_watchpoint:
5149         case bp_access_watchpoint:
5150           if (bs->stop)
5151             {
5152               if (bs->print)
5153                 this_action = BPSTAT_WHAT_STOP_NOISY;
5154               else
5155                 this_action = BPSTAT_WHAT_STOP_SILENT;
5156             }
5157           else
5158             {
5159               /* There was a watchpoint, but we're not stopping.
5160                  This requires no further action.  */
5161             }
5162           break;
5163         case bp_longjmp:
5164         case bp_longjmp_call_dummy:
5165         case bp_exception:
5166           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5167           retval.is_longjmp = bptype != bp_exception;
5168           break;
5169         case bp_longjmp_resume:
5170         case bp_exception_resume:
5171           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5172           retval.is_longjmp = bptype == bp_longjmp_resume;
5173           break;
5174         case bp_step_resume:
5175           if (bs->stop)
5176             this_action = BPSTAT_WHAT_STEP_RESUME;
5177           else
5178             {
5179               /* It is for the wrong frame.  */
5180               this_action = BPSTAT_WHAT_SINGLE;
5181             }
5182           break;
5183         case bp_hp_step_resume:
5184           if (bs->stop)
5185             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5186           else
5187             {
5188               /* It is for the wrong frame.  */
5189               this_action = BPSTAT_WHAT_SINGLE;
5190             }
5191           break;
5192         case bp_watchpoint_scope:
5193         case bp_thread_event:
5194         case bp_overlay_event:
5195         case bp_longjmp_master:
5196         case bp_std_terminate_master:
5197         case bp_exception_master:
5198           this_action = BPSTAT_WHAT_SINGLE;
5199           break;
5200         case bp_catchpoint:
5201           if (bs->stop)
5202             {
5203               if (bs->print)
5204                 this_action = BPSTAT_WHAT_STOP_NOISY;
5205               else
5206                 this_action = BPSTAT_WHAT_STOP_SILENT;
5207             }
5208           else
5209             {
5210               /* There was a catchpoint, but we're not stopping.
5211                  This requires no further action.  */
5212             }
5213           break;
5214         case bp_jit_event:
5215           jit_event = 1;
5216           this_action = BPSTAT_WHAT_SINGLE;
5217           break;
5218         case bp_call_dummy:
5219           /* Make sure the action is stop (silent or noisy),
5220              so infrun.c pops the dummy frame.  */
5221           retval.call_dummy = STOP_STACK_DUMMY;
5222           this_action = BPSTAT_WHAT_STOP_SILENT;
5223           break;
5224         case bp_std_terminate:
5225           /* Make sure the action is stop (silent or noisy),
5226              so infrun.c pops the dummy frame.  */
5227           retval.call_dummy = STOP_STD_TERMINATE;
5228           this_action = BPSTAT_WHAT_STOP_SILENT;
5229           break;
5230         case bp_tracepoint:
5231         case bp_fast_tracepoint:
5232         case bp_static_tracepoint:
5233           /* Tracepoint hits should not be reported back to GDB, and
5234              if one got through somehow, it should have been filtered
5235              out already.  */
5236           internal_error (__FILE__, __LINE__,
5237                           _("bpstat_what: tracepoint encountered"));
5238           break;
5239         case bp_gnu_ifunc_resolver:
5240           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5241           this_action = BPSTAT_WHAT_SINGLE;
5242           break;
5243         case bp_gnu_ifunc_resolver_return:
5244           /* The breakpoint will be removed, execution will restart from the
5245              PC of the former breakpoint.  */
5246           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5247           break;
5248
5249         case bp_dprintf:
5250           this_action = BPSTAT_WHAT_STOP_SILENT;
5251           break;
5252
5253         default:
5254           internal_error (__FILE__, __LINE__,
5255                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5256         }
5257
5258       retval.main_action = max (retval.main_action, this_action);
5259     }
5260
5261   /* These operations may affect the bs->breakpoint_at state so they are
5262      delayed after MAIN_ACTION is decided above.  */
5263
5264   if (jit_event)
5265     {
5266       if (debug_infrun)
5267         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5268
5269       handle_jit_event ();
5270     }
5271
5272   for (bs = bs_head; bs != NULL; bs = bs->next)
5273     {
5274       struct breakpoint *b = bs->breakpoint_at;
5275
5276       if (b == NULL)
5277         continue;
5278       switch (b->type)
5279         {
5280         case bp_gnu_ifunc_resolver:
5281           gnu_ifunc_resolver_stop (b);
5282           break;
5283         case bp_gnu_ifunc_resolver_return:
5284           gnu_ifunc_resolver_return_stop (b);
5285           break;
5286         }
5287     }
5288
5289   return retval;
5290 }
5291
5292 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5293    without hardware support).  This isn't related to a specific bpstat,
5294    just to things like whether watchpoints are set.  */
5295
5296 int
5297 bpstat_should_step (void)
5298 {
5299   struct breakpoint *b;
5300
5301   ALL_BREAKPOINTS (b)
5302     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5303       return 1;
5304   return 0;
5305 }
5306
5307 int
5308 bpstat_causes_stop (bpstat bs)
5309 {
5310   for (; bs != NULL; bs = bs->next)
5311     if (bs->stop)
5312       return 1;
5313
5314   return 0;
5315 }
5316
5317 \f
5318
5319 /* Compute a string of spaces suitable to indent the next line
5320    so it starts at the position corresponding to the table column
5321    named COL_NAME in the currently active table of UIOUT.  */
5322
5323 static char *
5324 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5325 {
5326   static char wrap_indent[80];
5327   int i, total_width, width, align;
5328   char *text;
5329
5330   total_width = 0;
5331   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5332     {
5333       if (strcmp (text, col_name) == 0)
5334         {
5335           gdb_assert (total_width < sizeof wrap_indent);
5336           memset (wrap_indent, ' ', total_width);
5337           wrap_indent[total_width] = 0;
5338
5339           return wrap_indent;
5340         }
5341
5342       total_width += width + 1;
5343     }
5344
5345   return NULL;
5346 }
5347
5348 /* Determine if the locations of this breakpoint will have their conditions
5349    evaluated by the target, host or a mix of both.  Returns the following:
5350
5351     "host": Host evals condition.
5352     "host or target": Host or Target evals condition.
5353     "target": Target evals condition.
5354 */
5355
5356 static const char *
5357 bp_condition_evaluator (struct breakpoint *b)
5358 {
5359   struct bp_location *bl;
5360   char host_evals = 0;
5361   char target_evals = 0;
5362
5363   if (!b)
5364     return NULL;
5365
5366   if (!is_breakpoint (b))
5367     return NULL;
5368
5369   if (gdb_evaluates_breakpoint_condition_p ()
5370       || !target_supports_evaluation_of_breakpoint_conditions ())
5371     return condition_evaluation_host;
5372
5373   for (bl = b->loc; bl; bl = bl->next)
5374     {
5375       if (bl->cond_bytecode)
5376         target_evals++;
5377       else
5378         host_evals++;
5379     }
5380
5381   if (host_evals && target_evals)
5382     return condition_evaluation_both;
5383   else if (target_evals)
5384     return condition_evaluation_target;
5385   else
5386     return condition_evaluation_host;
5387 }
5388
5389 /* Determine the breakpoint location's condition evaluator.  This is
5390    similar to bp_condition_evaluator, but for locations.  */
5391
5392 static const char *
5393 bp_location_condition_evaluator (struct bp_location *bl)
5394 {
5395   if (bl && !is_breakpoint (bl->owner))
5396     return NULL;
5397
5398   if (gdb_evaluates_breakpoint_condition_p ()
5399       || !target_supports_evaluation_of_breakpoint_conditions ())
5400     return condition_evaluation_host;
5401
5402   if (bl && bl->cond_bytecode)
5403     return condition_evaluation_target;
5404   else
5405     return condition_evaluation_host;
5406 }
5407
5408 /* Print the LOC location out of the list of B->LOC locations.  */
5409
5410 static void
5411 print_breakpoint_location (struct breakpoint *b,
5412                            struct bp_location *loc)
5413 {
5414   struct ui_out *uiout = current_uiout;
5415   struct cleanup *old_chain = save_current_program_space ();
5416
5417   if (loc != NULL && loc->shlib_disabled)
5418     loc = NULL;
5419
5420   if (loc != NULL)
5421     set_current_program_space (loc->pspace);
5422
5423   if (b->display_canonical)
5424     ui_out_field_string (uiout, "what", b->addr_string);
5425   else if (loc && loc->source_file)
5426     {
5427       struct symbol *sym 
5428         = find_pc_sect_function (loc->address, loc->section);
5429       if (sym)
5430         {
5431           ui_out_text (uiout, "in ");
5432           ui_out_field_string (uiout, "func",
5433                                SYMBOL_PRINT_NAME (sym));
5434           ui_out_text (uiout, " ");
5435           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5436           ui_out_text (uiout, "at ");
5437         }
5438       ui_out_field_string (uiout, "file", loc->source_file);
5439       ui_out_text (uiout, ":");
5440       
5441       if (ui_out_is_mi_like_p (uiout))
5442         {
5443           struct symtab_and_line sal = find_pc_line (loc->address, 0);
5444           char *fullname = symtab_to_fullname (sal.symtab);
5445           
5446           if (fullname)
5447             ui_out_field_string (uiout, "fullname", fullname);
5448         }
5449       
5450       ui_out_field_int (uiout, "line", loc->line_number);
5451     }
5452   else if (loc)
5453     {
5454       struct ui_file *stb = mem_fileopen ();
5455       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5456
5457       print_address_symbolic (loc->gdbarch, loc->address, stb,
5458                               demangle, "");
5459       ui_out_field_stream (uiout, "at", stb);
5460
5461       do_cleanups (stb_chain);
5462     }
5463   else
5464     ui_out_field_string (uiout, "pending", b->addr_string);
5465
5466   if (loc && is_breakpoint (b)
5467       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5468       && bp_condition_evaluator (b) == condition_evaluation_both)
5469     {
5470       ui_out_text (uiout, " (");
5471       ui_out_field_string (uiout, "evaluated-by",
5472                            bp_location_condition_evaluator (loc));
5473       ui_out_text (uiout, ")");
5474     }
5475
5476   do_cleanups (old_chain);
5477 }
5478
5479 static const char *
5480 bptype_string (enum bptype type)
5481 {
5482   struct ep_type_description
5483     {
5484       enum bptype type;
5485       char *description;
5486     };
5487   static struct ep_type_description bptypes[] =
5488   {
5489     {bp_none, "?deleted?"},
5490     {bp_breakpoint, "breakpoint"},
5491     {bp_hardware_breakpoint, "hw breakpoint"},
5492     {bp_until, "until"},
5493     {bp_finish, "finish"},
5494     {bp_watchpoint, "watchpoint"},
5495     {bp_hardware_watchpoint, "hw watchpoint"},
5496     {bp_read_watchpoint, "read watchpoint"},
5497     {bp_access_watchpoint, "acc watchpoint"},
5498     {bp_longjmp, "longjmp"},
5499     {bp_longjmp_resume, "longjmp resume"},
5500     {bp_longjmp_call_dummy, "longjmp for call dummy"},
5501     {bp_exception, "exception"},
5502     {bp_exception_resume, "exception resume"},
5503     {bp_step_resume, "step resume"},
5504     {bp_hp_step_resume, "high-priority step resume"},
5505     {bp_watchpoint_scope, "watchpoint scope"},
5506     {bp_call_dummy, "call dummy"},
5507     {bp_std_terminate, "std::terminate"},
5508     {bp_shlib_event, "shlib events"},
5509     {bp_thread_event, "thread events"},
5510     {bp_overlay_event, "overlay events"},
5511     {bp_longjmp_master, "longjmp master"},
5512     {bp_std_terminate_master, "std::terminate master"},
5513     {bp_exception_master, "exception master"},
5514     {bp_catchpoint, "catchpoint"},
5515     {bp_tracepoint, "tracepoint"},
5516     {bp_fast_tracepoint, "fast tracepoint"},
5517     {bp_static_tracepoint, "static tracepoint"},
5518     {bp_dprintf, "dprintf"},
5519     {bp_jit_event, "jit events"},
5520     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5521     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5522   };
5523
5524   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5525       || ((int) type != bptypes[(int) type].type))
5526     internal_error (__FILE__, __LINE__,
5527                     _("bptypes table does not describe type #%d."),
5528                     (int) type);
5529
5530   return bptypes[(int) type].description;
5531 }
5532
5533 /* Print B to gdb_stdout.  */
5534
5535 static void
5536 print_one_breakpoint_location (struct breakpoint *b,
5537                                struct bp_location *loc,
5538                                int loc_number,
5539                                struct bp_location **last_loc,
5540                                int allflag)
5541 {
5542   struct command_line *l;
5543   static char bpenables[] = "nynny";
5544
5545   struct ui_out *uiout = current_uiout;
5546   int header_of_multiple = 0;
5547   int part_of_multiple = (loc != NULL);
5548   struct value_print_options opts;
5549
5550   get_user_print_options (&opts);
5551
5552   gdb_assert (!loc || loc_number != 0);
5553   /* See comment in print_one_breakpoint concerning treatment of
5554      breakpoints with single disabled location.  */
5555   if (loc == NULL 
5556       && (b->loc != NULL 
5557           && (b->loc->next != NULL || !b->loc->enabled)))
5558     header_of_multiple = 1;
5559   if (loc == NULL)
5560     loc = b->loc;
5561
5562   annotate_record ();
5563
5564   /* 1 */
5565   annotate_field (0);
5566   if (part_of_multiple)
5567     {
5568       char *formatted;
5569       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5570       ui_out_field_string (uiout, "number", formatted);
5571       xfree (formatted);
5572     }
5573   else
5574     {
5575       ui_out_field_int (uiout, "number", b->number);
5576     }
5577
5578   /* 2 */
5579   annotate_field (1);
5580   if (part_of_multiple)
5581     ui_out_field_skip (uiout, "type");
5582   else
5583     ui_out_field_string (uiout, "type", bptype_string (b->type));
5584
5585   /* 3 */
5586   annotate_field (2);
5587   if (part_of_multiple)
5588     ui_out_field_skip (uiout, "disp");
5589   else
5590     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5591
5592
5593   /* 4 */
5594   annotate_field (3);
5595   if (part_of_multiple)
5596     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5597   else
5598     ui_out_field_fmt (uiout, "enabled", "%c", 
5599                       bpenables[(int) b->enable_state]);
5600   ui_out_spaces (uiout, 2);
5601
5602   
5603   /* 5 and 6 */
5604   if (b->ops != NULL && b->ops->print_one != NULL)
5605     {
5606       /* Although the print_one can possibly print all locations,
5607          calling it here is not likely to get any nice result.  So,
5608          make sure there's just one location.  */
5609       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5610       b->ops->print_one (b, last_loc);
5611     }
5612   else
5613     switch (b->type)
5614       {
5615       case bp_none:
5616         internal_error (__FILE__, __LINE__,
5617                         _("print_one_breakpoint: bp_none encountered\n"));
5618         break;
5619
5620       case bp_watchpoint:
5621       case bp_hardware_watchpoint:
5622       case bp_read_watchpoint:
5623       case bp_access_watchpoint:
5624         {
5625           struct watchpoint *w = (struct watchpoint *) b;
5626
5627           /* Field 4, the address, is omitted (which makes the columns
5628              not line up too nicely with the headers, but the effect
5629              is relatively readable).  */
5630           if (opts.addressprint)
5631             ui_out_field_skip (uiout, "addr");
5632           annotate_field (5);
5633           ui_out_field_string (uiout, "what", w->exp_string);
5634         }
5635         break;
5636
5637       case bp_breakpoint:
5638       case bp_hardware_breakpoint:
5639       case bp_until:
5640       case bp_finish:
5641       case bp_longjmp:
5642       case bp_longjmp_resume:
5643       case bp_longjmp_call_dummy:
5644       case bp_exception:
5645       case bp_exception_resume:
5646       case bp_step_resume:
5647       case bp_hp_step_resume:
5648       case bp_watchpoint_scope:
5649       case bp_call_dummy:
5650       case bp_std_terminate:
5651       case bp_shlib_event:
5652       case bp_thread_event:
5653       case bp_overlay_event:
5654       case bp_longjmp_master:
5655       case bp_std_terminate_master:
5656       case bp_exception_master:
5657       case bp_tracepoint:
5658       case bp_fast_tracepoint:
5659       case bp_static_tracepoint:
5660       case bp_dprintf:
5661       case bp_jit_event:
5662       case bp_gnu_ifunc_resolver:
5663       case bp_gnu_ifunc_resolver_return:
5664         if (opts.addressprint)
5665           {
5666             annotate_field (4);
5667             if (header_of_multiple)
5668               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5669             else if (b->loc == NULL || loc->shlib_disabled)
5670               ui_out_field_string (uiout, "addr", "<PENDING>");
5671             else
5672               ui_out_field_core_addr (uiout, "addr",
5673                                       loc->gdbarch, loc->address);
5674           }
5675         annotate_field (5);
5676         if (!header_of_multiple)
5677           print_breakpoint_location (b, loc);
5678         if (b->loc)
5679           *last_loc = b->loc;
5680         break;
5681       }
5682
5683
5684   /* For backward compatibility, don't display inferiors unless there
5685      are several.  */
5686   if (loc != NULL
5687       && !header_of_multiple
5688       && (allflag
5689           || (!gdbarch_has_global_breakpoints (target_gdbarch)
5690               && (number_of_program_spaces () > 1
5691                   || number_of_inferiors () > 1)
5692               /* LOC is for existing B, it cannot be in
5693                  moribund_locations and thus having NULL OWNER.  */
5694               && loc->owner->type != bp_catchpoint)))
5695     {
5696       struct inferior *inf;
5697       int first = 1;
5698
5699       for (inf = inferior_list; inf != NULL; inf = inf->next)
5700         {
5701           if (inf->pspace == loc->pspace)
5702             {
5703               if (first)
5704                 {
5705                   first = 0;
5706                   ui_out_text (uiout, " inf ");
5707                 }
5708               else
5709                 ui_out_text (uiout, ", ");
5710               ui_out_text (uiout, plongest (inf->num));
5711             }
5712         }
5713     }
5714
5715   if (!part_of_multiple)
5716     {
5717       if (b->thread != -1)
5718         {
5719           /* FIXME: This seems to be redundant and lost here; see the
5720              "stop only in" line a little further down.  */
5721           ui_out_text (uiout, " thread ");
5722           ui_out_field_int (uiout, "thread", b->thread);
5723         }
5724       else if (b->task != 0)
5725         {
5726           ui_out_text (uiout, " task ");
5727           ui_out_field_int (uiout, "task", b->task);
5728         }
5729     }
5730
5731   ui_out_text (uiout, "\n");
5732
5733   if (!part_of_multiple)
5734     b->ops->print_one_detail (b, uiout);
5735
5736   if (part_of_multiple && frame_id_p (b->frame_id))
5737     {
5738       annotate_field (6);
5739       ui_out_text (uiout, "\tstop only in stack frame at ");
5740       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
5741          the frame ID.  */
5742       ui_out_field_core_addr (uiout, "frame",
5743                               b->gdbarch, b->frame_id.stack_addr);
5744       ui_out_text (uiout, "\n");
5745     }
5746   
5747   if (!part_of_multiple && b->cond_string)
5748     {
5749       annotate_field (7);
5750       if (is_tracepoint (b))
5751         ui_out_text (uiout, "\ttrace only if ");
5752       else
5753         ui_out_text (uiout, "\tstop only if ");
5754       ui_out_field_string (uiout, "cond", b->cond_string);
5755
5756       /* Print whether the target is doing the breakpoint's condition
5757          evaluation.  If GDB is doing the evaluation, don't print anything.  */
5758       if (is_breakpoint (b)
5759           && breakpoint_condition_evaluation_mode ()
5760           == condition_evaluation_target)
5761         {
5762           ui_out_text (uiout, " (");
5763           ui_out_field_string (uiout, "evaluated-by",
5764                                bp_condition_evaluator (b));
5765           ui_out_text (uiout, " evals)");
5766         }
5767       ui_out_text (uiout, "\n");
5768     }
5769
5770   if (!part_of_multiple && b->thread != -1)
5771     {
5772       /* FIXME should make an annotation for this.  */
5773       ui_out_text (uiout, "\tstop only in thread ");
5774       ui_out_field_int (uiout, "thread", b->thread);
5775       ui_out_text (uiout, "\n");
5776     }
5777   
5778   if (!part_of_multiple && b->hit_count)
5779     {
5780       /* FIXME should make an annotation for this.  */
5781       if (is_catchpoint (b))
5782         ui_out_text (uiout, "\tcatchpoint");
5783       else if (is_tracepoint (b))
5784         ui_out_text (uiout, "\ttracepoint");
5785       else
5786         ui_out_text (uiout, "\tbreakpoint");
5787       ui_out_text (uiout, " already hit ");
5788       ui_out_field_int (uiout, "times", b->hit_count);
5789       if (b->hit_count == 1)
5790         ui_out_text (uiout, " time\n");
5791       else
5792         ui_out_text (uiout, " times\n");
5793     }
5794   
5795   /* Output the count also if it is zero, but only if this is mi.
5796      FIXME: Should have a better test for this.  */
5797   if (ui_out_is_mi_like_p (uiout))
5798     if (!part_of_multiple && b->hit_count == 0)
5799       ui_out_field_int (uiout, "times", b->hit_count);
5800
5801   if (!part_of_multiple && b->ignore_count)
5802     {
5803       annotate_field (8);
5804       ui_out_text (uiout, "\tignore next ");
5805       ui_out_field_int (uiout, "ignore", b->ignore_count);
5806       ui_out_text (uiout, " hits\n");
5807     }
5808
5809   /* Note that an enable count of 1 corresponds to "enable once"
5810      behavior, which is reported by the combination of enablement and
5811      disposition, so we don't need to mention it here.  */
5812   if (!part_of_multiple && b->enable_count > 1)
5813     {
5814       annotate_field (8);
5815       ui_out_text (uiout, "\tdisable after ");
5816       /* Tweak the wording to clarify that ignore and enable counts
5817          are distinct, and have additive effect.  */
5818       if (b->ignore_count)
5819         ui_out_text (uiout, "additional ");
5820       else
5821         ui_out_text (uiout, "next ");
5822       ui_out_field_int (uiout, "enable", b->enable_count);
5823       ui_out_text (uiout, " hits\n");
5824     }
5825
5826   if (!part_of_multiple && is_tracepoint (b))
5827     {
5828       struct tracepoint *tp = (struct tracepoint *) b;
5829
5830       if (tp->traceframe_usage)
5831         {
5832           ui_out_text (uiout, "\ttrace buffer usage ");
5833           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
5834           ui_out_text (uiout, " bytes\n");
5835         }
5836     }
5837   
5838   l = b->commands ? b->commands->commands : NULL;
5839   if (!part_of_multiple && l)
5840     {
5841       struct cleanup *script_chain;
5842
5843       annotate_field (9);
5844       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
5845       print_command_lines (uiout, l, 4);
5846       do_cleanups (script_chain);
5847     }
5848
5849   if (is_tracepoint (b))
5850     {
5851       struct tracepoint *t = (struct tracepoint *) b;
5852
5853       if (!part_of_multiple && t->pass_count)
5854         {
5855           annotate_field (10);
5856           ui_out_text (uiout, "\tpass count ");
5857           ui_out_field_int (uiout, "pass", t->pass_count);
5858           ui_out_text (uiout, " \n");
5859         }
5860     }
5861
5862   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5863     {
5864       if (is_watchpoint (b))
5865         {
5866           struct watchpoint *w = (struct watchpoint *) b;
5867
5868           ui_out_field_string (uiout, "original-location", w->exp_string);
5869         }
5870       else if (b->addr_string)
5871         ui_out_field_string (uiout, "original-location", b->addr_string);
5872     }
5873 }
5874
5875 static void
5876 print_one_breakpoint (struct breakpoint *b,
5877                       struct bp_location **last_loc, 
5878                       int allflag)
5879 {
5880   struct cleanup *bkpt_chain;
5881   struct ui_out *uiout = current_uiout;
5882
5883   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5884
5885   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5886   do_cleanups (bkpt_chain);
5887
5888   /* If this breakpoint has custom print function,
5889      it's already printed.  Otherwise, print individual
5890      locations, if any.  */
5891   if (b->ops == NULL || b->ops->print_one == NULL)
5892     {
5893       /* If breakpoint has a single location that is disabled, we
5894          print it as if it had several locations, since otherwise it's
5895          hard to represent "breakpoint enabled, location disabled"
5896          situation.
5897
5898          Note that while hardware watchpoints have several locations
5899          internally, that's not a property exposed to user.  */
5900       if (b->loc 
5901           && !is_hardware_watchpoint (b)
5902           && (b->loc->next || !b->loc->enabled))
5903         {
5904           struct bp_location *loc;
5905           int n = 1;
5906
5907           for (loc = b->loc; loc; loc = loc->next, ++n)
5908             {
5909               struct cleanup *inner2 =
5910                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5911               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5912               do_cleanups (inner2);
5913             }
5914         }
5915     }
5916 }
5917
5918 static int
5919 breakpoint_address_bits (struct breakpoint *b)
5920 {
5921   int print_address_bits = 0;
5922   struct bp_location *loc;
5923
5924   for (loc = b->loc; loc; loc = loc->next)
5925     {
5926       int addr_bit;
5927
5928       /* Software watchpoints that aren't watching memory don't have
5929          an address to print.  */
5930       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5931         continue;
5932
5933       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5934       if (addr_bit > print_address_bits)
5935         print_address_bits = addr_bit;
5936     }
5937
5938   return print_address_bits;
5939 }
5940
5941 struct captured_breakpoint_query_args
5942   {
5943     int bnum;
5944   };
5945
5946 static int
5947 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5948 {
5949   struct captured_breakpoint_query_args *args = data;
5950   struct breakpoint *b;
5951   struct bp_location *dummy_loc = NULL;
5952
5953   ALL_BREAKPOINTS (b)
5954     {
5955       if (args->bnum == b->number)
5956         {
5957           print_one_breakpoint (b, &dummy_loc, 0);
5958           return GDB_RC_OK;
5959         }
5960     }
5961   return GDB_RC_NONE;
5962 }
5963
5964 enum gdb_rc
5965 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5966                       char **error_message)
5967 {
5968   struct captured_breakpoint_query_args args;
5969
5970   args.bnum = bnum;
5971   /* For the moment we don't trust print_one_breakpoint() to not throw
5972      an error.  */
5973   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5974                                  error_message, RETURN_MASK_ALL) < 0)
5975     return GDB_RC_FAIL;
5976   else
5977     return GDB_RC_OK;
5978 }
5979
5980 /* Return true if this breakpoint was set by the user, false if it is
5981    internal or momentary.  */
5982
5983 int
5984 user_breakpoint_p (struct breakpoint *b)
5985 {
5986   return b->number > 0;
5987 }
5988
5989 /* Print information on user settable breakpoint (watchpoint, etc)
5990    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5991    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5992    FILTER is non-NULL, call it on each breakpoint and only include the
5993    ones for which it returns non-zero.  Return the total number of
5994    breakpoints listed.  */
5995
5996 static int
5997 breakpoint_1 (char *args, int allflag, 
5998               int (*filter) (const struct breakpoint *))
5999 {
6000   struct breakpoint *b;
6001   struct bp_location *last_loc = NULL;
6002   int nr_printable_breakpoints;
6003   struct cleanup *bkpttbl_chain;
6004   struct value_print_options opts;
6005   int print_address_bits = 0;
6006   int print_type_col_width = 14;
6007   struct ui_out *uiout = current_uiout;
6008
6009   get_user_print_options (&opts);
6010
6011   /* Compute the number of rows in the table, as well as the size
6012      required for address fields.  */
6013   nr_printable_breakpoints = 0;
6014   ALL_BREAKPOINTS (b)
6015     {
6016       /* If we have a filter, only list the breakpoints it accepts.  */
6017       if (filter && !filter (b))
6018         continue;
6019
6020       /* If we have an "args" string, it is a list of breakpoints to 
6021          accept.  Skip the others.  */
6022       if (args != NULL && *args != '\0')
6023         {
6024           if (allflag && parse_and_eval_long (args) != b->number)
6025             continue;
6026           if (!allflag && !number_is_in_list (args, b->number))
6027             continue;
6028         }
6029
6030       if (allflag || user_breakpoint_p (b))
6031         {
6032           int addr_bit, type_len;
6033
6034           addr_bit = breakpoint_address_bits (b);
6035           if (addr_bit > print_address_bits)
6036             print_address_bits = addr_bit;
6037
6038           type_len = strlen (bptype_string (b->type));
6039           if (type_len > print_type_col_width)
6040             print_type_col_width = type_len;
6041
6042           nr_printable_breakpoints++;
6043         }
6044     }
6045
6046   if (opts.addressprint)
6047     bkpttbl_chain 
6048       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6049                                              nr_printable_breakpoints,
6050                                              "BreakpointTable");
6051   else
6052     bkpttbl_chain 
6053       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6054                                              nr_printable_breakpoints,
6055                                              "BreakpointTable");
6056
6057   if (nr_printable_breakpoints > 0)
6058     annotate_breakpoints_headers ();
6059   if (nr_printable_breakpoints > 0)
6060     annotate_field (0);
6061   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6062   if (nr_printable_breakpoints > 0)
6063     annotate_field (1);
6064   ui_out_table_header (uiout, print_type_col_width, ui_left,
6065                        "type", "Type");                         /* 2 */
6066   if (nr_printable_breakpoints > 0)
6067     annotate_field (2);
6068   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6069   if (nr_printable_breakpoints > 0)
6070     annotate_field (3);
6071   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6072   if (opts.addressprint)
6073     {
6074       if (nr_printable_breakpoints > 0)
6075         annotate_field (4);
6076       if (print_address_bits <= 32)
6077         ui_out_table_header (uiout, 10, ui_left, 
6078                              "addr", "Address");                /* 5 */
6079       else
6080         ui_out_table_header (uiout, 18, ui_left, 
6081                              "addr", "Address");                /* 5 */
6082     }
6083   if (nr_printable_breakpoints > 0)
6084     annotate_field (5);
6085   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6086   ui_out_table_body (uiout);
6087   if (nr_printable_breakpoints > 0)
6088     annotate_breakpoints_table ();
6089
6090   ALL_BREAKPOINTS (b)
6091     {
6092       QUIT;
6093       /* If we have a filter, only list the breakpoints it accepts.  */
6094       if (filter && !filter (b))
6095         continue;
6096
6097       /* If we have an "args" string, it is a list of breakpoints to 
6098          accept.  Skip the others.  */
6099
6100       if (args != NULL && *args != '\0')
6101         {
6102           if (allflag)  /* maintenance info breakpoint */
6103             {
6104               if (parse_and_eval_long (args) != b->number)
6105                 continue;
6106             }
6107           else          /* all others */
6108             {
6109               if (!number_is_in_list (args, b->number))
6110                 continue;
6111             }
6112         }
6113       /* We only print out user settable breakpoints unless the
6114          allflag is set.  */
6115       if (allflag || user_breakpoint_p (b))
6116         print_one_breakpoint (b, &last_loc, allflag);
6117     }
6118
6119   do_cleanups (bkpttbl_chain);
6120
6121   if (nr_printable_breakpoints == 0)
6122     {
6123       /* If there's a filter, let the caller decide how to report
6124          empty list.  */
6125       if (!filter)
6126         {
6127           if (args == NULL || *args == '\0')
6128             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6129           else
6130             ui_out_message (uiout, 0, 
6131                             "No breakpoint or watchpoint matching '%s'.\n",
6132                             args);
6133         }
6134     }
6135   else
6136     {
6137       if (last_loc && !server_command)
6138         set_next_address (last_loc->gdbarch, last_loc->address);
6139     }
6140
6141   /* FIXME?  Should this be moved up so that it is only called when
6142      there have been breakpoints? */
6143   annotate_breakpoints_table_end ();
6144
6145   return nr_printable_breakpoints;
6146 }
6147
6148 /* Display the value of default-collect in a way that is generally
6149    compatible with the breakpoint list.  */
6150
6151 static void
6152 default_collect_info (void)
6153 {
6154   struct ui_out *uiout = current_uiout;
6155
6156   /* If it has no value (which is frequently the case), say nothing; a
6157      message like "No default-collect." gets in user's face when it's
6158      not wanted.  */
6159   if (!*default_collect)
6160     return;
6161
6162   /* The following phrase lines up nicely with per-tracepoint collect
6163      actions.  */
6164   ui_out_text (uiout, "default collect ");
6165   ui_out_field_string (uiout, "default-collect", default_collect);
6166   ui_out_text (uiout, " \n");
6167 }
6168   
6169 static void
6170 breakpoints_info (char *args, int from_tty)
6171 {
6172   breakpoint_1 (args, 0, NULL);
6173
6174   default_collect_info ();
6175 }
6176
6177 static void
6178 watchpoints_info (char *args, int from_tty)
6179 {
6180   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6181   struct ui_out *uiout = current_uiout;
6182
6183   if (num_printed == 0)
6184     {
6185       if (args == NULL || *args == '\0')
6186         ui_out_message (uiout, 0, "No watchpoints.\n");
6187       else
6188         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6189     }
6190 }
6191
6192 static void
6193 maintenance_info_breakpoints (char *args, int from_tty)
6194 {
6195   breakpoint_1 (args, 1, NULL);
6196
6197   default_collect_info ();
6198 }
6199
6200 static int
6201 breakpoint_has_pc (struct breakpoint *b,
6202                    struct program_space *pspace,
6203                    CORE_ADDR pc, struct obj_section *section)
6204 {
6205   struct bp_location *bl = b->loc;
6206
6207   for (; bl; bl = bl->next)
6208     {
6209       if (bl->pspace == pspace
6210           && bl->address == pc
6211           && (!overlay_debugging || bl->section == section))
6212         return 1;         
6213     }
6214   return 0;
6215 }
6216
6217 /* Print a message describing any user-breakpoints set at PC.  This
6218    concerns with logical breakpoints, so we match program spaces, not
6219    address spaces.  */
6220
6221 static void
6222 describe_other_breakpoints (struct gdbarch *gdbarch,
6223                             struct program_space *pspace, CORE_ADDR pc,
6224                             struct obj_section *section, int thread)
6225 {
6226   int others = 0;
6227   struct breakpoint *b;
6228
6229   ALL_BREAKPOINTS (b)
6230     others += (user_breakpoint_p (b)
6231                && breakpoint_has_pc (b, pspace, pc, section));
6232   if (others > 0)
6233     {
6234       if (others == 1)
6235         printf_filtered (_("Note: breakpoint "));
6236       else /* if (others == ???) */
6237         printf_filtered (_("Note: breakpoints "));
6238       ALL_BREAKPOINTS (b)
6239         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6240           {
6241             others--;
6242             printf_filtered ("%d", b->number);
6243             if (b->thread == -1 && thread != -1)
6244               printf_filtered (" (all threads)");
6245             else if (b->thread != -1)
6246               printf_filtered (" (thread %d)", b->thread);
6247             printf_filtered ("%s%s ",
6248                              ((b->enable_state == bp_disabled
6249                                || b->enable_state == bp_call_disabled)
6250                               ? " (disabled)"
6251                               : b->enable_state == bp_permanent 
6252                               ? " (permanent)"
6253                               : ""),
6254                              (others > 1) ? "," 
6255                              : ((others == 1) ? " and" : ""));
6256           }
6257       printf_filtered (_("also set at pc "));
6258       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6259       printf_filtered (".\n");
6260     }
6261 }
6262 \f
6263
6264 /* Return true iff it is meaningful to use the address member of
6265    BPT.  For some breakpoint types, the address member is irrelevant
6266    and it makes no sense to attempt to compare it to other addresses
6267    (or use it for any other purpose either).
6268
6269    More specifically, each of the following breakpoint types will
6270    always have a zero valued address and we don't want to mark
6271    breakpoints of any of these types to be a duplicate of an actual
6272    breakpoint at address zero:
6273
6274       bp_watchpoint
6275       bp_catchpoint
6276
6277 */
6278
6279 static int
6280 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6281 {
6282   enum bptype type = bpt->type;
6283
6284   return (type != bp_watchpoint && type != bp_catchpoint);
6285 }
6286
6287 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6288    true if LOC1 and LOC2 represent the same watchpoint location.  */
6289
6290 static int
6291 watchpoint_locations_match (struct bp_location *loc1, 
6292                             struct bp_location *loc2)
6293 {
6294   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6295   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6296
6297   /* Both of them must exist.  */
6298   gdb_assert (w1 != NULL);
6299   gdb_assert (w2 != NULL);
6300
6301   /* If the target can evaluate the condition expression in hardware,
6302      then we we need to insert both watchpoints even if they are at
6303      the same place.  Otherwise the watchpoint will only trigger when
6304      the condition of whichever watchpoint was inserted evaluates to
6305      true, not giving a chance for GDB to check the condition of the
6306      other watchpoint.  */
6307   if ((w1->cond_exp
6308        && target_can_accel_watchpoint_condition (loc1->address, 
6309                                                  loc1->length,
6310                                                  loc1->watchpoint_type,
6311                                                  w1->cond_exp))
6312       || (w2->cond_exp
6313           && target_can_accel_watchpoint_condition (loc2->address, 
6314                                                     loc2->length,
6315                                                     loc2->watchpoint_type,
6316                                                     w2->cond_exp)))
6317     return 0;
6318
6319   /* Note that this checks the owner's type, not the location's.  In
6320      case the target does not support read watchpoints, but does
6321      support access watchpoints, we'll have bp_read_watchpoint
6322      watchpoints with hw_access locations.  Those should be considered
6323      duplicates of hw_read locations.  The hw_read locations will
6324      become hw_access locations later.  */
6325   return (loc1->owner->type == loc2->owner->type
6326           && loc1->pspace->aspace == loc2->pspace->aspace
6327           && loc1->address == loc2->address
6328           && loc1->length == loc2->length);
6329 }
6330
6331 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6332    same breakpoint location.  In most targets, this can only be true
6333    if ASPACE1 matches ASPACE2.  On targets that have global
6334    breakpoints, the address space doesn't really matter.  */
6335
6336 static int
6337 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6338                           struct address_space *aspace2, CORE_ADDR addr2)
6339 {
6340   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6341            || aspace1 == aspace2)
6342           && addr1 == addr2);
6343 }
6344
6345 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6346    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6347    matches ASPACE2.  On targets that have global breakpoints, the address
6348    space doesn't really matter.  */
6349
6350 static int
6351 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6352                                 int len1, struct address_space *aspace2,
6353                                 CORE_ADDR addr2)
6354 {
6355   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6356            || aspace1 == aspace2)
6357           && addr2 >= addr1 && addr2 < addr1 + len1);
6358 }
6359
6360 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6361    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6362    matches the breakpoint's address space.  On targets that have global
6363    breakpoints, the address space doesn't really matter.  */
6364
6365 static int
6366 breakpoint_location_address_match (struct bp_location *bl,
6367                                    struct address_space *aspace,
6368                                    CORE_ADDR addr)
6369 {
6370   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6371                                     aspace, addr)
6372           || (bl->length
6373               && breakpoint_address_match_range (bl->pspace->aspace,
6374                                                  bl->address, bl->length,
6375                                                  aspace, addr)));
6376 }
6377
6378 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6379    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6380    true, otherwise returns false.  */
6381
6382 static int
6383 tracepoint_locations_match (struct bp_location *loc1,
6384                             struct bp_location *loc2)
6385 {
6386   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6387     /* Since tracepoint locations are never duplicated with others', tracepoint
6388        locations at the same address of different tracepoints are regarded as
6389        different locations.  */
6390     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6391   else
6392     return 0;
6393 }
6394
6395 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6396    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6397    represent the same location.  */
6398
6399 static int
6400 breakpoint_locations_match (struct bp_location *loc1, 
6401                             struct bp_location *loc2)
6402 {
6403   int hw_point1, hw_point2;
6404
6405   /* Both of them must not be in moribund_locations.  */
6406   gdb_assert (loc1->owner != NULL);
6407   gdb_assert (loc2->owner != NULL);
6408
6409   hw_point1 = is_hardware_watchpoint (loc1->owner);
6410   hw_point2 = is_hardware_watchpoint (loc2->owner);
6411
6412   if (hw_point1 != hw_point2)
6413     return 0;
6414   else if (hw_point1)
6415     return watchpoint_locations_match (loc1, loc2);
6416   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6417     return tracepoint_locations_match (loc1, loc2);
6418   else
6419     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6420     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6421                                      loc2->pspace->aspace, loc2->address)
6422             && loc1->length == loc2->length);
6423 }
6424
6425 static void
6426 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6427                                int bnum, int have_bnum)
6428 {
6429   /* The longest string possibly returned by hex_string_custom
6430      is 50 chars.  These must be at least that big for safety.  */
6431   char astr1[64];
6432   char astr2[64];
6433
6434   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6435   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6436   if (have_bnum)
6437     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6438              bnum, astr1, astr2);
6439   else
6440     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6441 }
6442
6443 /* Adjust a breakpoint's address to account for architectural
6444    constraints on breakpoint placement.  Return the adjusted address.
6445    Note: Very few targets require this kind of adjustment.  For most
6446    targets, this function is simply the identity function.  */
6447
6448 static CORE_ADDR
6449 adjust_breakpoint_address (struct gdbarch *gdbarch,
6450                            CORE_ADDR bpaddr, enum bptype bptype)
6451 {
6452   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6453     {
6454       /* Very few targets need any kind of breakpoint adjustment.  */
6455       return bpaddr;
6456     }
6457   else if (bptype == bp_watchpoint
6458            || bptype == bp_hardware_watchpoint
6459            || bptype == bp_read_watchpoint
6460            || bptype == bp_access_watchpoint
6461            || bptype == bp_catchpoint)
6462     {
6463       /* Watchpoints and the various bp_catch_* eventpoints should not
6464          have their addresses modified.  */
6465       return bpaddr;
6466     }
6467   else
6468     {
6469       CORE_ADDR adjusted_bpaddr;
6470
6471       /* Some targets have architectural constraints on the placement
6472          of breakpoint instructions.  Obtain the adjusted address.  */
6473       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6474
6475       /* An adjusted breakpoint address can significantly alter
6476          a user's expectations.  Print a warning if an adjustment
6477          is required.  */
6478       if (adjusted_bpaddr != bpaddr)
6479         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6480
6481       return adjusted_bpaddr;
6482     }
6483 }
6484
6485 void
6486 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6487                   struct breakpoint *owner)
6488 {
6489   memset (loc, 0, sizeof (*loc));
6490
6491   gdb_assert (ops != NULL);
6492
6493   loc->ops = ops;
6494   loc->owner = owner;
6495   loc->cond = NULL;
6496   loc->cond_bytecode = NULL;
6497   loc->shlib_disabled = 0;
6498   loc->enabled = 1;
6499
6500   switch (owner->type)
6501     {
6502     case bp_breakpoint:
6503     case bp_until:
6504     case bp_finish:
6505     case bp_longjmp:
6506     case bp_longjmp_resume:
6507     case bp_longjmp_call_dummy:
6508     case bp_exception:
6509     case bp_exception_resume:
6510     case bp_step_resume:
6511     case bp_hp_step_resume:
6512     case bp_watchpoint_scope:
6513     case bp_call_dummy:
6514     case bp_std_terminate:
6515     case bp_shlib_event:
6516     case bp_thread_event:
6517     case bp_overlay_event:
6518     case bp_jit_event:
6519     case bp_longjmp_master:
6520     case bp_std_terminate_master:
6521     case bp_exception_master:
6522     case bp_gnu_ifunc_resolver:
6523     case bp_gnu_ifunc_resolver_return:
6524     case bp_dprintf:
6525       loc->loc_type = bp_loc_software_breakpoint;
6526       mark_breakpoint_location_modified (loc);
6527       break;
6528     case bp_hardware_breakpoint:
6529       loc->loc_type = bp_loc_hardware_breakpoint;
6530       mark_breakpoint_location_modified (loc);
6531       break;
6532     case bp_hardware_watchpoint:
6533     case bp_read_watchpoint:
6534     case bp_access_watchpoint:
6535       loc->loc_type = bp_loc_hardware_watchpoint;
6536       break;
6537     case bp_watchpoint:
6538     case bp_catchpoint:
6539     case bp_tracepoint:
6540     case bp_fast_tracepoint:
6541     case bp_static_tracepoint:
6542       loc->loc_type = bp_loc_other;
6543       break;
6544     default:
6545       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6546     }
6547
6548   loc->refc = 1;
6549 }
6550
6551 /* Allocate a struct bp_location.  */
6552
6553 static struct bp_location *
6554 allocate_bp_location (struct breakpoint *bpt)
6555 {
6556   return bpt->ops->allocate_location (bpt);
6557 }
6558
6559 static void
6560 free_bp_location (struct bp_location *loc)
6561 {
6562   loc->ops->dtor (loc);
6563   xfree (loc);
6564 }
6565
6566 /* Increment reference count.  */
6567
6568 static void
6569 incref_bp_location (struct bp_location *bl)
6570 {
6571   ++bl->refc;
6572 }
6573
6574 /* Decrement reference count.  If the reference count reaches 0,
6575    destroy the bp_location.  Sets *BLP to NULL.  */
6576
6577 static void
6578 decref_bp_location (struct bp_location **blp)
6579 {
6580   gdb_assert ((*blp)->refc > 0);
6581
6582   if (--(*blp)->refc == 0)
6583     free_bp_location (*blp);
6584   *blp = NULL;
6585 }
6586
6587 /* Add breakpoint B at the end of the global breakpoint chain.  */
6588
6589 static void
6590 add_to_breakpoint_chain (struct breakpoint *b)
6591 {
6592   struct breakpoint *b1;
6593
6594   /* Add this breakpoint to the end of the chain so that a list of
6595      breakpoints will come out in order of increasing numbers.  */
6596
6597   b1 = breakpoint_chain;
6598   if (b1 == 0)
6599     breakpoint_chain = b;
6600   else
6601     {
6602       while (b1->next)
6603         b1 = b1->next;
6604       b1->next = b;
6605     }
6606 }
6607
6608 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6609
6610 static void
6611 init_raw_breakpoint_without_location (struct breakpoint *b,
6612                                       struct gdbarch *gdbarch,
6613                                       enum bptype bptype,
6614                                       const struct breakpoint_ops *ops)
6615 {
6616   memset (b, 0, sizeof (*b));
6617
6618   gdb_assert (ops != NULL);
6619
6620   b->ops = ops;
6621   b->type = bptype;
6622   b->gdbarch = gdbarch;
6623   b->language = current_language->la_language;
6624   b->input_radix = input_radix;
6625   b->thread = -1;
6626   b->enable_state = bp_enabled;
6627   b->next = 0;
6628   b->silent = 0;
6629   b->ignore_count = 0;
6630   b->commands = NULL;
6631   b->frame_id = null_frame_id;
6632   b->condition_not_parsed = 0;
6633   b->py_bp_object = NULL;
6634   b->related_breakpoint = b;
6635 }
6636
6637 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6638    that has type BPTYPE and has no locations as yet.  */
6639
6640 static struct breakpoint *
6641 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6642                                      enum bptype bptype,
6643                                      const struct breakpoint_ops *ops)
6644 {
6645   struct breakpoint *b = XNEW (struct breakpoint);
6646
6647   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6648   add_to_breakpoint_chain (b);
6649   return b;
6650 }
6651
6652 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6653    resolutions should be made as the user specified the location explicitly
6654    enough.  */
6655
6656 static void
6657 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
6658 {
6659   gdb_assert (loc->owner != NULL);
6660
6661   if (loc->owner->type == bp_breakpoint
6662       || loc->owner->type == bp_hardware_breakpoint
6663       || is_tracepoint (loc->owner))
6664     {
6665       int is_gnu_ifunc;
6666       const char *function_name;
6667       CORE_ADDR func_addr;
6668
6669       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
6670                                           &func_addr, NULL, &is_gnu_ifunc);
6671
6672       if (is_gnu_ifunc && !explicit_loc)
6673         {
6674           struct breakpoint *b = loc->owner;
6675
6676           gdb_assert (loc->pspace == current_program_space);
6677           if (gnu_ifunc_resolve_name (function_name,
6678                                       &loc->requested_address))
6679             {
6680               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
6681               loc->address = adjust_breakpoint_address (loc->gdbarch,
6682                                                         loc->requested_address,
6683                                                         b->type);
6684             }
6685           else if (b->type == bp_breakpoint && b->loc == loc
6686                    && loc->next == NULL && b->related_breakpoint == b)
6687             {
6688               /* Create only the whole new breakpoint of this type but do not
6689                  mess more complicated breakpoints with multiple locations.  */
6690               b->type = bp_gnu_ifunc_resolver;
6691               /* Remember the resolver's address for use by the return
6692                  breakpoint.  */
6693               loc->related_address = func_addr;
6694             }
6695         }
6696
6697       if (function_name)
6698         loc->function_name = xstrdup (function_name);
6699     }
6700 }
6701
6702 /* Attempt to determine architecture of location identified by SAL.  */
6703 struct gdbarch *
6704 get_sal_arch (struct symtab_and_line sal)
6705 {
6706   if (sal.section)
6707     return get_objfile_arch (sal.section->objfile);
6708   if (sal.symtab)
6709     return get_objfile_arch (sal.symtab->objfile);
6710
6711   return NULL;
6712 }
6713
6714 /* Low level routine for partially initializing a breakpoint of type
6715    BPTYPE.  The newly created breakpoint's address, section, source
6716    file name, and line number are provided by SAL.
6717
6718    It is expected that the caller will complete the initialization of
6719    the newly created breakpoint struct as well as output any status
6720    information regarding the creation of a new breakpoint.  */
6721
6722 static void
6723 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
6724                      struct symtab_and_line sal, enum bptype bptype,
6725                      const struct breakpoint_ops *ops)
6726 {
6727   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6728
6729   add_location_to_breakpoint (b, &sal);
6730
6731   if (bptype != bp_catchpoint)
6732     gdb_assert (sal.pspace != NULL);
6733
6734   /* Store the program space that was used to set the breakpoint,
6735      except for ordinary breakpoints, which are independent of the
6736      program space.  */
6737   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
6738     b->pspace = sal.pspace;
6739
6740   breakpoints_changed ();
6741 }
6742
6743 /* set_raw_breakpoint is a low level routine for allocating and
6744    partially initializing a breakpoint of type BPTYPE.  The newly
6745    created breakpoint's address, section, source file name, and line
6746    number are provided by SAL.  The newly created and partially
6747    initialized breakpoint is added to the breakpoint chain and
6748    is also returned as the value of this function.
6749
6750    It is expected that the caller will complete the initialization of
6751    the newly created breakpoint struct as well as output any status
6752    information regarding the creation of a new breakpoint.  In
6753    particular, set_raw_breakpoint does NOT set the breakpoint
6754    number!  Care should be taken to not allow an error to occur
6755    prior to completing the initialization of the breakpoint.  If this
6756    should happen, a bogus breakpoint will be left on the chain.  */
6757
6758 struct breakpoint *
6759 set_raw_breakpoint (struct gdbarch *gdbarch,
6760                     struct symtab_and_line sal, enum bptype bptype,
6761                     const struct breakpoint_ops *ops)
6762 {
6763   struct breakpoint *b = XNEW (struct breakpoint);
6764
6765   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
6766   add_to_breakpoint_chain (b);
6767   return b;
6768 }
6769
6770
6771 /* Note that the breakpoint object B describes a permanent breakpoint
6772    instruction, hard-wired into the inferior's code.  */
6773 void
6774 make_breakpoint_permanent (struct breakpoint *b)
6775 {
6776   struct bp_location *bl;
6777
6778   b->enable_state = bp_permanent;
6779
6780   /* By definition, permanent breakpoints are already present in the
6781      code.  Mark all locations as inserted.  For now,
6782      make_breakpoint_permanent is called in just one place, so it's
6783      hard to say if it's reasonable to have permanent breakpoint with
6784      multiple locations or not, but it's easy to implement.  */
6785   for (bl = b->loc; bl; bl = bl->next)
6786     bl->inserted = 1;
6787 }
6788
6789 /* Call this routine when stepping and nexting to enable a breakpoint
6790    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
6791    initiated the operation.  */
6792
6793 void
6794 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
6795 {
6796   struct breakpoint *b, *b_tmp;
6797   int thread = tp->num;
6798
6799   /* To avoid having to rescan all objfile symbols at every step,
6800      we maintain a list of continually-inserted but always disabled
6801      longjmp "master" breakpoints.  Here, we simply create momentary
6802      clones of those and enable them for the requested thread.  */
6803   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6804     if (b->pspace == current_program_space
6805         && (b->type == bp_longjmp_master
6806             || b->type == bp_exception_master))
6807       {
6808         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
6809         struct breakpoint *clone;
6810
6811         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
6812            after their removal.  */
6813         clone = momentary_breakpoint_from_master (b, type,
6814                                                   &longjmp_breakpoint_ops);
6815         clone->thread = thread;
6816       }
6817
6818   tp->initiating_frame = frame;
6819 }
6820
6821 /* Delete all longjmp breakpoints from THREAD.  */
6822 void
6823 delete_longjmp_breakpoint (int thread)
6824 {
6825   struct breakpoint *b, *b_tmp;
6826
6827   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6828     if (b->type == bp_longjmp || b->type == bp_exception)
6829       {
6830         if (b->thread == thread)
6831           delete_breakpoint (b);
6832       }
6833 }
6834
6835 void
6836 delete_longjmp_breakpoint_at_next_stop (int thread)
6837 {
6838   struct breakpoint *b, *b_tmp;
6839
6840   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6841     if (b->type == bp_longjmp || b->type == bp_exception)
6842       {
6843         if (b->thread == thread)
6844           b->disposition = disp_del_at_next_stop;
6845       }
6846 }
6847
6848 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
6849    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
6850    pointer to any of them.  Return NULL if this system cannot place longjmp
6851    breakpoints.  */
6852
6853 struct breakpoint *
6854 set_longjmp_breakpoint_for_call_dummy (void)
6855 {
6856   struct breakpoint *b, *retval = NULL;
6857
6858   ALL_BREAKPOINTS (b)
6859     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
6860       {
6861         struct breakpoint *new_b;
6862
6863         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
6864                                                   &momentary_breakpoint_ops);
6865         new_b->thread = pid_to_thread_id (inferior_ptid);
6866
6867         /* Link NEW_B into the chain of RETVAL breakpoints.  */
6868
6869         gdb_assert (new_b->related_breakpoint == new_b);
6870         if (retval == NULL)
6871           retval = new_b;
6872         new_b->related_breakpoint = retval;
6873         while (retval->related_breakpoint != new_b->related_breakpoint)
6874           retval = retval->related_breakpoint;
6875         retval->related_breakpoint = new_b;
6876       }
6877
6878   return retval;
6879 }
6880
6881 /* Verify all existing dummy frames and their associated breakpoints for
6882    THREAD.  Remove those which can no longer be found in the current frame
6883    stack.
6884
6885    You should call this function only at places where it is safe to currently
6886    unwind the whole stack.  Failed stack unwind would discard live dummy
6887    frames.  */
6888
6889 void
6890 check_longjmp_breakpoint_for_call_dummy (int thread)
6891 {
6892   struct breakpoint *b, *b_tmp;
6893
6894   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6895     if (b->type == bp_longjmp_call_dummy && b->thread == thread)
6896       {
6897         struct breakpoint *dummy_b = b->related_breakpoint;
6898
6899         while (dummy_b != b && dummy_b->type != bp_call_dummy)
6900           dummy_b = dummy_b->related_breakpoint;
6901         if (dummy_b->type != bp_call_dummy
6902             || frame_find_by_id (dummy_b->frame_id) != NULL)
6903           continue;
6904         
6905         dummy_frame_discard (dummy_b->frame_id);
6906
6907         while (b->related_breakpoint != b)
6908           {
6909             if (b_tmp == b->related_breakpoint)
6910               b_tmp = b->related_breakpoint->next;
6911             delete_breakpoint (b->related_breakpoint);
6912           }
6913         delete_breakpoint (b);
6914       }
6915 }
6916
6917 void
6918 enable_overlay_breakpoints (void)
6919 {
6920   struct breakpoint *b;
6921
6922   ALL_BREAKPOINTS (b)
6923     if (b->type == bp_overlay_event)
6924     {
6925       b->enable_state = bp_enabled;
6926       update_global_location_list (1);
6927       overlay_events_enabled = 1;
6928     }
6929 }
6930
6931 void
6932 disable_overlay_breakpoints (void)
6933 {
6934   struct breakpoint *b;
6935
6936   ALL_BREAKPOINTS (b)
6937     if (b->type == bp_overlay_event)
6938     {
6939       b->enable_state = bp_disabled;
6940       update_global_location_list (0);
6941       overlay_events_enabled = 0;
6942     }
6943 }
6944
6945 /* Set an active std::terminate breakpoint for each std::terminate
6946    master breakpoint.  */
6947 void
6948 set_std_terminate_breakpoint (void)
6949 {
6950   struct breakpoint *b, *b_tmp;
6951
6952   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6953     if (b->pspace == current_program_space
6954         && b->type == bp_std_terminate_master)
6955       {
6956         momentary_breakpoint_from_master (b, bp_std_terminate,
6957                                           &momentary_breakpoint_ops);
6958       }
6959 }
6960
6961 /* Delete all the std::terminate breakpoints.  */
6962 void
6963 delete_std_terminate_breakpoint (void)
6964 {
6965   struct breakpoint *b, *b_tmp;
6966
6967   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6968     if (b->type == bp_std_terminate)
6969       delete_breakpoint (b);
6970 }
6971
6972 struct breakpoint *
6973 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6974 {
6975   struct breakpoint *b;
6976
6977   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6978                                   &internal_breakpoint_ops);
6979
6980   b->enable_state = bp_enabled;
6981   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6982   b->addr_string
6983     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6984
6985   update_global_location_list_nothrow (1);
6986
6987   return b;
6988 }
6989
6990 void
6991 remove_thread_event_breakpoints (void)
6992 {
6993   struct breakpoint *b, *b_tmp;
6994
6995   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6996     if (b->type == bp_thread_event
6997         && b->loc->pspace == current_program_space)
6998       delete_breakpoint (b);
6999 }
7000
7001 struct lang_and_radix
7002   {
7003     enum language lang;
7004     int radix;
7005   };
7006
7007 /* Create a breakpoint for JIT code registration and unregistration.  */
7008
7009 struct breakpoint *
7010 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7011 {
7012   struct breakpoint *b;
7013
7014   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7015                                   &internal_breakpoint_ops);
7016   update_global_location_list_nothrow (1);
7017   return b;
7018 }
7019
7020 /* Remove JIT code registration and unregistration breakpoint(s).  */
7021
7022 void
7023 remove_jit_event_breakpoints (void)
7024 {
7025   struct breakpoint *b, *b_tmp;
7026
7027   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7028     if (b->type == bp_jit_event
7029         && b->loc->pspace == current_program_space)
7030       delete_breakpoint (b);
7031 }
7032
7033 void
7034 remove_solib_event_breakpoints (void)
7035 {
7036   struct breakpoint *b, *b_tmp;
7037
7038   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7039     if (b->type == bp_shlib_event
7040         && b->loc->pspace == current_program_space)
7041       delete_breakpoint (b);
7042 }
7043
7044 struct breakpoint *
7045 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7046 {
7047   struct breakpoint *b;
7048
7049   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7050                                   &internal_breakpoint_ops);
7051   update_global_location_list_nothrow (1);
7052   return b;
7053 }
7054
7055 /* Disable any breakpoints that are on code in shared libraries.  Only
7056    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7057
7058 void
7059 disable_breakpoints_in_shlibs (void)
7060 {
7061   struct bp_location *loc, **locp_tmp;
7062
7063   ALL_BP_LOCATIONS (loc, locp_tmp)
7064   {
7065     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7066     struct breakpoint *b = loc->owner;
7067
7068     /* We apply the check to all breakpoints, including disabled for
7069        those with loc->duplicate set.  This is so that when breakpoint
7070        becomes enabled, or the duplicate is removed, gdb will try to
7071        insert all breakpoints.  If we don't set shlib_disabled here,
7072        we'll try to insert those breakpoints and fail.  */
7073     if (((b->type == bp_breakpoint)
7074          || (b->type == bp_jit_event)
7075          || (b->type == bp_hardware_breakpoint)
7076          || (is_tracepoint (b)))
7077         && loc->pspace == current_program_space
7078         && !loc->shlib_disabled
7079 #ifdef PC_SOLIB
7080         && PC_SOLIB (loc->address)
7081 #else
7082         && solib_name_from_address (loc->pspace, loc->address)
7083 #endif
7084         )
7085       {
7086         loc->shlib_disabled = 1;
7087       }
7088   }
7089 }
7090
7091 /* Disable any breakpoints and tracepoints that are in an unloaded shared
7092    library.  Only apply to enabled breakpoints, disabled ones can just stay
7093    disabled.  */
7094
7095 static void
7096 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7097 {
7098   struct bp_location *loc, **locp_tmp;
7099   int disabled_shlib_breaks = 0;
7100
7101   /* SunOS a.out shared libraries are always mapped, so do not
7102      disable breakpoints; they will only be reported as unloaded
7103      through clear_solib when GDB discards its shared library
7104      list.  See clear_solib for more information.  */
7105   if (exec_bfd != NULL
7106       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7107     return;
7108
7109   ALL_BP_LOCATIONS (loc, locp_tmp)
7110   {
7111     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7112     struct breakpoint *b = loc->owner;
7113
7114     if (solib->pspace == loc->pspace
7115         && !loc->shlib_disabled
7116         && (((b->type == bp_breakpoint
7117               || b->type == bp_jit_event
7118               || b->type == bp_hardware_breakpoint)
7119              && (loc->loc_type == bp_loc_hardware_breakpoint
7120                  || loc->loc_type == bp_loc_software_breakpoint))
7121             || is_tracepoint (b))
7122         && solib_contains_address_p (solib, loc->address))
7123       {
7124         loc->shlib_disabled = 1;
7125         /* At this point, we cannot rely on remove_breakpoint
7126            succeeding so we must mark the breakpoint as not inserted
7127            to prevent future errors occurring in remove_breakpoints.  */
7128         loc->inserted = 0;
7129
7130         /* This may cause duplicate notifications for the same breakpoint.  */
7131         observer_notify_breakpoint_modified (b);
7132
7133         if (!disabled_shlib_breaks)
7134           {
7135             target_terminal_ours_for_output ();
7136             warning (_("Temporarily disabling breakpoints "
7137                        "for unloaded shared library \"%s\""),
7138                      solib->so_name);
7139           }
7140         disabled_shlib_breaks = 1;
7141       }
7142   }
7143 }
7144
7145 /* FORK & VFORK catchpoints.  */
7146
7147 /* An instance of this type is used to represent a fork or vfork
7148    catchpoint.  It includes a "struct breakpoint" as a kind of base
7149    class; users downcast to "struct breakpoint *" when needed.  A
7150    breakpoint is really of this type iff its ops pointer points to
7151    CATCH_FORK_BREAKPOINT_OPS.  */
7152
7153 struct fork_catchpoint
7154 {
7155   /* The base class.  */
7156   struct breakpoint base;
7157
7158   /* Process id of a child process whose forking triggered this
7159      catchpoint.  This field is only valid immediately after this
7160      catchpoint has triggered.  */
7161   ptid_t forked_inferior_pid;
7162 };
7163
7164 /* Implement the "insert" breakpoint_ops method for fork
7165    catchpoints.  */
7166
7167 static int
7168 insert_catch_fork (struct bp_location *bl)
7169 {
7170   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
7171 }
7172
7173 /* Implement the "remove" breakpoint_ops method for fork
7174    catchpoints.  */
7175
7176 static int
7177 remove_catch_fork (struct bp_location *bl)
7178 {
7179   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
7180 }
7181
7182 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7183    catchpoints.  */
7184
7185 static int
7186 breakpoint_hit_catch_fork (const struct bp_location *bl,
7187                            struct address_space *aspace, CORE_ADDR bp_addr,
7188                            const struct target_waitstatus *ws)
7189 {
7190   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7191
7192   if (ws->kind != TARGET_WAITKIND_FORKED)
7193     return 0;
7194
7195   c->forked_inferior_pid = ws->value.related_pid;
7196   return 1;
7197 }
7198
7199 /* Implement the "print_it" breakpoint_ops method for fork
7200    catchpoints.  */
7201
7202 static enum print_stop_action
7203 print_it_catch_fork (bpstat bs)
7204 {
7205   struct ui_out *uiout = current_uiout;
7206   struct breakpoint *b = bs->breakpoint_at;
7207   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7208
7209   annotate_catchpoint (b->number);
7210   if (b->disposition == disp_del)
7211     ui_out_text (uiout, "\nTemporary catchpoint ");
7212   else
7213     ui_out_text (uiout, "\nCatchpoint ");
7214   if (ui_out_is_mi_like_p (uiout))
7215     {
7216       ui_out_field_string (uiout, "reason",
7217                            async_reason_lookup (EXEC_ASYNC_FORK));
7218       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7219     }
7220   ui_out_field_int (uiout, "bkptno", b->number);
7221   ui_out_text (uiout, " (forked process ");
7222   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7223   ui_out_text (uiout, "), ");
7224   return PRINT_SRC_AND_LOC;
7225 }
7226
7227 /* Implement the "print_one" breakpoint_ops method for fork
7228    catchpoints.  */
7229
7230 static void
7231 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7232 {
7233   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7234   struct value_print_options opts;
7235   struct ui_out *uiout = current_uiout;
7236
7237   get_user_print_options (&opts);
7238
7239   /* Field 4, the address, is omitted (which makes the columns not
7240      line up too nicely with the headers, but the effect is relatively
7241      readable).  */
7242   if (opts.addressprint)
7243     ui_out_field_skip (uiout, "addr");
7244   annotate_field (5);
7245   ui_out_text (uiout, "fork");
7246   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7247     {
7248       ui_out_text (uiout, ", process ");
7249       ui_out_field_int (uiout, "what",
7250                         ptid_get_pid (c->forked_inferior_pid));
7251       ui_out_spaces (uiout, 1);
7252     }
7253 }
7254
7255 /* Implement the "print_mention" breakpoint_ops method for fork
7256    catchpoints.  */
7257
7258 static void
7259 print_mention_catch_fork (struct breakpoint *b)
7260 {
7261   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7262 }
7263
7264 /* Implement the "print_recreate" breakpoint_ops method for fork
7265    catchpoints.  */
7266
7267 static void
7268 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7269 {
7270   fprintf_unfiltered (fp, "catch fork");
7271   print_recreate_thread (b, fp);
7272 }
7273
7274 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7275
7276 static struct breakpoint_ops catch_fork_breakpoint_ops;
7277
7278 /* Implement the "insert" breakpoint_ops method for vfork
7279    catchpoints.  */
7280
7281 static int
7282 insert_catch_vfork (struct bp_location *bl)
7283 {
7284   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7285 }
7286
7287 /* Implement the "remove" breakpoint_ops method for vfork
7288    catchpoints.  */
7289
7290 static int
7291 remove_catch_vfork (struct bp_location *bl)
7292 {
7293   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7294 }
7295
7296 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7297    catchpoints.  */
7298
7299 static int
7300 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7301                             struct address_space *aspace, CORE_ADDR bp_addr,
7302                             const struct target_waitstatus *ws)
7303 {
7304   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7305
7306   if (ws->kind != TARGET_WAITKIND_VFORKED)
7307     return 0;
7308
7309   c->forked_inferior_pid = ws->value.related_pid;
7310   return 1;
7311 }
7312
7313 /* Implement the "print_it" breakpoint_ops method for vfork
7314    catchpoints.  */
7315
7316 static enum print_stop_action
7317 print_it_catch_vfork (bpstat bs)
7318 {
7319   struct ui_out *uiout = current_uiout;
7320   struct breakpoint *b = bs->breakpoint_at;
7321   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7322
7323   annotate_catchpoint (b->number);
7324   if (b->disposition == disp_del)
7325     ui_out_text (uiout, "\nTemporary catchpoint ");
7326   else
7327     ui_out_text (uiout, "\nCatchpoint ");
7328   if (ui_out_is_mi_like_p (uiout))
7329     {
7330       ui_out_field_string (uiout, "reason",
7331                            async_reason_lookup (EXEC_ASYNC_VFORK));
7332       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7333     }
7334   ui_out_field_int (uiout, "bkptno", b->number);
7335   ui_out_text (uiout, " (vforked process ");
7336   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7337   ui_out_text (uiout, "), ");
7338   return PRINT_SRC_AND_LOC;
7339 }
7340
7341 /* Implement the "print_one" breakpoint_ops method for vfork
7342    catchpoints.  */
7343
7344 static void
7345 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7346 {
7347   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7348   struct value_print_options opts;
7349   struct ui_out *uiout = current_uiout;
7350
7351   get_user_print_options (&opts);
7352   /* Field 4, the address, is omitted (which makes the columns not
7353      line up too nicely with the headers, but the effect is relatively
7354      readable).  */
7355   if (opts.addressprint)
7356     ui_out_field_skip (uiout, "addr");
7357   annotate_field (5);
7358   ui_out_text (uiout, "vfork");
7359   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7360     {
7361       ui_out_text (uiout, ", process ");
7362       ui_out_field_int (uiout, "what",
7363                         ptid_get_pid (c->forked_inferior_pid));
7364       ui_out_spaces (uiout, 1);
7365     }
7366 }
7367
7368 /* Implement the "print_mention" breakpoint_ops method for vfork
7369    catchpoints.  */
7370
7371 static void
7372 print_mention_catch_vfork (struct breakpoint *b)
7373 {
7374   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7375 }
7376
7377 /* Implement the "print_recreate" breakpoint_ops method for vfork
7378    catchpoints.  */
7379
7380 static void
7381 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7382 {
7383   fprintf_unfiltered (fp, "catch vfork");
7384   print_recreate_thread (b, fp);
7385 }
7386
7387 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7388
7389 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7390
7391 /* An instance of this type is used to represent an solib catchpoint.
7392    It includes a "struct breakpoint" as a kind of base class; users
7393    downcast to "struct breakpoint *" when needed.  A breakpoint is
7394    really of this type iff its ops pointer points to
7395    CATCH_SOLIB_BREAKPOINT_OPS.  */
7396
7397 struct solib_catchpoint
7398 {
7399   /* The base class.  */
7400   struct breakpoint base;
7401
7402   /* True for "catch load", false for "catch unload".  */
7403   unsigned char is_load;
7404
7405   /* Regular expression to match, if any.  COMPILED is only valid when
7406      REGEX is non-NULL.  */
7407   char *regex;
7408   regex_t compiled;
7409 };
7410
7411 static void
7412 dtor_catch_solib (struct breakpoint *b)
7413 {
7414   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7415
7416   if (self->regex)
7417     regfree (&self->compiled);
7418   xfree (self->regex);
7419
7420   base_breakpoint_ops.dtor (b);
7421 }
7422
7423 static int
7424 insert_catch_solib (struct bp_location *ignore)
7425 {
7426   return 0;
7427 }
7428
7429 static int
7430 remove_catch_solib (struct bp_location *ignore)
7431 {
7432   return 0;
7433 }
7434
7435 static int
7436 breakpoint_hit_catch_solib (const struct bp_location *bl,
7437                             struct address_space *aspace,
7438                             CORE_ADDR bp_addr,
7439                             const struct target_waitstatus *ws)
7440 {
7441   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7442   struct breakpoint *other;
7443
7444   if (ws->kind == TARGET_WAITKIND_LOADED)
7445     return 1;
7446
7447   ALL_BREAKPOINTS (other)
7448   {
7449     struct bp_location *other_bl;
7450
7451     if (other == bl->owner)
7452       continue;
7453
7454     if (other->type != bp_shlib_event)
7455       continue;
7456
7457     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7458       continue;
7459
7460     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7461       {
7462         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7463           return 1;
7464       }
7465   }
7466
7467   return 0;
7468 }
7469
7470 static void
7471 check_status_catch_solib (struct bpstats *bs)
7472 {
7473   struct solib_catchpoint *self
7474     = (struct solib_catchpoint *) bs->breakpoint_at;
7475   int ix;
7476
7477   if (self->is_load)
7478     {
7479       struct so_list *iter;
7480
7481       for (ix = 0;
7482            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7483                         ix, iter);
7484            ++ix)
7485         {
7486           if (!self->regex
7487               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7488             return;
7489         }
7490     }
7491   else
7492     {
7493       char *iter;
7494
7495       for (ix = 0;
7496            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7497                         ix, iter);
7498            ++ix)
7499         {
7500           if (!self->regex
7501               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7502             return;
7503         }
7504     }
7505
7506   bs->stop = 0;
7507   bs->print_it = print_it_noop;
7508 }
7509
7510 static enum print_stop_action
7511 print_it_catch_solib (bpstat bs)
7512 {
7513   struct breakpoint *b = bs->breakpoint_at;
7514   struct ui_out *uiout = current_uiout;
7515
7516   annotate_catchpoint (b->number);
7517   if (b->disposition == disp_del)
7518     ui_out_text (uiout, "\nTemporary catchpoint ");
7519   else
7520     ui_out_text (uiout, "\nCatchpoint ");
7521   ui_out_field_int (uiout, "bkptno", b->number);
7522   ui_out_text (uiout, "\n");
7523   if (ui_out_is_mi_like_p (uiout))
7524     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7525   print_solib_event (1);
7526   return PRINT_SRC_AND_LOC;
7527 }
7528
7529 static void
7530 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7531 {
7532   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7533   struct value_print_options opts;
7534   struct ui_out *uiout = current_uiout;
7535   char *msg;
7536
7537   get_user_print_options (&opts);
7538   /* Field 4, the address, is omitted (which makes the columns not
7539      line up too nicely with the headers, but the effect is relatively
7540      readable).  */
7541   if (opts.addressprint)
7542     {
7543       annotate_field (4);
7544       ui_out_field_skip (uiout, "addr");
7545     }
7546
7547   annotate_field (5);
7548   if (self->is_load)
7549     {
7550       if (self->regex)
7551         msg = xstrprintf (_("load of library matching %s"), self->regex);
7552       else
7553         msg = xstrdup (_("load of library"));
7554     }
7555   else
7556     {
7557       if (self->regex)
7558         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7559       else
7560         msg = xstrdup (_("unload of library"));
7561     }
7562   ui_out_field_string (uiout, "what", msg);
7563   xfree (msg);
7564 }
7565
7566 static void
7567 print_mention_catch_solib (struct breakpoint *b)
7568 {
7569   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7570
7571   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7572                    self->is_load ? "load" : "unload");
7573 }
7574
7575 static void
7576 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7577 {
7578   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7579
7580   fprintf_unfiltered (fp, "%s %s",
7581                       b->disposition == disp_del ? "tcatch" : "catch",
7582                       self->is_load ? "load" : "unload");
7583   if (self->regex)
7584     fprintf_unfiltered (fp, " %s", self->regex);
7585   fprintf_unfiltered (fp, "\n");
7586 }
7587
7588 static struct breakpoint_ops catch_solib_breakpoint_ops;
7589
7590 /* A helper function that does all the work for "catch load" and
7591    "catch unload".  */
7592
7593 static void
7594 catch_load_or_unload (char *arg, int from_tty, int is_load,
7595                       struct cmd_list_element *command)
7596 {
7597   struct solib_catchpoint *c;
7598   struct gdbarch *gdbarch = get_current_arch ();
7599   int tempflag;
7600   struct cleanup *cleanup;
7601
7602   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7603
7604   if (!arg)
7605     arg = "";
7606   arg = skip_spaces (arg);
7607
7608   c = XCNEW (struct solib_catchpoint);
7609   cleanup = make_cleanup (xfree, c);
7610
7611   if (*arg != '\0')
7612     {
7613       int errcode;
7614
7615       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7616       if (errcode != 0)
7617         {
7618           char *err = get_regcomp_error (errcode, &c->compiled);
7619
7620           make_cleanup (xfree, err);
7621           error (_("Invalid regexp (%s): %s"), err, arg);
7622         }
7623       c->regex = xstrdup (arg);
7624     }
7625
7626   c->is_load = is_load;
7627   init_catchpoint (&c->base, gdbarch, tempflag, NULL,
7628                    &catch_solib_breakpoint_ops);
7629
7630   discard_cleanups (cleanup);
7631   install_breakpoint (0, &c->base, 1);
7632 }
7633
7634 static void
7635 catch_load_command_1 (char *arg, int from_tty,
7636                       struct cmd_list_element *command)
7637 {
7638   catch_load_or_unload (arg, from_tty, 1, command);
7639 }
7640
7641 static void
7642 catch_unload_command_1 (char *arg, int from_tty,
7643                         struct cmd_list_element *command)
7644 {
7645   catch_load_or_unload (arg, from_tty, 0, command);
7646 }
7647
7648 DEF_VEC_I(int);
7649
7650 /* An instance of this type is used to represent a syscall catchpoint.
7651    It includes a "struct breakpoint" as a kind of base class; users
7652    downcast to "struct breakpoint *" when needed.  A breakpoint is
7653    really of this type iff its ops pointer points to
7654    CATCH_SYSCALL_BREAKPOINT_OPS.  */
7655
7656 struct syscall_catchpoint
7657 {
7658   /* The base class.  */
7659   struct breakpoint base;
7660
7661   /* Syscall numbers used for the 'catch syscall' feature.  If no
7662      syscall has been specified for filtering, its value is NULL.
7663      Otherwise, it holds a list of all syscalls to be caught.  The
7664      list elements are allocated with xmalloc.  */
7665   VEC(int) *syscalls_to_be_caught;
7666 };
7667
7668 /* Implement the "dtor" breakpoint_ops method for syscall
7669    catchpoints.  */
7670
7671 static void
7672 dtor_catch_syscall (struct breakpoint *b)
7673 {
7674   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7675
7676   VEC_free (int, c->syscalls_to_be_caught);
7677
7678   base_breakpoint_ops.dtor (b);
7679 }
7680
7681 static const struct inferior_data *catch_syscall_inferior_data = NULL;
7682
7683 struct catch_syscall_inferior_data
7684 {
7685   /* We keep a count of the number of times the user has requested a
7686      particular syscall to be tracked, and pass this information to the
7687      target.  This lets capable targets implement filtering directly.  */
7688
7689   /* Number of times that "any" syscall is requested.  */
7690   int any_syscall_count;
7691
7692   /* Count of each system call.  */
7693   VEC(int) *syscalls_counts;
7694
7695   /* This counts all syscall catch requests, so we can readily determine
7696      if any catching is necessary.  */
7697   int total_syscalls_count;
7698 };
7699
7700 static struct catch_syscall_inferior_data*
7701 get_catch_syscall_inferior_data (struct inferior *inf)
7702 {
7703   struct catch_syscall_inferior_data *inf_data;
7704
7705   inf_data = inferior_data (inf, catch_syscall_inferior_data);
7706   if (inf_data == NULL)
7707     {
7708       inf_data = XZALLOC (struct catch_syscall_inferior_data);
7709       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
7710     }
7711
7712   return inf_data;
7713 }
7714
7715 static void
7716 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
7717 {
7718   xfree (arg);
7719 }
7720
7721
7722 /* Implement the "insert" breakpoint_ops method for syscall
7723    catchpoints.  */
7724
7725 static int
7726 insert_catch_syscall (struct bp_location *bl)
7727 {
7728   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7729   struct inferior *inf = current_inferior ();
7730   struct catch_syscall_inferior_data *inf_data
7731     = get_catch_syscall_inferior_data (inf);
7732
7733   ++inf_data->total_syscalls_count;
7734   if (!c->syscalls_to_be_caught)
7735     ++inf_data->any_syscall_count;
7736   else
7737     {
7738       int i, iter;
7739
7740       for (i = 0;
7741            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7742            i++)
7743         {
7744           int elem;
7745
7746           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7747             {
7748               int old_size = VEC_length (int, inf_data->syscalls_counts);
7749               uintptr_t vec_addr_offset
7750                 = old_size * ((uintptr_t) sizeof (int));
7751               uintptr_t vec_addr;
7752               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
7753               vec_addr = ((uintptr_t) VEC_address (int,
7754                                                   inf_data->syscalls_counts)
7755                           + vec_addr_offset);
7756               memset ((void *) vec_addr, 0,
7757                       (iter + 1 - old_size) * sizeof (int));
7758             }
7759           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7760           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
7761         }
7762     }
7763
7764   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7765                                         inf_data->total_syscalls_count != 0,
7766                                         inf_data->any_syscall_count,
7767                                         VEC_length (int,
7768                                                     inf_data->syscalls_counts),
7769                                         VEC_address (int,
7770                                                      inf_data->syscalls_counts));
7771 }
7772
7773 /* Implement the "remove" breakpoint_ops method for syscall
7774    catchpoints.  */
7775
7776 static int
7777 remove_catch_syscall (struct bp_location *bl)
7778 {
7779   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7780   struct inferior *inf = current_inferior ();
7781   struct catch_syscall_inferior_data *inf_data
7782     = get_catch_syscall_inferior_data (inf);
7783
7784   --inf_data->total_syscalls_count;
7785   if (!c->syscalls_to_be_caught)
7786     --inf_data->any_syscall_count;
7787   else
7788     {
7789       int i, iter;
7790
7791       for (i = 0;
7792            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7793            i++)
7794         {
7795           int elem;
7796           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7797             /* Shouldn't happen.  */
7798             continue;
7799           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7800           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
7801         }
7802     }
7803
7804   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7805                                         inf_data->total_syscalls_count != 0,
7806                                         inf_data->any_syscall_count,
7807                                         VEC_length (int,
7808                                                     inf_data->syscalls_counts),
7809                                         VEC_address (int,
7810                                                      inf_data->syscalls_counts));
7811 }
7812
7813 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
7814    catchpoints.  */
7815
7816 static int
7817 breakpoint_hit_catch_syscall (const struct bp_location *bl,
7818                               struct address_space *aspace, CORE_ADDR bp_addr,
7819                               const struct target_waitstatus *ws)
7820 {
7821   /* We must check if we are catching specific syscalls in this
7822      breakpoint.  If we are, then we must guarantee that the called
7823      syscall is the same syscall we are catching.  */
7824   int syscall_number = 0;
7825   const struct syscall_catchpoint *c
7826     = (const struct syscall_catchpoint *) bl->owner;
7827
7828   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
7829       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
7830     return 0;
7831
7832   syscall_number = ws->value.syscall_number;
7833
7834   /* Now, checking if the syscall is the same.  */
7835   if (c->syscalls_to_be_caught)
7836     {
7837       int i, iter;
7838
7839       for (i = 0;
7840            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7841            i++)
7842         if (syscall_number == iter)
7843           break;
7844       /* Not the same.  */
7845       if (!iter)
7846         return 0;
7847     }
7848
7849   return 1;
7850 }
7851
7852 /* Implement the "print_it" breakpoint_ops method for syscall
7853    catchpoints.  */
7854
7855 static enum print_stop_action
7856 print_it_catch_syscall (bpstat bs)
7857 {
7858   struct ui_out *uiout = current_uiout;
7859   struct breakpoint *b = bs->breakpoint_at;
7860   /* These are needed because we want to know in which state a
7861      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
7862      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
7863      must print "called syscall" or "returned from syscall".  */
7864   ptid_t ptid;
7865   struct target_waitstatus last;
7866   struct syscall s;
7867
7868   get_last_target_status (&ptid, &last);
7869
7870   get_syscall_by_number (last.value.syscall_number, &s);
7871
7872   annotate_catchpoint (b->number);
7873
7874   if (b->disposition == disp_del)
7875     ui_out_text (uiout, "\nTemporary catchpoint ");
7876   else
7877     ui_out_text (uiout, "\nCatchpoint ");
7878   if (ui_out_is_mi_like_p (uiout))
7879     {
7880       ui_out_field_string (uiout, "reason",
7881                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
7882                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
7883                                                 : EXEC_ASYNC_SYSCALL_RETURN));
7884       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7885     }
7886   ui_out_field_int (uiout, "bkptno", b->number);
7887
7888   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
7889     ui_out_text (uiout, " (call to syscall ");
7890   else
7891     ui_out_text (uiout, " (returned from syscall ");
7892
7893   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
7894     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
7895   if (s.name != NULL)
7896     ui_out_field_string (uiout, "syscall-name", s.name);
7897
7898   ui_out_text (uiout, "), ");
7899
7900   return PRINT_SRC_AND_LOC;
7901 }
7902
7903 /* Implement the "print_one" breakpoint_ops method for syscall
7904    catchpoints.  */
7905
7906 static void
7907 print_one_catch_syscall (struct breakpoint *b,
7908                          struct bp_location **last_loc)
7909 {
7910   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7911   struct value_print_options opts;
7912   struct ui_out *uiout = current_uiout;
7913
7914   get_user_print_options (&opts);
7915   /* Field 4, the address, is omitted (which makes the columns not
7916      line up too nicely with the headers, but the effect is relatively
7917      readable).  */
7918   if (opts.addressprint)
7919     ui_out_field_skip (uiout, "addr");
7920   annotate_field (5);
7921
7922   if (c->syscalls_to_be_caught
7923       && VEC_length (int, c->syscalls_to_be_caught) > 1)
7924     ui_out_text (uiout, "syscalls \"");
7925   else
7926     ui_out_text (uiout, "syscall \"");
7927
7928   if (c->syscalls_to_be_caught)
7929     {
7930       int i, iter;
7931       char *text = xstrprintf ("%s", "");
7932
7933       for (i = 0;
7934            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7935            i++)
7936         {
7937           char *x = text;
7938           struct syscall s;
7939           get_syscall_by_number (iter, &s);
7940
7941           if (s.name != NULL)
7942             text = xstrprintf ("%s%s, ", text, s.name);
7943           else
7944             text = xstrprintf ("%s%d, ", text, iter);
7945
7946           /* We have to xfree the last 'text' (now stored at 'x')
7947              because xstrprintf dynamically allocates new space for it
7948              on every call.  */
7949           xfree (x);
7950         }
7951       /* Remove the last comma.  */
7952       text[strlen (text) - 2] = '\0';
7953       ui_out_field_string (uiout, "what", text);
7954     }
7955   else
7956     ui_out_field_string (uiout, "what", "<any syscall>");
7957   ui_out_text (uiout, "\" ");
7958 }
7959
7960 /* Implement the "print_mention" breakpoint_ops method for syscall
7961    catchpoints.  */
7962
7963 static void
7964 print_mention_catch_syscall (struct breakpoint *b)
7965 {
7966   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7967
7968   if (c->syscalls_to_be_caught)
7969     {
7970       int i, iter;
7971
7972       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
7973         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
7974       else
7975         printf_filtered (_("Catchpoint %d (syscall"), b->number);
7976
7977       for (i = 0;
7978            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7979            i++)
7980         {
7981           struct syscall s;
7982           get_syscall_by_number (iter, &s);
7983
7984           if (s.name)
7985             printf_filtered (" '%s' [%d]", s.name, s.number);
7986           else
7987             printf_filtered (" %d", s.number);
7988         }
7989       printf_filtered (")");
7990     }
7991   else
7992     printf_filtered (_("Catchpoint %d (any syscall)"),
7993                      b->number);
7994 }
7995
7996 /* Implement the "print_recreate" breakpoint_ops method for syscall
7997    catchpoints.  */
7998
7999 static void
8000 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8001 {
8002   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8003
8004   fprintf_unfiltered (fp, "catch syscall");
8005
8006   if (c->syscalls_to_be_caught)
8007     {
8008       int i, iter;
8009
8010       for (i = 0;
8011            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8012            i++)
8013         {
8014           struct syscall s;
8015
8016           get_syscall_by_number (iter, &s);
8017           if (s.name)
8018             fprintf_unfiltered (fp, " %s", s.name);
8019           else
8020             fprintf_unfiltered (fp, " %d", s.number);
8021         }
8022     }
8023   print_recreate_thread (b, fp);
8024 }
8025
8026 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8027
8028 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8029
8030 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8031
8032 static int
8033 syscall_catchpoint_p (struct breakpoint *b)
8034 {
8035   return (b->ops == &catch_syscall_breakpoint_ops);
8036 }
8037
8038 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8039    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8040    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8041    the breakpoint_ops structure associated to the catchpoint.  */
8042
8043 static void
8044 init_catchpoint (struct breakpoint *b,
8045                  struct gdbarch *gdbarch, int tempflag,
8046                  char *cond_string,
8047                  const struct breakpoint_ops *ops)
8048 {
8049   struct symtab_and_line sal;
8050
8051   init_sal (&sal);
8052   sal.pspace = current_program_space;
8053
8054   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8055
8056   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8057   b->disposition = tempflag ? disp_del : disp_donttouch;
8058 }
8059
8060 void
8061 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8062 {
8063   add_to_breakpoint_chain (b);
8064   set_breakpoint_number (internal, b);
8065   if (!internal)
8066     mention (b);
8067   observer_notify_breakpoint_created (b);
8068
8069   if (update_gll)
8070     update_global_location_list (1);
8071 }
8072
8073 static void
8074 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8075                                     int tempflag, char *cond_string,
8076                                     const struct breakpoint_ops *ops)
8077 {
8078   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8079
8080   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8081
8082   c->forked_inferior_pid = null_ptid;
8083
8084   install_breakpoint (0, &c->base, 1);
8085 }
8086
8087 /* Exec catchpoints.  */
8088
8089 /* An instance of this type is used to represent an exec catchpoint.
8090    It includes a "struct breakpoint" as a kind of base class; users
8091    downcast to "struct breakpoint *" when needed.  A breakpoint is
8092    really of this type iff its ops pointer points to
8093    CATCH_EXEC_BREAKPOINT_OPS.  */
8094
8095 struct exec_catchpoint
8096 {
8097   /* The base class.  */
8098   struct breakpoint base;
8099
8100   /* Filename of a program whose exec triggered this catchpoint.
8101      This field is only valid immediately after this catchpoint has
8102      triggered.  */
8103   char *exec_pathname;
8104 };
8105
8106 /* Implement the "dtor" breakpoint_ops method for exec
8107    catchpoints.  */
8108
8109 static void
8110 dtor_catch_exec (struct breakpoint *b)
8111 {
8112   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8113
8114   xfree (c->exec_pathname);
8115
8116   base_breakpoint_ops.dtor (b);
8117 }
8118
8119 static int
8120 insert_catch_exec (struct bp_location *bl)
8121 {
8122   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
8123 }
8124
8125 static int
8126 remove_catch_exec (struct bp_location *bl)
8127 {
8128   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
8129 }
8130
8131 static int
8132 breakpoint_hit_catch_exec (const struct bp_location *bl,
8133                            struct address_space *aspace, CORE_ADDR bp_addr,
8134                            const struct target_waitstatus *ws)
8135 {
8136   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8137
8138   if (ws->kind != TARGET_WAITKIND_EXECD)
8139     return 0;
8140
8141   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8142   return 1;
8143 }
8144
8145 static enum print_stop_action
8146 print_it_catch_exec (bpstat bs)
8147 {
8148   struct ui_out *uiout = current_uiout;
8149   struct breakpoint *b = bs->breakpoint_at;
8150   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8151
8152   annotate_catchpoint (b->number);
8153   if (b->disposition == disp_del)
8154     ui_out_text (uiout, "\nTemporary catchpoint ");
8155   else
8156     ui_out_text (uiout, "\nCatchpoint ");
8157   if (ui_out_is_mi_like_p (uiout))
8158     {
8159       ui_out_field_string (uiout, "reason",
8160                            async_reason_lookup (EXEC_ASYNC_EXEC));
8161       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8162     }
8163   ui_out_field_int (uiout, "bkptno", b->number);
8164   ui_out_text (uiout, " (exec'd ");
8165   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8166   ui_out_text (uiout, "), ");
8167
8168   return PRINT_SRC_AND_LOC;
8169 }
8170
8171 static void
8172 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8173 {
8174   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8175   struct value_print_options opts;
8176   struct ui_out *uiout = current_uiout;
8177
8178   get_user_print_options (&opts);
8179
8180   /* Field 4, the address, is omitted (which makes the columns
8181      not line up too nicely with the headers, but the effect
8182      is relatively readable).  */
8183   if (opts.addressprint)
8184     ui_out_field_skip (uiout, "addr");
8185   annotate_field (5);
8186   ui_out_text (uiout, "exec");
8187   if (c->exec_pathname != NULL)
8188     {
8189       ui_out_text (uiout, ", program \"");
8190       ui_out_field_string (uiout, "what", c->exec_pathname);
8191       ui_out_text (uiout, "\" ");
8192     }
8193 }
8194
8195 static void
8196 print_mention_catch_exec (struct breakpoint *b)
8197 {
8198   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8199 }
8200
8201 /* Implement the "print_recreate" breakpoint_ops method for exec
8202    catchpoints.  */
8203
8204 static void
8205 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8206 {
8207   fprintf_unfiltered (fp, "catch exec");
8208   print_recreate_thread (b, fp);
8209 }
8210
8211 static struct breakpoint_ops catch_exec_breakpoint_ops;
8212
8213 static void
8214 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8215                                  const struct breakpoint_ops *ops)
8216 {
8217   struct syscall_catchpoint *c;
8218   struct gdbarch *gdbarch = get_current_arch ();
8219
8220   c = XNEW (struct syscall_catchpoint);
8221   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8222   c->syscalls_to_be_caught = filter;
8223
8224   install_breakpoint (0, &c->base, 1);
8225 }
8226
8227 static int
8228 hw_breakpoint_used_count (void)
8229 {
8230   int i = 0;
8231   struct breakpoint *b;
8232   struct bp_location *bl;
8233
8234   ALL_BREAKPOINTS (b)
8235   {
8236     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8237       for (bl = b->loc; bl; bl = bl->next)
8238         {
8239           /* Special types of hardware breakpoints may use more than
8240              one register.  */
8241           i += b->ops->resources_needed (bl);
8242         }
8243   }
8244
8245   return i;
8246 }
8247
8248 /* Returns the resources B would use if it were a hardware
8249    watchpoint.  */
8250
8251 static int
8252 hw_watchpoint_use_count (struct breakpoint *b)
8253 {
8254   int i = 0;
8255   struct bp_location *bl;
8256
8257   if (!breakpoint_enabled (b))
8258     return 0;
8259
8260   for (bl = b->loc; bl; bl = bl->next)
8261     {
8262       /* Special types of hardware watchpoints may use more than
8263          one register.  */
8264       i += b->ops->resources_needed (bl);
8265     }
8266
8267   return i;
8268 }
8269
8270 /* Returns the sum the used resources of all hardware watchpoints of
8271    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8272    the sum of the used resources of all hardware watchpoints of other
8273    types _not_ TYPE.  */
8274
8275 static int
8276 hw_watchpoint_used_count_others (struct breakpoint *except,
8277                                  enum bptype type, int *other_type_used)
8278 {
8279   int i = 0;
8280   struct breakpoint *b;
8281
8282   *other_type_used = 0;
8283   ALL_BREAKPOINTS (b)
8284     {
8285       if (b == except)
8286         continue;
8287       if (!breakpoint_enabled (b))
8288         continue;
8289
8290       if (b->type == type)
8291         i += hw_watchpoint_use_count (b);
8292       else if (is_hardware_watchpoint (b))
8293         *other_type_used = 1;
8294     }
8295
8296   return i;
8297 }
8298
8299 void
8300 disable_watchpoints_before_interactive_call_start (void)
8301 {
8302   struct breakpoint *b;
8303
8304   ALL_BREAKPOINTS (b)
8305   {
8306     if (is_watchpoint (b) && breakpoint_enabled (b))
8307       {
8308         b->enable_state = bp_call_disabled;
8309         update_global_location_list (0);
8310       }
8311   }
8312 }
8313
8314 void
8315 enable_watchpoints_after_interactive_call_stop (void)
8316 {
8317   struct breakpoint *b;
8318
8319   ALL_BREAKPOINTS (b)
8320   {
8321     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8322       {
8323         b->enable_state = bp_enabled;
8324         update_global_location_list (1);
8325       }
8326   }
8327 }
8328
8329 void
8330 disable_breakpoints_before_startup (void)
8331 {
8332   current_program_space->executing_startup = 1;
8333   update_global_location_list (0);
8334 }
8335
8336 void
8337 enable_breakpoints_after_startup (void)
8338 {
8339   current_program_space->executing_startup = 0;
8340   breakpoint_re_set ();
8341 }
8342
8343
8344 /* Set a breakpoint that will evaporate an end of command
8345    at address specified by SAL.
8346    Restrict it to frame FRAME if FRAME is nonzero.  */
8347
8348 struct breakpoint *
8349 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8350                           struct frame_id frame_id, enum bptype type)
8351 {
8352   struct breakpoint *b;
8353
8354   /* If FRAME_ID is valid, it should be a real frame, not an inlined
8355      one.  */
8356   gdb_assert (!frame_id_inlined_p (frame_id));
8357
8358   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8359   b->enable_state = bp_enabled;
8360   b->disposition = disp_donttouch;
8361   b->frame_id = frame_id;
8362
8363   /* If we're debugging a multi-threaded program, then we want
8364      momentary breakpoints to be active in only a single thread of
8365      control.  */
8366   if (in_thread_list (inferior_ptid))
8367     b->thread = pid_to_thread_id (inferior_ptid);
8368
8369   update_global_location_list_nothrow (1);
8370
8371   return b;
8372 }
8373
8374 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8375    The new breakpoint will have type TYPE, and use OPS as it
8376    breakpoint_ops.  */
8377
8378 static struct breakpoint *
8379 momentary_breakpoint_from_master (struct breakpoint *orig,
8380                                   enum bptype type,
8381                                   const struct breakpoint_ops *ops)
8382 {
8383   struct breakpoint *copy;
8384
8385   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8386   copy->loc = allocate_bp_location (copy);
8387   set_breakpoint_location_function (copy->loc, 1);
8388
8389   copy->loc->gdbarch = orig->loc->gdbarch;
8390   copy->loc->requested_address = orig->loc->requested_address;
8391   copy->loc->address = orig->loc->address;
8392   copy->loc->section = orig->loc->section;
8393   copy->loc->pspace = orig->loc->pspace;
8394   copy->loc->probe = orig->loc->probe;
8395
8396   if (orig->loc->source_file != NULL)
8397     copy->loc->source_file = xstrdup (orig->loc->source_file);
8398
8399   copy->loc->line_number = orig->loc->line_number;
8400   copy->frame_id = orig->frame_id;
8401   copy->thread = orig->thread;
8402   copy->pspace = orig->pspace;
8403
8404   copy->enable_state = bp_enabled;
8405   copy->disposition = disp_donttouch;
8406   copy->number = internal_breakpoint_number--;
8407
8408   update_global_location_list_nothrow (0);
8409   return copy;
8410 }
8411
8412 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8413    ORIG is NULL.  */
8414
8415 struct breakpoint *
8416 clone_momentary_breakpoint (struct breakpoint *orig)
8417 {
8418   /* If there's nothing to clone, then return nothing.  */
8419   if (orig == NULL)
8420     return NULL;
8421
8422   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8423 }
8424
8425 struct breakpoint *
8426 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8427                                 enum bptype type)
8428 {
8429   struct symtab_and_line sal;
8430
8431   sal = find_pc_line (pc, 0);
8432   sal.pc = pc;
8433   sal.section = find_pc_overlay (pc);
8434   sal.explicit_pc = 1;
8435
8436   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8437 }
8438 \f
8439
8440 /* Tell the user we have just set a breakpoint B.  */
8441
8442 static void
8443 mention (struct breakpoint *b)
8444 {
8445   b->ops->print_mention (b);
8446   if (ui_out_is_mi_like_p (current_uiout))
8447     return;
8448   printf_filtered ("\n");
8449 }
8450 \f
8451
8452 static struct bp_location *
8453 add_location_to_breakpoint (struct breakpoint *b,
8454                             const struct symtab_and_line *sal)
8455 {
8456   struct bp_location *loc, **tmp;
8457   CORE_ADDR adjusted_address;
8458   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8459
8460   if (loc_gdbarch == NULL)
8461     loc_gdbarch = b->gdbarch;
8462
8463   /* Adjust the breakpoint's address prior to allocating a location.
8464      Once we call allocate_bp_location(), that mostly uninitialized
8465      location will be placed on the location chain.  Adjustment of the
8466      breakpoint may cause target_read_memory() to be called and we do
8467      not want its scan of the location chain to find a breakpoint and
8468      location that's only been partially initialized.  */
8469   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8470                                                 sal->pc, b->type);
8471
8472   loc = allocate_bp_location (b);
8473   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
8474     ;
8475   *tmp = loc;
8476
8477   loc->requested_address = sal->pc;
8478   loc->address = adjusted_address;
8479   loc->pspace = sal->pspace;
8480   loc->probe = sal->probe;
8481   gdb_assert (loc->pspace != NULL);
8482   loc->section = sal->section;
8483   loc->gdbarch = loc_gdbarch;
8484
8485   if (sal->symtab != NULL)
8486     loc->source_file = xstrdup (sal->symtab->filename);
8487   loc->line_number = sal->line;
8488
8489   set_breakpoint_location_function (loc,
8490                                     sal->explicit_pc || sal->explicit_line);
8491   return loc;
8492 }
8493 \f
8494
8495 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8496    return 0 otherwise.  */
8497
8498 static int
8499 bp_loc_is_permanent (struct bp_location *loc)
8500 {
8501   int len;
8502   CORE_ADDR addr;
8503   const gdb_byte *bpoint;
8504   gdb_byte *target_mem;
8505   struct cleanup *cleanup;
8506   int retval = 0;
8507
8508   gdb_assert (loc != NULL);
8509
8510   addr = loc->address;
8511   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8512
8513   /* Software breakpoints unsupported?  */
8514   if (bpoint == NULL)
8515     return 0;
8516
8517   target_mem = alloca (len);
8518
8519   /* Enable the automatic memory restoration from breakpoints while
8520      we read the memory.  Otherwise we could say about our temporary
8521      breakpoints they are permanent.  */
8522   cleanup = save_current_space_and_thread ();
8523
8524   switch_to_program_space_and_thread (loc->pspace);
8525   make_show_memory_breakpoints_cleanup (0);
8526
8527   if (target_read_memory (loc->address, target_mem, len) == 0
8528       && memcmp (target_mem, bpoint, len) == 0)
8529     retval = 1;
8530
8531   do_cleanups (cleanup);
8532
8533   return retval;
8534 }
8535
8536 /* The style in which to perform a dynamic printf.  This is a user
8537    option because different output options have different tradeoffs;
8538    if GDB does the printing, there is better error handling if there
8539    is a problem with any of the arguments, but using an inferior
8540    function lets you have special-purpose printers and sending of
8541    output to the same place as compiled-in print functions.  (Future
8542    styles may include the ability to do a target-side printf.)  */
8543
8544 static const char dprintf_style_gdb[] = "gdb";
8545 static const char dprintf_style_call[] = "call";
8546 static const char *const dprintf_style_enums[] = {
8547   dprintf_style_gdb,
8548   dprintf_style_call,
8549   NULL
8550 };
8551 static const char *dprintf_style = dprintf_style_gdb;
8552
8553 /* The function to use for dynamic printf if the preferred style is to
8554    call into the inferior.  The value is simply a string that is
8555    copied into the command, so it can be anything that GDB can
8556    evaluate to a callable address, not necessarily a function name.  */
8557
8558 static char *dprintf_function = "";
8559
8560 /* The channel to use for dynamic printf if the preferred style is to
8561    call into the inferior; if a nonempty string, it will be passed to
8562    the call as the first argument, with the format string as the
8563    second.  As with the dprintf function, this can be anything that
8564    GDB knows how to evaluate, so in addition to common choices like
8565    "stderr", this could be an app-specific expression like
8566    "mystreams[curlogger]".  */
8567
8568 static char *dprintf_channel = "";
8569
8570 /* Build a command list for the dprintf corresponding to the current
8571    settings of the dprintf style options.  */
8572
8573 static void
8574 update_dprintf_command_list (struct breakpoint *b)
8575 {
8576   char *dprintf_args = b->extra_string;
8577   char *printf_line = NULL;
8578
8579   if (!dprintf_args)
8580     return;
8581
8582   dprintf_args = skip_spaces (dprintf_args);
8583
8584   /* Allow a comma, as it may have terminated a location, but don't
8585      insist on it.  */
8586   if (*dprintf_args == ',')
8587     ++dprintf_args;
8588   dprintf_args = skip_spaces (dprintf_args);
8589
8590   if (*dprintf_args != '"')
8591     error (_("Bad format string, missing '\"'."));
8592
8593   if (strcmp (dprintf_style, "gdb") == 0)
8594     printf_line = xstrprintf ("printf %s", dprintf_args);
8595   else if (strcmp (dprintf_style, "call") == 0)
8596     {
8597       if (!dprintf_function)
8598         error (_("No function supplied for dprintf call"));
8599
8600       if (dprintf_channel && strlen (dprintf_channel) > 0)
8601         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8602                                   dprintf_function,
8603                                   dprintf_channel,
8604                                   dprintf_args);
8605       else
8606         printf_line = xstrprintf ("call (void) %s (%s)",
8607                                   dprintf_function,
8608                                   dprintf_args);
8609     }
8610   else
8611     internal_error (__FILE__, __LINE__,
8612                     _("Invalid dprintf style."));
8613
8614   /* Manufacture a printf/continue sequence.  */
8615   if (printf_line)
8616     {
8617       struct command_line *printf_cmd_line, *cont_cmd_line = NULL;
8618
8619       cont_cmd_line = xmalloc (sizeof (struct command_line));
8620       cont_cmd_line->control_type = simple_control;
8621       cont_cmd_line->body_count = 0;
8622       cont_cmd_line->body_list = NULL;
8623       cont_cmd_line->next = NULL;
8624       cont_cmd_line->line = xstrdup ("continue");
8625
8626       printf_cmd_line = xmalloc (sizeof (struct command_line));
8627       printf_cmd_line->control_type = simple_control;
8628       printf_cmd_line->body_count = 0;
8629       printf_cmd_line->body_list = NULL;
8630       printf_cmd_line->next = cont_cmd_line;
8631       printf_cmd_line->line = printf_line;
8632
8633       breakpoint_set_commands (b, printf_cmd_line);
8634     }
8635 }
8636
8637 /* Update all dprintf commands, making their command lists reflect
8638    current style settings.  */
8639
8640 static void
8641 update_dprintf_commands (char *args, int from_tty,
8642                          struct cmd_list_element *c)
8643 {
8644   struct breakpoint *b;
8645
8646   ALL_BREAKPOINTS (b)
8647     {
8648       if (b->type == bp_dprintf)
8649         update_dprintf_command_list (b);
8650     }
8651 }
8652
8653 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
8654    as textual description of the location, and COND_STRING
8655    as condition expression.  */
8656
8657 static void
8658 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8659                      struct symtabs_and_lines sals, char *addr_string,
8660                      char *filter, char *cond_string,
8661                      char *extra_string,
8662                      enum bptype type, enum bpdisp disposition,
8663                      int thread, int task, int ignore_count,
8664                      const struct breakpoint_ops *ops, int from_tty,
8665                      int enabled, int internal, unsigned flags,
8666                      int display_canonical)
8667 {
8668   int i;
8669
8670   if (type == bp_hardware_breakpoint)
8671     {
8672       int target_resources_ok;
8673
8674       i = hw_breakpoint_used_count ();
8675       target_resources_ok =
8676         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8677                                             i + 1, 0);
8678       if (target_resources_ok == 0)
8679         error (_("No hardware breakpoint support in the target."));
8680       else if (target_resources_ok < 0)
8681         error (_("Hardware breakpoints used exceeds limit."));
8682     }
8683
8684   gdb_assert (sals.nelts > 0);
8685
8686   for (i = 0; i < sals.nelts; ++i)
8687     {
8688       struct symtab_and_line sal = sals.sals[i];
8689       struct bp_location *loc;
8690
8691       if (from_tty)
8692         {
8693           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8694           if (!loc_gdbarch)
8695             loc_gdbarch = gdbarch;
8696
8697           describe_other_breakpoints (loc_gdbarch,
8698                                       sal.pspace, sal.pc, sal.section, thread);
8699         }
8700
8701       if (i == 0)
8702         {
8703           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8704           b->thread = thread;
8705           b->task = task;
8706
8707           b->cond_string = cond_string;
8708           b->extra_string = extra_string;
8709           b->ignore_count = ignore_count;
8710           b->enable_state = enabled ? bp_enabled : bp_disabled;
8711           b->disposition = disposition;
8712
8713           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8714             b->loc->inserted = 1;
8715
8716           if (type == bp_static_tracepoint)
8717             {
8718               struct tracepoint *t = (struct tracepoint *) b;
8719               struct static_tracepoint_marker marker;
8720
8721               if (strace_marker_p (b))
8722                 {
8723                   /* We already know the marker exists, otherwise, we
8724                      wouldn't see a sal for it.  */
8725                   char *p = &addr_string[3];
8726                   char *endp;
8727                   char *marker_str;
8728
8729                   p = skip_spaces (p);
8730
8731                   endp = skip_to_space (p);
8732
8733                   marker_str = savestring (p, endp - p);
8734                   t->static_trace_marker_id = marker_str;
8735
8736                   printf_filtered (_("Probed static tracepoint "
8737                                      "marker \"%s\"\n"),
8738                                    t->static_trace_marker_id);
8739                 }
8740               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8741                 {
8742                   t->static_trace_marker_id = xstrdup (marker.str_id);
8743                   release_static_tracepoint_marker (&marker);
8744
8745                   printf_filtered (_("Probed static tracepoint "
8746                                      "marker \"%s\"\n"),
8747                                    t->static_trace_marker_id);
8748                 }
8749               else
8750                 warning (_("Couldn't determine the static "
8751                            "tracepoint marker to probe"));
8752             }
8753
8754           loc = b->loc;
8755         }
8756       else
8757         {
8758           loc = add_location_to_breakpoint (b, &sal);
8759           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8760             loc->inserted = 1;
8761         }
8762
8763       if (bp_loc_is_permanent (loc))
8764         make_breakpoint_permanent (b);
8765
8766       if (b->cond_string)
8767         {
8768           char *arg = b->cond_string;
8769           loc->cond = parse_exp_1 (&arg, loc->address,
8770                                    block_for_pc (loc->address), 0);
8771           if (*arg)
8772               error (_("Garbage '%s' follows condition"), arg);
8773         }
8774
8775       /* Dynamic printf requires and uses additional arguments on the
8776          command line, otherwise it's an error.  */
8777       if (type == bp_dprintf)
8778         {
8779           if (b->extra_string)
8780             update_dprintf_command_list (b);
8781           else
8782             error (_("Format string required"));
8783         }
8784       else if (b->extra_string)
8785         error (_("Garbage '%s' at end of command"), b->extra_string);
8786     }
8787
8788   b->display_canonical = display_canonical;
8789   if (addr_string)
8790     b->addr_string = addr_string;
8791   else
8792     /* addr_string has to be used or breakpoint_re_set will delete
8793        me.  */
8794     b->addr_string
8795       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
8796   b->filter = filter;
8797 }
8798
8799 static void
8800 create_breakpoint_sal (struct gdbarch *gdbarch,
8801                        struct symtabs_and_lines sals, char *addr_string,
8802                        char *filter, char *cond_string,
8803                        char *extra_string,
8804                        enum bptype type, enum bpdisp disposition,
8805                        int thread, int task, int ignore_count,
8806                        const struct breakpoint_ops *ops, int from_tty,
8807                        int enabled, int internal, unsigned flags,
8808                        int display_canonical)
8809 {
8810   struct breakpoint *b;
8811   struct cleanup *old_chain;
8812
8813   if (is_tracepoint_type (type))
8814     {
8815       struct tracepoint *t;
8816
8817       t = XCNEW (struct tracepoint);
8818       b = &t->base;
8819     }
8820   else
8821     b = XNEW (struct breakpoint);
8822
8823   old_chain = make_cleanup (xfree, b);
8824
8825   init_breakpoint_sal (b, gdbarch,
8826                        sals, addr_string,
8827                        filter, cond_string, extra_string,
8828                        type, disposition,
8829                        thread, task, ignore_count,
8830                        ops, from_tty,
8831                        enabled, internal, flags,
8832                        display_canonical);
8833   discard_cleanups (old_chain);
8834
8835   install_breakpoint (internal, b, 0);
8836 }
8837
8838 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8839    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8840    value.  COND_STRING, if not NULL, specified the condition to be
8841    used for all breakpoints.  Essentially the only case where
8842    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8843    function.  In that case, it's still not possible to specify
8844    separate conditions for different overloaded functions, so
8845    we take just a single condition string.
8846    
8847    NOTE: If the function succeeds, the caller is expected to cleanup
8848    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8849    array contents).  If the function fails (error() is called), the
8850    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8851    COND and SALS arrays and each of those arrays contents.  */
8852
8853 static void
8854 create_breakpoints_sal (struct gdbarch *gdbarch,
8855                         struct linespec_result *canonical,
8856                         char *cond_string, char *extra_string,
8857                         enum bptype type, enum bpdisp disposition,
8858                         int thread, int task, int ignore_count,
8859                         const struct breakpoint_ops *ops, int from_tty,
8860                         int enabled, int internal, unsigned flags)
8861 {
8862   int i;
8863   struct linespec_sals *lsal;
8864
8865   if (canonical->pre_expanded)
8866     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
8867
8868   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
8869     {
8870       /* Note that 'addr_string' can be NULL in the case of a plain
8871          'break', without arguments.  */
8872       char *addr_string = (canonical->addr_string
8873                            ? xstrdup (canonical->addr_string)
8874                            : NULL);
8875       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
8876       struct cleanup *inner = make_cleanup (xfree, addr_string);
8877
8878       make_cleanup (xfree, filter_string);
8879       create_breakpoint_sal (gdbarch, lsal->sals,
8880                              addr_string,
8881                              filter_string,
8882                              cond_string, extra_string,
8883                              type, disposition,
8884                              thread, task, ignore_count, ops,
8885                              from_tty, enabled, internal, flags,
8886                              canonical->special_display);
8887       discard_cleanups (inner);
8888     }
8889 }
8890
8891 /* Parse ADDRESS which is assumed to be a SAL specification possibly
8892    followed by conditionals.  On return, SALS contains an array of SAL
8893    addresses found.  ADDR_STRING contains a vector of (canonical)
8894    address strings.  ADDRESS points to the end of the SAL.
8895
8896    The array and the line spec strings are allocated on the heap, it is
8897    the caller's responsibility to free them.  */
8898
8899 static void
8900 parse_breakpoint_sals (char **address,
8901                        struct linespec_result *canonical)
8902 {
8903   char *addr_start = *address;
8904
8905   /* If no arg given, or if first arg is 'if ', use the default
8906      breakpoint.  */
8907   if ((*address) == NULL
8908       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
8909     {
8910       /* The last displayed codepoint, if it's valid, is our default breakpoint
8911          address.  */
8912       if (last_displayed_sal_is_valid ())
8913         {
8914           struct linespec_sals lsal;
8915           struct symtab_and_line sal;
8916
8917           init_sal (&sal);              /* Initialize to zeroes.  */
8918           lsal.sals.sals = (struct symtab_and_line *)
8919             xmalloc (sizeof (struct symtab_and_line));
8920
8921           /* Set sal's pspace, pc, symtab, and line to the values
8922              corresponding to the last call to print_frame_info.  */
8923           get_last_displayed_sal (&sal);
8924           sal.section = find_pc_overlay (sal.pc);
8925
8926           /* "break" without arguments is equivalent to "break *PC"
8927              where PC is the last displayed codepoint's address.  So
8928              make sure to set sal.explicit_pc to prevent GDB from
8929              trying to expand the list of sals to include all other
8930              instances with the same symtab and line.  */
8931           sal.explicit_pc = 1;
8932
8933           lsal.sals.sals[0] = sal;
8934           lsal.sals.nelts = 1;
8935           lsal.canonical = NULL;
8936
8937           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
8938         }
8939       else
8940         error (_("No default breakpoint address now."));
8941     }
8942   else
8943     {
8944       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
8945
8946       /* Force almost all breakpoints to be in terms of the
8947          current_source_symtab (which is decode_line_1's default).
8948          This should produce the results we want almost all of the
8949          time while leaving default_breakpoint_* alone.
8950
8951          ObjC: However, don't match an Objective-C method name which
8952          may have a '+' or '-' succeeded by a '['.  */
8953       if (last_displayed_sal_is_valid ()
8954           && (!cursal.symtab
8955               || ((strchr ("+-", (*address)[0]) != NULL)
8956                   && ((*address)[1] != '['))))
8957         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8958                           get_last_displayed_symtab (),
8959                           get_last_displayed_line (),
8960                           canonical, NULL, NULL);
8961       else
8962         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8963                           cursal.symtab, cursal.line, canonical, NULL, NULL);
8964     }
8965 }
8966
8967
8968 /* Convert each SAL into a real PC.  Verify that the PC can be
8969    inserted as a breakpoint.  If it can't throw an error.  */
8970
8971 static void
8972 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
8973 {    
8974   int i;
8975
8976   for (i = 0; i < sals->nelts; i++)
8977     resolve_sal_pc (&sals->sals[i]);
8978 }
8979
8980 /* Fast tracepoints may have restrictions on valid locations.  For
8981    instance, a fast tracepoint using a jump instead of a trap will
8982    likely have to overwrite more bytes than a trap would, and so can
8983    only be placed where the instruction is longer than the jump, or a
8984    multi-instruction sequence does not have a jump into the middle of
8985    it, etc.  */
8986
8987 static void
8988 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8989                             struct symtabs_and_lines *sals)
8990 {
8991   int i, rslt;
8992   struct symtab_and_line *sal;
8993   char *msg;
8994   struct cleanup *old_chain;
8995
8996   for (i = 0; i < sals->nelts; i++)
8997     {
8998       struct gdbarch *sarch;
8999
9000       sal = &sals->sals[i];
9001
9002       sarch = get_sal_arch (*sal);
9003       /* We fall back to GDBARCH if there is no architecture
9004          associated with SAL.  */
9005       if (sarch == NULL)
9006         sarch = gdbarch;
9007       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9008                                                NULL, &msg);
9009       old_chain = make_cleanup (xfree, msg);
9010
9011       if (!rslt)
9012         error (_("May not have a fast tracepoint at 0x%s%s"),
9013                paddress (sarch, sal->pc), (msg ? msg : ""));
9014
9015       do_cleanups (old_chain);
9016     }
9017 }
9018
9019 /* Given TOK, a string specification of condition and thread, as
9020    accepted by the 'break' command, extract the condition
9021    string and thread number and set *COND_STRING and *THREAD.
9022    PC identifies the context at which the condition should be parsed.
9023    If no condition is found, *COND_STRING is set to NULL.
9024    If no thread is found, *THREAD is set to -1.  */
9025
9026 static void
9027 find_condition_and_thread (char *tok, CORE_ADDR pc,
9028                            char **cond_string, int *thread, int *task,
9029                            char **rest)
9030 {
9031   *cond_string = NULL;
9032   *thread = -1;
9033   while (tok && *tok)
9034     {
9035       char *end_tok;
9036       int toklen;
9037       char *cond_start = NULL;
9038       char *cond_end = NULL;
9039
9040       tok = skip_spaces (tok);
9041
9042       if ((*tok == '"' || *tok == ',') && rest)
9043         {
9044           *rest = savestring (tok, strlen (tok));
9045           return;
9046         }
9047
9048       end_tok = skip_to_space (tok);
9049
9050       toklen = end_tok - tok;
9051
9052       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9053         {
9054           struct expression *expr;
9055
9056           tok = cond_start = end_tok + 1;
9057           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9058           xfree (expr);
9059           cond_end = tok;
9060           *cond_string = savestring (cond_start, cond_end - cond_start);
9061         }
9062       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9063         {
9064           char *tmptok;
9065
9066           tok = end_tok + 1;
9067           tmptok = tok;
9068           *thread = strtol (tok, &tok, 0);
9069           if (tok == tmptok)
9070             error (_("Junk after thread keyword."));
9071           if (!valid_thread_id (*thread))
9072             error (_("Unknown thread %d."), *thread);
9073         }
9074       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9075         {
9076           char *tmptok;
9077
9078           tok = end_tok + 1;
9079           tmptok = tok;
9080           *task = strtol (tok, &tok, 0);
9081           if (tok == tmptok)
9082             error (_("Junk after task keyword."));
9083           if (!valid_task_id (*task))
9084             error (_("Unknown task %d."), *task);
9085         }
9086       else if (rest)
9087         {
9088           *rest = savestring (tok, strlen (tok));
9089           return;
9090         }
9091       else
9092         error (_("Junk at end of arguments."));
9093     }
9094 }
9095
9096 /* Decode a static tracepoint marker spec.  */
9097
9098 static struct symtabs_and_lines
9099 decode_static_tracepoint_spec (char **arg_p)
9100 {
9101   VEC(static_tracepoint_marker_p) *markers = NULL;
9102   struct symtabs_and_lines sals;
9103   struct cleanup *old_chain;
9104   char *p = &(*arg_p)[3];
9105   char *endp;
9106   char *marker_str;
9107   int i;
9108
9109   p = skip_spaces (p);
9110
9111   endp = skip_to_space (p);
9112
9113   marker_str = savestring (p, endp - p);
9114   old_chain = make_cleanup (xfree, marker_str);
9115
9116   markers = target_static_tracepoint_markers_by_strid (marker_str);
9117   if (VEC_empty(static_tracepoint_marker_p, markers))
9118     error (_("No known static tracepoint marker named %s"), marker_str);
9119
9120   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9121   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9122
9123   for (i = 0; i < sals.nelts; i++)
9124     {
9125       struct static_tracepoint_marker *marker;
9126
9127       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9128
9129       init_sal (&sals.sals[i]);
9130
9131       sals.sals[i] = find_pc_line (marker->address, 0);
9132       sals.sals[i].pc = marker->address;
9133
9134       release_static_tracepoint_marker (marker);
9135     }
9136
9137   do_cleanups (old_chain);
9138
9139   *arg_p = endp;
9140   return sals;
9141 }
9142
9143 /* Set a breakpoint.  This function is shared between CLI and MI
9144    functions for setting a breakpoint.  This function has two major
9145    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
9146    parameter.  If non-zero, the function will parse arg, extracting
9147    breakpoint location, address and thread.  Otherwise, ARG is just
9148    the location of breakpoint, with condition and thread specified by
9149    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
9150    the breakpoint number will be allocated from the internal
9151    breakpoint count.  Returns true if any breakpoint was created;
9152    false otherwise.  */
9153
9154 int
9155 create_breakpoint (struct gdbarch *gdbarch,
9156                    char *arg, char *cond_string,
9157                    int thread, char *extra_string,
9158                    int parse_condition_and_thread,
9159                    int tempflag, enum bptype type_wanted,
9160                    int ignore_count,
9161                    enum auto_boolean pending_break_support,
9162                    const struct breakpoint_ops *ops,
9163                    int from_tty, int enabled, int internal,
9164                    unsigned flags)
9165 {
9166   volatile struct gdb_exception e;
9167   char *copy_arg = NULL;
9168   char *addr_start = arg;
9169   struct linespec_result canonical;
9170   struct cleanup *old_chain;
9171   struct cleanup *bkpt_chain = NULL;
9172   int pending = 0;
9173   int task = 0;
9174   int prev_bkpt_count = breakpoint_count;
9175
9176   gdb_assert (ops != NULL);
9177
9178   init_linespec_result (&canonical);
9179
9180   TRY_CATCH (e, RETURN_MASK_ALL)
9181     {
9182       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9183                                      addr_start, &copy_arg);
9184     }
9185
9186   /* If caller is interested in rc value from parse, set value.  */
9187   switch (e.reason)
9188     {
9189     case GDB_NO_ERROR:
9190       if (VEC_empty (linespec_sals, canonical.sals))
9191         return 0;
9192       break;
9193     case RETURN_ERROR:
9194       switch (e.error)
9195         {
9196         case NOT_FOUND_ERROR:
9197
9198           /* If pending breakpoint support is turned off, throw
9199              error.  */
9200
9201           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9202             throw_exception (e);
9203
9204           exception_print (gdb_stderr, e);
9205
9206           /* If pending breakpoint support is auto query and the user
9207              selects no, then simply return the error code.  */
9208           if (pending_break_support == AUTO_BOOLEAN_AUTO
9209               && !nquery (_("Make %s pending on future shared library load? "),
9210                           bptype_string (type_wanted)))
9211             return 0;
9212
9213           /* At this point, either the user was queried about setting
9214              a pending breakpoint and selected yes, or pending
9215              breakpoint behavior is on and thus a pending breakpoint
9216              is defaulted on behalf of the user.  */
9217           {
9218             struct linespec_sals lsal;
9219
9220             copy_arg = xstrdup (addr_start);
9221             lsal.canonical = xstrdup (copy_arg);
9222             lsal.sals.nelts = 1;
9223             lsal.sals.sals = XNEW (struct symtab_and_line);
9224             init_sal (&lsal.sals.sals[0]);
9225             pending = 1;
9226             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9227           }
9228           break;
9229         default:
9230           throw_exception (e);
9231         }
9232       break;
9233     default:
9234       throw_exception (e);
9235     }
9236
9237   /* Create a chain of things that always need to be cleaned up.  */
9238   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9239
9240   /* ----------------------------- SNIP -----------------------------
9241      Anything added to the cleanup chain beyond this point is assumed
9242      to be part of a breakpoint.  If the breakpoint create succeeds
9243      then the memory is not reclaimed.  */
9244   bkpt_chain = make_cleanup (null_cleanup, 0);
9245
9246   /* Resolve all line numbers to PC's and verify that the addresses
9247      are ok for the target.  */
9248   if (!pending)
9249     {
9250       int ix;
9251       struct linespec_sals *iter;
9252
9253       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9254         breakpoint_sals_to_pc (&iter->sals);
9255     }
9256
9257   /* Fast tracepoints may have additional restrictions on location.  */
9258   if (!pending && type_wanted == bp_fast_tracepoint)
9259     {
9260       int ix;
9261       struct linespec_sals *iter;
9262
9263       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9264         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9265     }
9266
9267   /* Verify that condition can be parsed, before setting any
9268      breakpoints.  Allocate a separate condition expression for each
9269      breakpoint.  */
9270   if (!pending)
9271     {
9272       struct linespec_sals *lsal;
9273
9274       lsal = VEC_index (linespec_sals, canonical.sals, 0);
9275
9276       if (parse_condition_and_thread)
9277         {
9278             char *rest;
9279             /* Here we only parse 'arg' to separate condition
9280                from thread number, so parsing in context of first
9281                sal is OK.  When setting the breakpoint we'll 
9282                re-parse it in context of each sal.  */
9283             cond_string = NULL;
9284             thread = -1;
9285             rest = NULL;
9286             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9287                                        &thread, &task, &rest);
9288             if (cond_string)
9289                 make_cleanup (xfree, cond_string);
9290             if (rest)
9291               make_cleanup (xfree, rest);
9292             if (rest)
9293               extra_string = rest;
9294         }
9295       else
9296         {
9297             /* Create a private copy of condition string.  */
9298             if (cond_string)
9299             {
9300                 cond_string = xstrdup (cond_string);
9301                 make_cleanup (xfree, cond_string);
9302             }
9303             /* Create a private copy of any extra string.  */
9304             if (extra_string)
9305               {
9306                 extra_string = xstrdup (extra_string);
9307                 make_cleanup (xfree, extra_string);
9308               }
9309         }
9310
9311       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
9312                                    cond_string, extra_string, type_wanted,
9313                                    tempflag ? disp_del : disp_donttouch,
9314                                    thread, task, ignore_count, ops,
9315                                    from_tty, enabled, internal, flags);
9316     }
9317   else
9318     {
9319       struct breakpoint *b;
9320
9321       make_cleanup (xfree, copy_arg);
9322
9323       if (is_tracepoint_type (type_wanted))
9324         {
9325           struct tracepoint *t;
9326
9327           t = XCNEW (struct tracepoint);
9328           b = &t->base;
9329         }
9330       else
9331         b = XNEW (struct breakpoint);
9332
9333       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9334
9335       b->addr_string = copy_arg;
9336       b->cond_string = NULL;
9337       b->extra_string = NULL;
9338       b->ignore_count = ignore_count;
9339       b->disposition = tempflag ? disp_del : disp_donttouch;
9340       b->condition_not_parsed = 1;
9341       b->enable_state = enabled ? bp_enabled : bp_disabled;
9342       if ((type_wanted != bp_breakpoint
9343            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9344         b->pspace = current_program_space;
9345
9346       install_breakpoint (internal, b, 0);
9347     }
9348   
9349   if (VEC_length (linespec_sals, canonical.sals) > 1)
9350     {
9351       warning (_("Multiple breakpoints were set.\nUse the "
9352                  "\"delete\" command to delete unwanted breakpoints."));
9353       prev_breakpoint_count = prev_bkpt_count;
9354     }
9355
9356   /* That's it.  Discard the cleanups for data inserted into the
9357      breakpoint.  */
9358   discard_cleanups (bkpt_chain);
9359   /* But cleanup everything else.  */
9360   do_cleanups (old_chain);
9361
9362   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9363   update_global_location_list (1);
9364
9365   return 1;
9366 }
9367
9368 /* Set a breakpoint.
9369    ARG is a string describing breakpoint address,
9370    condition, and thread.
9371    FLAG specifies if a breakpoint is hardware on,
9372    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9373    and BP_TEMPFLAG.  */
9374
9375 static void
9376 break_command_1 (char *arg, int flag, int from_tty)
9377 {
9378   int tempflag = flag & BP_TEMPFLAG;
9379   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9380                              ? bp_hardware_breakpoint
9381                              : bp_breakpoint);
9382   struct breakpoint_ops *ops;
9383   const char *arg_cp = arg;
9384
9385   /* Matching breakpoints on probes.  */
9386   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9387     ops = &bkpt_probe_breakpoint_ops;
9388   else
9389     ops = &bkpt_breakpoint_ops;
9390
9391   create_breakpoint (get_current_arch (),
9392                      arg,
9393                      NULL, 0, NULL, 1 /* parse arg */,
9394                      tempflag, type_wanted,
9395                      0 /* Ignore count */,
9396                      pending_break_support,
9397                      ops,
9398                      from_tty,
9399                      1 /* enabled */,
9400                      0 /* internal */,
9401                      0);
9402 }
9403
9404 /* Helper function for break_command_1 and disassemble_command.  */
9405
9406 void
9407 resolve_sal_pc (struct symtab_and_line *sal)
9408 {
9409   CORE_ADDR pc;
9410
9411   if (sal->pc == 0 && sal->symtab != NULL)
9412     {
9413       if (!find_line_pc (sal->symtab, sal->line, &pc))
9414         error (_("No line %d in file \"%s\"."),
9415                sal->line, sal->symtab->filename);
9416       sal->pc = pc;
9417
9418       /* If this SAL corresponds to a breakpoint inserted using a line
9419          number, then skip the function prologue if necessary.  */
9420       if (sal->explicit_line)
9421         skip_prologue_sal (sal);
9422     }
9423
9424   if (sal->section == 0 && sal->symtab != NULL)
9425     {
9426       struct blockvector *bv;
9427       struct block *b;
9428       struct symbol *sym;
9429
9430       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9431       if (bv != NULL)
9432         {
9433           sym = block_linkage_function (b);
9434           if (sym != NULL)
9435             {
9436               fixup_symbol_section (sym, sal->symtab->objfile);
9437               sal->section = SYMBOL_OBJ_SECTION (sym);
9438             }
9439           else
9440             {
9441               /* It really is worthwhile to have the section, so we'll
9442                  just have to look harder. This case can be executed
9443                  if we have line numbers but no functions (as can
9444                  happen in assembly source).  */
9445
9446               struct minimal_symbol *msym;
9447               struct cleanup *old_chain = save_current_space_and_thread ();
9448
9449               switch_to_program_space_and_thread (sal->pspace);
9450
9451               msym = lookup_minimal_symbol_by_pc (sal->pc);
9452               if (msym)
9453                 sal->section = SYMBOL_OBJ_SECTION (msym);
9454
9455               do_cleanups (old_chain);
9456             }
9457         }
9458     }
9459 }
9460
9461 void
9462 break_command (char *arg, int from_tty)
9463 {
9464   break_command_1 (arg, 0, from_tty);
9465 }
9466
9467 void
9468 tbreak_command (char *arg, int from_tty)
9469 {
9470   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9471 }
9472
9473 static void
9474 hbreak_command (char *arg, int from_tty)
9475 {
9476   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9477 }
9478
9479 static void
9480 thbreak_command (char *arg, int from_tty)
9481 {
9482   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9483 }
9484
9485 static void
9486 stop_command (char *arg, int from_tty)
9487 {
9488   printf_filtered (_("Specify the type of breakpoint to set.\n\
9489 Usage: stop in <function | address>\n\
9490        stop at <line>\n"));
9491 }
9492
9493 static void
9494 stopin_command (char *arg, int from_tty)
9495 {
9496   int badInput = 0;
9497
9498   if (arg == (char *) NULL)
9499     badInput = 1;
9500   else if (*arg != '*')
9501     {
9502       char *argptr = arg;
9503       int hasColon = 0;
9504
9505       /* Look for a ':'.  If this is a line number specification, then
9506          say it is bad, otherwise, it should be an address or
9507          function/method name.  */
9508       while (*argptr && !hasColon)
9509         {
9510           hasColon = (*argptr == ':');
9511           argptr++;
9512         }
9513
9514       if (hasColon)
9515         badInput = (*argptr != ':');    /* Not a class::method */
9516       else
9517         badInput = isdigit (*arg);      /* a simple line number */
9518     }
9519
9520   if (badInput)
9521     printf_filtered (_("Usage: stop in <function | address>\n"));
9522   else
9523     break_command_1 (arg, 0, from_tty);
9524 }
9525
9526 static void
9527 stopat_command (char *arg, int from_tty)
9528 {
9529   int badInput = 0;
9530
9531   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9532     badInput = 1;
9533   else
9534     {
9535       char *argptr = arg;
9536       int hasColon = 0;
9537
9538       /* Look for a ':'.  If there is a '::' then get out, otherwise
9539          it is probably a line number.  */
9540       while (*argptr && !hasColon)
9541         {
9542           hasColon = (*argptr == ':');
9543           argptr++;
9544         }
9545
9546       if (hasColon)
9547         badInput = (*argptr == ':');    /* we have class::method */
9548       else
9549         badInput = !isdigit (*arg);     /* not a line number */
9550     }
9551
9552   if (badInput)
9553     printf_filtered (_("Usage: stop at <line>\n"));
9554   else
9555     break_command_1 (arg, 0, from_tty);
9556 }
9557
9558 void dprintf_command (char *arg, int from_tty);
9559
9560 /* The dynamic printf command is mostly like a regular breakpoint, but
9561    with a prewired command list consisting of a single output command,
9562    built from extra arguments supplied on the dprintf command
9563    line.  */
9564
9565 void
9566 dprintf_command (char *arg, int from_tty)
9567 {
9568   create_breakpoint (get_current_arch (),
9569                      arg,
9570                      NULL, 0, NULL, 1 /* parse arg */,
9571                      0, bp_dprintf,
9572                      0 /* Ignore count */,
9573                      pending_break_support,
9574                      &dprintf_breakpoint_ops,
9575                      from_tty,
9576                      1 /* enabled */,
9577                      0 /* internal */,
9578                      0);
9579 }
9580
9581 /* Implement the "breakpoint_hit" breakpoint_ops method for
9582    ranged breakpoints.  */
9583
9584 static int
9585 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9586                                   struct address_space *aspace,
9587                                   CORE_ADDR bp_addr,
9588                                   const struct target_waitstatus *ws)
9589 {
9590   if (ws->kind != TARGET_WAITKIND_STOPPED
9591       || ws->value.sig != GDB_SIGNAL_TRAP)
9592     return 0;
9593
9594   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9595                                          bl->length, aspace, bp_addr);
9596 }
9597
9598 /* Implement the "resources_needed" breakpoint_ops method for
9599    ranged breakpoints.  */
9600
9601 static int
9602 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9603 {
9604   return target_ranged_break_num_registers ();
9605 }
9606
9607 /* Implement the "print_it" breakpoint_ops method for
9608    ranged breakpoints.  */
9609
9610 static enum print_stop_action
9611 print_it_ranged_breakpoint (bpstat bs)
9612 {
9613   struct breakpoint *b = bs->breakpoint_at;
9614   struct bp_location *bl = b->loc;
9615   struct ui_out *uiout = current_uiout;
9616
9617   gdb_assert (b->type == bp_hardware_breakpoint);
9618
9619   /* Ranged breakpoints have only one location.  */
9620   gdb_assert (bl && bl->next == NULL);
9621
9622   annotate_breakpoint (b->number);
9623   if (b->disposition == disp_del)
9624     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
9625   else
9626     ui_out_text (uiout, "\nRanged breakpoint ");
9627   if (ui_out_is_mi_like_p (uiout))
9628     {
9629       ui_out_field_string (uiout, "reason",
9630                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9631       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9632     }
9633   ui_out_field_int (uiout, "bkptno", b->number);
9634   ui_out_text (uiout, ", ");
9635
9636   return PRINT_SRC_AND_LOC;
9637 }
9638
9639 /* Implement the "print_one" breakpoint_ops method for
9640    ranged breakpoints.  */
9641
9642 static void
9643 print_one_ranged_breakpoint (struct breakpoint *b,
9644                              struct bp_location **last_loc)
9645 {
9646   struct bp_location *bl = b->loc;
9647   struct value_print_options opts;
9648   struct ui_out *uiout = current_uiout;
9649
9650   /* Ranged breakpoints have only one location.  */
9651   gdb_assert (bl && bl->next == NULL);
9652
9653   get_user_print_options (&opts);
9654
9655   if (opts.addressprint)
9656     /* We don't print the address range here, it will be printed later
9657        by print_one_detail_ranged_breakpoint.  */
9658     ui_out_field_skip (uiout, "addr");
9659   annotate_field (5);
9660   print_breakpoint_location (b, bl);
9661   *last_loc = bl;
9662 }
9663
9664 /* Implement the "print_one_detail" breakpoint_ops method for
9665    ranged breakpoints.  */
9666
9667 static void
9668 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9669                                     struct ui_out *uiout)
9670 {
9671   CORE_ADDR address_start, address_end;
9672   struct bp_location *bl = b->loc;
9673   struct ui_file *stb = mem_fileopen ();
9674   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
9675
9676   gdb_assert (bl);
9677
9678   address_start = bl->address;
9679   address_end = address_start + bl->length - 1;
9680
9681   ui_out_text (uiout, "\taddress range: ");
9682   fprintf_unfiltered (stb, "[%s, %s]",
9683                       print_core_address (bl->gdbarch, address_start),
9684                       print_core_address (bl->gdbarch, address_end));
9685   ui_out_field_stream (uiout, "addr", stb);
9686   ui_out_text (uiout, "\n");
9687
9688   do_cleanups (cleanup);
9689 }
9690
9691 /* Implement the "print_mention" breakpoint_ops method for
9692    ranged breakpoints.  */
9693
9694 static void
9695 print_mention_ranged_breakpoint (struct breakpoint *b)
9696 {
9697   struct bp_location *bl = b->loc;
9698   struct ui_out *uiout = current_uiout;
9699
9700   gdb_assert (bl);
9701   gdb_assert (b->type == bp_hardware_breakpoint);
9702
9703   if (ui_out_is_mi_like_p (uiout))
9704     return;
9705
9706   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9707                    b->number, paddress (bl->gdbarch, bl->address),
9708                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9709 }
9710
9711 /* Implement the "print_recreate" breakpoint_ops method for
9712    ranged breakpoints.  */
9713
9714 static void
9715 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9716 {
9717   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
9718                       b->addr_string_range_end);
9719   print_recreate_thread (b, fp);
9720 }
9721
9722 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9723
9724 static struct breakpoint_ops ranged_breakpoint_ops;
9725
9726 /* Find the address where the end of the breakpoint range should be
9727    placed, given the SAL of the end of the range.  This is so that if
9728    the user provides a line number, the end of the range is set to the
9729    last instruction of the given line.  */
9730
9731 static CORE_ADDR
9732 find_breakpoint_range_end (struct symtab_and_line sal)
9733 {
9734   CORE_ADDR end;
9735
9736   /* If the user provided a PC value, use it.  Otherwise,
9737      find the address of the end of the given location.  */
9738   if (sal.explicit_pc)
9739     end = sal.pc;
9740   else
9741     {
9742       int ret;
9743       CORE_ADDR start;
9744
9745       ret = find_line_pc_range (sal, &start, &end);
9746       if (!ret)
9747         error (_("Could not find location of the end of the range."));
9748
9749       /* find_line_pc_range returns the start of the next line.  */
9750       end--;
9751     }
9752
9753   return end;
9754 }
9755
9756 /* Implement the "break-range" CLI command.  */
9757
9758 static void
9759 break_range_command (char *arg, int from_tty)
9760 {
9761   char *arg_start, *addr_string_start, *addr_string_end;
9762   struct linespec_result canonical_start, canonical_end;
9763   int bp_count, can_use_bp, length;
9764   CORE_ADDR end;
9765   struct breakpoint *b;
9766   struct symtab_and_line sal_start, sal_end;
9767   struct cleanup *cleanup_bkpt;
9768   struct linespec_sals *lsal_start, *lsal_end;
9769
9770   /* We don't support software ranged breakpoints.  */
9771   if (target_ranged_break_num_registers () < 0)
9772     error (_("This target does not support hardware ranged breakpoints."));
9773
9774   bp_count = hw_breakpoint_used_count ();
9775   bp_count += target_ranged_break_num_registers ();
9776   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9777                                                    bp_count, 0);
9778   if (can_use_bp < 0)
9779     error (_("Hardware breakpoints used exceeds limit."));
9780
9781   arg = skip_spaces (arg);
9782   if (arg == NULL || arg[0] == '\0')
9783     error(_("No address range specified."));
9784
9785   init_linespec_result (&canonical_start);
9786
9787   arg_start = arg;
9788   parse_breakpoint_sals (&arg, &canonical_start);
9789
9790   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
9791
9792   if (arg[0] != ',')
9793     error (_("Too few arguments."));
9794   else if (VEC_empty (linespec_sals, canonical_start.sals))
9795     error (_("Could not find location of the beginning of the range."));
9796
9797   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
9798
9799   if (VEC_length (linespec_sals, canonical_start.sals) > 1
9800       || lsal_start->sals.nelts != 1)
9801     error (_("Cannot create a ranged breakpoint with multiple locations."));
9802
9803   sal_start = lsal_start->sals.sals[0];
9804   addr_string_start = savestring (arg_start, arg - arg_start);
9805   make_cleanup (xfree, addr_string_start);
9806
9807   arg++;        /* Skip the comma.  */
9808   arg = skip_spaces (arg);
9809
9810   /* Parse the end location.  */
9811
9812   init_linespec_result (&canonical_end);
9813   arg_start = arg;
9814
9815   /* We call decode_line_full directly here instead of using
9816      parse_breakpoint_sals because we need to specify the start location's
9817      symtab and line as the default symtab and line for the end of the
9818      range.  This makes it possible to have ranges like "foo.c:27, +14",
9819      where +14 means 14 lines from the start location.  */
9820   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
9821                     sal_start.symtab, sal_start.line,
9822                     &canonical_end, NULL, NULL);
9823
9824   make_cleanup_destroy_linespec_result (&canonical_end);
9825
9826   if (VEC_empty (linespec_sals, canonical_end.sals))
9827     error (_("Could not find location of the end of the range."));
9828
9829   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
9830   if (VEC_length (linespec_sals, canonical_end.sals) > 1
9831       || lsal_end->sals.nelts != 1)
9832     error (_("Cannot create a ranged breakpoint with multiple locations."));
9833
9834   sal_end = lsal_end->sals.sals[0];
9835   addr_string_end = savestring (arg_start, arg - arg_start);
9836   make_cleanup (xfree, addr_string_end);
9837
9838   end = find_breakpoint_range_end (sal_end);
9839   if (sal_start.pc > end)
9840     error (_("Invalid address range, end precedes start."));
9841
9842   length = end - sal_start.pc + 1;
9843   if (length < 0)
9844     /* Length overflowed.  */
9845     error (_("Address range too large."));
9846   else if (length == 1)
9847     {
9848       /* This range is simple enough to be handled by
9849          the `hbreak' command.  */
9850       hbreak_command (addr_string_start, 1);
9851
9852       do_cleanups (cleanup_bkpt);
9853
9854       return;
9855     }
9856
9857   /* Now set up the breakpoint.  */
9858   b = set_raw_breakpoint (get_current_arch (), sal_start,
9859                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9860   set_breakpoint_count (breakpoint_count + 1);
9861   b->number = breakpoint_count;
9862   b->disposition = disp_donttouch;
9863   b->addr_string = xstrdup (addr_string_start);
9864   b->addr_string_range_end = xstrdup (addr_string_end);
9865   b->loc->length = length;
9866
9867   do_cleanups (cleanup_bkpt);
9868
9869   mention (b);
9870   observer_notify_breakpoint_created (b);
9871   update_global_location_list (1);
9872 }
9873
9874 /*  Return non-zero if EXP is verified as constant.  Returned zero
9875     means EXP is variable.  Also the constant detection may fail for
9876     some constant expressions and in such case still falsely return
9877     zero.  */
9878
9879 static int
9880 watchpoint_exp_is_const (const struct expression *exp)
9881 {
9882   int i = exp->nelts;
9883
9884   while (i > 0)
9885     {
9886       int oplenp, argsp;
9887
9888       /* We are only interested in the descriptor of each element.  */
9889       operator_length (exp, i, &oplenp, &argsp);
9890       i -= oplenp;
9891
9892       switch (exp->elts[i].opcode)
9893         {
9894         case BINOP_ADD:
9895         case BINOP_SUB:
9896         case BINOP_MUL:
9897         case BINOP_DIV:
9898         case BINOP_REM:
9899         case BINOP_MOD:
9900         case BINOP_LSH:
9901         case BINOP_RSH:
9902         case BINOP_LOGICAL_AND:
9903         case BINOP_LOGICAL_OR:
9904         case BINOP_BITWISE_AND:
9905         case BINOP_BITWISE_IOR:
9906         case BINOP_BITWISE_XOR:
9907         case BINOP_EQUAL:
9908         case BINOP_NOTEQUAL:
9909         case BINOP_LESS:
9910         case BINOP_GTR:
9911         case BINOP_LEQ:
9912         case BINOP_GEQ:
9913         case BINOP_REPEAT:
9914         case BINOP_COMMA:
9915         case BINOP_EXP:
9916         case BINOP_MIN:
9917         case BINOP_MAX:
9918         case BINOP_INTDIV:
9919         case BINOP_CONCAT:
9920         case BINOP_IN:
9921         case BINOP_RANGE:
9922         case TERNOP_COND:
9923         case TERNOP_SLICE:
9924         case TERNOP_SLICE_COUNT:
9925
9926         case OP_LONG:
9927         case OP_DOUBLE:
9928         case OP_DECFLOAT:
9929         case OP_LAST:
9930         case OP_COMPLEX:
9931         case OP_STRING:
9932         case OP_BITSTRING:
9933         case OP_ARRAY:
9934         case OP_TYPE:
9935         case OP_NAME:
9936         case OP_OBJC_NSSTRING:
9937
9938         case UNOP_NEG:
9939         case UNOP_LOGICAL_NOT:
9940         case UNOP_COMPLEMENT:
9941         case UNOP_ADDR:
9942         case UNOP_HIGH:
9943         case UNOP_CAST:
9944           /* Unary, binary and ternary operators: We have to check
9945              their operands.  If they are constant, then so is the
9946              result of that operation.  For instance, if A and B are
9947              determined to be constants, then so is "A + B".
9948
9949              UNOP_IND is one exception to the rule above, because the
9950              value of *ADDR is not necessarily a constant, even when
9951              ADDR is.  */
9952           break;
9953
9954         case OP_VAR_VALUE:
9955           /* Check whether the associated symbol is a constant.
9956
9957              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9958              possible that a buggy compiler could mark a variable as
9959              constant even when it is not, and TYPE_CONST would return
9960              true in this case, while SYMBOL_CLASS wouldn't.
9961
9962              We also have to check for function symbols because they
9963              are always constant.  */
9964           {
9965             struct symbol *s = exp->elts[i + 2].symbol;
9966
9967             if (SYMBOL_CLASS (s) != LOC_BLOCK
9968                 && SYMBOL_CLASS (s) != LOC_CONST
9969                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
9970               return 0;
9971             break;
9972           }
9973
9974         /* The default action is to return 0 because we are using
9975            the optimistic approach here: If we don't know something,
9976            then it is not a constant.  */
9977         default:
9978           return 0;
9979         }
9980     }
9981
9982   return 1;
9983 }
9984
9985 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
9986
9987 static void
9988 dtor_watchpoint (struct breakpoint *self)
9989 {
9990   struct watchpoint *w = (struct watchpoint *) self;
9991
9992   xfree (w->cond_exp);
9993   xfree (w->exp);
9994   xfree (w->exp_string);
9995   xfree (w->exp_string_reparse);
9996   value_free (w->val);
9997
9998   base_breakpoint_ops.dtor (self);
9999 }
10000
10001 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10002
10003 static void
10004 re_set_watchpoint (struct breakpoint *b)
10005 {
10006   struct watchpoint *w = (struct watchpoint *) b;
10007
10008   /* Watchpoint can be either on expression using entirely global
10009      variables, or it can be on local variables.
10010
10011      Watchpoints of the first kind are never auto-deleted, and even
10012      persist across program restarts.  Since they can use variables
10013      from shared libraries, we need to reparse expression as libraries
10014      are loaded and unloaded.
10015
10016      Watchpoints on local variables can also change meaning as result
10017      of solib event.  For example, if a watchpoint uses both a local
10018      and a global variables in expression, it's a local watchpoint,
10019      but unloading of a shared library will make the expression
10020      invalid.  This is not a very common use case, but we still
10021      re-evaluate expression, to avoid surprises to the user.
10022
10023      Note that for local watchpoints, we re-evaluate it only if
10024      watchpoints frame id is still valid.  If it's not, it means the
10025      watchpoint is out of scope and will be deleted soon.  In fact,
10026      I'm not sure we'll ever be called in this case.
10027
10028      If a local watchpoint's frame id is still valid, then
10029      w->exp_valid_block is likewise valid, and we can safely use it.
10030
10031      Don't do anything about disabled watchpoints, since they will be
10032      reevaluated again when enabled.  */
10033   update_watchpoint (w, 1 /* reparse */);
10034 }
10035
10036 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10037
10038 static int
10039 insert_watchpoint (struct bp_location *bl)
10040 {
10041   struct watchpoint *w = (struct watchpoint *) bl->owner;
10042   int length = w->exact ? 1 : bl->length;
10043
10044   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10045                                    w->cond_exp);
10046 }
10047
10048 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10049
10050 static int
10051 remove_watchpoint (struct bp_location *bl)
10052 {
10053   struct watchpoint *w = (struct watchpoint *) bl->owner;
10054   int length = w->exact ? 1 : bl->length;
10055
10056   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10057                                    w->cond_exp);
10058 }
10059
10060 static int
10061 breakpoint_hit_watchpoint (const struct bp_location *bl,
10062                            struct address_space *aspace, CORE_ADDR bp_addr,
10063                            const struct target_waitstatus *ws)
10064 {
10065   struct breakpoint *b = bl->owner;
10066   struct watchpoint *w = (struct watchpoint *) b;
10067
10068   /* Continuable hardware watchpoints are treated as non-existent if the
10069      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10070      some data address).  Otherwise gdb won't stop on a break instruction
10071      in the code (not from a breakpoint) when a hardware watchpoint has
10072      been defined.  Also skip watchpoints which we know did not trigger
10073      (did not match the data address).  */
10074   if (is_hardware_watchpoint (b)
10075       && w->watchpoint_triggered == watch_triggered_no)
10076     return 0;
10077
10078   return 1;
10079 }
10080
10081 static void
10082 check_status_watchpoint (bpstat bs)
10083 {
10084   gdb_assert (is_watchpoint (bs->breakpoint_at));
10085
10086   bpstat_check_watchpoint (bs);
10087 }
10088
10089 /* Implement the "resources_needed" breakpoint_ops method for
10090    hardware watchpoints.  */
10091
10092 static int
10093 resources_needed_watchpoint (const struct bp_location *bl)
10094 {
10095   struct watchpoint *w = (struct watchpoint *) bl->owner;
10096   int length = w->exact? 1 : bl->length;
10097
10098   return target_region_ok_for_hw_watchpoint (bl->address, length);
10099 }
10100
10101 /* Implement the "works_in_software_mode" breakpoint_ops method for
10102    hardware watchpoints.  */
10103
10104 static int
10105 works_in_software_mode_watchpoint (const struct breakpoint *b)
10106 {
10107   /* Read and access watchpoints only work with hardware support.  */
10108   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10109 }
10110
10111 static enum print_stop_action
10112 print_it_watchpoint (bpstat bs)
10113 {
10114   struct cleanup *old_chain;
10115   struct breakpoint *b;
10116   const struct bp_location *bl;
10117   struct ui_file *stb;
10118   enum print_stop_action result;
10119   struct watchpoint *w;
10120   struct ui_out *uiout = current_uiout;
10121
10122   gdb_assert (bs->bp_location_at != NULL);
10123
10124   bl = bs->bp_location_at;
10125   b = bs->breakpoint_at;
10126   w = (struct watchpoint *) b;
10127
10128   stb = mem_fileopen ();
10129   old_chain = make_cleanup_ui_file_delete (stb);
10130
10131   switch (b->type)
10132     {
10133     case bp_watchpoint:
10134     case bp_hardware_watchpoint:
10135       annotate_watchpoint (b->number);
10136       if (ui_out_is_mi_like_p (uiout))
10137         ui_out_field_string
10138           (uiout, "reason",
10139            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10140       mention (b);
10141       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10142       ui_out_text (uiout, "\nOld value = ");
10143       watchpoint_value_print (bs->old_val, stb);
10144       ui_out_field_stream (uiout, "old", stb);
10145       ui_out_text (uiout, "\nNew value = ");
10146       watchpoint_value_print (w->val, stb);
10147       ui_out_field_stream (uiout, "new", stb);
10148       ui_out_text (uiout, "\n");
10149       /* More than one watchpoint may have been triggered.  */
10150       result = PRINT_UNKNOWN;
10151       break;
10152
10153     case bp_read_watchpoint:
10154       if (ui_out_is_mi_like_p (uiout))
10155         ui_out_field_string
10156           (uiout, "reason",
10157            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10158       mention (b);
10159       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10160       ui_out_text (uiout, "\nValue = ");
10161       watchpoint_value_print (w->val, stb);
10162       ui_out_field_stream (uiout, "value", stb);
10163       ui_out_text (uiout, "\n");
10164       result = PRINT_UNKNOWN;
10165       break;
10166
10167     case bp_access_watchpoint:
10168       if (bs->old_val != NULL)
10169         {
10170           annotate_watchpoint (b->number);
10171           if (ui_out_is_mi_like_p (uiout))
10172             ui_out_field_string
10173               (uiout, "reason",
10174                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10175           mention (b);
10176           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10177           ui_out_text (uiout, "\nOld value = ");
10178           watchpoint_value_print (bs->old_val, stb);
10179           ui_out_field_stream (uiout, "old", stb);
10180           ui_out_text (uiout, "\nNew value = ");
10181         }
10182       else
10183         {
10184           mention (b);
10185           if (ui_out_is_mi_like_p (uiout))
10186             ui_out_field_string
10187               (uiout, "reason",
10188                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10189           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10190           ui_out_text (uiout, "\nValue = ");
10191         }
10192       watchpoint_value_print (w->val, stb);
10193       ui_out_field_stream (uiout, "new", stb);
10194       ui_out_text (uiout, "\n");
10195       result = PRINT_UNKNOWN;
10196       break;
10197     default:
10198       result = PRINT_UNKNOWN;
10199     }
10200
10201   do_cleanups (old_chain);
10202   return result;
10203 }
10204
10205 /* Implement the "print_mention" breakpoint_ops method for hardware
10206    watchpoints.  */
10207
10208 static void
10209 print_mention_watchpoint (struct breakpoint *b)
10210 {
10211   struct cleanup *ui_out_chain;
10212   struct watchpoint *w = (struct watchpoint *) b;
10213   struct ui_out *uiout = current_uiout;
10214
10215   switch (b->type)
10216     {
10217     case bp_watchpoint:
10218       ui_out_text (uiout, "Watchpoint ");
10219       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10220       break;
10221     case bp_hardware_watchpoint:
10222       ui_out_text (uiout, "Hardware watchpoint ");
10223       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10224       break;
10225     case bp_read_watchpoint:
10226       ui_out_text (uiout, "Hardware read watchpoint ");
10227       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10228       break;
10229     case bp_access_watchpoint:
10230       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10231       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10232       break;
10233     default:
10234       internal_error (__FILE__, __LINE__,
10235                       _("Invalid hardware watchpoint type."));
10236     }
10237
10238   ui_out_field_int (uiout, "number", b->number);
10239   ui_out_text (uiout, ": ");
10240   ui_out_field_string (uiout, "exp", w->exp_string);
10241   do_cleanups (ui_out_chain);
10242 }
10243
10244 /* Implement the "print_recreate" breakpoint_ops method for
10245    watchpoints.  */
10246
10247 static void
10248 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10249 {
10250   struct watchpoint *w = (struct watchpoint *) b;
10251
10252   switch (b->type)
10253     {
10254     case bp_watchpoint:
10255     case bp_hardware_watchpoint:
10256       fprintf_unfiltered (fp, "watch");
10257       break;
10258     case bp_read_watchpoint:
10259       fprintf_unfiltered (fp, "rwatch");
10260       break;
10261     case bp_access_watchpoint:
10262       fprintf_unfiltered (fp, "awatch");
10263       break;
10264     default:
10265       internal_error (__FILE__, __LINE__,
10266                       _("Invalid watchpoint type."));
10267     }
10268
10269   fprintf_unfiltered (fp, " %s", w->exp_string);
10270   print_recreate_thread (b, fp);
10271 }
10272
10273 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10274
10275 static struct breakpoint_ops watchpoint_breakpoint_ops;
10276
10277 /* Implement the "insert" breakpoint_ops method for
10278    masked hardware watchpoints.  */
10279
10280 static int
10281 insert_masked_watchpoint (struct bp_location *bl)
10282 {
10283   struct watchpoint *w = (struct watchpoint *) bl->owner;
10284
10285   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10286                                         bl->watchpoint_type);
10287 }
10288
10289 /* Implement the "remove" breakpoint_ops method for
10290    masked hardware watchpoints.  */
10291
10292 static int
10293 remove_masked_watchpoint (struct bp_location *bl)
10294 {
10295   struct watchpoint *w = (struct watchpoint *) bl->owner;
10296
10297   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10298                                         bl->watchpoint_type);
10299 }
10300
10301 /* Implement the "resources_needed" breakpoint_ops method for
10302    masked hardware watchpoints.  */
10303
10304 static int
10305 resources_needed_masked_watchpoint (const struct bp_location *bl)
10306 {
10307   struct watchpoint *w = (struct watchpoint *) bl->owner;
10308
10309   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10310 }
10311
10312 /* Implement the "works_in_software_mode" breakpoint_ops method for
10313    masked hardware watchpoints.  */
10314
10315 static int
10316 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10317 {
10318   return 0;
10319 }
10320
10321 /* Implement the "print_it" breakpoint_ops method for
10322    masked hardware watchpoints.  */
10323
10324 static enum print_stop_action
10325 print_it_masked_watchpoint (bpstat bs)
10326 {
10327   struct breakpoint *b = bs->breakpoint_at;
10328   struct ui_out *uiout = current_uiout;
10329
10330   /* Masked watchpoints have only one location.  */
10331   gdb_assert (b->loc && b->loc->next == NULL);
10332
10333   switch (b->type)
10334     {
10335     case bp_hardware_watchpoint:
10336       annotate_watchpoint (b->number);
10337       if (ui_out_is_mi_like_p (uiout))
10338         ui_out_field_string
10339           (uiout, "reason",
10340            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10341       break;
10342
10343     case bp_read_watchpoint:
10344       if (ui_out_is_mi_like_p (uiout))
10345         ui_out_field_string
10346           (uiout, "reason",
10347            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10348       break;
10349
10350     case bp_access_watchpoint:
10351       if (ui_out_is_mi_like_p (uiout))
10352         ui_out_field_string
10353           (uiout, "reason",
10354            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10355       break;
10356     default:
10357       internal_error (__FILE__, __LINE__,
10358                       _("Invalid hardware watchpoint type."));
10359     }
10360
10361   mention (b);
10362   ui_out_text (uiout, _("\n\
10363 Check the underlying instruction at PC for the memory\n\
10364 address and value which triggered this watchpoint.\n"));
10365   ui_out_text (uiout, "\n");
10366
10367   /* More than one watchpoint may have been triggered.  */
10368   return PRINT_UNKNOWN;
10369 }
10370
10371 /* Implement the "print_one_detail" breakpoint_ops method for
10372    masked hardware watchpoints.  */
10373
10374 static void
10375 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10376                                     struct ui_out *uiout)
10377 {
10378   struct watchpoint *w = (struct watchpoint *) b;
10379
10380   /* Masked watchpoints have only one location.  */
10381   gdb_assert (b->loc && b->loc->next == NULL);
10382
10383   ui_out_text (uiout, "\tmask ");
10384   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10385   ui_out_text (uiout, "\n");
10386 }
10387
10388 /* Implement the "print_mention" breakpoint_ops method for
10389    masked hardware watchpoints.  */
10390
10391 static void
10392 print_mention_masked_watchpoint (struct breakpoint *b)
10393 {
10394   struct watchpoint *w = (struct watchpoint *) b;
10395   struct ui_out *uiout = current_uiout;
10396   struct cleanup *ui_out_chain;
10397
10398   switch (b->type)
10399     {
10400     case bp_hardware_watchpoint:
10401       ui_out_text (uiout, "Masked hardware watchpoint ");
10402       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10403       break;
10404     case bp_read_watchpoint:
10405       ui_out_text (uiout, "Masked hardware read watchpoint ");
10406       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10407       break;
10408     case bp_access_watchpoint:
10409       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10410       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10411       break;
10412     default:
10413       internal_error (__FILE__, __LINE__,
10414                       _("Invalid hardware watchpoint type."));
10415     }
10416
10417   ui_out_field_int (uiout, "number", b->number);
10418   ui_out_text (uiout, ": ");
10419   ui_out_field_string (uiout, "exp", w->exp_string);
10420   do_cleanups (ui_out_chain);
10421 }
10422
10423 /* Implement the "print_recreate" breakpoint_ops method for
10424    masked hardware watchpoints.  */
10425
10426 static void
10427 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10428 {
10429   struct watchpoint *w = (struct watchpoint *) b;
10430   char tmp[40];
10431
10432   switch (b->type)
10433     {
10434     case bp_hardware_watchpoint:
10435       fprintf_unfiltered (fp, "watch");
10436       break;
10437     case bp_read_watchpoint:
10438       fprintf_unfiltered (fp, "rwatch");
10439       break;
10440     case bp_access_watchpoint:
10441       fprintf_unfiltered (fp, "awatch");
10442       break;
10443     default:
10444       internal_error (__FILE__, __LINE__,
10445                       _("Invalid hardware watchpoint type."));
10446     }
10447
10448   sprintf_vma (tmp, w->hw_wp_mask);
10449   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10450   print_recreate_thread (b, fp);
10451 }
10452
10453 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10454
10455 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10456
10457 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10458
10459 static int
10460 is_masked_watchpoint (const struct breakpoint *b)
10461 {
10462   return b->ops == &masked_watchpoint_breakpoint_ops;
10463 }
10464
10465 /* accessflag:  hw_write:  watch write, 
10466                 hw_read:   watch read, 
10467                 hw_access: watch access (read or write) */
10468 static void
10469 watch_command_1 (char *arg, int accessflag, int from_tty,
10470                  int just_location, int internal)
10471 {
10472   volatile struct gdb_exception e;
10473   struct breakpoint *b, *scope_breakpoint = NULL;
10474   struct expression *exp;
10475   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10476   struct value *val, *mark, *result;
10477   struct frame_info *frame;
10478   char *exp_start = NULL;
10479   char *exp_end = NULL;
10480   char *tok, *end_tok;
10481   int toklen = -1;
10482   char *cond_start = NULL;
10483   char *cond_end = NULL;
10484   enum bptype bp_type;
10485   int thread = -1;
10486   int pc = 0;
10487   /* Flag to indicate whether we are going to use masks for
10488      the hardware watchpoint.  */
10489   int use_mask = 0;
10490   CORE_ADDR mask = 0;
10491   struct watchpoint *w;
10492
10493   /* Make sure that we actually have parameters to parse.  */
10494   if (arg != NULL && arg[0] != '\0')
10495     {
10496       char *value_start;
10497
10498       /* Look for "parameter value" pairs at the end
10499          of the arguments string.  */
10500       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
10501         {
10502           /* Skip whitespace at the end of the argument list.  */
10503           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10504             tok--;
10505
10506           /* Find the beginning of the last token.
10507              This is the value of the parameter.  */
10508           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10509             tok--;
10510           value_start = tok + 1;
10511
10512           /* Skip whitespace.  */
10513           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10514             tok--;
10515
10516           end_tok = tok;
10517
10518           /* Find the beginning of the second to last token.
10519              This is the parameter itself.  */
10520           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10521             tok--;
10522           tok++;
10523           toklen = end_tok - tok + 1;
10524
10525           if (toklen == 6 && !strncmp (tok, "thread", 6))
10526             {
10527               /* At this point we've found a "thread" token, which means
10528                  the user is trying to set a watchpoint that triggers
10529                  only in a specific thread.  */
10530               char *endp;
10531
10532               if (thread != -1)
10533                 error(_("You can specify only one thread."));
10534
10535               /* Extract the thread ID from the next token.  */
10536               thread = strtol (value_start, &endp, 0);
10537
10538               /* Check if the user provided a valid numeric value for the
10539                  thread ID.  */
10540               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10541                 error (_("Invalid thread ID specification %s."), value_start);
10542
10543               /* Check if the thread actually exists.  */
10544               if (!valid_thread_id (thread))
10545                 error (_("Unknown thread %d."), thread);
10546             }
10547           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10548             {
10549               /* We've found a "mask" token, which means the user wants to
10550                  create a hardware watchpoint that is going to have the mask
10551                  facility.  */
10552               struct value *mask_value, *mark;
10553
10554               if (use_mask)
10555                 error(_("You can specify only one mask."));
10556
10557               use_mask = just_location = 1;
10558
10559               mark = value_mark ();
10560               mask_value = parse_to_comma_and_eval (&value_start);
10561               mask = value_as_address (mask_value);
10562               value_free_to_mark (mark);
10563             }
10564           else
10565             /* We didn't recognize what we found.  We should stop here.  */
10566             break;
10567
10568           /* Truncate the string and get rid of the "parameter value" pair before
10569              the arguments string is parsed by the parse_exp_1 function.  */
10570           *tok = '\0';
10571         }
10572     }
10573
10574   /* Parse the rest of the arguments.  */
10575   innermost_block = NULL;
10576   exp_start = arg;
10577   exp = parse_exp_1 (&arg, 0, 0, 0);
10578   exp_end = arg;
10579   /* Remove trailing whitespace from the expression before saving it.
10580      This makes the eventual display of the expression string a bit
10581      prettier.  */
10582   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10583     --exp_end;
10584
10585   /* Checking if the expression is not constant.  */
10586   if (watchpoint_exp_is_const (exp))
10587     {
10588       int len;
10589
10590       len = exp_end - exp_start;
10591       while (len > 0 && isspace (exp_start[len - 1]))
10592         len--;
10593       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10594     }
10595
10596   exp_valid_block = innermost_block;
10597   mark = value_mark ();
10598   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10599
10600   if (just_location)
10601     {
10602       int ret;
10603
10604       exp_valid_block = NULL;
10605       val = value_addr (result);
10606       release_value (val);
10607       value_free_to_mark (mark);
10608
10609       if (use_mask)
10610         {
10611           ret = target_masked_watch_num_registers (value_as_address (val),
10612                                                    mask);
10613           if (ret == -1)
10614             error (_("This target does not support masked watchpoints."));
10615           else if (ret == -2)
10616             error (_("Invalid mask or memory region."));
10617         }
10618     }
10619   else if (val != NULL)
10620     release_value (val);
10621
10622   tok = skip_spaces (arg);
10623   end_tok = skip_to_space (tok);
10624
10625   toklen = end_tok - tok;
10626   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10627     {
10628       struct expression *cond;
10629
10630       innermost_block = NULL;
10631       tok = cond_start = end_tok + 1;
10632       cond = parse_exp_1 (&tok, 0, 0, 0);
10633
10634       /* The watchpoint expression may not be local, but the condition
10635          may still be.  E.g.: `watch global if local > 0'.  */
10636       cond_exp_valid_block = innermost_block;
10637
10638       xfree (cond);
10639       cond_end = tok;
10640     }
10641   if (*tok)
10642     error (_("Junk at end of command."));
10643
10644   if (accessflag == hw_read)
10645     bp_type = bp_read_watchpoint;
10646   else if (accessflag == hw_access)
10647     bp_type = bp_access_watchpoint;
10648   else
10649     bp_type = bp_hardware_watchpoint;
10650
10651   frame = block_innermost_frame (exp_valid_block);
10652
10653   /* If the expression is "local", then set up a "watchpoint scope"
10654      breakpoint at the point where we've left the scope of the watchpoint
10655      expression.  Create the scope breakpoint before the watchpoint, so
10656      that we will encounter it first in bpstat_stop_status.  */
10657   if (exp_valid_block && frame)
10658     {
10659       if (frame_id_p (frame_unwind_caller_id (frame)))
10660         {
10661           scope_breakpoint
10662             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
10663                                           frame_unwind_caller_pc (frame),
10664                                           bp_watchpoint_scope,
10665                                           &momentary_breakpoint_ops);
10666
10667           scope_breakpoint->enable_state = bp_enabled;
10668
10669           /* Automatically delete the breakpoint when it hits.  */
10670           scope_breakpoint->disposition = disp_del;
10671
10672           /* Only break in the proper frame (help with recursion).  */
10673           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
10674
10675           /* Set the address at which we will stop.  */
10676           scope_breakpoint->loc->gdbarch
10677             = frame_unwind_caller_arch (frame);
10678           scope_breakpoint->loc->requested_address
10679             = frame_unwind_caller_pc (frame);
10680           scope_breakpoint->loc->address
10681             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10682                                          scope_breakpoint->loc->requested_address,
10683                                          scope_breakpoint->type);
10684         }
10685     }
10686
10687   /* Now set up the breakpoint.  */
10688
10689   w = XCNEW (struct watchpoint);
10690   b = &w->base;
10691   if (use_mask)
10692     init_raw_breakpoint_without_location (b, NULL, bp_type,
10693                                           &masked_watchpoint_breakpoint_ops);
10694   else
10695     init_raw_breakpoint_without_location (b, NULL, bp_type,
10696                                           &watchpoint_breakpoint_ops);
10697   b->thread = thread;
10698   b->disposition = disp_donttouch;
10699   b->pspace = current_program_space;
10700   w->exp = exp;
10701   w->exp_valid_block = exp_valid_block;
10702   w->cond_exp_valid_block = cond_exp_valid_block;
10703   if (just_location)
10704     {
10705       struct type *t = value_type (val);
10706       CORE_ADDR addr = value_as_address (val);
10707       char *name;
10708
10709       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
10710       name = type_to_string (t);
10711
10712       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
10713                                           core_addr_to_string (addr));
10714       xfree (name);
10715
10716       w->exp_string = xstrprintf ("-location %.*s",
10717                                   (int) (exp_end - exp_start), exp_start);
10718
10719       /* The above expression is in C.  */
10720       b->language = language_c;
10721     }
10722   else
10723     w->exp_string = savestring (exp_start, exp_end - exp_start);
10724
10725   if (use_mask)
10726     {
10727       w->hw_wp_mask = mask;
10728     }
10729   else
10730     {
10731       w->val = val;
10732       w->val_valid = 1;
10733     }
10734
10735   if (cond_start)
10736     b->cond_string = savestring (cond_start, cond_end - cond_start);
10737   else
10738     b->cond_string = 0;
10739
10740   if (frame)
10741     {
10742       w->watchpoint_frame = get_frame_id (frame);
10743       w->watchpoint_thread = inferior_ptid;
10744     }
10745   else
10746     {
10747       w->watchpoint_frame = null_frame_id;
10748       w->watchpoint_thread = null_ptid;
10749     }
10750
10751   if (scope_breakpoint != NULL)
10752     {
10753       /* The scope breakpoint is related to the watchpoint.  We will
10754          need to act on them together.  */
10755       b->related_breakpoint = scope_breakpoint;
10756       scope_breakpoint->related_breakpoint = b;
10757     }
10758
10759   if (!just_location)
10760     value_free_to_mark (mark);
10761
10762   TRY_CATCH (e, RETURN_MASK_ALL)
10763     {
10764       /* Finally update the new watchpoint.  This creates the locations
10765          that should be inserted.  */
10766       update_watchpoint (w, 1);
10767     }
10768   if (e.reason < 0)
10769     {
10770       delete_breakpoint (b);
10771       throw_exception (e);
10772     }
10773
10774   install_breakpoint (internal, b, 1);
10775 }
10776
10777 /* Return count of debug registers needed to watch the given expression.
10778    If the watchpoint cannot be handled in hardware return zero.  */
10779
10780 static int
10781 can_use_hardware_watchpoint (struct value *v)
10782 {
10783   int found_memory_cnt = 0;
10784   struct value *head = v;
10785
10786   /* Did the user specifically forbid us to use hardware watchpoints? */
10787   if (!can_use_hw_watchpoints)
10788     return 0;
10789
10790   /* Make sure that the value of the expression depends only upon
10791      memory contents, and values computed from them within GDB.  If we
10792      find any register references or function calls, we can't use a
10793      hardware watchpoint.
10794
10795      The idea here is that evaluating an expression generates a series
10796      of values, one holding the value of every subexpression.  (The
10797      expression a*b+c has five subexpressions: a, b, a*b, c, and
10798      a*b+c.)  GDB's values hold almost enough information to establish
10799      the criteria given above --- they identify memory lvalues,
10800      register lvalues, computed values, etcetera.  So we can evaluate
10801      the expression, and then scan the chain of values that leaves
10802      behind to decide whether we can detect any possible change to the
10803      expression's final value using only hardware watchpoints.
10804
10805      However, I don't think that the values returned by inferior
10806      function calls are special in any way.  So this function may not
10807      notice that an expression involving an inferior function call
10808      can't be watched with hardware watchpoints.  FIXME.  */
10809   for (; v; v = value_next (v))
10810     {
10811       if (VALUE_LVAL (v) == lval_memory)
10812         {
10813           if (v != head && value_lazy (v))
10814             /* A lazy memory lvalue in the chain is one that GDB never
10815                needed to fetch; we either just used its address (e.g.,
10816                `a' in `a.b') or we never needed it at all (e.g., `a'
10817                in `a,b').  This doesn't apply to HEAD; if that is
10818                lazy then it was not readable, but watch it anyway.  */
10819             ;
10820           else
10821             {
10822               /* Ahh, memory we actually used!  Check if we can cover
10823                  it with hardware watchpoints.  */
10824               struct type *vtype = check_typedef (value_type (v));
10825
10826               /* We only watch structs and arrays if user asked for it
10827                  explicitly, never if they just happen to appear in a
10828                  middle of some value chain.  */
10829               if (v == head
10830                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10831                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10832                 {
10833                   CORE_ADDR vaddr = value_address (v);
10834                   int len;
10835                   int num_regs;
10836
10837                   len = (target_exact_watchpoints
10838                          && is_scalar_type_recursive (vtype))?
10839                     1 : TYPE_LENGTH (value_type (v));
10840
10841                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10842                   if (!num_regs)
10843                     return 0;
10844                   else
10845                     found_memory_cnt += num_regs;
10846                 }
10847             }
10848         }
10849       else if (VALUE_LVAL (v) != not_lval
10850                && deprecated_value_modifiable (v) == 0)
10851         return 0;       /* These are values from the history (e.g., $1).  */
10852       else if (VALUE_LVAL (v) == lval_register)
10853         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10854     }
10855
10856   /* The expression itself looks suitable for using a hardware
10857      watchpoint, but give the target machine a chance to reject it.  */
10858   return found_memory_cnt;
10859 }
10860
10861 void
10862 watch_command_wrapper (char *arg, int from_tty, int internal)
10863 {
10864   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10865 }
10866
10867 /* A helper function that looks for an argument at the start of a
10868    string.  The argument must also either be at the end of the string,
10869    or be followed by whitespace.  Returns 1 if it finds the argument,
10870    0 otherwise.  If the argument is found, it updates *STR.  */
10871
10872 static int
10873 check_for_argument (char **str, char *arg, int arg_len)
10874 {
10875   if (strncmp (*str, arg, arg_len) == 0
10876       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
10877     {
10878       *str += arg_len;
10879       return 1;
10880     }
10881   return 0;
10882 }
10883
10884 /* A helper function that looks for the "-location" argument and then
10885    calls watch_command_1.  */
10886
10887 static void
10888 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
10889 {
10890   int just_location = 0;
10891
10892   if (arg
10893       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10894           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10895     {
10896       arg = skip_spaces (arg);
10897       just_location = 1;
10898     }
10899
10900   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10901 }
10902
10903 static void
10904 watch_command (char *arg, int from_tty)
10905 {
10906   watch_maybe_just_location (arg, hw_write, from_tty);
10907 }
10908
10909 void
10910 rwatch_command_wrapper (char *arg, int from_tty, int internal)
10911 {
10912   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10913 }
10914
10915 static void
10916 rwatch_command (char *arg, int from_tty)
10917 {
10918   watch_maybe_just_location (arg, hw_read, from_tty);
10919 }
10920
10921 void
10922 awatch_command_wrapper (char *arg, int from_tty, int internal)
10923 {
10924   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10925 }
10926
10927 static void
10928 awatch_command (char *arg, int from_tty)
10929 {
10930   watch_maybe_just_location (arg, hw_access, from_tty);
10931 }
10932 \f
10933
10934 /* Helper routines for the until_command routine in infcmd.c.  Here
10935    because it uses the mechanisms of breakpoints.  */
10936
10937 struct until_break_command_continuation_args
10938 {
10939   struct breakpoint *breakpoint;
10940   struct breakpoint *breakpoint2;
10941   int thread_num;
10942 };
10943
10944 /* This function is called by fetch_inferior_event via the
10945    cmd_continuation pointer, to complete the until command.  It takes
10946    care of cleaning up the temporary breakpoints set up by the until
10947    command.  */
10948 static void
10949 until_break_command_continuation (void *arg, int err)
10950 {
10951   struct until_break_command_continuation_args *a = arg;
10952
10953   delete_breakpoint (a->breakpoint);
10954   if (a->breakpoint2)
10955     delete_breakpoint (a->breakpoint2);
10956   delete_longjmp_breakpoint (a->thread_num);
10957 }
10958
10959 void
10960 until_break_command (char *arg, int from_tty, int anywhere)
10961 {
10962   struct symtabs_and_lines sals;
10963   struct symtab_and_line sal;
10964   struct frame_info *frame;
10965   struct gdbarch *frame_gdbarch;
10966   struct frame_id stack_frame_id;
10967   struct frame_id caller_frame_id;
10968   struct breakpoint *breakpoint;
10969   struct breakpoint *breakpoint2 = NULL;
10970   struct cleanup *old_chain;
10971   int thread;
10972   struct thread_info *tp;
10973
10974   clear_proceed_status ();
10975
10976   /* Set a breakpoint where the user wants it and at return from
10977      this function.  */
10978
10979   if (last_displayed_sal_is_valid ())
10980     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10981                           get_last_displayed_symtab (),
10982                           get_last_displayed_line ());
10983   else
10984     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10985                           (struct symtab *) NULL, 0);
10986
10987   if (sals.nelts != 1)
10988     error (_("Couldn't get information on specified line."));
10989
10990   sal = sals.sals[0];
10991   xfree (sals.sals);    /* malloc'd, so freed.  */
10992
10993   if (*arg)
10994     error (_("Junk at end of arguments."));
10995
10996   resolve_sal_pc (&sal);
10997
10998   tp = inferior_thread ();
10999   thread = tp->num;
11000
11001   old_chain = make_cleanup (null_cleanup, NULL);
11002
11003   /* Note linespec handling above invalidates the frame chain.
11004      Installing a breakpoint also invalidates the frame chain (as it
11005      may need to switch threads), so do any frame handling before
11006      that.  */
11007
11008   frame = get_selected_frame (NULL);
11009   frame_gdbarch = get_frame_arch (frame);
11010   stack_frame_id = get_stack_frame_id (frame);
11011   caller_frame_id = frame_unwind_caller_id (frame);
11012
11013   /* Keep within the current frame, or in frames called by the current
11014      one.  */
11015
11016   if (frame_id_p (caller_frame_id))
11017     {
11018       struct symtab_and_line sal2;
11019
11020       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11021       sal2.pc = frame_unwind_caller_pc (frame);
11022       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11023                                               sal2,
11024                                               caller_frame_id,
11025                                               bp_until);
11026       make_cleanup_delete_breakpoint (breakpoint2);
11027
11028       set_longjmp_breakpoint (tp, caller_frame_id);
11029       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11030     }
11031
11032   /* set_momentary_breakpoint could invalidate FRAME.  */
11033   frame = NULL;
11034
11035   if (anywhere)
11036     /* If the user told us to continue until a specified location,
11037        we don't specify a frame at which we need to stop.  */
11038     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11039                                            null_frame_id, bp_until);
11040   else
11041     /* Otherwise, specify the selected frame, because we want to stop
11042        only at the very same frame.  */
11043     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11044                                            stack_frame_id, bp_until);
11045   make_cleanup_delete_breakpoint (breakpoint);
11046
11047   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11048
11049   /* If we are running asynchronously, and proceed call above has
11050      actually managed to start the target, arrange for breakpoints to
11051      be deleted when the target stops.  Otherwise, we're already
11052      stopped and delete breakpoints via cleanup chain.  */
11053
11054   if (target_can_async_p () && is_running (inferior_ptid))
11055     {
11056       struct until_break_command_continuation_args *args;
11057       args = xmalloc (sizeof (*args));
11058
11059       args->breakpoint = breakpoint;
11060       args->breakpoint2 = breakpoint2;
11061       args->thread_num = thread;
11062
11063       discard_cleanups (old_chain);
11064       add_continuation (inferior_thread (),
11065                         until_break_command_continuation, args,
11066                         xfree);
11067     }
11068   else
11069     do_cleanups (old_chain);
11070 }
11071
11072 /* This function attempts to parse an optional "if <cond>" clause
11073    from the arg string.  If one is not found, it returns NULL.
11074
11075    Else, it returns a pointer to the condition string.  (It does not
11076    attempt to evaluate the string against a particular block.)  And,
11077    it updates arg to point to the first character following the parsed
11078    if clause in the arg string.  */
11079
11080 static char *
11081 ep_parse_optional_if_clause (char **arg)
11082 {
11083   char *cond_string;
11084
11085   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11086     return NULL;
11087
11088   /* Skip the "if" keyword.  */
11089   (*arg) += 2;
11090
11091   /* Skip any extra leading whitespace, and record the start of the
11092      condition string.  */
11093   *arg = skip_spaces (*arg);
11094   cond_string = *arg;
11095
11096   /* Assume that the condition occupies the remainder of the arg
11097      string.  */
11098   (*arg) += strlen (cond_string);
11099
11100   return cond_string;
11101 }
11102
11103 /* Commands to deal with catching events, such as signals, exceptions,
11104    process start/exit, etc.  */
11105
11106 typedef enum
11107 {
11108   catch_fork_temporary, catch_vfork_temporary,
11109   catch_fork_permanent, catch_vfork_permanent
11110 }
11111 catch_fork_kind;
11112
11113 static void
11114 catch_fork_command_1 (char *arg, int from_tty, 
11115                       struct cmd_list_element *command)
11116 {
11117   struct gdbarch *gdbarch = get_current_arch ();
11118   char *cond_string = NULL;
11119   catch_fork_kind fork_kind;
11120   int tempflag;
11121
11122   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11123   tempflag = (fork_kind == catch_fork_temporary
11124               || fork_kind == catch_vfork_temporary);
11125
11126   if (!arg)
11127     arg = "";
11128   arg = skip_spaces (arg);
11129
11130   /* The allowed syntax is:
11131      catch [v]fork
11132      catch [v]fork if <cond>
11133
11134      First, check if there's an if clause.  */
11135   cond_string = ep_parse_optional_if_clause (&arg);
11136
11137   if ((*arg != '\0') && !isspace (*arg))
11138     error (_("Junk at end of arguments."));
11139
11140   /* If this target supports it, create a fork or vfork catchpoint
11141      and enable reporting of such events.  */
11142   switch (fork_kind)
11143     {
11144     case catch_fork_temporary:
11145     case catch_fork_permanent:
11146       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11147                                           &catch_fork_breakpoint_ops);
11148       break;
11149     case catch_vfork_temporary:
11150     case catch_vfork_permanent:
11151       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11152                                           &catch_vfork_breakpoint_ops);
11153       break;
11154     default:
11155       error (_("unsupported or unknown fork kind; cannot catch it"));
11156       break;
11157     }
11158 }
11159
11160 static void
11161 catch_exec_command_1 (char *arg, int from_tty, 
11162                       struct cmd_list_element *command)
11163 {
11164   struct exec_catchpoint *c;
11165   struct gdbarch *gdbarch = get_current_arch ();
11166   int tempflag;
11167   char *cond_string = NULL;
11168
11169   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11170
11171   if (!arg)
11172     arg = "";
11173   arg = skip_spaces (arg);
11174
11175   /* The allowed syntax is:
11176      catch exec
11177      catch exec if <cond>
11178
11179      First, check if there's an if clause.  */
11180   cond_string = ep_parse_optional_if_clause (&arg);
11181
11182   if ((*arg != '\0') && !isspace (*arg))
11183     error (_("Junk at end of arguments."));
11184
11185   c = XNEW (struct exec_catchpoint);
11186   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11187                    &catch_exec_breakpoint_ops);
11188   c->exec_pathname = NULL;
11189
11190   install_breakpoint (0, &c->base, 1);
11191 }
11192
11193 static enum print_stop_action
11194 print_it_exception_catchpoint (bpstat bs)
11195 {
11196   struct ui_out *uiout = current_uiout;
11197   struct breakpoint *b = bs->breakpoint_at;
11198   int bp_temp, bp_throw;
11199
11200   annotate_catchpoint (b->number);
11201
11202   bp_throw = strstr (b->addr_string, "throw") != NULL;
11203   if (b->loc->address != b->loc->requested_address)
11204     breakpoint_adjustment_warning (b->loc->requested_address,
11205                                    b->loc->address,
11206                                    b->number, 1);
11207   bp_temp = b->disposition == disp_del;
11208   ui_out_text (uiout, 
11209                bp_temp ? "Temporary catchpoint "
11210                        : "Catchpoint ");
11211   if (!ui_out_is_mi_like_p (uiout))
11212     ui_out_field_int (uiout, "bkptno", b->number);
11213   ui_out_text (uiout,
11214                bp_throw ? " (exception thrown), "
11215                         : " (exception caught), ");
11216   if (ui_out_is_mi_like_p (uiout))
11217     {
11218       ui_out_field_string (uiout, "reason", 
11219                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11220       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11221       ui_out_field_int (uiout, "bkptno", b->number);
11222     }
11223   return PRINT_SRC_AND_LOC;
11224 }
11225
11226 static void
11227 print_one_exception_catchpoint (struct breakpoint *b, 
11228                                 struct bp_location **last_loc)
11229 {
11230   struct value_print_options opts;
11231   struct ui_out *uiout = current_uiout;
11232
11233   get_user_print_options (&opts);
11234   if (opts.addressprint)
11235     {
11236       annotate_field (4);
11237       if (b->loc == NULL || b->loc->shlib_disabled)
11238         ui_out_field_string (uiout, "addr", "<PENDING>");
11239       else
11240         ui_out_field_core_addr (uiout, "addr",
11241                                 b->loc->gdbarch, b->loc->address);
11242     }
11243   annotate_field (5);
11244   if (b->loc)
11245     *last_loc = b->loc;
11246   if (strstr (b->addr_string, "throw") != NULL)
11247     ui_out_field_string (uiout, "what", "exception throw");
11248   else
11249     ui_out_field_string (uiout, "what", "exception catch");
11250 }
11251
11252 static void
11253 print_mention_exception_catchpoint (struct breakpoint *b)
11254 {
11255   struct ui_out *uiout = current_uiout;
11256   int bp_temp;
11257   int bp_throw;
11258
11259   bp_temp = b->disposition == disp_del;
11260   bp_throw = strstr (b->addr_string, "throw") != NULL;
11261   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
11262                               : _("Catchpoint "));
11263   ui_out_field_int (uiout, "bkptno", b->number);
11264   ui_out_text (uiout, bp_throw ? _(" (throw)")
11265                                : _(" (catch)"));
11266 }
11267
11268 /* Implement the "print_recreate" breakpoint_ops method for throw and
11269    catch catchpoints.  */
11270
11271 static void
11272 print_recreate_exception_catchpoint (struct breakpoint *b, 
11273                                      struct ui_file *fp)
11274 {
11275   int bp_temp;
11276   int bp_throw;
11277
11278   bp_temp = b->disposition == disp_del;
11279   bp_throw = strstr (b->addr_string, "throw") != NULL;
11280   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
11281   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
11282   print_recreate_thread (b, fp);
11283 }
11284
11285 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
11286
11287 static int
11288 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
11289                           enum exception_event_kind ex_event, int from_tty)
11290 {
11291   char *trigger_func_name;
11292  
11293   if (ex_event == EX_EVENT_CATCH)
11294     trigger_func_name = "__cxa_begin_catch";
11295   else
11296     trigger_func_name = "__cxa_throw";
11297
11298   create_breakpoint (get_current_arch (),
11299                      trigger_func_name, cond_string, -1, NULL,
11300                      0 /* condition and thread are valid.  */,
11301                      tempflag, bp_breakpoint,
11302                      0,
11303                      AUTO_BOOLEAN_TRUE /* pending */,
11304                      &gnu_v3_exception_catchpoint_ops, from_tty,
11305                      1 /* enabled */,
11306                      0 /* internal */,
11307                      0);
11308
11309   return 1;
11310 }
11311
11312 /* Deal with "catch catch" and "catch throw" commands.  */
11313
11314 static void
11315 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
11316                            int tempflag, int from_tty)
11317 {
11318   char *cond_string = NULL;
11319
11320   if (!arg)
11321     arg = "";
11322   arg = skip_spaces (arg);
11323
11324   cond_string = ep_parse_optional_if_clause (&arg);
11325
11326   if ((*arg != '\0') && !isspace (*arg))
11327     error (_("Junk at end of arguments."));
11328
11329   if (ex_event != EX_EVENT_THROW
11330       && ex_event != EX_EVENT_CATCH)
11331     error (_("Unsupported or unknown exception event; cannot catch it"));
11332
11333   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
11334     return;
11335
11336   warning (_("Unsupported with this platform/compiler combination."));
11337 }
11338
11339 /* Implementation of "catch catch" command.  */
11340
11341 static void
11342 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
11343 {
11344   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11345
11346   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
11347 }
11348
11349 /* Implementation of "catch throw" command.  */
11350
11351 static void
11352 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
11353 {
11354   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11355
11356   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
11357 }
11358
11359 void
11360 init_ada_exception_breakpoint (struct breakpoint *b,
11361                                struct gdbarch *gdbarch,
11362                                struct symtab_and_line sal,
11363                                char *addr_string,
11364                                const struct breakpoint_ops *ops,
11365                                int tempflag,
11366                                int from_tty)
11367 {
11368   if (from_tty)
11369     {
11370       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11371       if (!loc_gdbarch)
11372         loc_gdbarch = gdbarch;
11373
11374       describe_other_breakpoints (loc_gdbarch,
11375                                   sal.pspace, sal.pc, sal.section, -1);
11376       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11377          version for exception catchpoints, because two catchpoints
11378          used for different exception names will use the same address.
11379          In this case, a "breakpoint ... also set at..." warning is
11380          unproductive.  Besides, the warning phrasing is also a bit
11381          inappropriate, we should use the word catchpoint, and tell
11382          the user what type of catchpoint it is.  The above is good
11383          enough for now, though.  */
11384     }
11385
11386   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11387
11388   b->enable_state = bp_enabled;
11389   b->disposition = tempflag ? disp_del : disp_donttouch;
11390   b->addr_string = addr_string;
11391   b->language = language_ada;
11392 }
11393
11394 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11395    filter list, or NULL if no filtering is required.  */
11396 static VEC(int) *
11397 catch_syscall_split_args (char *arg)
11398 {
11399   VEC(int) *result = NULL;
11400   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11401
11402   while (*arg != '\0')
11403     {
11404       int i, syscall_number;
11405       char *endptr;
11406       char cur_name[128];
11407       struct syscall s;
11408
11409       /* Skip whitespace.  */
11410       while (isspace (*arg))
11411         arg++;
11412
11413       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11414         cur_name[i] = arg[i];
11415       cur_name[i] = '\0';
11416       arg += i;
11417
11418       /* Check if the user provided a syscall name or a number.  */
11419       syscall_number = (int) strtol (cur_name, &endptr, 0);
11420       if (*endptr == '\0')
11421         get_syscall_by_number (syscall_number, &s);
11422       else
11423         {
11424           /* We have a name.  Let's check if it's valid and convert it
11425              to a number.  */
11426           get_syscall_by_name (cur_name, &s);
11427
11428           if (s.number == UNKNOWN_SYSCALL)
11429             /* Here we have to issue an error instead of a warning,
11430                because GDB cannot do anything useful if there's no
11431                syscall number to be caught.  */
11432             error (_("Unknown syscall name '%s'."), cur_name);
11433         }
11434
11435       /* Ok, it's valid.  */
11436       VEC_safe_push (int, result, s.number);
11437     }
11438
11439   discard_cleanups (cleanup);
11440   return result;
11441 }
11442
11443 /* Implement the "catch syscall" command.  */
11444
11445 static void
11446 catch_syscall_command_1 (char *arg, int from_tty, 
11447                          struct cmd_list_element *command)
11448 {
11449   int tempflag;
11450   VEC(int) *filter;
11451   struct syscall s;
11452   struct gdbarch *gdbarch = get_current_arch ();
11453
11454   /* Checking if the feature if supported.  */
11455   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11456     error (_("The feature 'catch syscall' is not supported on \
11457 this architecture yet."));
11458
11459   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11460
11461   arg = skip_spaces (arg);
11462
11463   /* We need to do this first "dummy" translation in order
11464      to get the syscall XML file loaded or, most important,
11465      to display a warning to the user if there's no XML file
11466      for his/her architecture.  */
11467   get_syscall_by_number (0, &s);
11468
11469   /* The allowed syntax is:
11470      catch syscall
11471      catch syscall <name | number> [<name | number> ... <name | number>]
11472
11473      Let's check if there's a syscall name.  */
11474
11475   if (arg != NULL)
11476     filter = catch_syscall_split_args (arg);
11477   else
11478     filter = NULL;
11479
11480   create_syscall_event_catchpoint (tempflag, filter,
11481                                    &catch_syscall_breakpoint_ops);
11482 }
11483
11484 static void
11485 catch_command (char *arg, int from_tty)
11486 {
11487   error (_("Catch requires an event name."));
11488 }
11489 \f
11490
11491 static void
11492 tcatch_command (char *arg, int from_tty)
11493 {
11494   error (_("Catch requires an event name."));
11495 }
11496
11497 /* A qsort comparison function that sorts breakpoints in order.  */
11498
11499 static int
11500 compare_breakpoints (const void *a, const void *b)
11501 {
11502   const breakpoint_p *ba = a;
11503   uintptr_t ua = (uintptr_t) *ba;
11504   const breakpoint_p *bb = b;
11505   uintptr_t ub = (uintptr_t) *bb;
11506
11507   if ((*ba)->number < (*bb)->number)
11508     return -1;
11509   else if ((*ba)->number > (*bb)->number)
11510     return 1;
11511
11512   /* Now sort by address, in case we see, e..g, two breakpoints with
11513      the number 0.  */
11514   if (ua < ub)
11515     return -1;
11516   return ub > ub ? 1 : 0;
11517 }
11518
11519 /* Delete breakpoints by address or line.  */
11520
11521 static void
11522 clear_command (char *arg, int from_tty)
11523 {
11524   struct breakpoint *b, *prev;
11525   VEC(breakpoint_p) *found = 0;
11526   int ix;
11527   int default_match;
11528   struct symtabs_and_lines sals;
11529   struct symtab_and_line sal;
11530   int i;
11531   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11532
11533   if (arg)
11534     {
11535       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
11536                                      | DECODE_LINE_LIST_MODE));
11537       default_match = 0;
11538     }
11539   else
11540     {
11541       sals.sals = (struct symtab_and_line *)
11542         xmalloc (sizeof (struct symtab_and_line));
11543       make_cleanup (xfree, sals.sals);
11544       init_sal (&sal);          /* Initialize to zeroes.  */
11545
11546       /* Set sal's line, symtab, pc, and pspace to the values
11547          corresponding to the last call to print_frame_info.  If the
11548          codepoint is not valid, this will set all the fields to 0.  */
11549       get_last_displayed_sal (&sal);
11550       if (sal.symtab == 0)
11551         error (_("No source file specified."));
11552
11553       sals.sals[0] = sal;
11554       sals.nelts = 1;
11555
11556       default_match = 1;
11557     }
11558
11559   /* We don't call resolve_sal_pc here.  That's not as bad as it
11560      seems, because all existing breakpoints typically have both
11561      file/line and pc set.  So, if clear is given file/line, we can
11562      match this to existing breakpoint without obtaining pc at all.
11563
11564      We only support clearing given the address explicitly 
11565      present in breakpoint table.  Say, we've set breakpoint 
11566      at file:line.  There were several PC values for that file:line,
11567      due to optimization, all in one block.
11568
11569      We've picked one PC value.  If "clear" is issued with another
11570      PC corresponding to the same file:line, the breakpoint won't
11571      be cleared.  We probably can still clear the breakpoint, but 
11572      since the other PC value is never presented to user, user
11573      can only find it by guessing, and it does not seem important
11574      to support that.  */
11575
11576   /* For each line spec given, delete bps which correspond to it.  Do
11577      it in two passes, solely to preserve the current behavior that
11578      from_tty is forced true if we delete more than one
11579      breakpoint.  */
11580
11581   found = NULL;
11582   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11583   for (i = 0; i < sals.nelts; i++)
11584     {
11585       int is_abs, sal_name_len;
11586
11587       /* If exact pc given, clear bpts at that pc.
11588          If line given (pc == 0), clear all bpts on specified line.
11589          If defaulting, clear all bpts on default line
11590          or at default pc.
11591
11592          defaulting    sal.pc != 0    tests to do
11593
11594          0              1             pc
11595          1              1             pc _and_ line
11596          0              0             line
11597          1              0             <can't happen> */
11598
11599       sal = sals.sals[i];
11600       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
11601       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
11602
11603       /* Find all matching breakpoints and add them to 'found'.  */
11604       ALL_BREAKPOINTS (b)
11605         {
11606           int match = 0;
11607           /* Are we going to delete b?  */
11608           if (b->type != bp_none && !is_watchpoint (b))
11609             {
11610               struct bp_location *loc = b->loc;
11611               for (; loc; loc = loc->next)
11612                 {
11613                   /* If the user specified file:line, don't allow a PC
11614                      match.  This matches historical gdb behavior.  */
11615                   int pc_match = (!sal.explicit_line
11616                                   && sal.pc
11617                                   && (loc->pspace == sal.pspace)
11618                                   && (loc->address == sal.pc)
11619                                   && (!section_is_overlay (loc->section)
11620                                       || loc->section == sal.section));
11621                   int line_match = 0;
11622
11623                   if ((default_match || sal.explicit_line)
11624                       && loc->source_file != NULL
11625                       && sal.symtab != NULL
11626                       && sal.pspace == loc->pspace
11627                       && loc->line_number == sal.line)
11628                     {
11629                       if (filename_cmp (loc->source_file,
11630                                         sal.symtab->filename) == 0)
11631                         line_match = 1;
11632                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
11633                                && compare_filenames_for_search (loc->source_file,
11634                                                                 sal.symtab->filename,
11635                                                                 sal_name_len))
11636                         line_match = 1;
11637                     }
11638
11639                   if (pc_match || line_match)
11640                     {
11641                       match = 1;
11642                       break;
11643                     }
11644                 }
11645             }
11646
11647           if (match)
11648             VEC_safe_push(breakpoint_p, found, b);
11649         }
11650     }
11651
11652   /* Now go thru the 'found' chain and delete them.  */
11653   if (VEC_empty(breakpoint_p, found))
11654     {
11655       if (arg)
11656         error (_("No breakpoint at %s."), arg);
11657       else
11658         error (_("No breakpoint at this line."));
11659     }
11660
11661   /* Remove duplicates from the vec.  */
11662   qsort (VEC_address (breakpoint_p, found),
11663          VEC_length (breakpoint_p, found),
11664          sizeof (breakpoint_p),
11665          compare_breakpoints);
11666   prev = VEC_index (breakpoint_p, found, 0);
11667   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11668     {
11669       if (b == prev)
11670         {
11671           VEC_ordered_remove (breakpoint_p, found, ix);
11672           --ix;
11673         }
11674     }
11675
11676   if (VEC_length(breakpoint_p, found) > 1)
11677     from_tty = 1;       /* Always report if deleted more than one.  */
11678   if (from_tty)
11679     {
11680       if (VEC_length(breakpoint_p, found) == 1)
11681         printf_unfiltered (_("Deleted breakpoint "));
11682       else
11683         printf_unfiltered (_("Deleted breakpoints "));
11684     }
11685   breakpoints_changed ();
11686
11687   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11688     {
11689       if (from_tty)
11690         printf_unfiltered ("%d ", b->number);
11691       delete_breakpoint (b);
11692     }
11693   if (from_tty)
11694     putchar_unfiltered ('\n');
11695
11696   do_cleanups (cleanups);
11697 }
11698 \f
11699 /* Delete breakpoint in BS if they are `delete' breakpoints and
11700    all breakpoints that are marked for deletion, whether hit or not.
11701    This is called after any breakpoint is hit, or after errors.  */
11702
11703 void
11704 breakpoint_auto_delete (bpstat bs)
11705 {
11706   struct breakpoint *b, *b_tmp;
11707
11708   for (; bs; bs = bs->next)
11709     if (bs->breakpoint_at
11710         && bs->breakpoint_at->disposition == disp_del
11711         && bs->stop)
11712       delete_breakpoint (bs->breakpoint_at);
11713
11714   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11715   {
11716     if (b->disposition == disp_del_at_next_stop)
11717       delete_breakpoint (b);
11718   }
11719 }
11720
11721 /* A comparison function for bp_location AP and BP being interfaced to
11722    qsort.  Sort elements primarily by their ADDRESS (no matter what
11723    does breakpoint_address_is_meaningful say for its OWNER),
11724    secondarily by ordering first bp_permanent OWNERed elements and
11725    terciarily just ensuring the array is sorted stable way despite
11726    qsort being an unstable algorithm.  */
11727
11728 static int
11729 bp_location_compare (const void *ap, const void *bp)
11730 {
11731   struct bp_location *a = *(void **) ap;
11732   struct bp_location *b = *(void **) bp;
11733   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11734   int a_perm = a->owner->enable_state == bp_permanent;
11735   int b_perm = b->owner->enable_state == bp_permanent;
11736
11737   if (a->address != b->address)
11738     return (a->address > b->address) - (a->address < b->address);
11739
11740   /* Sort locations at the same address by their pspace number, keeping
11741      locations of the same inferior (in a multi-inferior environment)
11742      grouped.  */
11743
11744   if (a->pspace->num != b->pspace->num)
11745     return ((a->pspace->num > b->pspace->num)
11746             - (a->pspace->num < b->pspace->num));
11747
11748   /* Sort permanent breakpoints first.  */
11749   if (a_perm != b_perm)
11750     return (a_perm < b_perm) - (a_perm > b_perm);
11751
11752   /* Make the internal GDB representation stable across GDB runs
11753      where A and B memory inside GDB can differ.  Breakpoint locations of
11754      the same type at the same address can be sorted in arbitrary order.  */
11755
11756   if (a->owner->number != b->owner->number)
11757     return ((a->owner->number > b->owner->number)
11758             - (a->owner->number < b->owner->number));
11759
11760   return (a > b) - (a < b);
11761 }
11762
11763 /* Set bp_location_placed_address_before_address_max and
11764    bp_location_shadow_len_after_address_max according to the current
11765    content of the bp_location array.  */
11766
11767 static void
11768 bp_location_target_extensions_update (void)
11769 {
11770   struct bp_location *bl, **blp_tmp;
11771
11772   bp_location_placed_address_before_address_max = 0;
11773   bp_location_shadow_len_after_address_max = 0;
11774
11775   ALL_BP_LOCATIONS (bl, blp_tmp)
11776     {
11777       CORE_ADDR start, end, addr;
11778
11779       if (!bp_location_has_shadow (bl))
11780         continue;
11781
11782       start = bl->target_info.placed_address;
11783       end = start + bl->target_info.shadow_len;
11784
11785       gdb_assert (bl->address >= start);
11786       addr = bl->address - start;
11787       if (addr > bp_location_placed_address_before_address_max)
11788         bp_location_placed_address_before_address_max = addr;
11789
11790       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11791
11792       gdb_assert (bl->address < end);
11793       addr = end - bl->address;
11794       if (addr > bp_location_shadow_len_after_address_max)
11795         bp_location_shadow_len_after_address_max = addr;
11796     }
11797 }
11798
11799 /* Download tracepoint locations if they haven't been.  */
11800
11801 static void
11802 download_tracepoint_locations (void)
11803 {
11804   struct bp_location *bl, **blp_tmp;
11805   struct cleanup *old_chain;
11806
11807   if (!target_can_download_tracepoint ())
11808     return;
11809
11810   old_chain = save_current_space_and_thread ();
11811
11812   ALL_BP_LOCATIONS (bl, blp_tmp)
11813     {
11814       struct tracepoint *t;
11815
11816       if (!is_tracepoint (bl->owner))
11817         continue;
11818
11819       if ((bl->owner->type == bp_fast_tracepoint
11820            ? !may_insert_fast_tracepoints
11821            : !may_insert_tracepoints))
11822         continue;
11823
11824       /* In tracepoint, locations are _never_ duplicated, so
11825          should_be_inserted is equivalent to
11826          unduplicated_should_be_inserted.  */
11827       if (!should_be_inserted (bl) || bl->inserted)
11828         continue;
11829
11830       switch_to_program_space_and_thread (bl->pspace);
11831
11832       target_download_tracepoint (bl);
11833
11834       bl->inserted = 1;
11835       t = (struct tracepoint *) bl->owner;
11836       t->number_on_target = bl->owner->number;
11837     }
11838
11839   do_cleanups (old_chain);
11840 }
11841
11842 /* Swap the insertion/duplication state between two locations.  */
11843
11844 static void
11845 swap_insertion (struct bp_location *left, struct bp_location *right)
11846 {
11847   const int left_inserted = left->inserted;
11848   const int left_duplicate = left->duplicate;
11849   const int left_needs_update = left->needs_update;
11850   const struct bp_target_info left_target_info = left->target_info;
11851
11852   /* Locations of tracepoints can never be duplicated.  */
11853   if (is_tracepoint (left->owner))
11854     gdb_assert (!left->duplicate);
11855   if (is_tracepoint (right->owner))
11856     gdb_assert (!right->duplicate);
11857
11858   left->inserted = right->inserted;
11859   left->duplicate = right->duplicate;
11860   left->needs_update = right->needs_update;
11861   left->target_info = right->target_info;
11862   right->inserted = left_inserted;
11863   right->duplicate = left_duplicate;
11864   right->needs_update = left_needs_update;
11865   right->target_info = left_target_info;
11866 }
11867
11868 /* Force the re-insertion of the locations at ADDRESS.  This is called
11869    once a new/deleted/modified duplicate location is found and we are evaluating
11870    conditions on the target's side.  Such conditions need to be updated on
11871    the target.  */
11872
11873 static void
11874 force_breakpoint_reinsertion (struct bp_location *bl)
11875 {
11876   struct bp_location **locp = NULL, **loc2p;
11877   struct bp_location *loc;
11878   CORE_ADDR address = 0;
11879   int pspace_num;
11880
11881   address = bl->address;
11882   pspace_num = bl->pspace->num;
11883
11884   /* This is only meaningful if the target is
11885      evaluating conditions and if the user has
11886      opted for condition evaluation on the target's
11887      side.  */
11888   if (gdb_evaluates_breakpoint_condition_p ()
11889       || !target_supports_evaluation_of_breakpoint_conditions ())
11890     return;
11891
11892   /* Flag all breakpoint locations with this address and
11893      the same program space as the location
11894      as "its condition has changed".  We need to
11895      update the conditions on the target's side.  */
11896   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11897     {
11898       loc = *loc2p;
11899
11900       if (!is_breakpoint (loc->owner)
11901           || pspace_num != loc->pspace->num)
11902         continue;
11903
11904       /* Flag the location appropriately.  We use a different state to
11905          let everyone know that we already updated the set of locations
11906          with addr bl->address and program space bl->pspace.  This is so
11907          we don't have to keep calling these functions just to mark locations
11908          that have already been marked.  */
11909       loc->condition_changed = condition_updated;
11910
11911       /* Free the agent expression bytecode as well.  We will compute
11912          it later on.  */
11913       if (loc->cond_bytecode)
11914         {
11915           free_agent_expr (loc->cond_bytecode);
11916           loc->cond_bytecode = NULL;
11917         }
11918     }
11919 }
11920
11921 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
11922    into the inferior, only remove already-inserted locations that no
11923    longer should be inserted.  Functions that delete a breakpoint or
11924    breakpoints should pass false, so that deleting a breakpoint
11925    doesn't have the side effect of inserting the locations of other
11926    breakpoints that are marked not-inserted, but should_be_inserted
11927    returns true on them.
11928
11929    This behaviour is useful is situations close to tear-down -- e.g.,
11930    after an exec, while the target still has execution, but breakpoint
11931    shadows of the previous executable image should *NOT* be restored
11932    to the new image; or before detaching, where the target still has
11933    execution and wants to delete breakpoints from GDB's lists, and all
11934    breakpoints had already been removed from the inferior.  */
11935
11936 static void
11937 update_global_location_list (int should_insert)
11938 {
11939   struct breakpoint *b;
11940   struct bp_location **locp, *loc;
11941   struct cleanup *cleanups;
11942   /* Last breakpoint location address that was marked for update.  */
11943   CORE_ADDR last_addr = 0;
11944   /* Last breakpoint location program space that was marked for update.  */
11945   int last_pspace_num = -1;
11946
11947   /* Used in the duplicates detection below.  When iterating over all
11948      bp_locations, points to the first bp_location of a given address.
11949      Breakpoints and watchpoints of different types are never
11950      duplicates of each other.  Keep one pointer for each type of
11951      breakpoint/watchpoint, so we only need to loop over all locations
11952      once.  */
11953   struct bp_location *bp_loc_first;  /* breakpoint */
11954   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11955   struct bp_location *awp_loc_first; /* access watchpoint */
11956   struct bp_location *rwp_loc_first; /* read watchpoint */
11957
11958   /* Saved former bp_location array which we compare against the newly
11959      built bp_location from the current state of ALL_BREAKPOINTS.  */
11960   struct bp_location **old_location, **old_locp;
11961   unsigned old_location_count;
11962
11963   old_location = bp_location;
11964   old_location_count = bp_location_count;
11965   bp_location = NULL;
11966   bp_location_count = 0;
11967   cleanups = make_cleanup (xfree, old_location);
11968
11969   ALL_BREAKPOINTS (b)
11970     for (loc = b->loc; loc; loc = loc->next)
11971       bp_location_count++;
11972
11973   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
11974   locp = bp_location;
11975   ALL_BREAKPOINTS (b)
11976     for (loc = b->loc; loc; loc = loc->next)
11977       *locp++ = loc;
11978   qsort (bp_location, bp_location_count, sizeof (*bp_location),
11979          bp_location_compare);
11980
11981   bp_location_target_extensions_update ();
11982
11983   /* Identify bp_location instances that are no longer present in the
11984      new list, and therefore should be freed.  Note that it's not
11985      necessary that those locations should be removed from inferior --
11986      if there's another location at the same address (previously
11987      marked as duplicate), we don't need to remove/insert the
11988      location.
11989      
11990      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11991      and former bp_location array state respectively.  */
11992
11993   locp = bp_location;
11994   for (old_locp = old_location; old_locp < old_location + old_location_count;
11995        old_locp++)
11996     {
11997       struct bp_location *old_loc = *old_locp;
11998       struct bp_location **loc2p;
11999
12000       /* Tells if 'old_loc' is found among the new locations.  If
12001          not, we have to free it.  */
12002       int found_object = 0;
12003       /* Tells if the location should remain inserted in the target.  */
12004       int keep_in_target = 0;
12005       int removed = 0;
12006
12007       /* Skip LOCP entries which will definitely never be needed.
12008          Stop either at or being the one matching OLD_LOC.  */
12009       while (locp < bp_location + bp_location_count
12010              && (*locp)->address < old_loc->address)
12011         locp++;
12012
12013       for (loc2p = locp;
12014            (loc2p < bp_location + bp_location_count
12015             && (*loc2p)->address == old_loc->address);
12016            loc2p++)
12017         {
12018           /* Check if this is a new/duplicated location or a duplicated
12019              location that had its condition modified.  If so, we want to send
12020              its condition to the target if evaluation of conditions is taking
12021              place there.  */
12022           if ((*loc2p)->condition_changed == condition_modified
12023               && (last_addr != old_loc->address
12024                   || last_pspace_num != old_loc->pspace->num))
12025             {
12026               force_breakpoint_reinsertion (*loc2p);
12027               last_pspace_num = old_loc->pspace->num;
12028             }
12029
12030           if (*loc2p == old_loc)
12031             found_object = 1;
12032         }
12033
12034       /* We have already handled this address, update it so that we don't
12035          have to go through updates again.  */
12036       last_addr = old_loc->address;
12037
12038       /* Target-side condition evaluation: Handle deleted locations.  */
12039       if (!found_object)
12040         force_breakpoint_reinsertion (old_loc);
12041
12042       /* If this location is no longer present, and inserted, look if
12043          there's maybe a new location at the same address.  If so,
12044          mark that one inserted, and don't remove this one.  This is
12045          needed so that we don't have a time window where a breakpoint
12046          at certain location is not inserted.  */
12047
12048       if (old_loc->inserted)
12049         {
12050           /* If the location is inserted now, we might have to remove
12051              it.  */
12052
12053           if (found_object && should_be_inserted (old_loc))
12054             {
12055               /* The location is still present in the location list,
12056                  and still should be inserted.  Don't do anything.  */
12057               keep_in_target = 1;
12058             }
12059           else
12060             {
12061               /* This location still exists, but it won't be kept in the
12062                  target since it may have been disabled.  We proceed to
12063                  remove its target-side condition.  */
12064
12065               /* The location is either no longer present, or got
12066                  disabled.  See if there's another location at the
12067                  same address, in which case we don't need to remove
12068                  this one from the target.  */
12069
12070               /* OLD_LOC comes from existing struct breakpoint.  */
12071               if (breakpoint_address_is_meaningful (old_loc->owner))
12072                 {
12073                   for (loc2p = locp;
12074                        (loc2p < bp_location + bp_location_count
12075                         && (*loc2p)->address == old_loc->address);
12076                        loc2p++)
12077                     {
12078                       struct bp_location *loc2 = *loc2p;
12079
12080                       if (breakpoint_locations_match (loc2, old_loc))
12081                         {
12082                           /* Read watchpoint locations are switched to
12083                              access watchpoints, if the former are not
12084                              supported, but the latter are.  */
12085                           if (is_hardware_watchpoint (old_loc->owner))
12086                             {
12087                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12088                               loc2->watchpoint_type = old_loc->watchpoint_type;
12089                             }
12090
12091                           /* loc2 is a duplicated location. We need to check
12092                              if it should be inserted in case it will be
12093                              unduplicated.  */
12094                           if (loc2 != old_loc
12095                               && unduplicated_should_be_inserted (loc2))
12096                             {
12097                               swap_insertion (old_loc, loc2);
12098                               keep_in_target = 1;
12099                               break;
12100                             }
12101                         }
12102                     }
12103                 }
12104             }
12105
12106           if (!keep_in_target)
12107             {
12108               if (remove_breakpoint (old_loc, mark_uninserted))
12109                 {
12110                   /* This is just about all we can do.  We could keep
12111                      this location on the global list, and try to
12112                      remove it next time, but there's no particular
12113                      reason why we will succeed next time.
12114                      
12115                      Note that at this point, old_loc->owner is still
12116                      valid, as delete_breakpoint frees the breakpoint
12117                      only after calling us.  */
12118                   printf_filtered (_("warning: Error removing "
12119                                      "breakpoint %d\n"), 
12120                                    old_loc->owner->number);
12121                 }
12122               removed = 1;
12123             }
12124         }
12125
12126       if (!found_object)
12127         {
12128           if (removed && non_stop
12129               && breakpoint_address_is_meaningful (old_loc->owner)
12130               && !is_hardware_watchpoint (old_loc->owner))
12131             {
12132               /* This location was removed from the target.  In
12133                  non-stop mode, a race condition is possible where
12134                  we've removed a breakpoint, but stop events for that
12135                  breakpoint are already queued and will arrive later.
12136                  We apply an heuristic to be able to distinguish such
12137                  SIGTRAPs from other random SIGTRAPs: we keep this
12138                  breakpoint location for a bit, and will retire it
12139                  after we see some number of events.  The theory here
12140                  is that reporting of events should, "on the average",
12141                  be fair, so after a while we'll see events from all
12142                  threads that have anything of interest, and no longer
12143                  need to keep this breakpoint location around.  We
12144                  don't hold locations forever so to reduce chances of
12145                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12146                  SIGTRAP.
12147
12148                  The heuristic failing can be disastrous on
12149                  decr_pc_after_break targets.
12150
12151                  On decr_pc_after_break targets, like e.g., x86-linux,
12152                  if we fail to recognize a late breakpoint SIGTRAP,
12153                  because events_till_retirement has reached 0 too
12154                  soon, we'll fail to do the PC adjustment, and report
12155                  a random SIGTRAP to the user.  When the user resumes
12156                  the inferior, it will most likely immediately crash
12157                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12158                  corrupted, because of being resumed e.g., in the
12159                  middle of a multi-byte instruction, or skipped a
12160                  one-byte instruction.  This was actually seen happen
12161                  on native x86-linux, and should be less rare on
12162                  targets that do not support new thread events, like
12163                  remote, due to the heuristic depending on
12164                  thread_count.
12165
12166                  Mistaking a random SIGTRAP for a breakpoint trap
12167                  causes similar symptoms (PC adjustment applied when
12168                  it shouldn't), but then again, playing with SIGTRAPs
12169                  behind the debugger's back is asking for trouble.
12170
12171                  Since hardware watchpoint traps are always
12172                  distinguishable from other traps, so we don't need to
12173                  apply keep hardware watchpoint moribund locations
12174                  around.  We simply always ignore hardware watchpoint
12175                  traps we can no longer explain.  */
12176
12177               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12178               old_loc->owner = NULL;
12179
12180               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12181             }
12182           else
12183             {
12184               old_loc->owner = NULL;
12185               decref_bp_location (&old_loc);
12186             }
12187         }
12188     }
12189
12190   /* Rescan breakpoints at the same address and section, marking the
12191      first one as "first" and any others as "duplicates".  This is so
12192      that the bpt instruction is only inserted once.  If we have a
12193      permanent breakpoint at the same place as BPT, make that one the
12194      official one, and the rest as duplicates.  Permanent breakpoints
12195      are sorted first for the same address.
12196
12197      Do the same for hardware watchpoints, but also considering the
12198      watchpoint's type (regular/access/read) and length.  */
12199
12200   bp_loc_first = NULL;
12201   wp_loc_first = NULL;
12202   awp_loc_first = NULL;
12203   rwp_loc_first = NULL;
12204   ALL_BP_LOCATIONS (loc, locp)
12205     {
12206       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12207          non-NULL.  */
12208       struct bp_location **loc_first_p;
12209       b = loc->owner;
12210
12211       if (!should_be_inserted (loc)
12212           || !breakpoint_address_is_meaningful (b)
12213           /* Don't detect duplicate for tracepoint locations because they are
12214            never duplicated.  See the comments in field `duplicate' of
12215            `struct bp_location'.  */
12216           || is_tracepoint (b))
12217         {
12218           /* Clear the condition modification flag.  */
12219           loc->condition_changed = condition_unchanged;
12220           continue;
12221         }
12222
12223       /* Permanent breakpoint should always be inserted.  */
12224       if (b->enable_state == bp_permanent && ! loc->inserted)
12225         internal_error (__FILE__, __LINE__,
12226                         _("allegedly permanent breakpoint is not "
12227                         "actually inserted"));
12228
12229       if (b->type == bp_hardware_watchpoint)
12230         loc_first_p = &wp_loc_first;
12231       else if (b->type == bp_read_watchpoint)
12232         loc_first_p = &rwp_loc_first;
12233       else if (b->type == bp_access_watchpoint)
12234         loc_first_p = &awp_loc_first;
12235       else
12236         loc_first_p = &bp_loc_first;
12237
12238       if (*loc_first_p == NULL
12239           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12240           || !breakpoint_locations_match (loc, *loc_first_p))
12241         {
12242           *loc_first_p = loc;
12243           loc->duplicate = 0;
12244
12245           if (is_breakpoint (loc->owner) && loc->condition_changed)
12246             {
12247               loc->needs_update = 1;
12248               /* Clear the condition modification flag.  */
12249               loc->condition_changed = condition_unchanged;
12250             }
12251           continue;
12252         }
12253
12254
12255       /* This and the above ensure the invariant that the first location
12256          is not duplicated, and is the inserted one.
12257          All following are marked as duplicated, and are not inserted.  */
12258       if (loc->inserted)
12259         swap_insertion (loc, *loc_first_p);
12260       loc->duplicate = 1;
12261
12262       /* Clear the condition modification flag.  */
12263       loc->condition_changed = condition_unchanged;
12264
12265       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12266           && b->enable_state != bp_permanent)
12267         internal_error (__FILE__, __LINE__,
12268                         _("another breakpoint was inserted on top of "
12269                         "a permanent breakpoint"));
12270     }
12271
12272   if (breakpoints_always_inserted_mode ()
12273       && (have_live_inferiors ()
12274           || (gdbarch_has_global_breakpoints (target_gdbarch))))
12275     {
12276       if (should_insert)
12277         insert_breakpoint_locations ();
12278       else
12279         {
12280           /* Though should_insert is false, we may need to update conditions
12281              on the target's side if it is evaluating such conditions.  We
12282              only update conditions for locations that are marked
12283              "needs_update".  */
12284           update_inserted_breakpoint_locations ();
12285         }
12286     }
12287
12288   if (should_insert)
12289     download_tracepoint_locations ();
12290
12291   do_cleanups (cleanups);
12292 }
12293
12294 void
12295 breakpoint_retire_moribund (void)
12296 {
12297   struct bp_location *loc;
12298   int ix;
12299
12300   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12301     if (--(loc->events_till_retirement) == 0)
12302       {
12303         decref_bp_location (&loc);
12304         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12305         --ix;
12306       }
12307 }
12308
12309 static void
12310 update_global_location_list_nothrow (int inserting)
12311 {
12312   volatile struct gdb_exception e;
12313
12314   TRY_CATCH (e, RETURN_MASK_ERROR)
12315     update_global_location_list (inserting);
12316 }
12317
12318 /* Clear BKP from a BPS.  */
12319
12320 static void
12321 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12322 {
12323   bpstat bs;
12324
12325   for (bs = bps; bs; bs = bs->next)
12326     if (bs->breakpoint_at == bpt)
12327       {
12328         bs->breakpoint_at = NULL;
12329         bs->old_val = NULL;
12330         /* bs->commands will be freed later.  */
12331       }
12332 }
12333
12334 /* Callback for iterate_over_threads.  */
12335 static int
12336 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12337 {
12338   struct breakpoint *bpt = data;
12339
12340   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12341   return 0;
12342 }
12343
12344 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12345    callbacks.  */
12346
12347 static void
12348 say_where (struct breakpoint *b)
12349 {
12350   struct ui_out *uiout = current_uiout;
12351   struct value_print_options opts;
12352
12353   get_user_print_options (&opts);
12354
12355   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12356      single string.  */
12357   if (b->loc == NULL)
12358     {
12359       printf_filtered (_(" (%s) pending."), b->addr_string);
12360     }
12361   else
12362     {
12363       if (opts.addressprint || b->loc->source_file == NULL)
12364         {
12365           printf_filtered (" at ");
12366           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12367                           gdb_stdout);
12368         }
12369       if (b->loc->source_file)
12370         {
12371           /* If there is a single location, we can print the location
12372              more nicely.  */
12373           if (b->loc->next == NULL)
12374             printf_filtered (": file %s, line %d.",
12375                              b->loc->source_file, b->loc->line_number);
12376           else
12377             /* This is not ideal, but each location may have a
12378                different file name, and this at least reflects the
12379                real situation somewhat.  */
12380             printf_filtered (": %s.", b->addr_string);
12381         }
12382
12383       if (b->loc->next)
12384         {
12385           struct bp_location *loc = b->loc;
12386           int n = 0;
12387           for (; loc; loc = loc->next)
12388             ++n;
12389           printf_filtered (" (%d locations)", n);
12390         }
12391     }
12392 }
12393
12394 /* Default bp_location_ops methods.  */
12395
12396 static void
12397 bp_location_dtor (struct bp_location *self)
12398 {
12399   xfree (self->cond);
12400   if (self->cond_bytecode)
12401     free_agent_expr (self->cond_bytecode);
12402   xfree (self->function_name);
12403   xfree (self->source_file);
12404 }
12405
12406 static const struct bp_location_ops bp_location_ops =
12407 {
12408   bp_location_dtor
12409 };
12410
12411 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12412    inherit from.  */
12413
12414 static void
12415 base_breakpoint_dtor (struct breakpoint *self)
12416 {
12417   decref_counted_command_line (&self->commands);
12418   xfree (self->cond_string);
12419   xfree (self->addr_string);
12420   xfree (self->filter);
12421   xfree (self->addr_string_range_end);
12422 }
12423
12424 static struct bp_location *
12425 base_breakpoint_allocate_location (struct breakpoint *self)
12426 {
12427   struct bp_location *loc;
12428
12429   loc = XNEW (struct bp_location);
12430   init_bp_location (loc, &bp_location_ops, self);
12431   return loc;
12432 }
12433
12434 static void
12435 base_breakpoint_re_set (struct breakpoint *b)
12436 {
12437   /* Nothing to re-set. */
12438 }
12439
12440 #define internal_error_pure_virtual_called() \
12441   gdb_assert_not_reached ("pure virtual function called")
12442
12443 static int
12444 base_breakpoint_insert_location (struct bp_location *bl)
12445 {
12446   internal_error_pure_virtual_called ();
12447 }
12448
12449 static int
12450 base_breakpoint_remove_location (struct bp_location *bl)
12451 {
12452   internal_error_pure_virtual_called ();
12453 }
12454
12455 static int
12456 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12457                                 struct address_space *aspace,
12458                                 CORE_ADDR bp_addr,
12459                                 const struct target_waitstatus *ws)
12460 {
12461   internal_error_pure_virtual_called ();
12462 }
12463
12464 static void
12465 base_breakpoint_check_status (bpstat bs)
12466 {
12467   /* Always stop.   */
12468 }
12469
12470 /* A "works_in_software_mode" breakpoint_ops method that just internal
12471    errors.  */
12472
12473 static int
12474 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12475 {
12476   internal_error_pure_virtual_called ();
12477 }
12478
12479 /* A "resources_needed" breakpoint_ops method that just internal
12480    errors.  */
12481
12482 static int
12483 base_breakpoint_resources_needed (const struct bp_location *bl)
12484 {
12485   internal_error_pure_virtual_called ();
12486 }
12487
12488 static enum print_stop_action
12489 base_breakpoint_print_it (bpstat bs)
12490 {
12491   internal_error_pure_virtual_called ();
12492 }
12493
12494 static void
12495 base_breakpoint_print_one_detail (const struct breakpoint *self,
12496                                   struct ui_out *uiout)
12497 {
12498   /* nothing */
12499 }
12500
12501 static void
12502 base_breakpoint_print_mention (struct breakpoint *b)
12503 {
12504   internal_error_pure_virtual_called ();
12505 }
12506
12507 static void
12508 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12509 {
12510   internal_error_pure_virtual_called ();
12511 }
12512
12513 static void
12514 base_breakpoint_create_sals_from_address (char **arg,
12515                                           struct linespec_result *canonical,
12516                                           enum bptype type_wanted,
12517                                           char *addr_start,
12518                                           char **copy_arg)
12519 {
12520   internal_error_pure_virtual_called ();
12521 }
12522
12523 static void
12524 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12525                                         struct linespec_result *c,
12526                                         struct linespec_sals *lsal,
12527                                         char *cond_string,
12528                                         char *extra_string,
12529                                         enum bptype type_wanted,
12530                                         enum bpdisp disposition,
12531                                         int thread,
12532                                         int task, int ignore_count,
12533                                         const struct breakpoint_ops *o,
12534                                         int from_tty, int enabled,
12535                                         int internal, unsigned flags)
12536 {
12537   internal_error_pure_virtual_called ();
12538 }
12539
12540 static void
12541 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12542                                  struct symtabs_and_lines *sals)
12543 {
12544   internal_error_pure_virtual_called ();
12545 }
12546
12547 static struct breakpoint_ops base_breakpoint_ops =
12548 {
12549   base_breakpoint_dtor,
12550   base_breakpoint_allocate_location,
12551   base_breakpoint_re_set,
12552   base_breakpoint_insert_location,
12553   base_breakpoint_remove_location,
12554   base_breakpoint_breakpoint_hit,
12555   base_breakpoint_check_status,
12556   base_breakpoint_resources_needed,
12557   base_breakpoint_works_in_software_mode,
12558   base_breakpoint_print_it,
12559   NULL,
12560   base_breakpoint_print_one_detail,
12561   base_breakpoint_print_mention,
12562   base_breakpoint_print_recreate,
12563   base_breakpoint_create_sals_from_address,
12564   base_breakpoint_create_breakpoints_sal,
12565   base_breakpoint_decode_linespec,
12566 };
12567
12568 /* Default breakpoint_ops methods.  */
12569
12570 static void
12571 bkpt_re_set (struct breakpoint *b)
12572 {
12573   /* FIXME: is this still reachable?  */
12574   if (b->addr_string == NULL)
12575     {
12576       /* Anything without a string can't be re-set.  */
12577       delete_breakpoint (b);
12578       return;
12579     }
12580
12581   breakpoint_re_set_default (b);
12582 }
12583
12584 static int
12585 bkpt_insert_location (struct bp_location *bl)
12586 {
12587   if (bl->loc_type == bp_loc_hardware_breakpoint)
12588     return target_insert_hw_breakpoint (bl->gdbarch,
12589                                         &bl->target_info);
12590   else
12591     return target_insert_breakpoint (bl->gdbarch,
12592                                      &bl->target_info);
12593 }
12594
12595 static int
12596 bkpt_remove_location (struct bp_location *bl)
12597 {
12598   if (bl->loc_type == bp_loc_hardware_breakpoint)
12599     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12600   else
12601     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12602 }
12603
12604 static int
12605 bkpt_breakpoint_hit (const struct bp_location *bl,
12606                      struct address_space *aspace, CORE_ADDR bp_addr,
12607                      const struct target_waitstatus *ws)
12608 {
12609   struct breakpoint *b = bl->owner;
12610
12611   if (ws->kind != TARGET_WAITKIND_STOPPED
12612       || ws->value.sig != GDB_SIGNAL_TRAP)
12613     return 0;
12614
12615   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12616                                  aspace, bp_addr))
12617     return 0;
12618
12619   if (overlay_debugging         /* unmapped overlay section */
12620       && section_is_overlay (bl->section)
12621       && !section_is_mapped (bl->section))
12622     return 0;
12623
12624   return 1;
12625 }
12626
12627 static int
12628 bkpt_resources_needed (const struct bp_location *bl)
12629 {
12630   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12631
12632   return 1;
12633 }
12634
12635 static enum print_stop_action
12636 bkpt_print_it (bpstat bs)
12637 {
12638   struct breakpoint *b;
12639   const struct bp_location *bl;
12640   int bp_temp;
12641   struct ui_out *uiout = current_uiout;
12642
12643   gdb_assert (bs->bp_location_at != NULL);
12644
12645   bl = bs->bp_location_at;
12646   b = bs->breakpoint_at;
12647
12648   bp_temp = b->disposition == disp_del;
12649   if (bl->address != bl->requested_address)
12650     breakpoint_adjustment_warning (bl->requested_address,
12651                                    bl->address,
12652                                    b->number, 1);
12653   annotate_breakpoint (b->number);
12654   if (bp_temp)
12655     ui_out_text (uiout, "\nTemporary breakpoint ");
12656   else
12657     ui_out_text (uiout, "\nBreakpoint ");
12658   if (ui_out_is_mi_like_p (uiout))
12659     {
12660       ui_out_field_string (uiout, "reason",
12661                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12662       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12663     }
12664   ui_out_field_int (uiout, "bkptno", b->number);
12665   ui_out_text (uiout, ", ");
12666
12667   return PRINT_SRC_AND_LOC;
12668 }
12669
12670 static void
12671 bkpt_print_mention (struct breakpoint *b)
12672 {
12673   if (ui_out_is_mi_like_p (current_uiout))
12674     return;
12675
12676   switch (b->type)
12677     {
12678     case bp_breakpoint:
12679     case bp_gnu_ifunc_resolver:
12680       if (b->disposition == disp_del)
12681         printf_filtered (_("Temporary breakpoint"));
12682       else
12683         printf_filtered (_("Breakpoint"));
12684       printf_filtered (_(" %d"), b->number);
12685       if (b->type == bp_gnu_ifunc_resolver)
12686         printf_filtered (_(" at gnu-indirect-function resolver"));
12687       break;
12688     case bp_hardware_breakpoint:
12689       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12690       break;
12691     case bp_dprintf:
12692       printf_filtered (_("Dprintf %d"), b->number);
12693       break;
12694     }
12695
12696   say_where (b);
12697 }
12698
12699 static void
12700 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12701 {
12702   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12703     fprintf_unfiltered (fp, "tbreak");
12704   else if (tp->type == bp_breakpoint)
12705     fprintf_unfiltered (fp, "break");
12706   else if (tp->type == bp_hardware_breakpoint
12707            && tp->disposition == disp_del)
12708     fprintf_unfiltered (fp, "thbreak");
12709   else if (tp->type == bp_hardware_breakpoint)
12710     fprintf_unfiltered (fp, "hbreak");
12711   else
12712     internal_error (__FILE__, __LINE__,
12713                     _("unhandled breakpoint type %d"), (int) tp->type);
12714
12715   fprintf_unfiltered (fp, " %s", tp->addr_string);
12716   print_recreate_thread (tp, fp);
12717 }
12718
12719 static void
12720 bkpt_create_sals_from_address (char **arg,
12721                                struct linespec_result *canonical,
12722                                enum bptype type_wanted,
12723                                char *addr_start, char **copy_arg)
12724 {
12725   create_sals_from_address_default (arg, canonical, type_wanted,
12726                                     addr_start, copy_arg);
12727 }
12728
12729 static void
12730 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12731                              struct linespec_result *canonical,
12732                              struct linespec_sals *lsal,
12733                              char *cond_string,
12734                              char *extra_string,
12735                              enum bptype type_wanted,
12736                              enum bpdisp disposition,
12737                              int thread,
12738                              int task, int ignore_count,
12739                              const struct breakpoint_ops *ops,
12740                              int from_tty, int enabled,
12741                              int internal, unsigned flags)
12742 {
12743   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12744                                   cond_string, extra_string,
12745                                   type_wanted,
12746                                   disposition, thread, task,
12747                                   ignore_count, ops, from_tty,
12748                                   enabled, internal, flags);
12749 }
12750
12751 static void
12752 bkpt_decode_linespec (struct breakpoint *b, char **s,
12753                       struct symtabs_and_lines *sals)
12754 {
12755   decode_linespec_default (b, s, sals);
12756 }
12757
12758 /* Virtual table for internal breakpoints.  */
12759
12760 static void
12761 internal_bkpt_re_set (struct breakpoint *b)
12762 {
12763   switch (b->type)
12764     {
12765       /* Delete overlay event and longjmp master breakpoints; they
12766          will be reset later by breakpoint_re_set.  */
12767     case bp_overlay_event:
12768     case bp_longjmp_master:
12769     case bp_std_terminate_master:
12770     case bp_exception_master:
12771       delete_breakpoint (b);
12772       break;
12773
12774       /* This breakpoint is special, it's set up when the inferior
12775          starts and we really don't want to touch it.  */
12776     case bp_shlib_event:
12777
12778       /* Like bp_shlib_event, this breakpoint type is special.  Once
12779          it is set up, we do not want to touch it.  */
12780     case bp_thread_event:
12781       break;
12782     }
12783 }
12784
12785 static void
12786 internal_bkpt_check_status (bpstat bs)
12787 {
12788   if (bs->breakpoint_at->type == bp_shlib_event)
12789     {
12790       /* If requested, stop when the dynamic linker notifies GDB of
12791          events.  This allows the user to get control and place
12792          breakpoints in initializer routines for dynamically loaded
12793          objects (among other things).  */
12794       bs->stop = stop_on_solib_events;
12795       bs->print = stop_on_solib_events;
12796     }
12797   else
12798     bs->stop = 0;
12799 }
12800
12801 static enum print_stop_action
12802 internal_bkpt_print_it (bpstat bs)
12803 {
12804   struct ui_out *uiout = current_uiout;
12805   struct breakpoint *b;
12806
12807   b = bs->breakpoint_at;
12808
12809   switch (b->type)
12810     {
12811     case bp_shlib_event:
12812       /* Did we stop because the user set the stop_on_solib_events
12813          variable?  (If so, we report this as a generic, "Stopped due
12814          to shlib event" message.) */
12815       print_solib_event (0);
12816       break;
12817
12818     case bp_thread_event:
12819       /* Not sure how we will get here.
12820          GDB should not stop for these breakpoints.  */
12821       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12822       break;
12823
12824     case bp_overlay_event:
12825       /* By analogy with the thread event, GDB should not stop for these.  */
12826       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12827       break;
12828
12829     case bp_longjmp_master:
12830       /* These should never be enabled.  */
12831       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12832       break;
12833
12834     case bp_std_terminate_master:
12835       /* These should never be enabled.  */
12836       printf_filtered (_("std::terminate Master Breakpoint: "
12837                          "gdb should not stop!\n"));
12838       break;
12839
12840     case bp_exception_master:
12841       /* These should never be enabled.  */
12842       printf_filtered (_("Exception Master Breakpoint: "
12843                          "gdb should not stop!\n"));
12844       break;
12845     }
12846
12847   return PRINT_NOTHING;
12848 }
12849
12850 static void
12851 internal_bkpt_print_mention (struct breakpoint *b)
12852 {
12853   /* Nothing to mention.  These breakpoints are internal.  */
12854 }
12855
12856 /* Virtual table for momentary breakpoints  */
12857
12858 static void
12859 momentary_bkpt_re_set (struct breakpoint *b)
12860 {
12861   /* Keep temporary breakpoints, which can be encountered when we step
12862      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
12863      Otherwise these should have been blown away via the cleanup chain
12864      or by breakpoint_init_inferior when we rerun the executable.  */
12865 }
12866
12867 static void
12868 momentary_bkpt_check_status (bpstat bs)
12869 {
12870   /* Nothing.  The point of these breakpoints is causing a stop.  */
12871 }
12872
12873 static enum print_stop_action
12874 momentary_bkpt_print_it (bpstat bs)
12875 {
12876   struct ui_out *uiout = current_uiout;
12877
12878   if (ui_out_is_mi_like_p (uiout))
12879     {
12880       struct breakpoint *b = bs->breakpoint_at;
12881
12882       switch (b->type)
12883         {
12884         case bp_finish:
12885           ui_out_field_string
12886             (uiout, "reason",
12887              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
12888           break;
12889
12890         case bp_until:
12891           ui_out_field_string
12892             (uiout, "reason",
12893              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
12894           break;
12895         }
12896     }
12897
12898   return PRINT_UNKNOWN;
12899 }
12900
12901 static void
12902 momentary_bkpt_print_mention (struct breakpoint *b)
12903 {
12904   /* Nothing to mention.  These breakpoints are internal.  */
12905 }
12906
12907 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
12908
12909    It gets cleared already on the removal of the first one of such placed
12910    breakpoints.  This is OK as they get all removed altogether.  */
12911
12912 static void
12913 longjmp_bkpt_dtor (struct breakpoint *self)
12914 {
12915   struct thread_info *tp = find_thread_id (self->thread);
12916
12917   if (tp)
12918     tp->initiating_frame = null_frame_id;
12919
12920   momentary_breakpoint_ops.dtor (self);
12921 }
12922
12923 /* Specific methods for probe breakpoints.  */
12924
12925 static int
12926 bkpt_probe_insert_location (struct bp_location *bl)
12927 {
12928   int v = bkpt_insert_location (bl);
12929
12930   if (v == 0)
12931     {
12932       /* The insertion was successful, now let's set the probe's semaphore
12933          if needed.  */
12934       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
12935     }
12936
12937   return v;
12938 }
12939
12940 static int
12941 bkpt_probe_remove_location (struct bp_location *bl)
12942 {
12943   /* Let's clear the semaphore before removing the location.  */
12944   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
12945
12946   return bkpt_remove_location (bl);
12947 }
12948
12949 static void
12950 bkpt_probe_create_sals_from_address (char **arg,
12951                                      struct linespec_result *canonical,
12952                                      enum bptype type_wanted,
12953                                      char *addr_start, char **copy_arg)
12954 {
12955   struct linespec_sals lsal;
12956
12957   lsal.sals = parse_probes (arg, canonical);
12958
12959   *copy_arg = xstrdup (canonical->addr_string);
12960   lsal.canonical = xstrdup (*copy_arg);
12961
12962   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12963 }
12964
12965 static void
12966 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
12967                             struct symtabs_and_lines *sals)
12968 {
12969   *sals = parse_probes (s, NULL);
12970   if (!sals->sals)
12971     error (_("probe not found"));
12972 }
12973
12974 /* The breakpoint_ops structure to be used in tracepoints.  */
12975
12976 static void
12977 tracepoint_re_set (struct breakpoint *b)
12978 {
12979   breakpoint_re_set_default (b);
12980 }
12981
12982 static int
12983 tracepoint_breakpoint_hit (const struct bp_location *bl,
12984                            struct address_space *aspace, CORE_ADDR bp_addr,
12985                            const struct target_waitstatus *ws)
12986 {
12987   /* By definition, the inferior does not report stops at
12988      tracepoints.  */
12989   return 0;
12990 }
12991
12992 static void
12993 tracepoint_print_one_detail (const struct breakpoint *self,
12994                              struct ui_out *uiout)
12995 {
12996   struct tracepoint *tp = (struct tracepoint *) self;
12997   if (tp->static_trace_marker_id)
12998     {
12999       gdb_assert (self->type == bp_static_tracepoint);
13000
13001       ui_out_text (uiout, "\tmarker id is ");
13002       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13003                            tp->static_trace_marker_id);
13004       ui_out_text (uiout, "\n");
13005     }
13006 }
13007
13008 static void
13009 tracepoint_print_mention (struct breakpoint *b)
13010 {
13011   if (ui_out_is_mi_like_p (current_uiout))
13012     return;
13013
13014   switch (b->type)
13015     {
13016     case bp_tracepoint:
13017       printf_filtered (_("Tracepoint"));
13018       printf_filtered (_(" %d"), b->number);
13019       break;
13020     case bp_fast_tracepoint:
13021       printf_filtered (_("Fast tracepoint"));
13022       printf_filtered (_(" %d"), b->number);
13023       break;
13024     case bp_static_tracepoint:
13025       printf_filtered (_("Static tracepoint"));
13026       printf_filtered (_(" %d"), b->number);
13027       break;
13028     default:
13029       internal_error (__FILE__, __LINE__,
13030                       _("unhandled tracepoint type %d"), (int) b->type);
13031     }
13032
13033   say_where (b);
13034 }
13035
13036 static void
13037 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13038 {
13039   struct tracepoint *tp = (struct tracepoint *) self;
13040
13041   if (self->type == bp_fast_tracepoint)
13042     fprintf_unfiltered (fp, "ftrace");
13043   if (self->type == bp_static_tracepoint)
13044     fprintf_unfiltered (fp, "strace");
13045   else if (self->type == bp_tracepoint)
13046     fprintf_unfiltered (fp, "trace");
13047   else
13048     internal_error (__FILE__, __LINE__,
13049                     _("unhandled tracepoint type %d"), (int) self->type);
13050
13051   fprintf_unfiltered (fp, " %s", self->addr_string);
13052   print_recreate_thread (self, fp);
13053
13054   if (tp->pass_count)
13055     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13056 }
13057
13058 static void
13059 tracepoint_create_sals_from_address (char **arg,
13060                                      struct linespec_result *canonical,
13061                                      enum bptype type_wanted,
13062                                      char *addr_start, char **copy_arg)
13063 {
13064   create_sals_from_address_default (arg, canonical, type_wanted,
13065                                     addr_start, copy_arg);
13066 }
13067
13068 static void
13069 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13070                                    struct linespec_result *canonical,
13071                                    struct linespec_sals *lsal,
13072                                    char *cond_string,
13073                                    char *extra_string,
13074                                    enum bptype type_wanted,
13075                                    enum bpdisp disposition,
13076                                    int thread,
13077                                    int task, int ignore_count,
13078                                    const struct breakpoint_ops *ops,
13079                                    int from_tty, int enabled,
13080                                    int internal, unsigned flags)
13081 {
13082   create_breakpoints_sal_default (gdbarch, canonical, lsal,
13083                                   cond_string, extra_string,
13084                                   type_wanted,
13085                                   disposition, thread, task,
13086                                   ignore_count, ops, from_tty,
13087                                   enabled, internal, flags);
13088 }
13089
13090 static void
13091 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13092                             struct symtabs_and_lines *sals)
13093 {
13094   decode_linespec_default (b, s, sals);
13095 }
13096
13097 struct breakpoint_ops tracepoint_breakpoint_ops;
13098
13099 /* The breakpoint_ops structure to be use on tracepoints placed in a
13100    static probe.  */
13101
13102 static void
13103 tracepoint_probe_create_sals_from_address (char **arg,
13104                                            struct linespec_result *canonical,
13105                                            enum bptype type_wanted,
13106                                            char *addr_start, char **copy_arg)
13107 {
13108   /* We use the same method for breakpoint on probes.  */
13109   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13110                                        addr_start, copy_arg);
13111 }
13112
13113 static void
13114 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13115                                   struct symtabs_and_lines *sals)
13116 {
13117   /* We use the same method for breakpoint on probes.  */
13118   bkpt_probe_decode_linespec (b, s, sals);
13119 }
13120
13121 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13122
13123 /* The breakpoint_ops structure to be used on static tracepoints with
13124    markers (`-m').  */
13125
13126 static void
13127 strace_marker_create_sals_from_address (char **arg,
13128                                         struct linespec_result *canonical,
13129                                         enum bptype type_wanted,
13130                                         char *addr_start, char **copy_arg)
13131 {
13132   struct linespec_sals lsal;
13133
13134   lsal.sals = decode_static_tracepoint_spec (arg);
13135
13136   *copy_arg = savestring (addr_start, *arg - addr_start);
13137
13138   canonical->addr_string = xstrdup (*copy_arg);
13139   lsal.canonical = xstrdup (*copy_arg);
13140   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13141 }
13142
13143 static void
13144 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13145                                       struct linespec_result *canonical,
13146                                       struct linespec_sals *lsal,
13147                                       char *cond_string,
13148                                       char *extra_string,
13149                                       enum bptype type_wanted,
13150                                       enum bpdisp disposition,
13151                                       int thread,
13152                                       int task, int ignore_count,
13153                                       const struct breakpoint_ops *ops,
13154                                       int from_tty, int enabled,
13155                                       int internal, unsigned flags)
13156 {
13157   int i;
13158
13159   /* If the user is creating a static tracepoint by marker id
13160      (strace -m MARKER_ID), then store the sals index, so that
13161      breakpoint_re_set can try to match up which of the newly
13162      found markers corresponds to this one, and, don't try to
13163      expand multiple locations for each sal, given than SALS
13164      already should contain all sals for MARKER_ID.  */
13165
13166   for (i = 0; i < lsal->sals.nelts; ++i)
13167     {
13168       struct symtabs_and_lines expanded;
13169       struct tracepoint *tp;
13170       struct cleanup *old_chain;
13171       char *addr_string;
13172
13173       expanded.nelts = 1;
13174       expanded.sals = &lsal->sals.sals[i];
13175
13176       addr_string = xstrdup (canonical->addr_string);
13177       old_chain = make_cleanup (xfree, addr_string);
13178
13179       tp = XCNEW (struct tracepoint);
13180       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13181                            addr_string, NULL,
13182                            cond_string, extra_string,
13183                            type_wanted, disposition,
13184                            thread, task, ignore_count, ops,
13185                            from_tty, enabled, internal, flags,
13186                            canonical->special_display);
13187       /* Given that its possible to have multiple markers with
13188          the same string id, if the user is creating a static
13189          tracepoint by marker id ("strace -m MARKER_ID"), then
13190          store the sals index, so that breakpoint_re_set can
13191          try to match up which of the newly found markers
13192          corresponds to this one  */
13193       tp->static_trace_marker_id_idx = i;
13194
13195       install_breakpoint (internal, &tp->base, 0);
13196
13197       discard_cleanups (old_chain);
13198     }
13199 }
13200
13201 static void
13202 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13203                                struct symtabs_and_lines *sals)
13204 {
13205   struct tracepoint *tp = (struct tracepoint *) b;
13206
13207   *sals = decode_static_tracepoint_spec (s);
13208   if (sals->nelts > tp->static_trace_marker_id_idx)
13209     {
13210       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13211       sals->nelts = 1;
13212     }
13213   else
13214     error (_("marker %s not found"), tp->static_trace_marker_id);
13215 }
13216
13217 static struct breakpoint_ops strace_marker_breakpoint_ops;
13218
13219 static int
13220 strace_marker_p (struct breakpoint *b)
13221 {
13222   return b->ops == &strace_marker_breakpoint_ops;
13223 }
13224
13225 /* Delete a breakpoint and clean up all traces of it in the data
13226    structures.  */
13227
13228 void
13229 delete_breakpoint (struct breakpoint *bpt)
13230 {
13231   struct breakpoint *b;
13232
13233   gdb_assert (bpt != NULL);
13234
13235   /* Has this bp already been deleted?  This can happen because
13236      multiple lists can hold pointers to bp's.  bpstat lists are
13237      especial culprits.
13238
13239      One example of this happening is a watchpoint's scope bp.  When
13240      the scope bp triggers, we notice that the watchpoint is out of
13241      scope, and delete it.  We also delete its scope bp.  But the
13242      scope bp is marked "auto-deleting", and is already on a bpstat.
13243      That bpstat is then checked for auto-deleting bp's, which are
13244      deleted.
13245
13246      A real solution to this problem might involve reference counts in
13247      bp's, and/or giving them pointers back to their referencing
13248      bpstat's, and teaching delete_breakpoint to only free a bp's
13249      storage when no more references were extent.  A cheaper bandaid
13250      was chosen.  */
13251   if (bpt->type == bp_none)
13252     return;
13253
13254   /* At least avoid this stale reference until the reference counting
13255      of breakpoints gets resolved.  */
13256   if (bpt->related_breakpoint != bpt)
13257     {
13258       struct breakpoint *related;
13259       struct watchpoint *w;
13260
13261       if (bpt->type == bp_watchpoint_scope)
13262         w = (struct watchpoint *) bpt->related_breakpoint;
13263       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13264         w = (struct watchpoint *) bpt;
13265       else
13266         w = NULL;
13267       if (w != NULL)
13268         watchpoint_del_at_next_stop (w);
13269
13270       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13271       for (related = bpt; related->related_breakpoint != bpt;
13272            related = related->related_breakpoint);
13273       related->related_breakpoint = bpt->related_breakpoint;
13274       bpt->related_breakpoint = bpt;
13275     }
13276
13277   /* watch_command_1 creates a watchpoint but only sets its number if
13278      update_watchpoint succeeds in creating its bp_locations.  If there's
13279      a problem in that process, we'll be asked to delete the half-created
13280      watchpoint.  In that case, don't announce the deletion.  */
13281   if (bpt->number)
13282     observer_notify_breakpoint_deleted (bpt);
13283
13284   if (breakpoint_chain == bpt)
13285     breakpoint_chain = bpt->next;
13286
13287   ALL_BREAKPOINTS (b)
13288     if (b->next == bpt)
13289     {
13290       b->next = bpt->next;
13291       break;
13292     }
13293
13294   /* Be sure no bpstat's are pointing at the breakpoint after it's
13295      been freed.  */
13296   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13297      in all threads for now.  Note that we cannot just remove bpstats
13298      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13299      commands are associated with the bpstat; if we remove it here,
13300      then the later call to bpstat_do_actions (&stop_bpstat); in
13301      event-top.c won't do anything, and temporary breakpoints with
13302      commands won't work.  */
13303
13304   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13305
13306   /* Now that breakpoint is removed from breakpoint list, update the
13307      global location list.  This will remove locations that used to
13308      belong to this breakpoint.  Do this before freeing the breakpoint
13309      itself, since remove_breakpoint looks at location's owner.  It
13310      might be better design to have location completely
13311      self-contained, but it's not the case now.  */
13312   update_global_location_list (0);
13313
13314   bpt->ops->dtor (bpt);
13315   /* On the chance that someone will soon try again to delete this
13316      same bp, we mark it as deleted before freeing its storage.  */
13317   bpt->type = bp_none;
13318   xfree (bpt);
13319 }
13320
13321 static void
13322 do_delete_breakpoint_cleanup (void *b)
13323 {
13324   delete_breakpoint (b);
13325 }
13326
13327 struct cleanup *
13328 make_cleanup_delete_breakpoint (struct breakpoint *b)
13329 {
13330   return make_cleanup (do_delete_breakpoint_cleanup, b);
13331 }
13332
13333 /* Iterator function to call a user-provided callback function once
13334    for each of B and its related breakpoints.  */
13335
13336 static void
13337 iterate_over_related_breakpoints (struct breakpoint *b,
13338                                   void (*function) (struct breakpoint *,
13339                                                     void *),
13340                                   void *data)
13341 {
13342   struct breakpoint *related;
13343
13344   related = b;
13345   do
13346     {
13347       struct breakpoint *next;
13348
13349       /* FUNCTION may delete RELATED.  */
13350       next = related->related_breakpoint;
13351
13352       if (next == related)
13353         {
13354           /* RELATED is the last ring entry.  */
13355           function (related, data);
13356
13357           /* FUNCTION may have deleted it, so we'd never reach back to
13358              B.  There's nothing left to do anyway, so just break
13359              out.  */
13360           break;
13361         }
13362       else
13363         function (related, data);
13364
13365       related = next;
13366     }
13367   while (related != b);
13368 }
13369
13370 static void
13371 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13372 {
13373   delete_breakpoint (b);
13374 }
13375
13376 /* A callback for map_breakpoint_numbers that calls
13377    delete_breakpoint.  */
13378
13379 static void
13380 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13381 {
13382   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13383 }
13384
13385 void
13386 delete_command (char *arg, int from_tty)
13387 {
13388   struct breakpoint *b, *b_tmp;
13389
13390   dont_repeat ();
13391
13392   if (arg == 0)
13393     {
13394       int breaks_to_delete = 0;
13395
13396       /* Delete all breakpoints if no argument.  Do not delete
13397          internal breakpoints, these have to be deleted with an
13398          explicit breakpoint number argument.  */
13399       ALL_BREAKPOINTS (b)
13400         if (user_breakpoint_p (b))
13401           {
13402             breaks_to_delete = 1;
13403             break;
13404           }
13405
13406       /* Ask user only if there are some breakpoints to delete.  */
13407       if (!from_tty
13408           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13409         {
13410           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13411             if (user_breakpoint_p (b))
13412               delete_breakpoint (b);
13413         }
13414     }
13415   else
13416     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13417 }
13418
13419 static int
13420 all_locations_are_pending (struct bp_location *loc)
13421 {
13422   for (; loc; loc = loc->next)
13423     if (!loc->shlib_disabled
13424         && !loc->pspace->executing_startup)
13425       return 0;
13426   return 1;
13427 }
13428
13429 /* Subroutine of update_breakpoint_locations to simplify it.
13430    Return non-zero if multiple fns in list LOC have the same name.
13431    Null names are ignored.  */
13432
13433 static int
13434 ambiguous_names_p (struct bp_location *loc)
13435 {
13436   struct bp_location *l;
13437   htab_t htab = htab_create_alloc (13, htab_hash_string,
13438                                    (int (*) (const void *, 
13439                                              const void *)) streq,
13440                                    NULL, xcalloc, xfree);
13441
13442   for (l = loc; l != NULL; l = l->next)
13443     {
13444       const char **slot;
13445       const char *name = l->function_name;
13446
13447       /* Allow for some names to be NULL, ignore them.  */
13448       if (name == NULL)
13449         continue;
13450
13451       slot = (const char **) htab_find_slot (htab, (const void *) name,
13452                                              INSERT);
13453       /* NOTE: We can assume slot != NULL here because xcalloc never
13454          returns NULL.  */
13455       if (*slot != NULL)
13456         {
13457           htab_delete (htab);
13458           return 1;
13459         }
13460       *slot = name;
13461     }
13462
13463   htab_delete (htab);
13464   return 0;
13465 }
13466
13467 /* When symbols change, it probably means the sources changed as well,
13468    and it might mean the static tracepoint markers are no longer at
13469    the same address or line numbers they used to be at last we
13470    checked.  Losing your static tracepoints whenever you rebuild is
13471    undesirable.  This function tries to resync/rematch gdb static
13472    tracepoints with the markers on the target, for static tracepoints
13473    that have not been set by marker id.  Static tracepoint that have
13474    been set by marker id are reset by marker id in breakpoint_re_set.
13475    The heuristic is:
13476
13477    1) For a tracepoint set at a specific address, look for a marker at
13478    the old PC.  If one is found there, assume to be the same marker.
13479    If the name / string id of the marker found is different from the
13480    previous known name, assume that means the user renamed the marker
13481    in the sources, and output a warning.
13482
13483    2) For a tracepoint set at a given line number, look for a marker
13484    at the new address of the old line number.  If one is found there,
13485    assume to be the same marker.  If the name / string id of the
13486    marker found is different from the previous known name, assume that
13487    means the user renamed the marker in the sources, and output a
13488    warning.
13489
13490    3) If a marker is no longer found at the same address or line, it
13491    may mean the marker no longer exists.  But it may also just mean
13492    the code changed a bit.  Maybe the user added a few lines of code
13493    that made the marker move up or down (in line number terms).  Ask
13494    the target for info about the marker with the string id as we knew
13495    it.  If found, update line number and address in the matching
13496    static tracepoint.  This will get confused if there's more than one
13497    marker with the same ID (possible in UST, although unadvised
13498    precisely because it confuses tools).  */
13499
13500 static struct symtab_and_line
13501 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13502 {
13503   struct tracepoint *tp = (struct tracepoint *) b;
13504   struct static_tracepoint_marker marker;
13505   CORE_ADDR pc;
13506
13507   pc = sal.pc;
13508   if (sal.line)
13509     find_line_pc (sal.symtab, sal.line, &pc);
13510
13511   if (target_static_tracepoint_marker_at (pc, &marker))
13512     {
13513       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13514         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13515                  b->number,
13516                  tp->static_trace_marker_id, marker.str_id);
13517
13518       xfree (tp->static_trace_marker_id);
13519       tp->static_trace_marker_id = xstrdup (marker.str_id);
13520       release_static_tracepoint_marker (&marker);
13521
13522       return sal;
13523     }
13524
13525   /* Old marker wasn't found on target at lineno.  Try looking it up
13526      by string ID.  */
13527   if (!sal.explicit_pc
13528       && sal.line != 0
13529       && sal.symtab != NULL
13530       && tp->static_trace_marker_id != NULL)
13531     {
13532       VEC(static_tracepoint_marker_p) *markers;
13533
13534       markers
13535         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13536
13537       if (!VEC_empty(static_tracepoint_marker_p, markers))
13538         {
13539           struct symtab_and_line sal2;
13540           struct symbol *sym;
13541           struct static_tracepoint_marker *tpmarker;
13542           struct ui_out *uiout = current_uiout;
13543
13544           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13545
13546           xfree (tp->static_trace_marker_id);
13547           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13548
13549           warning (_("marker for static tracepoint %d (%s) not "
13550                      "found at previous line number"),
13551                    b->number, tp->static_trace_marker_id);
13552
13553           init_sal (&sal2);
13554
13555           sal2.pc = tpmarker->address;
13556
13557           sal2 = find_pc_line (tpmarker->address, 0);
13558           sym = find_pc_sect_function (tpmarker->address, NULL);
13559           ui_out_text (uiout, "Now in ");
13560           if (sym)
13561             {
13562               ui_out_field_string (uiout, "func",
13563                                    SYMBOL_PRINT_NAME (sym));
13564               ui_out_text (uiout, " at ");
13565             }
13566           ui_out_field_string (uiout, "file", sal2.symtab->filename);
13567           ui_out_text (uiout, ":");
13568
13569           if (ui_out_is_mi_like_p (uiout))
13570             {
13571               char *fullname = symtab_to_fullname (sal2.symtab);
13572
13573               if (fullname)
13574                 ui_out_field_string (uiout, "fullname", fullname);
13575             }
13576
13577           ui_out_field_int (uiout, "line", sal2.line);
13578           ui_out_text (uiout, "\n");
13579
13580           b->loc->line_number = sal2.line;
13581
13582           xfree (b->loc->source_file);
13583           if (sym)
13584             b->loc->source_file = xstrdup (sal2.symtab->filename);
13585           else
13586             b->loc->source_file = NULL;
13587
13588           xfree (b->addr_string);
13589           b->addr_string = xstrprintf ("%s:%d",
13590                                        sal2.symtab->filename,
13591                                        b->loc->line_number);
13592
13593           /* Might be nice to check if function changed, and warn if
13594              so.  */
13595
13596           release_static_tracepoint_marker (tpmarker);
13597         }
13598     }
13599   return sal;
13600 }
13601
13602 /* Returns 1 iff locations A and B are sufficiently same that
13603    we don't need to report breakpoint as changed.  */
13604
13605 static int
13606 locations_are_equal (struct bp_location *a, struct bp_location *b)
13607 {
13608   while (a && b)
13609     {
13610       if (a->address != b->address)
13611         return 0;
13612
13613       if (a->shlib_disabled != b->shlib_disabled)
13614         return 0;
13615
13616       if (a->enabled != b->enabled)
13617         return 0;
13618
13619       a = a->next;
13620       b = b->next;
13621     }
13622
13623   if ((a == NULL) != (b == NULL))
13624     return 0;
13625
13626   return 1;
13627 }
13628
13629 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13630    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13631    a ranged breakpoint.  */
13632
13633 void
13634 update_breakpoint_locations (struct breakpoint *b,
13635                              struct symtabs_and_lines sals,
13636                              struct symtabs_and_lines sals_end)
13637 {
13638   int i;
13639   struct bp_location *existing_locations = b->loc;
13640
13641   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13642     {
13643       /* Ranged breakpoints have only one start location and one end
13644          location.  */
13645       b->enable_state = bp_disabled;
13646       update_global_location_list (1);
13647       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13648                            "multiple locations found\n"),
13649                          b->number);
13650       return;
13651     }
13652
13653   /* If there's no new locations, and all existing locations are
13654      pending, don't do anything.  This optimizes the common case where
13655      all locations are in the same shared library, that was unloaded.
13656      We'd like to retain the location, so that when the library is
13657      loaded again, we don't loose the enabled/disabled status of the
13658      individual locations.  */
13659   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13660     return;
13661
13662   b->loc = NULL;
13663
13664   for (i = 0; i < sals.nelts; ++i)
13665     {
13666       struct bp_location *new_loc;
13667
13668       switch_to_program_space_and_thread (sals.sals[i].pspace);
13669
13670       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13671
13672       /* Reparse conditions, they might contain references to the
13673          old symtab.  */
13674       if (b->cond_string != NULL)
13675         {
13676           char *s;
13677           volatile struct gdb_exception e;
13678
13679           s = b->cond_string;
13680           TRY_CATCH (e, RETURN_MASK_ERROR)
13681             {
13682               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
13683                                            block_for_pc (sals.sals[i].pc), 
13684                                            0);
13685             }
13686           if (e.reason < 0)
13687             {
13688               warning (_("failed to reevaluate condition "
13689                          "for breakpoint %d: %s"), 
13690                        b->number, e.message);
13691               new_loc->enabled = 0;
13692             }
13693         }
13694
13695       if (sals_end.nelts)
13696         {
13697           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
13698
13699           new_loc->length = end - sals.sals[0].pc + 1;
13700         }
13701     }
13702
13703   /* Update locations of permanent breakpoints.  */
13704   if (b->enable_state == bp_permanent)
13705     make_breakpoint_permanent (b);
13706
13707   /* If possible, carry over 'disable' status from existing
13708      breakpoints.  */
13709   {
13710     struct bp_location *e = existing_locations;
13711     /* If there are multiple breakpoints with the same function name,
13712        e.g. for inline functions, comparing function names won't work.
13713        Instead compare pc addresses; this is just a heuristic as things
13714        may have moved, but in practice it gives the correct answer
13715        often enough until a better solution is found.  */
13716     int have_ambiguous_names = ambiguous_names_p (b->loc);
13717
13718     for (; e; e = e->next)
13719       {
13720         if (!e->enabled && e->function_name)
13721           {
13722             struct bp_location *l = b->loc;
13723             if (have_ambiguous_names)
13724               {
13725                 for (; l; l = l->next)
13726                   if (breakpoint_locations_match (e, l))
13727                     {
13728                       l->enabled = 0;
13729                       break;
13730                     }
13731               }
13732             else
13733               {
13734                 for (; l; l = l->next)
13735                   if (l->function_name
13736                       && strcmp (e->function_name, l->function_name) == 0)
13737                     {
13738                       l->enabled = 0;
13739                       break;
13740                     }
13741               }
13742           }
13743       }
13744   }
13745
13746   if (!locations_are_equal (existing_locations, b->loc))
13747     observer_notify_breakpoint_modified (b);
13748
13749   update_global_location_list (1);
13750 }
13751
13752 /* Find the SaL locations corresponding to the given ADDR_STRING.
13753    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13754
13755 static struct symtabs_and_lines
13756 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
13757 {
13758   char *s;
13759   struct symtabs_and_lines sals = {0};
13760   volatile struct gdb_exception e;
13761
13762   gdb_assert (b->ops != NULL);
13763   s = addr_string;
13764
13765   TRY_CATCH (e, RETURN_MASK_ERROR)
13766     {
13767       b->ops->decode_linespec (b, &s, &sals);
13768     }
13769   if (e.reason < 0)
13770     {
13771       int not_found_and_ok = 0;
13772       /* For pending breakpoints, it's expected that parsing will
13773          fail until the right shared library is loaded.  User has
13774          already told to create pending breakpoints and don't need
13775          extra messages.  If breakpoint is in bp_shlib_disabled
13776          state, then user already saw the message about that
13777          breakpoint being disabled, and don't want to see more
13778          errors.  */
13779       if (e.error == NOT_FOUND_ERROR
13780           && (b->condition_not_parsed 
13781               || (b->loc && b->loc->shlib_disabled)
13782               || (b->loc && b->loc->pspace->executing_startup)
13783               || b->enable_state == bp_disabled))
13784         not_found_and_ok = 1;
13785
13786       if (!not_found_and_ok)
13787         {
13788           /* We surely don't want to warn about the same breakpoint
13789              10 times.  One solution, implemented here, is disable
13790              the breakpoint on error.  Another solution would be to
13791              have separate 'warning emitted' flag.  Since this
13792              happens only when a binary has changed, I don't know
13793              which approach is better.  */
13794           b->enable_state = bp_disabled;
13795           throw_exception (e);
13796         }
13797     }
13798
13799   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
13800     {
13801       int i;
13802
13803       for (i = 0; i < sals.nelts; ++i)
13804         resolve_sal_pc (&sals.sals[i]);
13805       if (b->condition_not_parsed && s && s[0])
13806         {
13807           char *cond_string = 0;
13808           int thread = -1;
13809           int task = 0;
13810           char *extra_string = NULL;
13811
13812           find_condition_and_thread (s, sals.sals[0].pc,
13813                                      &cond_string, &thread, &task,
13814                                      &extra_string);
13815           if (cond_string)
13816             b->cond_string = cond_string;
13817           b->thread = thread;
13818           b->task = task;
13819           if (extra_string)
13820             b->extra_string = extra_string;
13821           b->condition_not_parsed = 0;
13822         }
13823
13824       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13825         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
13826
13827       *found = 1;
13828     }
13829   else
13830     *found = 0;
13831
13832   return sals;
13833 }
13834
13835 /* The default re_set method, for typical hardware or software
13836    breakpoints.  Reevaluate the breakpoint and recreate its
13837    locations.  */
13838
13839 static void
13840 breakpoint_re_set_default (struct breakpoint *b)
13841 {
13842   int found;
13843   struct symtabs_and_lines sals, sals_end;
13844   struct symtabs_and_lines expanded = {0};
13845   struct symtabs_and_lines expanded_end = {0};
13846
13847   sals = addr_string_to_sals (b, b->addr_string, &found);
13848   if (found)
13849     {
13850       make_cleanup (xfree, sals.sals);
13851       expanded = sals;
13852     }
13853
13854   if (b->addr_string_range_end)
13855     {
13856       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
13857       if (found)
13858         {
13859           make_cleanup (xfree, sals_end.sals);
13860           expanded_end = sals_end;
13861         }
13862     }
13863
13864   update_breakpoint_locations (b, expanded, expanded_end);
13865 }
13866
13867 /* Default method for creating SALs from an address string.  It basically
13868    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13869
13870 static void
13871 create_sals_from_address_default (char **arg,
13872                                   struct linespec_result *canonical,
13873                                   enum bptype type_wanted,
13874                                   char *addr_start, char **copy_arg)
13875 {
13876   parse_breakpoint_sals (arg, canonical);
13877 }
13878
13879 /* Call create_breakpoints_sal for the given arguments.  This is the default
13880    function for the `create_breakpoints_sal' method of
13881    breakpoint_ops.  */
13882
13883 static void
13884 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13885                                 struct linespec_result *canonical,
13886                                 struct linespec_sals *lsal,
13887                                 char *cond_string,
13888                                 char *extra_string,
13889                                 enum bptype type_wanted,
13890                                 enum bpdisp disposition,
13891                                 int thread,
13892                                 int task, int ignore_count,
13893                                 const struct breakpoint_ops *ops,
13894                                 int from_tty, int enabled,
13895                                 int internal, unsigned flags)
13896 {
13897   create_breakpoints_sal (gdbarch, canonical, cond_string,
13898                           extra_string,
13899                           type_wanted, disposition,
13900                           thread, task, ignore_count, ops, from_tty,
13901                           enabled, internal, flags);
13902 }
13903
13904 /* Decode the line represented by S by calling decode_line_full.  This is the
13905    default function for the `decode_linespec' method of breakpoint_ops.  */
13906
13907 static void
13908 decode_linespec_default (struct breakpoint *b, char **s,
13909                          struct symtabs_and_lines *sals)
13910 {
13911   struct linespec_result canonical;
13912
13913   init_linespec_result (&canonical);
13914   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
13915                     (struct symtab *) NULL, 0,
13916                     &canonical, multiple_symbols_all,
13917                     b->filter);
13918
13919   /* We should get 0 or 1 resulting SALs.  */
13920   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
13921
13922   if (VEC_length (linespec_sals, canonical.sals) > 0)
13923     {
13924       struct linespec_sals *lsal;
13925
13926       lsal = VEC_index (linespec_sals, canonical.sals, 0);
13927       *sals = lsal->sals;
13928       /* Arrange it so the destructor does not free the
13929          contents.  */
13930       lsal->sals.sals = NULL;
13931     }
13932
13933   destroy_linespec_result (&canonical);
13934 }
13935
13936 /* Prepare the global context for a re-set of breakpoint B.  */
13937
13938 static struct cleanup *
13939 prepare_re_set_context (struct breakpoint *b)
13940 {
13941   struct cleanup *cleanups;
13942
13943   input_radix = b->input_radix;
13944   cleanups = save_current_space_and_thread ();
13945   if (b->pspace != NULL)
13946     switch_to_program_space_and_thread (b->pspace);
13947   set_language (b->language);
13948
13949   return cleanups;
13950 }
13951
13952 /* Reset a breakpoint given it's struct breakpoint * BINT.
13953    The value we return ends up being the return value from catch_errors.
13954    Unused in this case.  */
13955
13956 static int
13957 breakpoint_re_set_one (void *bint)
13958 {
13959   /* Get past catch_errs.  */
13960   struct breakpoint *b = (struct breakpoint *) bint;
13961   struct cleanup *cleanups;
13962
13963   cleanups = prepare_re_set_context (b);
13964   b->ops->re_set (b);
13965   do_cleanups (cleanups);
13966   return 0;
13967 }
13968
13969 /* Re-set all breakpoints after symbols have been re-loaded.  */
13970 void
13971 breakpoint_re_set (void)
13972 {
13973   struct breakpoint *b, *b_tmp;
13974   enum language save_language;
13975   int save_input_radix;
13976   struct cleanup *old_chain;
13977
13978   save_language = current_language->la_language;
13979   save_input_radix = input_radix;
13980   old_chain = save_current_program_space ();
13981
13982   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13983   {
13984     /* Format possible error msg.  */
13985     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
13986                                 b->number);
13987     struct cleanup *cleanups = make_cleanup (xfree, message);
13988     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
13989     do_cleanups (cleanups);
13990   }
13991   set_language (save_language);
13992   input_radix = save_input_radix;
13993
13994   jit_breakpoint_re_set ();
13995
13996   do_cleanups (old_chain);
13997
13998   create_overlay_event_breakpoint ();
13999   create_longjmp_master_breakpoint ();
14000   create_std_terminate_master_breakpoint ();
14001   create_exception_master_breakpoint ();
14002
14003   /* While we're at it, reset the skip list too.  */
14004   skip_re_set ();
14005 }
14006 \f
14007 /* Reset the thread number of this breakpoint:
14008
14009    - If the breakpoint is for all threads, leave it as-is.
14010    - Else, reset it to the current thread for inferior_ptid.  */
14011 void
14012 breakpoint_re_set_thread (struct breakpoint *b)
14013 {
14014   if (b->thread != -1)
14015     {
14016       if (in_thread_list (inferior_ptid))
14017         b->thread = pid_to_thread_id (inferior_ptid);
14018
14019       /* We're being called after following a fork.  The new fork is
14020          selected as current, and unless this was a vfork will have a
14021          different program space from the original thread.  Reset that
14022          as well.  */
14023       b->loc->pspace = current_program_space;
14024     }
14025 }
14026
14027 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14028    If from_tty is nonzero, it prints a message to that effect,
14029    which ends with a period (no newline).  */
14030
14031 void
14032 set_ignore_count (int bptnum, int count, int from_tty)
14033 {
14034   struct breakpoint *b;
14035
14036   if (count < 0)
14037     count = 0;
14038
14039   ALL_BREAKPOINTS (b)
14040     if (b->number == bptnum)
14041     {
14042       if (is_tracepoint (b))
14043         {
14044           if (from_tty && count != 0)
14045             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14046                              bptnum);
14047           return;
14048         }
14049       
14050       b->ignore_count = count;
14051       if (from_tty)
14052         {
14053           if (count == 0)
14054             printf_filtered (_("Will stop next time "
14055                                "breakpoint %d is reached."),
14056                              bptnum);
14057           else if (count == 1)
14058             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14059                              bptnum);
14060           else
14061             printf_filtered (_("Will ignore next %d "
14062                                "crossings of breakpoint %d."),
14063                              count, bptnum);
14064         }
14065       breakpoints_changed ();
14066       observer_notify_breakpoint_modified (b);
14067       return;
14068     }
14069
14070   error (_("No breakpoint number %d."), bptnum);
14071 }
14072
14073 /* Command to set ignore-count of breakpoint N to COUNT.  */
14074
14075 static void
14076 ignore_command (char *args, int from_tty)
14077 {
14078   char *p = args;
14079   int num;
14080
14081   if (p == 0)
14082     error_no_arg (_("a breakpoint number"));
14083
14084   num = get_number (&p);
14085   if (num == 0)
14086     error (_("bad breakpoint number: '%s'"), args);
14087   if (*p == 0)
14088     error (_("Second argument (specified ignore-count) is missing."));
14089
14090   set_ignore_count (num,
14091                     longest_to_int (value_as_long (parse_and_eval (p))),
14092                     from_tty);
14093   if (from_tty)
14094     printf_filtered ("\n");
14095 }
14096 \f
14097 /* Call FUNCTION on each of the breakpoints
14098    whose numbers are given in ARGS.  */
14099
14100 static void
14101 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14102                                                       void *),
14103                         void *data)
14104 {
14105   int num;
14106   struct breakpoint *b, *tmp;
14107   int match;
14108   struct get_number_or_range_state state;
14109
14110   if (args == 0)
14111     error_no_arg (_("one or more breakpoint numbers"));
14112
14113   init_number_or_range (&state, args);
14114
14115   while (!state.finished)
14116     {
14117       char *p = state.string;
14118
14119       match = 0;
14120
14121       num = get_number_or_range (&state);
14122       if (num == 0)
14123         {
14124           warning (_("bad breakpoint number at or near '%s'"), p);
14125         }
14126       else
14127         {
14128           ALL_BREAKPOINTS_SAFE (b, tmp)
14129             if (b->number == num)
14130               {
14131                 match = 1;
14132                 function (b, data);
14133                 break;
14134               }
14135           if (match == 0)
14136             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14137         }
14138     }
14139 }
14140
14141 static struct bp_location *
14142 find_location_by_number (char *number)
14143 {
14144   char *dot = strchr (number, '.');
14145   char *p1;
14146   int bp_num;
14147   int loc_num;
14148   struct breakpoint *b;
14149   struct bp_location *loc;  
14150
14151   *dot = '\0';
14152
14153   p1 = number;
14154   bp_num = get_number (&p1);
14155   if (bp_num == 0)
14156     error (_("Bad breakpoint number '%s'"), number);
14157
14158   ALL_BREAKPOINTS (b)
14159     if (b->number == bp_num)
14160       {
14161         break;
14162       }
14163
14164   if (!b || b->number != bp_num)
14165     error (_("Bad breakpoint number '%s'"), number);
14166   
14167   p1 = dot+1;
14168   loc_num = get_number (&p1);
14169   if (loc_num == 0)
14170     error (_("Bad breakpoint location number '%s'"), number);
14171
14172   --loc_num;
14173   loc = b->loc;
14174   for (;loc_num && loc; --loc_num, loc = loc->next)
14175     ;
14176   if (!loc)
14177     error (_("Bad breakpoint location number '%s'"), dot+1);
14178     
14179   return loc;  
14180 }
14181
14182
14183 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14184    If from_tty is nonzero, it prints a message to that effect,
14185    which ends with a period (no newline).  */
14186
14187 void
14188 disable_breakpoint (struct breakpoint *bpt)
14189 {
14190   /* Never disable a watchpoint scope breakpoint; we want to
14191      hit them when we leave scope so we can delete both the
14192      watchpoint and its scope breakpoint at that time.  */
14193   if (bpt->type == bp_watchpoint_scope)
14194     return;
14195
14196   /* You can't disable permanent breakpoints.  */
14197   if (bpt->enable_state == bp_permanent)
14198     return;
14199
14200   bpt->enable_state = bp_disabled;
14201
14202   /* Mark breakpoint locations modified.  */
14203   mark_breakpoint_modified (bpt);
14204
14205   if (target_supports_enable_disable_tracepoint ()
14206       && current_trace_status ()->running && is_tracepoint (bpt))
14207     {
14208       struct bp_location *location;
14209      
14210       for (location = bpt->loc; location; location = location->next)
14211         target_disable_tracepoint (location);
14212     }
14213
14214   update_global_location_list (0);
14215
14216   observer_notify_breakpoint_modified (bpt);
14217 }
14218
14219 /* A callback for iterate_over_related_breakpoints.  */
14220
14221 static void
14222 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14223 {
14224   disable_breakpoint (b);
14225 }
14226
14227 /* A callback for map_breakpoint_numbers that calls
14228    disable_breakpoint.  */
14229
14230 static void
14231 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14232 {
14233   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14234 }
14235
14236 static void
14237 disable_command (char *args, int from_tty)
14238 {
14239   if (args == 0)
14240     {
14241       struct breakpoint *bpt;
14242
14243       ALL_BREAKPOINTS (bpt)
14244         if (user_breakpoint_p (bpt))
14245           disable_breakpoint (bpt);
14246     }
14247   else if (strchr (args, '.'))
14248     {
14249       struct bp_location *loc = find_location_by_number (args);
14250       if (loc)
14251         {
14252           if (loc->enabled)
14253             {
14254               loc->enabled = 0;
14255               mark_breakpoint_location_modified (loc);
14256             }
14257           if (target_supports_enable_disable_tracepoint ()
14258               && current_trace_status ()->running && loc->owner
14259               && is_tracepoint (loc->owner))
14260             target_disable_tracepoint (loc);
14261         }
14262       update_global_location_list (0);
14263     }
14264   else
14265     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
14266 }
14267
14268 static void
14269 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14270                         int count)
14271 {
14272   int target_resources_ok;
14273
14274   if (bpt->type == bp_hardware_breakpoint)
14275     {
14276       int i;
14277       i = hw_breakpoint_used_count ();
14278       target_resources_ok = 
14279         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14280                                             i + 1, 0);
14281       if (target_resources_ok == 0)
14282         error (_("No hardware breakpoint support in the target."));
14283       else if (target_resources_ok < 0)
14284         error (_("Hardware breakpoints used exceeds limit."));
14285     }
14286
14287   if (is_watchpoint (bpt))
14288     {
14289       /* Initialize it just to avoid a GCC false warning.  */
14290       enum enable_state orig_enable_state = 0;
14291       volatile struct gdb_exception e;
14292
14293       TRY_CATCH (e, RETURN_MASK_ALL)
14294         {
14295           struct watchpoint *w = (struct watchpoint *) bpt;
14296
14297           orig_enable_state = bpt->enable_state;
14298           bpt->enable_state = bp_enabled;
14299           update_watchpoint (w, 1 /* reparse */);
14300         }
14301       if (e.reason < 0)
14302         {
14303           bpt->enable_state = orig_enable_state;
14304           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14305                              bpt->number);
14306           return;
14307         }
14308     }
14309
14310   if (bpt->enable_state != bp_permanent)
14311     bpt->enable_state = bp_enabled;
14312
14313   bpt->enable_state = bp_enabled;
14314
14315   /* Mark breakpoint locations modified.  */
14316   mark_breakpoint_modified (bpt);
14317
14318   if (target_supports_enable_disable_tracepoint ()
14319       && current_trace_status ()->running && is_tracepoint (bpt))
14320     {
14321       struct bp_location *location;
14322
14323       for (location = bpt->loc; location; location = location->next)
14324         target_enable_tracepoint (location);
14325     }
14326
14327   bpt->disposition = disposition;
14328   bpt->enable_count = count;
14329   update_global_location_list (1);
14330   breakpoints_changed ();
14331   
14332   observer_notify_breakpoint_modified (bpt);
14333 }
14334
14335
14336 void
14337 enable_breakpoint (struct breakpoint *bpt)
14338 {
14339   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14340 }
14341
14342 static void
14343 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14344 {
14345   enable_breakpoint (bpt);
14346 }
14347
14348 /* A callback for map_breakpoint_numbers that calls
14349    enable_breakpoint.  */
14350
14351 static void
14352 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14353 {
14354   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14355 }
14356
14357 /* The enable command enables the specified breakpoints (or all defined
14358    breakpoints) so they once again become (or continue to be) effective
14359    in stopping the inferior.  */
14360
14361 static void
14362 enable_command (char *args, int from_tty)
14363 {
14364   if (args == 0)
14365     {
14366       struct breakpoint *bpt;
14367
14368       ALL_BREAKPOINTS (bpt)
14369         if (user_breakpoint_p (bpt))
14370           enable_breakpoint (bpt);
14371     }
14372   else if (strchr (args, '.'))
14373     {
14374       struct bp_location *loc = find_location_by_number (args);
14375       if (loc)
14376         {
14377           if (!loc->enabled)
14378             {
14379               loc->enabled = 1;
14380               mark_breakpoint_location_modified (loc);
14381             }
14382           if (target_supports_enable_disable_tracepoint ()
14383               && current_trace_status ()->running && loc->owner
14384               && is_tracepoint (loc->owner))
14385             target_enable_tracepoint (loc);
14386         }
14387       update_global_location_list (1);
14388     }
14389   else
14390     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
14391 }
14392
14393 /* This struct packages up disposition data for application to multiple
14394    breakpoints.  */
14395
14396 struct disp_data
14397 {
14398   enum bpdisp disp;
14399   int count;
14400 };
14401
14402 static void
14403 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14404 {
14405   struct disp_data disp_data = *(struct disp_data *) arg;
14406
14407   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14408 }
14409
14410 static void
14411 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14412 {
14413   struct disp_data disp = { disp_disable, 1 };
14414
14415   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14416 }
14417
14418 static void
14419 enable_once_command (char *args, int from_tty)
14420 {
14421   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14422 }
14423
14424 static void
14425 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14426 {
14427   struct disp_data disp = { disp_disable, *(int *) countptr };
14428
14429   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14430 }
14431
14432 static void
14433 enable_count_command (char *args, int from_tty)
14434 {
14435   int count = get_number (&args);
14436
14437   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14438 }
14439
14440 static void
14441 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14442 {
14443   struct disp_data disp = { disp_del, 1 };
14444
14445   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14446 }
14447
14448 static void
14449 enable_delete_command (char *args, int from_tty)
14450 {
14451   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14452 }
14453 \f
14454 static void
14455 set_breakpoint_cmd (char *args, int from_tty)
14456 {
14457 }
14458
14459 static void
14460 show_breakpoint_cmd (char *args, int from_tty)
14461 {
14462 }
14463
14464 /* Invalidate last known value of any hardware watchpoint if
14465    the memory which that value represents has been written to by
14466    GDB itself.  */
14467
14468 static void
14469 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
14470                                       const bfd_byte *data)
14471 {
14472   struct breakpoint *bp;
14473
14474   ALL_BREAKPOINTS (bp)
14475     if (bp->enable_state == bp_enabled
14476         && bp->type == bp_hardware_watchpoint)
14477       {
14478         struct watchpoint *wp = (struct watchpoint *) bp;
14479
14480         if (wp->val_valid && wp->val)
14481           {
14482             struct bp_location *loc;
14483
14484             for (loc = bp->loc; loc != NULL; loc = loc->next)
14485               if (loc->loc_type == bp_loc_hardware_watchpoint
14486                   && loc->address + loc->length > addr
14487                   && addr + len > loc->address)
14488                 {
14489                   value_free (wp->val);
14490                   wp->val = NULL;
14491                   wp->val_valid = 0;
14492                 }
14493           }
14494       }
14495 }
14496
14497 /* Use the last displayed codepoint's values, or nothing
14498    if they aren't valid.  */
14499
14500 struct symtabs_and_lines
14501 decode_line_spec_1 (char *string, int flags)
14502 {
14503   struct symtabs_and_lines sals;
14504
14505   if (string == 0)
14506     error (_("Empty line specification."));
14507   if (last_displayed_sal_is_valid ())
14508     sals = decode_line_1 (&string, flags,
14509                           get_last_displayed_symtab (),
14510                           get_last_displayed_line ());
14511   else
14512     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
14513   if (*string)
14514     error (_("Junk at end of line specification: %s"), string);
14515   return sals;
14516 }
14517
14518 /* Create and insert a raw software breakpoint at PC.  Return an
14519    identifier, which should be used to remove the breakpoint later.
14520    In general, places which call this should be using something on the
14521    breakpoint chain instead; this function should be eliminated
14522    someday.  */
14523
14524 void *
14525 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14526                                   struct address_space *aspace, CORE_ADDR pc)
14527 {
14528   struct bp_target_info *bp_tgt;
14529
14530   bp_tgt = XZALLOC (struct bp_target_info);
14531
14532   bp_tgt->placed_address_space = aspace;
14533   bp_tgt->placed_address = pc;
14534
14535   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14536     {
14537       /* Could not insert the breakpoint.  */
14538       xfree (bp_tgt);
14539       return NULL;
14540     }
14541
14542   return bp_tgt;
14543 }
14544
14545 /* Remove a breakpoint BP inserted by
14546    deprecated_insert_raw_breakpoint.  */
14547
14548 int
14549 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14550 {
14551   struct bp_target_info *bp_tgt = bp;
14552   int ret;
14553
14554   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14555   xfree (bp_tgt);
14556
14557   return ret;
14558 }
14559
14560 /* One (or perhaps two) breakpoints used for software single
14561    stepping.  */
14562
14563 static void *single_step_breakpoints[2];
14564 static struct gdbarch *single_step_gdbarch[2];
14565
14566 /* Create and insert a breakpoint for software single step.  */
14567
14568 void
14569 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14570                                struct address_space *aspace, 
14571                                CORE_ADDR next_pc)
14572 {
14573   void **bpt_p;
14574
14575   if (single_step_breakpoints[0] == NULL)
14576     {
14577       bpt_p = &single_step_breakpoints[0];
14578       single_step_gdbarch[0] = gdbarch;
14579     }
14580   else
14581     {
14582       gdb_assert (single_step_breakpoints[1] == NULL);
14583       bpt_p = &single_step_breakpoints[1];
14584       single_step_gdbarch[1] = gdbarch;
14585     }
14586
14587   /* NOTE drow/2006-04-11: A future improvement to this function would
14588      be to only create the breakpoints once, and actually put them on
14589      the breakpoint chain.  That would let us use set_raw_breakpoint.
14590      We could adjust the addresses each time they were needed.  Doing
14591      this requires corresponding changes elsewhere where single step
14592      breakpoints are handled, however.  So, for now, we use this.  */
14593
14594   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14595   if (*bpt_p == NULL)
14596     error (_("Could not insert single-step breakpoint at %s"),
14597              paddress (gdbarch, next_pc));
14598 }
14599
14600 /* Check if the breakpoints used for software single stepping
14601    were inserted or not.  */
14602
14603 int
14604 single_step_breakpoints_inserted (void)
14605 {
14606   return (single_step_breakpoints[0] != NULL
14607           || single_step_breakpoints[1] != NULL);
14608 }
14609
14610 /* Remove and delete any breakpoints used for software single step.  */
14611
14612 void
14613 remove_single_step_breakpoints (void)
14614 {
14615   gdb_assert (single_step_breakpoints[0] != NULL);
14616
14617   /* See insert_single_step_breakpoint for more about this deprecated
14618      call.  */
14619   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14620                                     single_step_breakpoints[0]);
14621   single_step_gdbarch[0] = NULL;
14622   single_step_breakpoints[0] = NULL;
14623
14624   if (single_step_breakpoints[1] != NULL)
14625     {
14626       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14627                                         single_step_breakpoints[1]);
14628       single_step_gdbarch[1] = NULL;
14629       single_step_breakpoints[1] = NULL;
14630     }
14631 }
14632
14633 /* Delete software single step breakpoints without removing them from
14634    the inferior.  This is intended to be used if the inferior's address
14635    space where they were inserted is already gone, e.g. after exit or
14636    exec.  */
14637
14638 void
14639 cancel_single_step_breakpoints (void)
14640 {
14641   int i;
14642
14643   for (i = 0; i < 2; i++)
14644     if (single_step_breakpoints[i])
14645       {
14646         xfree (single_step_breakpoints[i]);
14647         single_step_breakpoints[i] = NULL;
14648         single_step_gdbarch[i] = NULL;
14649       }
14650 }
14651
14652 /* Detach software single-step breakpoints from INFERIOR_PTID without
14653    removing them.  */
14654
14655 static void
14656 detach_single_step_breakpoints (void)
14657 {
14658   int i;
14659
14660   for (i = 0; i < 2; i++)
14661     if (single_step_breakpoints[i])
14662       target_remove_breakpoint (single_step_gdbarch[i],
14663                                 single_step_breakpoints[i]);
14664 }
14665
14666 /* Check whether a software single-step breakpoint is inserted at
14667    PC.  */
14668
14669 static int
14670 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
14671                                         CORE_ADDR pc)
14672 {
14673   int i;
14674
14675   for (i = 0; i < 2; i++)
14676     {
14677       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
14678       if (bp_tgt
14679           && breakpoint_address_match (bp_tgt->placed_address_space,
14680                                        bp_tgt->placed_address,
14681                                        aspace, pc))
14682         return 1;
14683     }
14684
14685   return 0;
14686 }
14687
14688 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
14689    non-zero otherwise.  */
14690 static int
14691 is_syscall_catchpoint_enabled (struct breakpoint *bp)
14692 {
14693   if (syscall_catchpoint_p (bp)
14694       && bp->enable_state != bp_disabled
14695       && bp->enable_state != bp_call_disabled)
14696     return 1;
14697   else
14698     return 0;
14699 }
14700
14701 int
14702 catch_syscall_enabled (void)
14703 {
14704   struct catch_syscall_inferior_data *inf_data
14705     = get_catch_syscall_inferior_data (current_inferior ());
14706
14707   return inf_data->total_syscalls_count != 0;
14708 }
14709
14710 int
14711 catching_syscall_number (int syscall_number)
14712 {
14713   struct breakpoint *bp;
14714
14715   ALL_BREAKPOINTS (bp)
14716     if (is_syscall_catchpoint_enabled (bp))
14717       {
14718         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
14719
14720         if (c->syscalls_to_be_caught)
14721           {
14722             int i, iter;
14723             for (i = 0;
14724                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
14725                  i++)
14726               if (syscall_number == iter)
14727                 return 1;
14728           }
14729         else
14730           return 1;
14731       }
14732
14733   return 0;
14734 }
14735
14736 /* Complete syscall names.  Used by "catch syscall".  */
14737 static VEC (char_ptr) *
14738 catch_syscall_completer (struct cmd_list_element *cmd,
14739                          char *text, char *word)
14740 {
14741   const char **list = get_syscall_names ();
14742   VEC (char_ptr) *retlist
14743     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
14744
14745   xfree (list);
14746   return retlist;
14747 }
14748
14749 /* Tracepoint-specific operations.  */
14750
14751 /* Set tracepoint count to NUM.  */
14752 static void
14753 set_tracepoint_count (int num)
14754 {
14755   tracepoint_count = num;
14756   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14757 }
14758
14759 static void
14760 trace_command (char *arg, int from_tty)
14761 {
14762   struct breakpoint_ops *ops;
14763   const char *arg_cp = arg;
14764
14765   if (arg && probe_linespec_to_ops (&arg_cp))
14766     ops = &tracepoint_probe_breakpoint_ops;
14767   else
14768     ops = &tracepoint_breakpoint_ops;
14769
14770   if (create_breakpoint (get_current_arch (),
14771                          arg,
14772                          NULL, 0, NULL, 1 /* parse arg */,
14773                          0 /* tempflag */,
14774                          bp_tracepoint /* type_wanted */,
14775                          0 /* Ignore count */,
14776                          pending_break_support,
14777                          ops,
14778                          from_tty,
14779                          1 /* enabled */,
14780                          0 /* internal */, 0))
14781     set_tracepoint_count (breakpoint_count);
14782 }
14783
14784 static void
14785 ftrace_command (char *arg, int from_tty)
14786 {
14787   if (create_breakpoint (get_current_arch (),
14788                          arg,
14789                          NULL, 0, NULL, 1 /* parse arg */,
14790                          0 /* tempflag */,
14791                          bp_fast_tracepoint /* type_wanted */,
14792                          0 /* Ignore count */,
14793                          pending_break_support,
14794                          &tracepoint_breakpoint_ops,
14795                          from_tty,
14796                          1 /* enabled */,
14797                          0 /* internal */, 0))
14798     set_tracepoint_count (breakpoint_count);
14799 }
14800
14801 /* strace command implementation.  Creates a static tracepoint.  */
14802
14803 static void
14804 strace_command (char *arg, int from_tty)
14805 {
14806   struct breakpoint_ops *ops;
14807
14808   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14809      or with a normal static tracepoint.  */
14810   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
14811     ops = &strace_marker_breakpoint_ops;
14812   else
14813     ops = &tracepoint_breakpoint_ops;
14814
14815   if (create_breakpoint (get_current_arch (),
14816                          arg,
14817                          NULL, 0, NULL, 1 /* parse arg */,
14818                          0 /* tempflag */,
14819                          bp_static_tracepoint /* type_wanted */,
14820                          0 /* Ignore count */,
14821                          pending_break_support,
14822                          ops,
14823                          from_tty,
14824                          1 /* enabled */,
14825                          0 /* internal */, 0))
14826     set_tracepoint_count (breakpoint_count);
14827 }
14828
14829 /* Set up a fake reader function that gets command lines from a linked
14830    list that was acquired during tracepoint uploading.  */
14831
14832 static struct uploaded_tp *this_utp;
14833 static int next_cmd;
14834
14835 static char *
14836 read_uploaded_action (void)
14837 {
14838   char *rslt;
14839
14840   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14841
14842   next_cmd++;
14843
14844   return rslt;
14845 }
14846
14847 /* Given information about a tracepoint as recorded on a target (which
14848    can be either a live system or a trace file), attempt to create an
14849    equivalent GDB tracepoint.  This is not a reliable process, since
14850    the target does not necessarily have all the information used when
14851    the tracepoint was originally defined.  */
14852   
14853 struct tracepoint *
14854 create_tracepoint_from_upload (struct uploaded_tp *utp)
14855 {
14856   char *addr_str, small_buf[100];
14857   struct tracepoint *tp;
14858
14859   if (utp->at_string)
14860     addr_str = utp->at_string;
14861   else
14862     {
14863       /* In the absence of a source location, fall back to raw
14864          address.  Since there is no way to confirm that the address
14865          means the same thing as when the trace was started, warn the
14866          user.  */
14867       warning (_("Uploaded tracepoint %d has no "
14868                  "source location, using raw address"),
14869                utp->number);
14870       sprintf (small_buf, "*%s", hex_string (utp->addr));
14871       addr_str = small_buf;
14872     }
14873
14874   /* There's not much we can do with a sequence of bytecodes.  */
14875   if (utp->cond && !utp->cond_string)
14876     warning (_("Uploaded tracepoint %d condition "
14877                "has no source form, ignoring it"),
14878              utp->number);
14879
14880   if (!create_breakpoint (get_current_arch (),
14881                           addr_str,
14882                           utp->cond_string, -1, NULL,
14883                           0 /* parse cond/thread */,
14884                           0 /* tempflag */,
14885                           utp->type /* type_wanted */,
14886                           0 /* Ignore count */,
14887                           pending_break_support,
14888                           &tracepoint_breakpoint_ops,
14889                           0 /* from_tty */,
14890                           utp->enabled /* enabled */,
14891                           0 /* internal */,
14892                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14893     return NULL;
14894
14895   set_tracepoint_count (breakpoint_count);
14896   
14897   /* Get the tracepoint we just created.  */
14898   tp = get_tracepoint (tracepoint_count);
14899   gdb_assert (tp != NULL);
14900
14901   if (utp->pass > 0)
14902     {
14903       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
14904
14905       trace_pass_command (small_buf, 0);
14906     }
14907
14908   /* If we have uploaded versions of the original commands, set up a
14909      special-purpose "reader" function and call the usual command line
14910      reader, then pass the result to the breakpoint command-setting
14911      function.  */
14912   if (!VEC_empty (char_ptr, utp->cmd_strings))
14913     {
14914       struct command_line *cmd_list;
14915
14916       this_utp = utp;
14917       next_cmd = 0;
14918
14919       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14920
14921       breakpoint_set_commands (&tp->base, cmd_list);
14922     }
14923   else if (!VEC_empty (char_ptr, utp->actions)
14924            || !VEC_empty (char_ptr, utp->step_actions))
14925     warning (_("Uploaded tracepoint %d actions "
14926                "have no source form, ignoring them"),
14927              utp->number);
14928
14929   /* Copy any status information that might be available.  */
14930   tp->base.hit_count = utp->hit_count;
14931   tp->traceframe_usage = utp->traceframe_usage;
14932
14933   return tp;
14934 }
14935   
14936 /* Print information on tracepoint number TPNUM_EXP, or all if
14937    omitted.  */
14938
14939 static void
14940 tracepoints_info (char *args, int from_tty)
14941 {
14942   struct ui_out *uiout = current_uiout;
14943   int num_printed;
14944
14945   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14946
14947   if (num_printed == 0)
14948     {
14949       if (args == NULL || *args == '\0')
14950         ui_out_message (uiout, 0, "No tracepoints.\n");
14951       else
14952         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
14953     }
14954
14955   default_collect_info ();
14956 }
14957
14958 /* The 'enable trace' command enables tracepoints.
14959    Not supported by all targets.  */
14960 static void
14961 enable_trace_command (char *args, int from_tty)
14962 {
14963   enable_command (args, from_tty);
14964 }
14965
14966 /* The 'disable trace' command disables tracepoints.
14967    Not supported by all targets.  */
14968 static void
14969 disable_trace_command (char *args, int from_tty)
14970 {
14971   disable_command (args, from_tty);
14972 }
14973
14974 /* Remove a tracepoint (or all if no argument).  */
14975 static void
14976 delete_trace_command (char *arg, int from_tty)
14977 {
14978   struct breakpoint *b, *b_tmp;
14979
14980   dont_repeat ();
14981
14982   if (arg == 0)
14983     {
14984       int breaks_to_delete = 0;
14985
14986       /* Delete all breakpoints if no argument.
14987          Do not delete internal or call-dummy breakpoints, these
14988          have to be deleted with an explicit breakpoint number 
14989          argument.  */
14990       ALL_TRACEPOINTS (b)
14991         if (is_tracepoint (b) && user_breakpoint_p (b))
14992           {
14993             breaks_to_delete = 1;
14994             break;
14995           }
14996
14997       /* Ask user only if there are some breakpoints to delete.  */
14998       if (!from_tty
14999           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15000         {
15001           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15002             if (is_tracepoint (b) && user_breakpoint_p (b))
15003               delete_breakpoint (b);
15004         }
15005     }
15006   else
15007     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15008 }
15009
15010 /* Helper function for trace_pass_command.  */
15011
15012 static void
15013 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15014 {
15015   tp->pass_count = count;
15016   observer_notify_tracepoint_modified (tp->base.number);
15017   if (from_tty)
15018     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15019                      tp->base.number, count);
15020 }
15021
15022 /* Set passcount for tracepoint.
15023
15024    First command argument is passcount, second is tracepoint number.
15025    If tracepoint number omitted, apply to most recently defined.
15026    Also accepts special argument "all".  */
15027
15028 static void
15029 trace_pass_command (char *args, int from_tty)
15030 {
15031   struct tracepoint *t1;
15032   unsigned int count;
15033
15034   if (args == 0 || *args == 0)
15035     error (_("passcount command requires an "
15036              "argument (count + optional TP num)"));
15037
15038   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15039
15040   while (*args && isspace ((int) *args))
15041     args++;
15042
15043   if (*args && strncasecmp (args, "all", 3) == 0)
15044     {
15045       struct breakpoint *b;
15046
15047       args += 3;                        /* Skip special argument "all".  */
15048       if (*args)
15049         error (_("Junk at end of arguments."));
15050
15051       ALL_TRACEPOINTS (b)
15052       {
15053         t1 = (struct tracepoint *) b;
15054         trace_pass_set_count (t1, count, from_tty);
15055       }
15056     }
15057   else if (*args == '\0')
15058     {
15059       t1 = get_tracepoint_by_number (&args, NULL, 1);
15060       if (t1)
15061         trace_pass_set_count (t1, count, from_tty);
15062     }
15063   else
15064     {
15065       struct get_number_or_range_state state;
15066
15067       init_number_or_range (&state, args);
15068       while (!state.finished)
15069         {
15070           t1 = get_tracepoint_by_number (&args, &state, 1);
15071           if (t1)
15072             trace_pass_set_count (t1, count, from_tty);
15073         }
15074     }
15075 }
15076
15077 struct tracepoint *
15078 get_tracepoint (int num)
15079 {
15080   struct breakpoint *t;
15081
15082   ALL_TRACEPOINTS (t)
15083     if (t->number == num)
15084       return (struct tracepoint *) t;
15085
15086   return NULL;
15087 }
15088
15089 /* Find the tracepoint with the given target-side number (which may be
15090    different from the tracepoint number after disconnecting and
15091    reconnecting).  */
15092
15093 struct tracepoint *
15094 get_tracepoint_by_number_on_target (int num)
15095 {
15096   struct breakpoint *b;
15097
15098   ALL_TRACEPOINTS (b)
15099     {
15100       struct tracepoint *t = (struct tracepoint *) b;
15101
15102       if (t->number_on_target == num)
15103         return t;
15104     }
15105
15106   return NULL;
15107 }
15108
15109 /* Utility: parse a tracepoint number and look it up in the list.
15110    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15111    If OPTIONAL_P is true, then if the argument is missing, the most
15112    recent tracepoint (tracepoint_count) is returned.  */
15113 struct tracepoint *
15114 get_tracepoint_by_number (char **arg,
15115                           struct get_number_or_range_state *state,
15116                           int optional_p)
15117 {
15118   extern int tracepoint_count;
15119   struct breakpoint *t;
15120   int tpnum;
15121   char *instring = arg == NULL ? NULL : *arg;
15122
15123   if (state)
15124     {
15125       gdb_assert (!state->finished);
15126       tpnum = get_number_or_range (state);
15127     }
15128   else if (arg == NULL || *arg == NULL || ! **arg)
15129     {
15130       if (optional_p)
15131         tpnum = tracepoint_count;
15132       else
15133         error_no_arg (_("tracepoint number"));
15134     }
15135   else
15136     tpnum = get_number (arg);
15137
15138   if (tpnum <= 0)
15139     {
15140       if (instring && *instring)
15141         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15142                          instring);
15143       else
15144         printf_filtered (_("Tracepoint argument missing "
15145                            "and no previous tracepoint\n"));
15146       return NULL;
15147     }
15148
15149   ALL_TRACEPOINTS (t)
15150     if (t->number == tpnum)
15151     {
15152       return (struct tracepoint *) t;
15153     }
15154
15155   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
15156   return NULL;
15157 }
15158
15159 void
15160 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
15161 {
15162   if (b->thread != -1)
15163     fprintf_unfiltered (fp, " thread %d", b->thread);
15164
15165   if (b->task != 0)
15166     fprintf_unfiltered (fp, " task %d", b->task);
15167
15168   fprintf_unfiltered (fp, "\n");
15169 }
15170
15171 /* Save information on user settable breakpoints (watchpoints, etc) to
15172    a new script file named FILENAME.  If FILTER is non-NULL, call it
15173    on each breakpoint and only include the ones for which it returns
15174    non-zero.  */
15175
15176 static void
15177 save_breakpoints (char *filename, int from_tty,
15178                   int (*filter) (const struct breakpoint *))
15179 {
15180   struct breakpoint *tp;
15181   int any = 0;
15182   char *pathname;
15183   struct cleanup *cleanup;
15184   struct ui_file *fp;
15185   int extra_trace_bits = 0;
15186
15187   if (filename == 0 || *filename == 0)
15188     error (_("Argument required (file name in which to save)"));
15189
15190   /* See if we have anything to save.  */
15191   ALL_BREAKPOINTS (tp)
15192   {
15193     /* Skip internal and momentary breakpoints.  */
15194     if (!user_breakpoint_p (tp))
15195       continue;
15196
15197     /* If we have a filter, only save the breakpoints it accepts.  */
15198     if (filter && !filter (tp))
15199       continue;
15200
15201     any = 1;
15202
15203     if (is_tracepoint (tp))
15204       {
15205         extra_trace_bits = 1;
15206
15207         /* We can stop searching.  */
15208         break;
15209       }
15210   }
15211
15212   if (!any)
15213     {
15214       warning (_("Nothing to save."));
15215       return;
15216     }
15217
15218   pathname = tilde_expand (filename);
15219   cleanup = make_cleanup (xfree, pathname);
15220   fp = gdb_fopen (pathname, "w");
15221   if (!fp)
15222     error (_("Unable to open file '%s' for saving (%s)"),
15223            filename, safe_strerror (errno));
15224   make_cleanup_ui_file_delete (fp);
15225
15226   if (extra_trace_bits)
15227     save_trace_state_variables (fp);
15228
15229   ALL_BREAKPOINTS (tp)
15230   {
15231     /* Skip internal and momentary breakpoints.  */
15232     if (!user_breakpoint_p (tp))
15233       continue;
15234
15235     /* If we have a filter, only save the breakpoints it accepts.  */
15236     if (filter && !filter (tp))
15237       continue;
15238
15239     tp->ops->print_recreate (tp, fp);
15240
15241     /* Note, we can't rely on tp->number for anything, as we can't
15242        assume the recreated breakpoint numbers will match.  Use $bpnum
15243        instead.  */
15244
15245     if (tp->cond_string)
15246       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15247
15248     if (tp->ignore_count)
15249       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15250
15251     if (tp->commands)
15252       {
15253         volatile struct gdb_exception ex;       
15254
15255         fprintf_unfiltered (fp, "  commands\n");
15256         
15257         ui_out_redirect (current_uiout, fp);
15258         TRY_CATCH (ex, RETURN_MASK_ALL)
15259           {
15260             print_command_lines (current_uiout, tp->commands->commands, 2);
15261           }
15262         ui_out_redirect (current_uiout, NULL);
15263
15264         if (ex.reason < 0)
15265           throw_exception (ex);
15266
15267         fprintf_unfiltered (fp, "  end\n");
15268       }
15269
15270     if (tp->enable_state == bp_disabled)
15271       fprintf_unfiltered (fp, "disable\n");
15272
15273     /* If this is a multi-location breakpoint, check if the locations
15274        should be individually disabled.  Watchpoint locations are
15275        special, and not user visible.  */
15276     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15277       {
15278         struct bp_location *loc;
15279         int n = 1;
15280
15281         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15282           if (!loc->enabled)
15283             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15284       }
15285   }
15286
15287   if (extra_trace_bits && *default_collect)
15288     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15289
15290   do_cleanups (cleanup);
15291   if (from_tty)
15292     printf_filtered (_("Saved to file '%s'.\n"), filename);
15293 }
15294
15295 /* The `save breakpoints' command.  */
15296
15297 static void
15298 save_breakpoints_command (char *args, int from_tty)
15299 {
15300   save_breakpoints (args, from_tty, NULL);
15301 }
15302
15303 /* The `save tracepoints' command.  */
15304
15305 static void
15306 save_tracepoints_command (char *args, int from_tty)
15307 {
15308   save_breakpoints (args, from_tty, is_tracepoint);
15309 }
15310
15311 /* Create a vector of all tracepoints.  */
15312
15313 VEC(breakpoint_p) *
15314 all_tracepoints (void)
15315 {
15316   VEC(breakpoint_p) *tp_vec = 0;
15317   struct breakpoint *tp;
15318
15319   ALL_TRACEPOINTS (tp)
15320   {
15321     VEC_safe_push (breakpoint_p, tp_vec, tp);
15322   }
15323
15324   return tp_vec;
15325 }
15326
15327 \f
15328 /* This help string is used for the break, hbreak, tbreak and thbreak
15329    commands.  It is defined as a macro to prevent duplication.
15330    COMMAND should be a string constant containing the name of the
15331    command.  */
15332 #define BREAK_ARGS_HELP(command) \
15333 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15334 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15335 If a line number is specified, break at start of code for that line.\n\
15336 If a function is specified, break at start of code for that function.\n\
15337 If an address is specified, break at that exact address.\n\
15338 With no LOCATION, uses current execution address of the selected\n\
15339 stack frame.  This is useful for breaking on return to a stack frame.\n\
15340 \n\
15341 THREADNUM is the number from \"info threads\".\n\
15342 CONDITION is a boolean expression.\n\
15343 \n\
15344 Multiple breakpoints at one place are permitted, and useful if their\n\
15345 conditions are different.\n\
15346 \n\
15347 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15348
15349 /* List of subcommands for "catch".  */
15350 static struct cmd_list_element *catch_cmdlist;
15351
15352 /* List of subcommands for "tcatch".  */
15353 static struct cmd_list_element *tcatch_cmdlist;
15354
15355 void
15356 add_catch_command (char *name, char *docstring,
15357                    void (*sfunc) (char *args, int from_tty,
15358                                   struct cmd_list_element *command),
15359                    completer_ftype *completer,
15360                    void *user_data_catch,
15361                    void *user_data_tcatch)
15362 {
15363   struct cmd_list_element *command;
15364
15365   command = add_cmd (name, class_breakpoint, NULL, docstring,
15366                      &catch_cmdlist);
15367   set_cmd_sfunc (command, sfunc);
15368   set_cmd_context (command, user_data_catch);
15369   set_cmd_completer (command, completer);
15370
15371   command = add_cmd (name, class_breakpoint, NULL, docstring,
15372                      &tcatch_cmdlist);
15373   set_cmd_sfunc (command, sfunc);
15374   set_cmd_context (command, user_data_tcatch);
15375   set_cmd_completer (command, completer);
15376 }
15377
15378 static void
15379 clear_syscall_counts (struct inferior *inf)
15380 {
15381   struct catch_syscall_inferior_data *inf_data
15382     = get_catch_syscall_inferior_data (inf);
15383
15384   inf_data->total_syscalls_count = 0;
15385   inf_data->any_syscall_count = 0;
15386   VEC_free (int, inf_data->syscalls_counts);
15387 }
15388
15389 static void
15390 save_command (char *arg, int from_tty)
15391 {
15392   printf_unfiltered (_("\"save\" must be followed by "
15393                        "the name of a save subcommand.\n"));
15394   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15395 }
15396
15397 struct breakpoint *
15398 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15399                           void *data)
15400 {
15401   struct breakpoint *b, *b_tmp;
15402
15403   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15404     {
15405       if ((*callback) (b, data))
15406         return b;
15407     }
15408
15409   return NULL;
15410 }
15411
15412 /* Zero if any of the breakpoint's locations could be a location where
15413    functions have been inlined, nonzero otherwise.  */
15414
15415 static int
15416 is_non_inline_function (struct breakpoint *b)
15417 {
15418   /* The shared library event breakpoint is set on the address of a
15419      non-inline function.  */
15420   if (b->type == bp_shlib_event)
15421     return 1;
15422
15423   return 0;
15424 }
15425
15426 /* Nonzero if the specified PC cannot be a location where functions
15427    have been inlined.  */
15428
15429 int
15430 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15431                            const struct target_waitstatus *ws)
15432 {
15433   struct breakpoint *b;
15434   struct bp_location *bl;
15435
15436   ALL_BREAKPOINTS (b)
15437     {
15438       if (!is_non_inline_function (b))
15439         continue;
15440
15441       for (bl = b->loc; bl != NULL; bl = bl->next)
15442         {
15443           if (!bl->shlib_disabled
15444               && bpstat_check_location (bl, aspace, pc, ws))
15445             return 1;
15446         }
15447     }
15448
15449   return 0;
15450 }
15451
15452 void
15453 initialize_breakpoint_ops (void)
15454 {
15455   static int initialized = 0;
15456
15457   struct breakpoint_ops *ops;
15458
15459   if (initialized)
15460     return;
15461   initialized = 1;
15462
15463   /* The breakpoint_ops structure to be inherit by all kinds of
15464      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15465      internal and momentary breakpoints, etc.).  */
15466   ops = &bkpt_base_breakpoint_ops;
15467   *ops = base_breakpoint_ops;
15468   ops->re_set = bkpt_re_set;
15469   ops->insert_location = bkpt_insert_location;
15470   ops->remove_location = bkpt_remove_location;
15471   ops->breakpoint_hit = bkpt_breakpoint_hit;
15472   ops->create_sals_from_address = bkpt_create_sals_from_address;
15473   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15474   ops->decode_linespec = bkpt_decode_linespec;
15475
15476   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15477   ops = &bkpt_breakpoint_ops;
15478   *ops = bkpt_base_breakpoint_ops;
15479   ops->re_set = bkpt_re_set;
15480   ops->resources_needed = bkpt_resources_needed;
15481   ops->print_it = bkpt_print_it;
15482   ops->print_mention = bkpt_print_mention;
15483   ops->print_recreate = bkpt_print_recreate;
15484
15485   /* Ranged breakpoints.  */
15486   ops = &ranged_breakpoint_ops;
15487   *ops = bkpt_breakpoint_ops;
15488   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15489   ops->resources_needed = resources_needed_ranged_breakpoint;
15490   ops->print_it = print_it_ranged_breakpoint;
15491   ops->print_one = print_one_ranged_breakpoint;
15492   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15493   ops->print_mention = print_mention_ranged_breakpoint;
15494   ops->print_recreate = print_recreate_ranged_breakpoint;
15495
15496   /* Internal breakpoints.  */
15497   ops = &internal_breakpoint_ops;
15498   *ops = bkpt_base_breakpoint_ops;
15499   ops->re_set = internal_bkpt_re_set;
15500   ops->check_status = internal_bkpt_check_status;
15501   ops->print_it = internal_bkpt_print_it;
15502   ops->print_mention = internal_bkpt_print_mention;
15503
15504   /* Momentary breakpoints.  */
15505   ops = &momentary_breakpoint_ops;
15506   *ops = bkpt_base_breakpoint_ops;
15507   ops->re_set = momentary_bkpt_re_set;
15508   ops->check_status = momentary_bkpt_check_status;
15509   ops->print_it = momentary_bkpt_print_it;
15510   ops->print_mention = momentary_bkpt_print_mention;
15511
15512   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
15513   ops = &longjmp_breakpoint_ops;
15514   *ops = momentary_breakpoint_ops;
15515   ops->dtor = longjmp_bkpt_dtor;
15516
15517   /* Probe breakpoints.  */
15518   ops = &bkpt_probe_breakpoint_ops;
15519   *ops = bkpt_breakpoint_ops;
15520   ops->insert_location = bkpt_probe_insert_location;
15521   ops->remove_location = bkpt_probe_remove_location;
15522   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15523   ops->decode_linespec = bkpt_probe_decode_linespec;
15524
15525   /* GNU v3 exception catchpoints.  */
15526   ops = &gnu_v3_exception_catchpoint_ops;
15527   *ops = bkpt_breakpoint_ops;
15528   ops->print_it = print_it_exception_catchpoint;
15529   ops->print_one = print_one_exception_catchpoint;
15530   ops->print_mention = print_mention_exception_catchpoint;
15531   ops->print_recreate = print_recreate_exception_catchpoint;
15532
15533   /* Watchpoints.  */
15534   ops = &watchpoint_breakpoint_ops;
15535   *ops = base_breakpoint_ops;
15536   ops->dtor = dtor_watchpoint;
15537   ops->re_set = re_set_watchpoint;
15538   ops->insert_location = insert_watchpoint;
15539   ops->remove_location = remove_watchpoint;
15540   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15541   ops->check_status = check_status_watchpoint;
15542   ops->resources_needed = resources_needed_watchpoint;
15543   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15544   ops->print_it = print_it_watchpoint;
15545   ops->print_mention = print_mention_watchpoint;
15546   ops->print_recreate = print_recreate_watchpoint;
15547
15548   /* Masked watchpoints.  */
15549   ops = &masked_watchpoint_breakpoint_ops;
15550   *ops = watchpoint_breakpoint_ops;
15551   ops->insert_location = insert_masked_watchpoint;
15552   ops->remove_location = remove_masked_watchpoint;
15553   ops->resources_needed = resources_needed_masked_watchpoint;
15554   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15555   ops->print_it = print_it_masked_watchpoint;
15556   ops->print_one_detail = print_one_detail_masked_watchpoint;
15557   ops->print_mention = print_mention_masked_watchpoint;
15558   ops->print_recreate = print_recreate_masked_watchpoint;
15559
15560   /* Tracepoints.  */
15561   ops = &tracepoint_breakpoint_ops;
15562   *ops = base_breakpoint_ops;
15563   ops->re_set = tracepoint_re_set;
15564   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15565   ops->print_one_detail = tracepoint_print_one_detail;
15566   ops->print_mention = tracepoint_print_mention;
15567   ops->print_recreate = tracepoint_print_recreate;
15568   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15569   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15570   ops->decode_linespec = tracepoint_decode_linespec;
15571
15572   /* Probe tracepoints.  */
15573   ops = &tracepoint_probe_breakpoint_ops;
15574   *ops = tracepoint_breakpoint_ops;
15575   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15576   ops->decode_linespec = tracepoint_probe_decode_linespec;
15577
15578   /* Static tracepoints with marker (`-m').  */
15579   ops = &strace_marker_breakpoint_ops;
15580   *ops = tracepoint_breakpoint_ops;
15581   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15582   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15583   ops->decode_linespec = strace_marker_decode_linespec;
15584
15585   /* Fork catchpoints.  */
15586   ops = &catch_fork_breakpoint_ops;
15587   *ops = base_breakpoint_ops;
15588   ops->insert_location = insert_catch_fork;
15589   ops->remove_location = remove_catch_fork;
15590   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15591   ops->print_it = print_it_catch_fork;
15592   ops->print_one = print_one_catch_fork;
15593   ops->print_mention = print_mention_catch_fork;
15594   ops->print_recreate = print_recreate_catch_fork;
15595
15596   /* Vfork catchpoints.  */
15597   ops = &catch_vfork_breakpoint_ops;
15598   *ops = base_breakpoint_ops;
15599   ops->insert_location = insert_catch_vfork;
15600   ops->remove_location = remove_catch_vfork;
15601   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15602   ops->print_it = print_it_catch_vfork;
15603   ops->print_one = print_one_catch_vfork;
15604   ops->print_mention = print_mention_catch_vfork;
15605   ops->print_recreate = print_recreate_catch_vfork;
15606
15607   /* Exec catchpoints.  */
15608   ops = &catch_exec_breakpoint_ops;
15609   *ops = base_breakpoint_ops;
15610   ops->dtor = dtor_catch_exec;
15611   ops->insert_location = insert_catch_exec;
15612   ops->remove_location = remove_catch_exec;
15613   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15614   ops->print_it = print_it_catch_exec;
15615   ops->print_one = print_one_catch_exec;
15616   ops->print_mention = print_mention_catch_exec;
15617   ops->print_recreate = print_recreate_catch_exec;
15618
15619   /* Syscall catchpoints.  */
15620   ops = &catch_syscall_breakpoint_ops;
15621   *ops = base_breakpoint_ops;
15622   ops->dtor = dtor_catch_syscall;
15623   ops->insert_location = insert_catch_syscall;
15624   ops->remove_location = remove_catch_syscall;
15625   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15626   ops->print_it = print_it_catch_syscall;
15627   ops->print_one = print_one_catch_syscall;
15628   ops->print_mention = print_mention_catch_syscall;
15629   ops->print_recreate = print_recreate_catch_syscall;
15630
15631   /* Solib-related catchpoints.  */
15632   ops = &catch_solib_breakpoint_ops;
15633   *ops = base_breakpoint_ops;
15634   ops->dtor = dtor_catch_solib;
15635   ops->insert_location = insert_catch_solib;
15636   ops->remove_location = remove_catch_solib;
15637   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15638   ops->check_status = check_status_catch_solib;
15639   ops->print_it = print_it_catch_solib;
15640   ops->print_one = print_one_catch_solib;
15641   ops->print_mention = print_mention_catch_solib;
15642   ops->print_recreate = print_recreate_catch_solib;
15643
15644   ops = &dprintf_breakpoint_ops;
15645   *ops = bkpt_base_breakpoint_ops;
15646   ops->re_set = bkpt_re_set;
15647   ops->resources_needed = bkpt_resources_needed;
15648   ops->print_it = bkpt_print_it;
15649   ops->print_mention = bkpt_print_mention;
15650   ops->print_recreate = bkpt_print_recreate;
15651 }
15652
15653 void
15654 _initialize_breakpoint (void)
15655 {
15656   struct cmd_list_element *c;
15657
15658   initialize_breakpoint_ops ();
15659
15660   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15661   observer_attach_inferior_exit (clear_syscall_counts);
15662   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15663
15664   breakpoint_objfile_key
15665     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15666
15667   catch_syscall_inferior_data
15668     = register_inferior_data_with_cleanup (catch_syscall_inferior_data_cleanup);
15669
15670   breakpoint_chain = 0;
15671   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15672      before a breakpoint is set.  */
15673   breakpoint_count = 0;
15674
15675   tracepoint_count = 0;
15676
15677   add_com ("ignore", class_breakpoint, ignore_command, _("\
15678 Set ignore-count of breakpoint number N to COUNT.\n\
15679 Usage is `ignore N COUNT'."));
15680   if (xdb_commands)
15681     add_com_alias ("bc", "ignore", class_breakpoint, 1);
15682
15683   add_com ("commands", class_breakpoint, commands_command, _("\
15684 Set commands to be executed when a breakpoint is hit.\n\
15685 Give breakpoint number as argument after \"commands\".\n\
15686 With no argument, the targeted breakpoint is the last one set.\n\
15687 The commands themselves follow starting on the next line.\n\
15688 Type a line containing \"end\" to indicate the end of them.\n\
15689 Give \"silent\" as the first line to make the breakpoint silent;\n\
15690 then no output is printed when it is hit, except what the commands print."));
15691
15692   c = add_com ("condition", class_breakpoint, condition_command, _("\
15693 Specify breakpoint number N to break only if COND is true.\n\
15694 Usage is `condition N COND', where N is an integer and COND is an\n\
15695 expression to be evaluated whenever breakpoint N is reached."));
15696   set_cmd_completer (c, condition_completer);
15697
15698   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15699 Set a temporary breakpoint.\n\
15700 Like \"break\" except the breakpoint is only temporary,\n\
15701 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15702 by using \"enable delete\" on the breakpoint number.\n\
15703 \n"
15704 BREAK_ARGS_HELP ("tbreak")));
15705   set_cmd_completer (c, location_completer);
15706
15707   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15708 Set a hardware assisted breakpoint.\n\
15709 Like \"break\" except the breakpoint requires hardware support,\n\
15710 some target hardware may not have this support.\n\
15711 \n"
15712 BREAK_ARGS_HELP ("hbreak")));
15713   set_cmd_completer (c, location_completer);
15714
15715   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15716 Set a temporary hardware assisted breakpoint.\n\
15717 Like \"hbreak\" except the breakpoint is only temporary,\n\
15718 so it will be deleted when hit.\n\
15719 \n"
15720 BREAK_ARGS_HELP ("thbreak")));
15721   set_cmd_completer (c, location_completer);
15722
15723   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15724 Enable some breakpoints.\n\
15725 Give breakpoint numbers (separated by spaces) as arguments.\n\
15726 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15727 This is used to cancel the effect of the \"disable\" command.\n\
15728 With a subcommand you can enable temporarily."),
15729                   &enablelist, "enable ", 1, &cmdlist);
15730   if (xdb_commands)
15731     add_com ("ab", class_breakpoint, enable_command, _("\
15732 Enable some breakpoints.\n\
15733 Give breakpoint numbers (separated by spaces) as arguments.\n\
15734 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15735 This is used to cancel the effect of the \"disable\" command.\n\
15736 With a subcommand you can enable temporarily."));
15737
15738   add_com_alias ("en", "enable", class_breakpoint, 1);
15739
15740   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15741 Enable some breakpoints.\n\
15742 Give breakpoint numbers (separated by spaces) as arguments.\n\
15743 This is used to cancel the effect of the \"disable\" command.\n\
15744 May be abbreviated to simply \"enable\".\n"),
15745                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15746
15747   add_cmd ("once", no_class, enable_once_command, _("\
15748 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15749 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15750            &enablebreaklist);
15751
15752   add_cmd ("delete", no_class, enable_delete_command, _("\
15753 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15754 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15755            &enablebreaklist);
15756
15757   add_cmd ("count", no_class, enable_count_command, _("\
15758 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15759 If a breakpoint is hit while enabled in this fashion,\n\
15760 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15761            &enablebreaklist);
15762
15763   add_cmd ("delete", no_class, enable_delete_command, _("\
15764 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15765 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15766            &enablelist);
15767
15768   add_cmd ("once", no_class, enable_once_command, _("\
15769 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15770 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15771            &enablelist);
15772
15773   add_cmd ("count", no_class, enable_count_command, _("\
15774 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15775 If a breakpoint is hit while enabled in this fashion,\n\
15776 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15777            &enablelist);
15778
15779   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15780 Disable some breakpoints.\n\
15781 Arguments are breakpoint numbers with spaces in between.\n\
15782 To disable all breakpoints, give no argument.\n\
15783 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15784                   &disablelist, "disable ", 1, &cmdlist);
15785   add_com_alias ("dis", "disable", class_breakpoint, 1);
15786   add_com_alias ("disa", "disable", class_breakpoint, 1);
15787   if (xdb_commands)
15788     add_com ("sb", class_breakpoint, disable_command, _("\
15789 Disable some breakpoints.\n\
15790 Arguments are breakpoint numbers with spaces in between.\n\
15791 To disable all breakpoints, give no argument.\n\
15792 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
15793
15794   add_cmd ("breakpoints", class_alias, disable_command, _("\
15795 Disable some breakpoints.\n\
15796 Arguments are breakpoint numbers with spaces in between.\n\
15797 To disable all breakpoints, give no argument.\n\
15798 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15799 This command may be abbreviated \"disable\"."),
15800            &disablelist);
15801
15802   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15803 Delete some breakpoints or auto-display expressions.\n\
15804 Arguments are breakpoint numbers with spaces in between.\n\
15805 To delete all breakpoints, give no argument.\n\
15806 \n\
15807 Also a prefix command for deletion of other GDB objects.\n\
15808 The \"unset\" command is also an alias for \"delete\"."),
15809                   &deletelist, "delete ", 1, &cmdlist);
15810   add_com_alias ("d", "delete", class_breakpoint, 1);
15811   add_com_alias ("del", "delete", class_breakpoint, 1);
15812   if (xdb_commands)
15813     add_com ("db", class_breakpoint, delete_command, _("\
15814 Delete some breakpoints.\n\
15815 Arguments are breakpoint numbers with spaces in between.\n\
15816 To delete all breakpoints, give no argument.\n"));
15817
15818   add_cmd ("breakpoints", class_alias, delete_command, _("\
15819 Delete some breakpoints or auto-display expressions.\n\
15820 Arguments are breakpoint numbers with spaces in between.\n\
15821 To delete all breakpoints, give no argument.\n\
15822 This command may be abbreviated \"delete\"."),
15823            &deletelist);
15824
15825   add_com ("clear", class_breakpoint, clear_command, _("\
15826 Clear breakpoint at specified line or function.\n\
15827 Argument may be line number, function name, or \"*\" and an address.\n\
15828 If line number is specified, all breakpoints in that line are cleared.\n\
15829 If function is specified, breakpoints at beginning of function are cleared.\n\
15830 If an address is specified, breakpoints at that address are cleared.\n\
15831 \n\
15832 With no argument, clears all breakpoints in the line that the selected frame\n\
15833 is executing in.\n\
15834 \n\
15835 See also the \"delete\" command which clears breakpoints by number."));
15836   add_com_alias ("cl", "clear", class_breakpoint, 1);
15837
15838   c = add_com ("break", class_breakpoint, break_command, _("\
15839 Set breakpoint at specified line or function.\n"
15840 BREAK_ARGS_HELP ("break")));
15841   set_cmd_completer (c, location_completer);
15842
15843   add_com_alias ("b", "break", class_run, 1);
15844   add_com_alias ("br", "break", class_run, 1);
15845   add_com_alias ("bre", "break", class_run, 1);
15846   add_com_alias ("brea", "break", class_run, 1);
15847
15848   if (xdb_commands)
15849    add_com_alias ("ba", "break", class_breakpoint, 1);
15850
15851   if (dbx_commands)
15852     {
15853       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15854 Break in function/address or break at a line in the current file."),
15855                              &stoplist, "stop ", 1, &cmdlist);
15856       add_cmd ("in", class_breakpoint, stopin_command,
15857                _("Break in function or address."), &stoplist);
15858       add_cmd ("at", class_breakpoint, stopat_command,
15859                _("Break at a line in the current file."), &stoplist);
15860       add_com ("status", class_info, breakpoints_info, _("\
15861 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15862 The \"Type\" column indicates one of:\n\
15863 \tbreakpoint     - normal breakpoint\n\
15864 \twatchpoint     - watchpoint\n\
15865 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15866 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15867 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15868 address and file/line number respectively.\n\
15869 \n\
15870 Convenience variable \"$_\" and default examine address for \"x\"\n\
15871 are set to the address of the last breakpoint listed unless the command\n\
15872 is prefixed with \"server \".\n\n\
15873 Convenience variable \"$bpnum\" contains the number of the last\n\
15874 breakpoint set."));
15875     }
15876
15877   add_info ("breakpoints", breakpoints_info, _("\
15878 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15879 The \"Type\" column indicates one of:\n\
15880 \tbreakpoint     - normal breakpoint\n\
15881 \twatchpoint     - watchpoint\n\
15882 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15883 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15884 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15885 address and file/line number respectively.\n\
15886 \n\
15887 Convenience variable \"$_\" and default examine address for \"x\"\n\
15888 are set to the address of the last breakpoint listed unless the command\n\
15889 is prefixed with \"server \".\n\n\
15890 Convenience variable \"$bpnum\" contains the number of the last\n\
15891 breakpoint set."));
15892
15893   add_info_alias ("b", "breakpoints", 1);
15894
15895   if (xdb_commands)
15896     add_com ("lb", class_breakpoint, breakpoints_info, _("\
15897 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15898 The \"Type\" column indicates one of:\n\
15899 \tbreakpoint     - normal breakpoint\n\
15900 \twatchpoint     - watchpoint\n\
15901 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15902 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15903 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15904 address and file/line number respectively.\n\
15905 \n\
15906 Convenience variable \"$_\" and default examine address for \"x\"\n\
15907 are set to the address of the last breakpoint listed unless the command\n\
15908 is prefixed with \"server \".\n\n\
15909 Convenience variable \"$bpnum\" contains the number of the last\n\
15910 breakpoint set."));
15911
15912   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15913 Status of all breakpoints, or breakpoint number NUMBER.\n\
15914 The \"Type\" column indicates one of:\n\
15915 \tbreakpoint     - normal breakpoint\n\
15916 \twatchpoint     - watchpoint\n\
15917 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15918 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15919 \tuntil          - internal breakpoint used by the \"until\" command\n\
15920 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15921 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15922 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15923 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15924 address and file/line number respectively.\n\
15925 \n\
15926 Convenience variable \"$_\" and default examine address for \"x\"\n\
15927 are set to the address of the last breakpoint listed unless the command\n\
15928 is prefixed with \"server \".\n\n\
15929 Convenience variable \"$bpnum\" contains the number of the last\n\
15930 breakpoint set."),
15931            &maintenanceinfolist);
15932
15933   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15934 Set catchpoints to catch events."),
15935                   &catch_cmdlist, "catch ",
15936                   0/*allow-unknown*/, &cmdlist);
15937
15938   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15939 Set temporary catchpoints to catch events."),
15940                   &tcatch_cmdlist, "tcatch ",
15941                   0/*allow-unknown*/, &cmdlist);
15942
15943   /* Add catch and tcatch sub-commands.  */
15944   add_catch_command ("catch", _("\
15945 Catch an exception, when caught."),
15946                      catch_catch_command,
15947                      NULL,
15948                      CATCH_PERMANENT,
15949                      CATCH_TEMPORARY);
15950   add_catch_command ("throw", _("\
15951 Catch an exception, when thrown."),
15952                      catch_throw_command,
15953                      NULL,
15954                      CATCH_PERMANENT,
15955                      CATCH_TEMPORARY);
15956   add_catch_command ("fork", _("Catch calls to fork."),
15957                      catch_fork_command_1,
15958                      NULL,
15959                      (void *) (uintptr_t) catch_fork_permanent,
15960                      (void *) (uintptr_t) catch_fork_temporary);
15961   add_catch_command ("vfork", _("Catch calls to vfork."),
15962                      catch_fork_command_1,
15963                      NULL,
15964                      (void *) (uintptr_t) catch_vfork_permanent,
15965                      (void *) (uintptr_t) catch_vfork_temporary);
15966   add_catch_command ("exec", _("Catch calls to exec."),
15967                      catch_exec_command_1,
15968                      NULL,
15969                      CATCH_PERMANENT,
15970                      CATCH_TEMPORARY);
15971   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15972 Usage: catch load [REGEX]\n\
15973 If REGEX is given, only stop for libraries matching the regular expression."),
15974                      catch_load_command_1,
15975                      NULL,
15976                      CATCH_PERMANENT,
15977                      CATCH_TEMPORARY);
15978   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15979 Usage: catch unload [REGEX]\n\
15980 If REGEX is given, only stop for libraries matching the regular expression."),
15981                      catch_unload_command_1,
15982                      NULL,
15983                      CATCH_PERMANENT,
15984                      CATCH_TEMPORARY);
15985   add_catch_command ("syscall", _("\
15986 Catch system calls by their names and/or numbers.\n\
15987 Arguments say which system calls to catch.  If no arguments\n\
15988 are given, every system call will be caught.\n\
15989 Arguments, if given, should be one or more system call names\n\
15990 (if your system supports that), or system call numbers."),
15991                      catch_syscall_command_1,
15992                      catch_syscall_completer,
15993                      CATCH_PERMANENT,
15994                      CATCH_TEMPORARY);
15995
15996   c = add_com ("watch", class_breakpoint, watch_command, _("\
15997 Set a watchpoint for an expression.\n\
15998 Usage: watch [-l|-location] EXPRESSION\n\
15999 A watchpoint stops execution of your program whenever the value of\n\
16000 an expression changes.\n\
16001 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16002 the memory to which it refers."));
16003   set_cmd_completer (c, expression_completer);
16004
16005   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16006 Set a read watchpoint for an expression.\n\
16007 Usage: rwatch [-l|-location] EXPRESSION\n\
16008 A watchpoint stops execution of your program whenever the value of\n\
16009 an expression is read.\n\
16010 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16011 the memory to which it refers."));
16012   set_cmd_completer (c, expression_completer);
16013
16014   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16015 Set a watchpoint for an expression.\n\
16016 Usage: awatch [-l|-location] EXPRESSION\n\
16017 A watchpoint stops execution of your program whenever the value of\n\
16018 an expression is either read or written.\n\
16019 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16020 the memory to which it refers."));
16021   set_cmd_completer (c, expression_completer);
16022
16023   add_info ("watchpoints", watchpoints_info, _("\
16024 Status of specified watchpoints (all watchpoints if no argument)."));
16025
16026   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16027      respond to changes - contrary to the description.  */
16028   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16029                             &can_use_hw_watchpoints, _("\
16030 Set debugger's willingness to use watchpoint hardware."), _("\
16031 Show debugger's willingness to use watchpoint hardware."), _("\
16032 If zero, gdb will not use hardware for new watchpoints, even if\n\
16033 such is available.  (However, any hardware watchpoints that were\n\
16034 created before setting this to nonzero, will continue to use watchpoint\n\
16035 hardware.)"),
16036                             NULL,
16037                             show_can_use_hw_watchpoints,
16038                             &setlist, &showlist);
16039
16040   can_use_hw_watchpoints = 1;
16041
16042   /* Tracepoint manipulation commands.  */
16043
16044   c = add_com ("trace", class_breakpoint, trace_command, _("\
16045 Set a tracepoint at specified line or function.\n\
16046 \n"
16047 BREAK_ARGS_HELP ("trace") "\n\
16048 Do \"help tracepoints\" for info on other tracepoint commands."));
16049   set_cmd_completer (c, location_completer);
16050
16051   add_com_alias ("tp", "trace", class_alias, 0);
16052   add_com_alias ("tr", "trace", class_alias, 1);
16053   add_com_alias ("tra", "trace", class_alias, 1);
16054   add_com_alias ("trac", "trace", class_alias, 1);
16055
16056   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16057 Set a fast tracepoint at specified line or function.\n\
16058 \n"
16059 BREAK_ARGS_HELP ("ftrace") "\n\
16060 Do \"help tracepoints\" for info on other tracepoint commands."));
16061   set_cmd_completer (c, location_completer);
16062
16063   c = add_com ("strace", class_breakpoint, strace_command, _("\
16064 Set a static tracepoint at specified line, function or marker.\n\
16065 \n\
16066 strace [LOCATION] [if CONDITION]\n\
16067 LOCATION may be a line number, function name, \"*\" and an address,\n\
16068 or -m MARKER_ID.\n\
16069 If a line number is specified, probe the marker at start of code\n\
16070 for that line.  If a function is specified, probe the marker at start\n\
16071 of code for that function.  If an address is specified, probe the marker\n\
16072 at that exact address.  If a marker id is specified, probe the marker\n\
16073 with that name.  With no LOCATION, uses current execution address of\n\
16074 the selected stack frame.\n\
16075 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16076 This collects arbitrary user data passed in the probe point call to the\n\
16077 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16078 by printing the $_sdata variable like any other convenience variable.\n\
16079 \n\
16080 CONDITION is a boolean expression.\n\
16081 \n\
16082 Multiple tracepoints at one place are permitted, and useful if their\n\
16083 conditions are different.\n\
16084 \n\
16085 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16086 Do \"help tracepoints\" for info on other tracepoint commands."));
16087   set_cmd_completer (c, location_completer);
16088
16089   add_info ("tracepoints", tracepoints_info, _("\
16090 Status of specified tracepoints (all tracepoints if no argument).\n\
16091 Convenience variable \"$tpnum\" contains the number of the\n\
16092 last tracepoint set."));
16093
16094   add_info_alias ("tp", "tracepoints", 1);
16095
16096   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16097 Delete specified tracepoints.\n\
16098 Arguments are tracepoint numbers, separated by spaces.\n\
16099 No argument means delete all tracepoints."),
16100            &deletelist);
16101
16102   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16103 Disable specified tracepoints.\n\
16104 Arguments are tracepoint numbers, separated by spaces.\n\
16105 No argument means disable all tracepoints."),
16106            &disablelist);
16107   deprecate_cmd (c, "disable");
16108
16109   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16110 Enable specified tracepoints.\n\
16111 Arguments are tracepoint numbers, separated by spaces.\n\
16112 No argument means enable all tracepoints."),
16113            &enablelist);
16114   deprecate_cmd (c, "enable");
16115
16116   add_com ("passcount", class_trace, trace_pass_command, _("\
16117 Set the passcount for a tracepoint.\n\
16118 The trace will end when the tracepoint has been passed 'count' times.\n\
16119 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16120 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16121
16122   add_prefix_cmd ("save", class_breakpoint, save_command,
16123                   _("Save breakpoint definitions as a script."),
16124                   &save_cmdlist, "save ",
16125                   0/*allow-unknown*/, &cmdlist);
16126
16127   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16128 Save current breakpoint definitions as a script.\n\
16129 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16130 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16131 session to restore them."),
16132                &save_cmdlist);
16133   set_cmd_completer (c, filename_completer);
16134
16135   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16136 Save current tracepoint definitions as a script.\n\
16137 Use the 'source' command in another debug session to restore them."),
16138                &save_cmdlist);
16139   set_cmd_completer (c, filename_completer);
16140
16141   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
16142   deprecate_cmd (c, "save tracepoints");
16143
16144   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
16145 Breakpoint specific settings\n\
16146 Configure various breakpoint-specific variables such as\n\
16147 pending breakpoint behavior"),
16148                   &breakpoint_set_cmdlist, "set breakpoint ",
16149                   0/*allow-unknown*/, &setlist);
16150   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
16151 Breakpoint specific settings\n\
16152 Configure various breakpoint-specific variables such as\n\
16153 pending breakpoint behavior"),
16154                   &breakpoint_show_cmdlist, "show breakpoint ",
16155                   0/*allow-unknown*/, &showlist);
16156
16157   add_setshow_auto_boolean_cmd ("pending", no_class,
16158                                 &pending_break_support, _("\
16159 Set debugger's behavior regarding pending breakpoints."), _("\
16160 Show debugger's behavior regarding pending breakpoints."), _("\
16161 If on, an unrecognized breakpoint location will cause gdb to create a\n\
16162 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
16163 an error.  If auto, an unrecognized breakpoint location results in a\n\
16164 user-query to see if a pending breakpoint should be created."),
16165                                 NULL,
16166                                 show_pending_break_support,
16167                                 &breakpoint_set_cmdlist,
16168                                 &breakpoint_show_cmdlist);
16169
16170   pending_break_support = AUTO_BOOLEAN_AUTO;
16171
16172   add_setshow_boolean_cmd ("auto-hw", no_class,
16173                            &automatic_hardware_breakpoints, _("\
16174 Set automatic usage of hardware breakpoints."), _("\
16175 Show automatic usage of hardware breakpoints."), _("\
16176 If set, the debugger will automatically use hardware breakpoints for\n\
16177 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16178 a warning will be emitted for such breakpoints."),
16179                            NULL,
16180                            show_automatic_hardware_breakpoints,
16181                            &breakpoint_set_cmdlist,
16182                            &breakpoint_show_cmdlist);
16183
16184   add_setshow_enum_cmd ("always-inserted", class_support,
16185                         always_inserted_enums, &always_inserted_mode, _("\
16186 Set mode for inserting breakpoints."), _("\
16187 Show mode for inserting breakpoints."), _("\
16188 When this mode is off, breakpoints are inserted in inferior when it is\n\
16189 resumed, and removed when execution stops.  When this mode is on,\n\
16190 breakpoints are inserted immediately and removed only when the user\n\
16191 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16192 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16193 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16194 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16195 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16196                            NULL,
16197                            &show_always_inserted_mode,
16198                            &breakpoint_set_cmdlist,
16199                            &breakpoint_show_cmdlist);
16200
16201   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16202                         condition_evaluation_enums,
16203                         &condition_evaluation_mode_1, _("\
16204 Set mode of breakpoint condition evaluation."), _("\
16205 Show mode of breakpoint condition evaluation."), _("\
16206 When this is set to \"host\", breakpoint conditions will be\n\
16207 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16208 breakpoint conditions will be downloaded to the target (if the target\n\
16209 supports such feature) and conditions will be evaluated on the target's side.\n\
16210 If this is set to \"auto\" (default), this will be automatically set to\n\
16211 \"target\" if it supports condition evaluation, otherwise it will\n\
16212 be set to \"gdb\""),
16213                            &set_condition_evaluation_mode,
16214                            &show_condition_evaluation_mode,
16215                            &breakpoint_set_cmdlist,
16216                            &breakpoint_show_cmdlist);
16217
16218   add_com ("break-range", class_breakpoint, break_range_command, _("\
16219 Set a breakpoint for an address range.\n\
16220 break-range START-LOCATION, END-LOCATION\n\
16221 where START-LOCATION and END-LOCATION can be one of the following:\n\
16222   LINENUM, for that line in the current file,\n\
16223   FILE:LINENUM, for that line in that file,\n\
16224   +OFFSET, for that number of lines after the current line\n\
16225            or the start of the range\n\
16226   FUNCTION, for the first line in that function,\n\
16227   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16228   *ADDRESS, for the instruction at that address.\n\
16229 \n\
16230 The breakpoint will stop execution of the inferior whenever it executes\n\
16231 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16232 range (including START-LOCATION and END-LOCATION)."));
16233
16234   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16235 Set a dynamic printf at specified line or function.\n\
16236 dprintf location,format string,arg1,arg2,...\n\
16237 location may be a line number, function name, or \"*\" and an address.\n\
16238 If a line number is specified, break at start of code for that line.\n\
16239 If a function is specified, break at start of code for that function.\n\
16240 "));
16241   set_cmd_completer (c, location_completer);
16242
16243   add_setshow_enum_cmd ("dprintf-style", class_support,
16244                         dprintf_style_enums, &dprintf_style, _("\
16245 Set the style of usage for dynamic printf."), _("\
16246 Show the style of usage for dynamic printf."), _("\
16247 This setting chooses how GDB will do a dynamic printf.\n\
16248 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16249 console, as with the \"printf\" command.\n\
16250 If the value is \"call\", the print is done by calling a function in your\n\
16251 program; by default printf(), but you can choose a different function or\n\
16252 output stream by setting dprintf-function and dprintf-channel."),
16253                         update_dprintf_commands, NULL,
16254                         &setlist, &showlist);
16255
16256   dprintf_function = xstrdup ("printf");
16257   add_setshow_string_cmd ("dprintf-function", class_support,
16258                           &dprintf_function, _("\
16259 Set the function to use for dynamic printf"), _("\
16260 Show the function to use for dynamic printf"), NULL,
16261                           update_dprintf_commands, NULL,
16262                           &setlist, &showlist);
16263
16264   dprintf_channel = xstrdup ("");
16265   add_setshow_string_cmd ("dprintf-channel", class_support,
16266                           &dprintf_channel, _("\
16267 Set the channel to use for dynamic printf"), _("\
16268 Show the channel to use for dynamic printf"), NULL,
16269                           update_dprintf_commands, NULL,
16270                           &setlist, &showlist);
16271
16272   automatic_hardware_breakpoints = 1;
16273
16274   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16275 }