2012-04-27 Sergio Durigan Junior <sergiodj@redhat.com>
[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
72 /* readline include files */
73 #include "readline/readline.h"
74 #include "readline/history.h"
75
76 /* readline defines this.  */
77 #undef savestring
78
79 #include "mi/mi-common.h"
80 #include "python/python.h"
81
82 /* Prototypes for local functions.  */
83
84 static void enable_delete_command (char *, int);
85
86 static void enable_once_command (char *, int);
87
88 static void enable_count_command (char *, int);
89
90 static void disable_command (char *, int);
91
92 static void enable_command (char *, int);
93
94 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
95                                                       void *),
96                                     void *);
97
98 static void ignore_command (char *, int);
99
100 static int breakpoint_re_set_one (void *);
101
102 static void breakpoint_re_set_default (struct breakpoint *);
103
104 static void create_sals_from_address_default (char **,
105                                               struct linespec_result *,
106                                               enum bptype, char *,
107                                               char **);
108
109 static void create_breakpoints_sal_default (struct gdbarch *,
110                                             struct linespec_result *,
111                                             struct linespec_sals *,
112                                             char *, enum bptype,
113                                             enum bpdisp, int, int,
114                                             int,
115                                             const struct breakpoint_ops *,
116                                             int, int, int, unsigned);
117
118 static void decode_linespec_default (struct breakpoint *, char **,
119                                      struct symtabs_and_lines *);
120
121 static void clear_command (char *, int);
122
123 static void catch_command (char *, int);
124
125 static int can_use_hardware_watchpoint (struct value *);
126
127 static void break_command_1 (char *, int, int);
128
129 static void mention (struct breakpoint *);
130
131 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
132                                                                enum bptype,
133                                                                const struct breakpoint_ops *);
134 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
135                                                        const struct symtab_and_line *);
136
137 /* This function is used in gdbtk sources and thus can not be made
138    static.  */
139 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
140                                        struct symtab_and_line,
141                                        enum bptype,
142                                        const struct breakpoint_ops *);
143
144 static struct breakpoint *
145   momentary_breakpoint_from_master (struct breakpoint *orig,
146                                     enum bptype type,
147                                     const struct breakpoint_ops *ops);
148
149 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
150
151 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
152                                             CORE_ADDR bpaddr,
153                                             enum bptype bptype);
154
155 static void describe_other_breakpoints (struct gdbarch *,
156                                         struct program_space *, CORE_ADDR,
157                                         struct obj_section *, int);
158
159 static int breakpoint_address_match (struct address_space *aspace1,
160                                      CORE_ADDR addr1,
161                                      struct address_space *aspace2,
162                                      CORE_ADDR addr2);
163
164 static int watchpoint_locations_match (struct bp_location *loc1,
165                                        struct bp_location *loc2);
166
167 static int breakpoint_location_address_match (struct bp_location *bl,
168                                               struct address_space *aspace,
169                                               CORE_ADDR addr);
170
171 static void breakpoints_info (char *, int);
172
173 static void watchpoints_info (char *, int);
174
175 static int breakpoint_1 (char *, int, 
176                          int (*) (const struct breakpoint *));
177
178 static int breakpoint_cond_eval (void *);
179
180 static void cleanup_executing_breakpoints (void *);
181
182 static void commands_command (char *, int);
183
184 static void condition_command (char *, int);
185
186 typedef enum
187   {
188     mark_inserted,
189     mark_uninserted
190   }
191 insertion_state_t;
192
193 static int remove_breakpoint (struct bp_location *, insertion_state_t);
194 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
195
196 static enum print_stop_action print_bp_stop_message (bpstat bs);
197
198 static int watchpoint_check (void *);
199
200 static void maintenance_info_breakpoints (char *, int);
201
202 static int hw_breakpoint_used_count (void);
203
204 static int hw_watchpoint_use_count (struct breakpoint *);
205
206 static int hw_watchpoint_used_count_others (struct breakpoint *except,
207                                             enum bptype type,
208                                             int *other_type_used);
209
210 static void hbreak_command (char *, int);
211
212 static void thbreak_command (char *, int);
213
214 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
215                                     int count);
216
217 static void stop_command (char *arg, int from_tty);
218
219 static void stopin_command (char *arg, int from_tty);
220
221 static void stopat_command (char *arg, int from_tty);
222
223 static char *ep_parse_optional_if_clause (char **arg);
224
225 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
226                                        char *arg, int tempflag, int from_tty);
227
228 static void tcatch_command (char *arg, int from_tty);
229
230 static void detach_single_step_breakpoints (void);
231
232 static int single_step_breakpoint_inserted_here_p (struct address_space *,
233                                                    CORE_ADDR pc);
234
235 static void free_bp_location (struct bp_location *loc);
236 static void incref_bp_location (struct bp_location *loc);
237 static void decref_bp_location (struct bp_location **loc);
238
239 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
240
241 static void update_global_location_list (int);
242
243 static void update_global_location_list_nothrow (int);
244
245 static int is_hardware_watchpoint (const struct breakpoint *bpt);
246
247 static void insert_breakpoint_locations (void);
248
249 static int syscall_catchpoint_p (struct breakpoint *b);
250
251 static void tracepoints_info (char *, int);
252
253 static void delete_trace_command (char *, int);
254
255 static void enable_trace_command (char *, int);
256
257 static void disable_trace_command (char *, int);
258
259 static void trace_pass_command (char *, int);
260
261 static int is_masked_watchpoint (const struct breakpoint *b);
262
263 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
264
265 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
266    otherwise.  */
267
268 static int strace_marker_p (struct breakpoint *b);
269
270 static void init_catchpoint (struct breakpoint *b,
271                              struct gdbarch *gdbarch, int tempflag,
272                              char *cond_string,
273                              const struct breakpoint_ops *ops);
274
275 /* The abstract base class all breakpoint_ops structures inherit
276    from.  */
277 static struct breakpoint_ops base_breakpoint_ops;
278
279 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
280    that are implemented on top of software or hardware breakpoints
281    (user breakpoints, internal and momentary breakpoints, etc.).  */
282 static struct breakpoint_ops bkpt_base_breakpoint_ops;
283
284 /* Internal breakpoints class type.  */
285 static struct breakpoint_ops internal_breakpoint_ops;
286
287 /* Momentary breakpoints class type.  */
288 static struct breakpoint_ops momentary_breakpoint_ops;
289
290 /* The breakpoint_ops structure to be used in regular user created
291    breakpoints.  */
292 struct breakpoint_ops bkpt_breakpoint_ops;
293
294 /* Breakpoints set on probes.  */
295 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
296
297 /* A reference-counted struct command_line.  This lets multiple
298    breakpoints share a single command list.  */
299 struct counted_command_line
300 {
301   /* The reference count.  */
302   int refc;
303
304   /* The command list.  */
305   struct command_line *commands;
306 };
307
308 struct command_line *
309 breakpoint_commands (struct breakpoint *b)
310 {
311   return b->commands ? b->commands->commands : NULL;
312 }
313
314 /* Flag indicating that a command has proceeded the inferior past the
315    current breakpoint.  */
316
317 static int breakpoint_proceeded;
318
319 const char *
320 bpdisp_text (enum bpdisp disp)
321 {
322   /* NOTE: the following values are a part of MI protocol and
323      represent values of 'disp' field returned when inferior stops at
324      a breakpoint.  */
325   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
326
327   return bpdisps[(int) disp];
328 }
329
330 /* Prototypes for exported functions.  */
331 /* If FALSE, gdb will not use hardware support for watchpoints, even
332    if such is available.  */
333 static int can_use_hw_watchpoints;
334
335 static void
336 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
337                              struct cmd_list_element *c,
338                              const char *value)
339 {
340   fprintf_filtered (file,
341                     _("Debugger's willingness to use "
342                       "watchpoint hardware is %s.\n"),
343                     value);
344 }
345
346 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
347    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
348    for unrecognized breakpoint locations.
349    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
350 static enum auto_boolean pending_break_support;
351 static void
352 show_pending_break_support (struct ui_file *file, int from_tty,
353                             struct cmd_list_element *c,
354                             const char *value)
355 {
356   fprintf_filtered (file,
357                     _("Debugger's behavior regarding "
358                       "pending breakpoints is %s.\n"),
359                     value);
360 }
361
362 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
363    set with "break" but falling in read-only memory.
364    If 0, gdb will warn about such breakpoints, but won't automatically
365    use hardware breakpoints.  */
366 static int automatic_hardware_breakpoints;
367 static void
368 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
369                                      struct cmd_list_element *c,
370                                      const char *value)
371 {
372   fprintf_filtered (file,
373                     _("Automatic usage of hardware breakpoints is %s.\n"),
374                     value);
375 }
376
377 /* If on, gdb will keep breakpoints inserted even as inferior is
378    stopped, and immediately insert any new breakpoints.  If off, gdb
379    will insert breakpoints into inferior only when resuming it, and
380    will remove breakpoints upon stop.  If auto, GDB will behave as ON
381    if in non-stop mode, and as OFF if all-stop mode.*/
382
383 static const char always_inserted_auto[] = "auto";
384 static const char always_inserted_on[] = "on";
385 static const char always_inserted_off[] = "off";
386 static const char *const always_inserted_enums[] = {
387   always_inserted_auto,
388   always_inserted_off,
389   always_inserted_on,
390   NULL
391 };
392 static const char *always_inserted_mode = always_inserted_auto;
393 static void
394 show_always_inserted_mode (struct ui_file *file, int from_tty,
395                      struct cmd_list_element *c, const char *value)
396 {
397   if (always_inserted_mode == always_inserted_auto)
398     fprintf_filtered (file,
399                       _("Always inserted breakpoint "
400                         "mode is %s (currently %s).\n"),
401                       value,
402                       breakpoints_always_inserted_mode () ? "on" : "off");
403   else
404     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
405                       value);
406 }
407
408 int
409 breakpoints_always_inserted_mode (void)
410 {
411   return (always_inserted_mode == always_inserted_on
412           || (always_inserted_mode == always_inserted_auto && non_stop));
413 }
414
415 static const char condition_evaluation_both[] = "host or target";
416
417 /* Modes for breakpoint condition evaluation.  */
418 static const char condition_evaluation_auto[] = "auto";
419 static const char condition_evaluation_host[] = "host";
420 static const char condition_evaluation_target[] = "target";
421 static const char *const condition_evaluation_enums[] = {
422   condition_evaluation_auto,
423   condition_evaluation_host,
424   condition_evaluation_target,
425   NULL
426 };
427
428 /* Global that holds the current mode for breakpoint condition evaluation.  */
429 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
430
431 /* Global that we use to display information to the user (gets its value from
432    condition_evaluation_mode_1.  */
433 static const char *condition_evaluation_mode = condition_evaluation_auto;
434
435 /* Translate a condition evaluation mode MODE into either "host"
436    or "target".  This is used mostly to translate from "auto" to the
437    real setting that is being used.  It returns the translated
438    evaluation mode.  */
439
440 static const char *
441 translate_condition_evaluation_mode (const char *mode)
442 {
443   if (mode == condition_evaluation_auto)
444     {
445       if (target_supports_evaluation_of_breakpoint_conditions ())
446         return condition_evaluation_target;
447       else
448         return condition_evaluation_host;
449     }
450   else
451     return mode;
452 }
453
454 /* Discovers what condition_evaluation_auto translates to.  */
455
456 static const char *
457 breakpoint_condition_evaluation_mode (void)
458 {
459   return translate_condition_evaluation_mode (condition_evaluation_mode);
460 }
461
462 /* Return true if GDB should evaluate breakpoint conditions or false
463    otherwise.  */
464
465 static int
466 gdb_evaluates_breakpoint_condition_p (void)
467 {
468   const char *mode = breakpoint_condition_evaluation_mode ();
469
470   return (mode == condition_evaluation_host);
471 }
472
473 void _initialize_breakpoint (void);
474
475 /* Are we executing breakpoint commands?  */
476 static int executing_breakpoint_commands;
477
478 /* Are overlay event breakpoints enabled? */
479 static int overlay_events_enabled;
480
481 /* See description in breakpoint.h. */
482 int target_exact_watchpoints = 0;
483
484 /* Walk the following statement or block through all breakpoints.
485    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
486    current breakpoint.  */
487
488 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
489
490 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
491         for (B = breakpoint_chain;      \
492              B ? (TMP=B->next, 1): 0;   \
493              B = TMP)
494
495 /* Similar iterator for the low-level breakpoints.  SAFE variant is
496    not provided so update_global_location_list must not be called
497    while executing the block of ALL_BP_LOCATIONS.  */
498
499 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
500         for (BP_TMP = bp_location;                                      \
501              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
502              BP_TMP++)
503
504 /* Iterates through locations with address ADDRESS for the currently selected
505    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
506    to where the loop should start from.
507    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
508    appropriate location to start with.  */
509
510 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
511         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
512              BP_LOCP_TMP = BP_LOCP_START;                               \
513              BP_LOCP_START                                              \
514              && (BP_LOCP_TMP < bp_location + bp_location_count          \
515              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
516              BP_LOCP_TMP++)
517
518 /* Iterator for tracepoints only.  */
519
520 #define ALL_TRACEPOINTS(B)  \
521   for (B = breakpoint_chain; B; B = B->next)  \
522     if (is_tracepoint (B))
523
524 /* Chains of all breakpoints defined.  */
525
526 struct breakpoint *breakpoint_chain;
527
528 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
529
530 static struct bp_location **bp_location;
531
532 /* Number of elements of BP_LOCATION.  */
533
534 static unsigned bp_location_count;
535
536 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
537    ADDRESS for the current elements of BP_LOCATION which get a valid
538    result from bp_location_has_shadow.  You can use it for roughly
539    limiting the subrange of BP_LOCATION to scan for shadow bytes for
540    an address you need to read.  */
541
542 static CORE_ADDR bp_location_placed_address_before_address_max;
543
544 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
545    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
546    BP_LOCATION which get a valid result from bp_location_has_shadow.
547    You can use it for roughly limiting the subrange of BP_LOCATION to
548    scan for shadow bytes for an address you need to read.  */
549
550 static CORE_ADDR bp_location_shadow_len_after_address_max;
551
552 /* The locations that no longer correspond to any breakpoint, unlinked
553    from bp_location array, but for which a hit may still be reported
554    by a target.  */
555 VEC(bp_location_p) *moribund_locations = NULL;
556
557 /* Number of last breakpoint made.  */
558
559 static int breakpoint_count;
560
561 /* The value of `breakpoint_count' before the last command that
562    created breakpoints.  If the last (break-like) command created more
563    than one breakpoint, then the difference between BREAKPOINT_COUNT
564    and PREV_BREAKPOINT_COUNT is more than one.  */
565 static int prev_breakpoint_count;
566
567 /* Number of last tracepoint made.  */
568
569 static int tracepoint_count;
570
571 static struct cmd_list_element *breakpoint_set_cmdlist;
572 static struct cmd_list_element *breakpoint_show_cmdlist;
573 struct cmd_list_element *save_cmdlist;
574
575 /* Return whether a breakpoint is an active enabled breakpoint.  */
576 static int
577 breakpoint_enabled (struct breakpoint *b)
578 {
579   return (b->enable_state == bp_enabled);
580 }
581
582 /* Set breakpoint count to NUM.  */
583
584 static void
585 set_breakpoint_count (int num)
586 {
587   prev_breakpoint_count = breakpoint_count;
588   breakpoint_count = num;
589   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
590 }
591
592 /* Used by `start_rbreak_breakpoints' below, to record the current
593    breakpoint count before "rbreak" creates any breakpoint.  */
594 static int rbreak_start_breakpoint_count;
595
596 /* Called at the start an "rbreak" command to record the first
597    breakpoint made.  */
598
599 void
600 start_rbreak_breakpoints (void)
601 {
602   rbreak_start_breakpoint_count = breakpoint_count;
603 }
604
605 /* Called at the end of an "rbreak" command to record the last
606    breakpoint made.  */
607
608 void
609 end_rbreak_breakpoints (void)
610 {
611   prev_breakpoint_count = rbreak_start_breakpoint_count;
612 }
613
614 /* Used in run_command to zero the hit count when a new run starts.  */
615
616 void
617 clear_breakpoint_hit_counts (void)
618 {
619   struct breakpoint *b;
620
621   ALL_BREAKPOINTS (b)
622     b->hit_count = 0;
623 }
624
625 /* Allocate a new counted_command_line with reference count of 1.
626    The new structure owns COMMANDS.  */
627
628 static struct counted_command_line *
629 alloc_counted_command_line (struct command_line *commands)
630 {
631   struct counted_command_line *result
632     = xmalloc (sizeof (struct counted_command_line));
633
634   result->refc = 1;
635   result->commands = commands;
636   return result;
637 }
638
639 /* Increment reference count.  This does nothing if CMD is NULL.  */
640
641 static void
642 incref_counted_command_line (struct counted_command_line *cmd)
643 {
644   if (cmd)
645     ++cmd->refc;
646 }
647
648 /* Decrement reference count.  If the reference count reaches 0,
649    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
650    nothing if *CMDP is NULL.  */
651
652 static void
653 decref_counted_command_line (struct counted_command_line **cmdp)
654 {
655   if (*cmdp)
656     {
657       if (--(*cmdp)->refc == 0)
658         {
659           free_command_lines (&(*cmdp)->commands);
660           xfree (*cmdp);
661         }
662       *cmdp = NULL;
663     }
664 }
665
666 /* A cleanup function that calls decref_counted_command_line.  */
667
668 static void
669 do_cleanup_counted_command_line (void *arg)
670 {
671   decref_counted_command_line (arg);
672 }
673
674 /* Create a cleanup that calls decref_counted_command_line on the
675    argument.  */
676
677 static struct cleanup *
678 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
679 {
680   return make_cleanup (do_cleanup_counted_command_line, cmdp);
681 }
682
683 \f
684 /* Return the breakpoint with the specified number, or NULL
685    if the number does not refer to an existing breakpoint.  */
686
687 struct breakpoint *
688 get_breakpoint (int num)
689 {
690   struct breakpoint *b;
691
692   ALL_BREAKPOINTS (b)
693     if (b->number == num)
694       return b;
695   
696   return NULL;
697 }
698
699 \f
700
701 /* Mark locations as "conditions have changed" in case the target supports
702    evaluating conditions on its side.  */
703
704 static void
705 mark_breakpoint_modified (struct breakpoint *b)
706 {
707   struct bp_location *loc;
708
709   /* This is only meaningful if the target is
710      evaluating conditions and if the user has
711      opted for condition evaluation on the target's
712      side.  */
713   if (gdb_evaluates_breakpoint_condition_p ()
714       || !target_supports_evaluation_of_breakpoint_conditions ())
715     return;
716
717   if (!is_breakpoint (b))
718     return;
719
720   for (loc = b->loc; loc; loc = loc->next)
721     loc->condition_changed = condition_modified;
722 }
723
724 /* Mark location as "conditions have changed" in case the target supports
725    evaluating conditions on its side.  */
726
727 static void
728 mark_breakpoint_location_modified (struct bp_location *loc)
729 {
730   /* This is only meaningful if the target is
731      evaluating conditions and if the user has
732      opted for condition evaluation on the target's
733      side.  */
734   if (gdb_evaluates_breakpoint_condition_p ()
735       || !target_supports_evaluation_of_breakpoint_conditions ())
736
737     return;
738
739   if (!is_breakpoint (loc->owner))
740     return;
741
742   loc->condition_changed = condition_modified;
743 }
744
745 /* Sets the condition-evaluation mode using the static global
746    condition_evaluation_mode.  */
747
748 static void
749 set_condition_evaluation_mode (char *args, int from_tty,
750                                struct cmd_list_element *c)
751 {
752   struct breakpoint *b;
753   const char *old_mode, *new_mode;
754
755   if ((condition_evaluation_mode_1 == condition_evaluation_target)
756       && !target_supports_evaluation_of_breakpoint_conditions ())
757     {
758       condition_evaluation_mode_1 = condition_evaluation_mode;
759       warning (_("Target does not support breakpoint condition evaluation.\n"
760                  "Using host evaluation mode instead."));
761       return;
762     }
763
764   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
765   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
766
767   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
768      settings was "auto".  */
769   condition_evaluation_mode = condition_evaluation_mode_1;
770
771   /* Only update the mode if the user picked a different one.  */
772   if (new_mode != old_mode)
773     {
774       struct bp_location *loc, **loc_tmp;
775       /* If the user switched to a different evaluation mode, we
776          need to synch the changes with the target as follows:
777
778          "host" -> "target": Send all (valid) conditions to the target.
779          "target" -> "host": Remove all the conditions from the target.
780       */
781
782       if (new_mode == condition_evaluation_target)
783         {
784           /* Mark everything modified and synch conditions with the
785              target.  */
786           ALL_BP_LOCATIONS (loc, loc_tmp)
787             mark_breakpoint_location_modified (loc);
788         }
789       else
790         {
791           /* Manually mark non-duplicate locations to synch conditions
792              with the target.  We do this to remove all the conditions the
793              target knows about.  */
794           ALL_BP_LOCATIONS (loc, loc_tmp)
795             if (is_breakpoint (loc->owner) && loc->inserted)
796               loc->needs_update = 1;
797         }
798
799       /* Do the update.  */
800       update_global_location_list (1);
801     }
802
803   return;
804 }
805
806 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
807    what "auto" is translating to.  */
808
809 static void
810 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
811                                 struct cmd_list_element *c, const char *value)
812 {
813   if (condition_evaluation_mode == condition_evaluation_auto)
814     fprintf_filtered (file,
815                       _("Breakpoint condition evaluation "
816                         "mode is %s (currently %s).\n"),
817                       value,
818                       breakpoint_condition_evaluation_mode ());
819   else
820     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
821                       value);
822 }
823
824 /* A comparison function for bp_location AP and BP that is used by
825    bsearch.  This comparison function only cares about addresses, unlike
826    the more general bp_location_compare function.  */
827
828 static int
829 bp_location_compare_addrs (const void *ap, const void *bp)
830 {
831   struct bp_location *a = *(void **) ap;
832   struct bp_location *b = *(void **) bp;
833
834   if (a->address == b->address)
835     return 0;
836   else
837     return ((a->address > b->address) - (a->address < b->address));
838 }
839
840 /* Helper function to skip all bp_locations with addresses
841    less than ADDRESS.  It returns the first bp_location that
842    is greater than or equal to ADDRESS.  If none is found, just
843    return NULL.  */
844
845 static struct bp_location **
846 get_first_locp_gte_addr (CORE_ADDR address)
847 {
848   struct bp_location dummy_loc;
849   struct bp_location *dummy_locp = &dummy_loc;
850   struct bp_location **locp_found = NULL;
851
852   /* Initialize the dummy location's address field.  */
853   memset (&dummy_loc, 0, sizeof (struct bp_location));
854   dummy_loc.address = address;
855
856   /* Find a close match to the first location at ADDRESS.  */
857   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
858                         sizeof (struct bp_location **),
859                         bp_location_compare_addrs);
860
861   /* Nothing was found, nothing left to do.  */
862   if (locp_found == NULL)
863     return NULL;
864
865   /* We may have found a location that is at ADDRESS but is not the first in the
866      location's list.  Go backwards (if possible) and locate the first one.  */
867   while ((locp_found - 1) >= bp_location
868          && (*(locp_found - 1))->address == address)
869     locp_found--;
870
871   return locp_found;
872 }
873
874 void
875 set_breakpoint_condition (struct breakpoint *b, char *exp,
876                           int from_tty)
877 {
878   xfree (b->cond_string);
879   b->cond_string = NULL;
880
881   if (is_watchpoint (b))
882     {
883       struct watchpoint *w = (struct watchpoint *) b;
884
885       xfree (w->cond_exp);
886       w->cond_exp = NULL;
887     }
888   else
889     {
890       struct bp_location *loc;
891
892       for (loc = b->loc; loc; loc = loc->next)
893         {
894           xfree (loc->cond);
895           loc->cond = NULL;
896
897           /* No need to free the condition agent expression
898              bytecode (if we have one).  We will handle this
899              when we go through update_global_location_list.  */
900         }
901     }
902
903   if (*exp == 0)
904     {
905       if (from_tty)
906         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
907     }
908   else
909     {
910       char *arg = exp;
911
912       /* I don't know if it matters whether this is the string the user
913          typed in or the decompiled expression.  */
914       b->cond_string = xstrdup (arg);
915       b->condition_not_parsed = 0;
916
917       if (is_watchpoint (b))
918         {
919           struct watchpoint *w = (struct watchpoint *) b;
920
921           innermost_block = NULL;
922           arg = exp;
923           w->cond_exp = parse_exp_1 (&arg, 0, 0);
924           if (*arg)
925             error (_("Junk at end of expression"));
926           w->cond_exp_valid_block = innermost_block;
927         }
928       else
929         {
930           struct bp_location *loc;
931
932           for (loc = b->loc; loc; loc = loc->next)
933             {
934               arg = exp;
935               loc->cond =
936                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
937               if (*arg)
938                 error (_("Junk at end of expression"));
939             }
940         }
941     }
942   mark_breakpoint_modified (b);
943
944   breakpoints_changed ();
945   observer_notify_breakpoint_modified (b);
946 }
947
948 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
949
950 static void
951 condition_command (char *arg, int from_tty)
952 {
953   struct breakpoint *b;
954   char *p;
955   int bnum;
956
957   if (arg == 0)
958     error_no_arg (_("breakpoint number"));
959
960   p = arg;
961   bnum = get_number (&p);
962   if (bnum == 0)
963     error (_("Bad breakpoint argument: '%s'"), arg);
964
965   ALL_BREAKPOINTS (b)
966     if (b->number == bnum)
967       {
968         /* Check if this breakpoint has a Python object assigned to
969            it, and if it has a definition of the "stop"
970            method.  This method and conditions entered into GDB from
971            the CLI are mutually exclusive.  */
972         if (b->py_bp_object
973             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
974           error (_("Cannot set a condition where a Python 'stop' "
975                    "method has been defined in the breakpoint."));
976         set_breakpoint_condition (b, p, from_tty);
977
978         if (is_breakpoint (b))
979           update_global_location_list (1);
980
981         return;
982       }
983
984   error (_("No breakpoint number %d."), bnum);
985 }
986
987 /* Check that COMMAND do not contain commands that are suitable
988    only for tracepoints and not suitable for ordinary breakpoints.
989    Throw if any such commands is found.  */
990
991 static void
992 check_no_tracepoint_commands (struct command_line *commands)
993 {
994   struct command_line *c;
995
996   for (c = commands; c; c = c->next)
997     {
998       int i;
999
1000       if (c->control_type == while_stepping_control)
1001         error (_("The 'while-stepping' command can "
1002                  "only be used for tracepoints"));
1003
1004       for (i = 0; i < c->body_count; ++i)
1005         check_no_tracepoint_commands ((c->body_list)[i]);
1006
1007       /* Not that command parsing removes leading whitespace and comment
1008          lines and also empty lines.  So, we only need to check for
1009          command directly.  */
1010       if (strstr (c->line, "collect ") == c->line)
1011         error (_("The 'collect' command can only be used for tracepoints"));
1012
1013       if (strstr (c->line, "teval ") == c->line)
1014         error (_("The 'teval' command can only be used for tracepoints"));
1015     }
1016 }
1017
1018 /* Encapsulate tests for different types of tracepoints.  */
1019
1020 static int
1021 is_tracepoint_type (enum bptype type)
1022 {
1023   return (type == bp_tracepoint
1024           || type == bp_fast_tracepoint
1025           || type == bp_static_tracepoint);
1026 }
1027
1028 int
1029 is_tracepoint (const struct breakpoint *b)
1030 {
1031   return is_tracepoint_type (b->type);
1032 }
1033
1034 /* A helper function that validates that COMMANDS are valid for a
1035    breakpoint.  This function will throw an exception if a problem is
1036    found.  */
1037
1038 static void
1039 validate_commands_for_breakpoint (struct breakpoint *b,
1040                                   struct command_line *commands)
1041 {
1042   if (is_tracepoint (b))
1043     {
1044       /* We need to verify that each top-level element of commands is
1045          valid for tracepoints, that there's at most one
1046          while-stepping element, and that while-stepping's body has
1047          valid tracing commands excluding nested while-stepping.  */
1048       struct command_line *c;
1049       struct command_line *while_stepping = 0;
1050       for (c = commands; c; c = c->next)
1051         {
1052           if (c->control_type == while_stepping_control)
1053             {
1054               if (b->type == bp_fast_tracepoint)
1055                 error (_("The 'while-stepping' command "
1056                          "cannot be used for fast tracepoint"));
1057               else if (b->type == bp_static_tracepoint)
1058                 error (_("The 'while-stepping' command "
1059                          "cannot be used for static tracepoint"));
1060
1061               if (while_stepping)
1062                 error (_("The 'while-stepping' command "
1063                          "can be used only once"));
1064               else
1065                 while_stepping = c;
1066             }
1067         }
1068       if (while_stepping)
1069         {
1070           struct command_line *c2;
1071
1072           gdb_assert (while_stepping->body_count == 1);
1073           c2 = while_stepping->body_list[0];
1074           for (; c2; c2 = c2->next)
1075             {
1076               if (c2->control_type == while_stepping_control)
1077                 error (_("The 'while-stepping' command cannot be nested"));
1078             }
1079         }
1080     }
1081   else
1082     {
1083       check_no_tracepoint_commands (commands);
1084     }
1085 }
1086
1087 /* Return a vector of all the static tracepoints set at ADDR.  The
1088    caller is responsible for releasing the vector.  */
1089
1090 VEC(breakpoint_p) *
1091 static_tracepoints_here (CORE_ADDR addr)
1092 {
1093   struct breakpoint *b;
1094   VEC(breakpoint_p) *found = 0;
1095   struct bp_location *loc;
1096
1097   ALL_BREAKPOINTS (b)
1098     if (b->type == bp_static_tracepoint)
1099       {
1100         for (loc = b->loc; loc; loc = loc->next)
1101           if (loc->address == addr)
1102             VEC_safe_push(breakpoint_p, found, b);
1103       }
1104
1105   return found;
1106 }
1107
1108 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1109    validate that only allowed commands are included.  */
1110
1111 void
1112 breakpoint_set_commands (struct breakpoint *b, 
1113                          struct command_line *commands)
1114 {
1115   validate_commands_for_breakpoint (b, commands);
1116
1117   decref_counted_command_line (&b->commands);
1118   b->commands = alloc_counted_command_line (commands);
1119   breakpoints_changed ();
1120   observer_notify_breakpoint_modified (b);
1121 }
1122
1123 /* Set the internal `silent' flag on the breakpoint.  Note that this
1124    is not the same as the "silent" that may appear in the breakpoint's
1125    commands.  */
1126
1127 void
1128 breakpoint_set_silent (struct breakpoint *b, int silent)
1129 {
1130   int old_silent = b->silent;
1131
1132   b->silent = silent;
1133   if (old_silent != silent)
1134     observer_notify_breakpoint_modified (b);
1135 }
1136
1137 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1138    breakpoint work for any thread.  */
1139
1140 void
1141 breakpoint_set_thread (struct breakpoint *b, int thread)
1142 {
1143   int old_thread = b->thread;
1144
1145   b->thread = thread;
1146   if (old_thread != thread)
1147     observer_notify_breakpoint_modified (b);
1148 }
1149
1150 /* Set the task for this breakpoint.  If TASK is 0, make the
1151    breakpoint work for any task.  */
1152
1153 void
1154 breakpoint_set_task (struct breakpoint *b, int task)
1155 {
1156   int old_task = b->task;
1157
1158   b->task = task;
1159   if (old_task != task)
1160     observer_notify_breakpoint_modified (b);
1161 }
1162
1163 void
1164 check_tracepoint_command (char *line, void *closure)
1165 {
1166   struct breakpoint *b = closure;
1167
1168   validate_actionline (&line, b);
1169 }
1170
1171 /* A structure used to pass information through
1172    map_breakpoint_numbers.  */
1173
1174 struct commands_info
1175 {
1176   /* True if the command was typed at a tty.  */
1177   int from_tty;
1178
1179   /* The breakpoint range spec.  */
1180   char *arg;
1181
1182   /* Non-NULL if the body of the commands are being read from this
1183      already-parsed command.  */
1184   struct command_line *control;
1185
1186   /* The command lines read from the user, or NULL if they have not
1187      yet been read.  */
1188   struct counted_command_line *cmd;
1189 };
1190
1191 /* A callback for map_breakpoint_numbers that sets the commands for
1192    commands_command.  */
1193
1194 static void
1195 do_map_commands_command (struct breakpoint *b, void *data)
1196 {
1197   struct commands_info *info = data;
1198
1199   if (info->cmd == NULL)
1200     {
1201       struct command_line *l;
1202
1203       if (info->control != NULL)
1204         l = copy_command_lines (info->control->body_list[0]);
1205       else
1206         {
1207           struct cleanup *old_chain;
1208           char *str;
1209
1210           str = xstrprintf (_("Type commands for breakpoint(s) "
1211                               "%s, one per line."),
1212                             info->arg);
1213
1214           old_chain = make_cleanup (xfree, str);
1215
1216           l = read_command_lines (str,
1217                                   info->from_tty, 1,
1218                                   (is_tracepoint (b)
1219                                    ? check_tracepoint_command : 0),
1220                                   b);
1221
1222           do_cleanups (old_chain);
1223         }
1224
1225       info->cmd = alloc_counted_command_line (l);
1226     }
1227
1228   /* If a breakpoint was on the list more than once, we don't need to
1229      do anything.  */
1230   if (b->commands != info->cmd)
1231     {
1232       validate_commands_for_breakpoint (b, info->cmd->commands);
1233       incref_counted_command_line (info->cmd);
1234       decref_counted_command_line (&b->commands);
1235       b->commands = info->cmd;
1236       breakpoints_changed ();
1237       observer_notify_breakpoint_modified (b);
1238     }
1239 }
1240
1241 static void
1242 commands_command_1 (char *arg, int from_tty, 
1243                     struct command_line *control)
1244 {
1245   struct cleanup *cleanups;
1246   struct commands_info info;
1247
1248   info.from_tty = from_tty;
1249   info.control = control;
1250   info.cmd = NULL;
1251   /* If we read command lines from the user, then `info' will hold an
1252      extra reference to the commands that we must clean up.  */
1253   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1254
1255   if (arg == NULL || !*arg)
1256     {
1257       if (breakpoint_count - prev_breakpoint_count > 1)
1258         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1259                           breakpoint_count);
1260       else if (breakpoint_count > 0)
1261         arg = xstrprintf ("%d", breakpoint_count);
1262       else
1263         {
1264           /* So that we don't try to free the incoming non-NULL
1265              argument in the cleanup below.  Mapping breakpoint
1266              numbers will fail in this case.  */
1267           arg = NULL;
1268         }
1269     }
1270   else
1271     /* The command loop has some static state, so we need to preserve
1272        our argument.  */
1273     arg = xstrdup (arg);
1274
1275   if (arg != NULL)
1276     make_cleanup (xfree, arg);
1277
1278   info.arg = arg;
1279
1280   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1281
1282   if (info.cmd == NULL)
1283     error (_("No breakpoints specified."));
1284
1285   do_cleanups (cleanups);
1286 }
1287
1288 static void
1289 commands_command (char *arg, int from_tty)
1290 {
1291   commands_command_1 (arg, from_tty, NULL);
1292 }
1293
1294 /* Like commands_command, but instead of reading the commands from
1295    input stream, takes them from an already parsed command structure.
1296
1297    This is used by cli-script.c to DTRT with breakpoint commands
1298    that are part of if and while bodies.  */
1299 enum command_control_type
1300 commands_from_control_command (char *arg, struct command_line *cmd)
1301 {
1302   commands_command_1 (arg, 0, cmd);
1303   return simple_control;
1304 }
1305
1306 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1307
1308 static int
1309 bp_location_has_shadow (struct bp_location *bl)
1310 {
1311   if (bl->loc_type != bp_loc_software_breakpoint)
1312     return 0;
1313   if (!bl->inserted)
1314     return 0;
1315   if (bl->target_info.shadow_len == 0)
1316     /* BL isn't valid, or doesn't shadow memory.  */
1317     return 0;
1318   return 1;
1319 }
1320
1321 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1322    by replacing any memory breakpoints with their shadowed contents.
1323
1324    If READBUF is not NULL, this buffer must not overlap with any of
1325    the breakpoint location's shadow_contents buffers.  Otherwise,
1326    a failed assertion internal error will be raised.
1327
1328    The range of shadowed area by each bp_location is:
1329      bl->address - bp_location_placed_address_before_address_max
1330      up to bl->address + bp_location_shadow_len_after_address_max
1331    The range we were requested to resolve shadows for is:
1332      memaddr ... memaddr + len
1333    Thus the safe cutoff boundaries for performance optimization are
1334      memaddr + len <= (bl->address
1335                        - bp_location_placed_address_before_address_max)
1336    and:
1337      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1338
1339 void
1340 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1341                         const gdb_byte *writebuf_org,
1342                         ULONGEST memaddr, LONGEST len)
1343 {
1344   /* Left boundary, right boundary and median element of our binary
1345      search.  */
1346   unsigned bc_l, bc_r, bc;
1347
1348   /* Find BC_L which is a leftmost element which may affect BUF
1349      content.  It is safe to report lower value but a failure to
1350      report higher one.  */
1351
1352   bc_l = 0;
1353   bc_r = bp_location_count;
1354   while (bc_l + 1 < bc_r)
1355     {
1356       struct bp_location *bl;
1357
1358       bc = (bc_l + bc_r) / 2;
1359       bl = bp_location[bc];
1360
1361       /* Check first BL->ADDRESS will not overflow due to the added
1362          constant.  Then advance the left boundary only if we are sure
1363          the BC element can in no way affect the BUF content (MEMADDR
1364          to MEMADDR + LEN range).
1365
1366          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1367          offset so that we cannot miss a breakpoint with its shadow
1368          range tail still reaching MEMADDR.  */
1369
1370       if ((bl->address + bp_location_shadow_len_after_address_max
1371            >= bl->address)
1372           && (bl->address + bp_location_shadow_len_after_address_max
1373               <= memaddr))
1374         bc_l = bc;
1375       else
1376         bc_r = bc;
1377     }
1378
1379   /* Due to the binary search above, we need to make sure we pick the
1380      first location that's at BC_L's address.  E.g., if there are
1381      multiple locations at the same address, BC_L may end up pointing
1382      at a duplicate location, and miss the "master"/"inserted"
1383      location.  Say, given locations L1, L2 and L3 at addresses A and
1384      B:
1385
1386       L1@A, L2@A, L3@B, ...
1387
1388      BC_L could end up pointing at location L2, while the "master"
1389      location could be L1.  Since the `loc->inserted' flag is only set
1390      on "master" locations, we'd forget to restore the shadow of L1
1391      and L2.  */
1392   while (bc_l > 0
1393          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1394     bc_l--;
1395
1396   /* Now do full processing of the found relevant range of elements.  */
1397
1398   for (bc = bc_l; bc < bp_location_count; bc++)
1399   {
1400     struct bp_location *bl = bp_location[bc];
1401     CORE_ADDR bp_addr = 0;
1402     int bp_size = 0;
1403     int bptoffset = 0;
1404
1405     /* bp_location array has BL->OWNER always non-NULL.  */
1406     if (bl->owner->type == bp_none)
1407       warning (_("reading through apparently deleted breakpoint #%d?"),
1408                bl->owner->number);
1409
1410     /* Performance optimization: any further element can no longer affect BUF
1411        content.  */
1412
1413     if (bl->address >= bp_location_placed_address_before_address_max
1414         && memaddr + len <= (bl->address
1415                              - bp_location_placed_address_before_address_max))
1416       break;
1417
1418     if (!bp_location_has_shadow (bl))
1419       continue;
1420     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1421                                    current_program_space->aspace, 0))
1422       continue;
1423
1424     /* Addresses and length of the part of the breakpoint that
1425        we need to copy.  */
1426     bp_addr = bl->target_info.placed_address;
1427     bp_size = bl->target_info.shadow_len;
1428
1429     if (bp_addr + bp_size <= memaddr)
1430       /* The breakpoint is entirely before the chunk of memory we
1431          are reading.  */
1432       continue;
1433
1434     if (bp_addr >= memaddr + len)
1435       /* The breakpoint is entirely after the chunk of memory we are
1436          reading.  */
1437       continue;
1438
1439     /* Offset within shadow_contents.  */
1440     if (bp_addr < memaddr)
1441       {
1442         /* Only copy the second part of the breakpoint.  */
1443         bp_size -= memaddr - bp_addr;
1444         bptoffset = memaddr - bp_addr;
1445         bp_addr = memaddr;
1446       }
1447
1448     if (bp_addr + bp_size > memaddr + len)
1449       {
1450         /* Only copy the first part of the breakpoint.  */
1451         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1452       }
1453
1454     if (readbuf != NULL)
1455       {
1456         /* Verify that the readbuf buffer does not overlap with
1457            the shadow_contents buffer.  */
1458         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1459                     || readbuf >= (bl->target_info.shadow_contents
1460                                    + bl->target_info.shadow_len));
1461
1462         /* Update the read buffer with this inserted breakpoint's
1463            shadow.  */
1464         memcpy (readbuf + bp_addr - memaddr,
1465                 bl->target_info.shadow_contents + bptoffset, bp_size);
1466       }
1467     else
1468       {
1469         struct gdbarch *gdbarch = bl->gdbarch;
1470         const unsigned char *bp;
1471         CORE_ADDR placed_address = bl->target_info.placed_address;
1472         unsigned placed_size = bl->target_info.placed_size;
1473
1474         /* Update the shadow with what we want to write to memory.  */
1475         memcpy (bl->target_info.shadow_contents + bptoffset,
1476                 writebuf_org + bp_addr - memaddr, bp_size);
1477
1478         /* Determine appropriate breakpoint contents and size for this
1479            address.  */
1480         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1481
1482         /* Update the final write buffer with this inserted
1483            breakpoint's INSN.  */
1484         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1485       }
1486   }
1487 }
1488 \f
1489
1490 /* Return true if BPT is either a software breakpoint or a hardware
1491    breakpoint.  */
1492
1493 int
1494 is_breakpoint (const struct breakpoint *bpt)
1495 {
1496   return (bpt->type == bp_breakpoint
1497           || bpt->type == bp_hardware_breakpoint);
1498 }
1499
1500 /* Return true if BPT is of any hardware watchpoint kind.  */
1501
1502 static int
1503 is_hardware_watchpoint (const struct breakpoint *bpt)
1504 {
1505   return (bpt->type == bp_hardware_watchpoint
1506           || bpt->type == bp_read_watchpoint
1507           || bpt->type == bp_access_watchpoint);
1508 }
1509
1510 /* Return true if BPT is of any watchpoint kind, hardware or
1511    software.  */
1512
1513 int
1514 is_watchpoint (const struct breakpoint *bpt)
1515 {
1516   return (is_hardware_watchpoint (bpt)
1517           || bpt->type == bp_watchpoint);
1518 }
1519
1520 /* Returns true if the current thread and its running state are safe
1521    to evaluate or update watchpoint B.  Watchpoints on local
1522    expressions need to be evaluated in the context of the thread that
1523    was current when the watchpoint was created, and, that thread needs
1524    to be stopped to be able to select the correct frame context.
1525    Watchpoints on global expressions can be evaluated on any thread,
1526    and in any state.  It is presently left to the target allowing
1527    memory accesses when threads are running.  */
1528
1529 static int
1530 watchpoint_in_thread_scope (struct watchpoint *b)
1531 {
1532   return (b->base.pspace == current_program_space
1533           && (ptid_equal (b->watchpoint_thread, null_ptid)
1534               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1535                   && !is_executing (inferior_ptid))));
1536 }
1537
1538 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1539    associated bp_watchpoint_scope breakpoint.  */
1540
1541 static void
1542 watchpoint_del_at_next_stop (struct watchpoint *w)
1543 {
1544   struct breakpoint *b = &w->base;
1545
1546   if (b->related_breakpoint != b)
1547     {
1548       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1549       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1550       b->related_breakpoint->disposition = disp_del_at_next_stop;
1551       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1552       b->related_breakpoint = b;
1553     }
1554   b->disposition = disp_del_at_next_stop;
1555 }
1556
1557 /* Assuming that B is a watchpoint:
1558    - Reparse watchpoint expression, if REPARSE is non-zero
1559    - Evaluate expression and store the result in B->val
1560    - Evaluate the condition if there is one, and store the result
1561      in b->loc->cond.
1562    - Update the list of values that must be watched in B->loc.
1563
1564    If the watchpoint disposition is disp_del_at_next_stop, then do
1565    nothing.  If this is local watchpoint that is out of scope, delete
1566    it.
1567
1568    Even with `set breakpoint always-inserted on' the watchpoints are
1569    removed + inserted on each stop here.  Normal breakpoints must
1570    never be removed because they might be missed by a running thread
1571    when debugging in non-stop mode.  On the other hand, hardware
1572    watchpoints (is_hardware_watchpoint; processed here) are specific
1573    to each LWP since they are stored in each LWP's hardware debug
1574    registers.  Therefore, such LWP must be stopped first in order to
1575    be able to modify its hardware watchpoints.
1576
1577    Hardware watchpoints must be reset exactly once after being
1578    presented to the user.  It cannot be done sooner, because it would
1579    reset the data used to present the watchpoint hit to the user.  And
1580    it must not be done later because it could display the same single
1581    watchpoint hit during multiple GDB stops.  Note that the latter is
1582    relevant only to the hardware watchpoint types bp_read_watchpoint
1583    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1584    not user-visible - its hit is suppressed if the memory content has
1585    not changed.
1586
1587    The following constraints influence the location where we can reset
1588    hardware watchpoints:
1589
1590    * target_stopped_by_watchpoint and target_stopped_data_address are
1591      called several times when GDB stops.
1592
1593    [linux] 
1594    * Multiple hardware watchpoints can be hit at the same time,
1595      causing GDB to stop.  GDB only presents one hardware watchpoint
1596      hit at a time as the reason for stopping, and all the other hits
1597      are presented later, one after the other, each time the user
1598      requests the execution to be resumed.  Execution is not resumed
1599      for the threads still having pending hit event stored in
1600      LWP_INFO->STATUS.  While the watchpoint is already removed from
1601      the inferior on the first stop the thread hit event is kept being
1602      reported from its cached value by linux_nat_stopped_data_address
1603      until the real thread resume happens after the watchpoint gets
1604      presented and thus its LWP_INFO->STATUS gets reset.
1605
1606    Therefore the hardware watchpoint hit can get safely reset on the
1607    watchpoint removal from inferior.  */
1608
1609 static void
1610 update_watchpoint (struct watchpoint *b, int reparse)
1611 {
1612   int within_current_scope;
1613   struct frame_id saved_frame_id;
1614   int frame_saved;
1615
1616   /* If this is a local watchpoint, we only want to check if the
1617      watchpoint frame is in scope if the current thread is the thread
1618      that was used to create the watchpoint.  */
1619   if (!watchpoint_in_thread_scope (b))
1620     return;
1621
1622   if (b->base.disposition == disp_del_at_next_stop)
1623     return;
1624  
1625   frame_saved = 0;
1626
1627   /* Determine if the watchpoint is within scope.  */
1628   if (b->exp_valid_block == NULL)
1629     within_current_scope = 1;
1630   else
1631     {
1632       struct frame_info *fi = get_current_frame ();
1633       struct gdbarch *frame_arch = get_frame_arch (fi);
1634       CORE_ADDR frame_pc = get_frame_pc (fi);
1635
1636       /* If we're in a function epilogue, unwinding may not work
1637          properly, so do not attempt to recreate locations at this
1638          point.  See similar comments in watchpoint_check.  */
1639       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1640         return;
1641
1642       /* Save the current frame's ID so we can restore it after
1643          evaluating the watchpoint expression on its own frame.  */
1644       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1645          took a frame parameter, so that we didn't have to change the
1646          selected frame.  */
1647       frame_saved = 1;
1648       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1649
1650       fi = frame_find_by_id (b->watchpoint_frame);
1651       within_current_scope = (fi != NULL);
1652       if (within_current_scope)
1653         select_frame (fi);
1654     }
1655
1656   /* We don't free locations.  They are stored in the bp_location array
1657      and update_global_location_list will eventually delete them and
1658      remove breakpoints if needed.  */
1659   b->base.loc = NULL;
1660
1661   if (within_current_scope && reparse)
1662     {
1663       char *s;
1664
1665       if (b->exp)
1666         {
1667           xfree (b->exp);
1668           b->exp = NULL;
1669         }
1670       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1671       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1672       /* If the meaning of expression itself changed, the old value is
1673          no longer relevant.  We don't want to report a watchpoint hit
1674          to the user when the old value and the new value may actually
1675          be completely different objects.  */
1676       value_free (b->val);
1677       b->val = NULL;
1678       b->val_valid = 0;
1679
1680       /* Note that unlike with breakpoints, the watchpoint's condition
1681          expression is stored in the breakpoint object, not in the
1682          locations (re)created below.  */
1683       if (b->base.cond_string != NULL)
1684         {
1685           if (b->cond_exp != NULL)
1686             {
1687               xfree (b->cond_exp);
1688               b->cond_exp = NULL;
1689             }
1690
1691           s = b->base.cond_string;
1692           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1693         }
1694     }
1695
1696   /* If we failed to parse the expression, for example because
1697      it refers to a global variable in a not-yet-loaded shared library,
1698      don't try to insert watchpoint.  We don't automatically delete
1699      such watchpoint, though, since failure to parse expression
1700      is different from out-of-scope watchpoint.  */
1701   if ( !target_has_execution)
1702     {
1703       /* Without execution, memory can't change.  No use to try and
1704          set watchpoint locations.  The watchpoint will be reset when
1705          the target gains execution, through breakpoint_re_set.  */
1706     }
1707   else if (within_current_scope && b->exp)
1708     {
1709       int pc = 0;
1710       struct value *val_chain, *v, *result, *next;
1711       struct program_space *frame_pspace;
1712
1713       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1714
1715       /* Avoid setting b->val if it's already set.  The meaning of
1716          b->val is 'the last value' user saw, and we should update
1717          it only if we reported that last value to user.  As it
1718          happens, the code that reports it updates b->val directly.
1719          We don't keep track of the memory value for masked
1720          watchpoints.  */
1721       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1722         {
1723           b->val = v;
1724           b->val_valid = 1;
1725         }
1726
1727       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1728
1729       /* Look at each value on the value chain.  */
1730       for (v = val_chain; v; v = value_next (v))
1731         {
1732           /* If it's a memory location, and GDB actually needed
1733              its contents to evaluate the expression, then we
1734              must watch it.  If the first value returned is
1735              still lazy, that means an error occurred reading it;
1736              watch it anyway in case it becomes readable.  */
1737           if (VALUE_LVAL (v) == lval_memory
1738               && (v == val_chain || ! value_lazy (v)))
1739             {
1740               struct type *vtype = check_typedef (value_type (v));
1741
1742               /* We only watch structs and arrays if user asked
1743                  for it explicitly, never if they just happen to
1744                  appear in the middle of some value chain.  */
1745               if (v == result
1746                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1747                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1748                 {
1749                   CORE_ADDR addr;
1750                   int len, type;
1751                   struct bp_location *loc, **tmp;
1752
1753                   addr = value_address (v);
1754                   len = TYPE_LENGTH (value_type (v));
1755                   type = hw_write;
1756                   if (b->base.type == bp_read_watchpoint)
1757                     type = hw_read;
1758                   else if (b->base.type == bp_access_watchpoint)
1759                     type = hw_access;
1760
1761                   loc = allocate_bp_location (&b->base);
1762                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1763                     ;
1764                   *tmp = loc;
1765                   loc->gdbarch = get_type_arch (value_type (v));
1766
1767                   loc->pspace = frame_pspace;
1768                   loc->address = addr;
1769                   loc->length = len;
1770                   loc->watchpoint_type = type;
1771                 }
1772             }
1773         }
1774
1775       /* Change the type of breakpoint between hardware assisted or
1776          an ordinary watchpoint depending on the hardware support
1777          and free hardware slots.  REPARSE is set when the inferior
1778          is started.  */
1779       if (reparse)
1780         {
1781           int reg_cnt;
1782           enum bp_loc_type loc_type;
1783           struct bp_location *bl;
1784
1785           reg_cnt = can_use_hardware_watchpoint (val_chain);
1786
1787           if (reg_cnt)
1788             {
1789               int i, target_resources_ok, other_type_used;
1790               enum bptype type;
1791
1792               /* Use an exact watchpoint when there's only one memory region to be
1793                  watched, and only one debug register is needed to watch it.  */
1794               b->exact = target_exact_watchpoints && reg_cnt == 1;
1795
1796               /* We need to determine how many resources are already
1797                  used for all other hardware watchpoints plus this one
1798                  to see if we still have enough resources to also fit
1799                  this watchpoint in as well.  */
1800
1801               /* If this is a software watchpoint, we try to turn it
1802                  to a hardware one -- count resources as if B was of
1803                  hardware watchpoint type.  */
1804               type = b->base.type;
1805               if (type == bp_watchpoint)
1806                 type = bp_hardware_watchpoint;
1807
1808               /* This watchpoint may or may not have been placed on
1809                  the list yet at this point (it won't be in the list
1810                  if we're trying to create it for the first time,
1811                  through watch_command), so always account for it
1812                  manually.  */
1813
1814               /* Count resources used by all watchpoints except B.  */
1815               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1816
1817               /* Add in the resources needed for B.  */
1818               i += hw_watchpoint_use_count (&b->base);
1819
1820               target_resources_ok
1821                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1822               if (target_resources_ok <= 0)
1823                 {
1824                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1825
1826                   if (target_resources_ok == 0 && !sw_mode)
1827                     error (_("Target does not support this type of "
1828                              "hardware watchpoint."));
1829                   else if (target_resources_ok < 0 && !sw_mode)
1830                     error (_("There are not enough available hardware "
1831                              "resources for this watchpoint."));
1832
1833                   /* Downgrade to software watchpoint.  */
1834                   b->base.type = bp_watchpoint;
1835                 }
1836               else
1837                 {
1838                   /* If this was a software watchpoint, we've just
1839                      found we have enough resources to turn it to a
1840                      hardware watchpoint.  Otherwise, this is a
1841                      nop.  */
1842                   b->base.type = type;
1843                 }
1844             }
1845           else if (!b->base.ops->works_in_software_mode (&b->base))
1846             error (_("Expression cannot be implemented with "
1847                      "read/access watchpoint."));
1848           else
1849             b->base.type = bp_watchpoint;
1850
1851           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1852                       : bp_loc_hardware_watchpoint);
1853           for (bl = b->base.loc; bl; bl = bl->next)
1854             bl->loc_type = loc_type;
1855         }
1856
1857       for (v = val_chain; v; v = next)
1858         {
1859           next = value_next (v);
1860           if (v != b->val)
1861             value_free (v);
1862         }
1863
1864       /* If a software watchpoint is not watching any memory, then the
1865          above left it without any location set up.  But,
1866          bpstat_stop_status requires a location to be able to report
1867          stops, so make sure there's at least a dummy one.  */
1868       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1869         {
1870           struct breakpoint *base = &b->base;
1871           base->loc = allocate_bp_location (base);
1872           base->loc->pspace = frame_pspace;
1873           base->loc->address = -1;
1874           base->loc->length = -1;
1875           base->loc->watchpoint_type = -1;
1876         }
1877     }
1878   else if (!within_current_scope)
1879     {
1880       printf_filtered (_("\
1881 Watchpoint %d deleted because the program has left the block\n\
1882 in which its expression is valid.\n"),
1883                        b->base.number);
1884       watchpoint_del_at_next_stop (b);
1885     }
1886
1887   /* Restore the selected frame.  */
1888   if (frame_saved)
1889     select_frame (frame_find_by_id (saved_frame_id));
1890 }
1891
1892
1893 /* Returns 1 iff breakpoint location should be
1894    inserted in the inferior.  We don't differentiate the type of BL's owner
1895    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1896    breakpoint_ops is not defined, because in insert_bp_location,
1897    tracepoint's insert_location will not be called.  */
1898 static int
1899 should_be_inserted (struct bp_location *bl)
1900 {
1901   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1902     return 0;
1903
1904   if (bl->owner->disposition == disp_del_at_next_stop)
1905     return 0;
1906
1907   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1908     return 0;
1909
1910   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1911     return 0;
1912
1913   /* This is set for example, when we're attached to the parent of a
1914      vfork, and have detached from the child.  The child is running
1915      free, and we expect it to do an exec or exit, at which point the
1916      OS makes the parent schedulable again (and the target reports
1917      that the vfork is done).  Until the child is done with the shared
1918      memory region, do not insert breakpoints in the parent, otherwise
1919      the child could still trip on the parent's breakpoints.  Since
1920      the parent is blocked anyway, it won't miss any breakpoint.  */
1921   if (bl->pspace->breakpoints_not_allowed)
1922     return 0;
1923
1924   return 1;
1925 }
1926
1927 /* Same as should_be_inserted but does the check assuming
1928    that the location is not duplicated.  */
1929
1930 static int
1931 unduplicated_should_be_inserted (struct bp_location *bl)
1932 {
1933   int result;
1934   const int save_duplicate = bl->duplicate;
1935
1936   bl->duplicate = 0;
1937   result = should_be_inserted (bl);
1938   bl->duplicate = save_duplicate;
1939   return result;
1940 }
1941
1942 /* Parses a conditional described by an expression COND into an
1943    agent expression bytecode suitable for evaluation
1944    by the bytecode interpreter.  Return NULL if there was
1945    any error during parsing.  */
1946
1947 static struct agent_expr *
1948 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
1949 {
1950   struct agent_expr *aexpr = NULL;
1951   struct cleanup *old_chain = NULL;
1952   volatile struct gdb_exception ex;
1953
1954   if (!cond)
1955     return NULL;
1956
1957   /* We don't want to stop processing, so catch any errors
1958      that may show up.  */
1959   TRY_CATCH (ex, RETURN_MASK_ERROR)
1960     {
1961       aexpr = gen_eval_for_expr (scope, cond);
1962     }
1963
1964   if (ex.reason < 0)
1965     {
1966       /* If we got here, it means the condition could not be parsed to a valid
1967          bytecode expression and thus can't be evaluated on the target's side.
1968          It's no use iterating through the conditions.  */
1969       return NULL;
1970     }
1971
1972   /* We have a valid agent expression.  */
1973   return aexpr;
1974 }
1975
1976 /* Based on location BL, create a list of breakpoint conditions to be
1977    passed on to the target.  If we have duplicated locations with different
1978    conditions, we will add such conditions to the list.  The idea is that the
1979    target will evaluate the list of conditions and will only notify GDB when
1980    one of them is true.  */
1981
1982 static void
1983 build_target_condition_list (struct bp_location *bl)
1984 {
1985   struct bp_location **locp = NULL, **loc2p;
1986   int null_condition_or_parse_error = 0;
1987   int modified = bl->needs_update;
1988   struct bp_location *loc;
1989
1990   /* This is only meaningful if the target is
1991      evaluating conditions and if the user has
1992      opted for condition evaluation on the target's
1993      side.  */
1994   if (gdb_evaluates_breakpoint_condition_p ()
1995       || !target_supports_evaluation_of_breakpoint_conditions ())
1996     return;
1997
1998   /* Do a first pass to check for locations with no assigned
1999      conditions or conditions that fail to parse to a valid agent expression
2000      bytecode.  If any of these happen, then it's no use to send conditions
2001      to the target since this location will always trigger and generate a
2002      response back to GDB.  */
2003   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2004     {
2005       loc = (*loc2p);
2006       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2007         {
2008           if (modified)
2009             {
2010               struct agent_expr *aexpr;
2011
2012               /* Re-parse the conditions since something changed.  In that
2013                  case we already freed the condition bytecodes (see
2014                  force_breakpoint_reinsertion).  We just
2015                  need to parse the condition to bytecodes again.  */
2016               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2017               loc->cond_bytecode = aexpr;
2018
2019               /* Check if we managed to parse the conditional expression
2020                  correctly.  If not, we will not send this condition
2021                  to the target.  */
2022               if (aexpr)
2023                 continue;
2024             }
2025
2026           /* If we have a NULL bytecode expression, it means something
2027              went wrong or we have a null condition expression.  */
2028           if (!loc->cond_bytecode)
2029             {
2030               null_condition_or_parse_error = 1;
2031               break;
2032             }
2033         }
2034     }
2035
2036   /* If any of these happened, it means we will have to evaluate the conditions
2037      for the location's address on gdb's side.  It is no use keeping bytecodes
2038      for all the other duplicate locations, thus we free all of them here.
2039
2040      This is so we have a finer control over which locations' conditions are
2041      being evaluated by GDB or the remote stub.  */
2042   if (null_condition_or_parse_error)
2043     {
2044       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2045         {
2046           loc = (*loc2p);
2047           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2048             {
2049               /* Only go as far as the first NULL bytecode is
2050                  located.  */
2051               if (!loc->cond_bytecode)
2052                 return;
2053
2054               free_agent_expr (loc->cond_bytecode);
2055               loc->cond_bytecode = NULL;
2056             }
2057         }
2058     }
2059
2060   /* No NULL conditions or failed bytecode generation.  Build a condition list
2061      for this location's address.  */
2062   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2063     {
2064       loc = (*loc2p);
2065       if (loc->cond
2066           && is_breakpoint (loc->owner)
2067           && loc->pspace->num == bl->pspace->num
2068           && loc->owner->enable_state == bp_enabled
2069           && loc->enabled)
2070         /* Add the condition to the vector.  This will be used later to send the
2071            conditions to the target.  */
2072         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2073                        loc->cond_bytecode);
2074     }
2075
2076   return;
2077 }
2078
2079 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2080    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2081    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2082    Returns 0 for success, 1 if the bp_location type is not supported or
2083    -1 for failure.
2084
2085    NOTE drow/2003-09-09: This routine could be broken down to an
2086    object-style method for each breakpoint or catchpoint type.  */
2087 static int
2088 insert_bp_location (struct bp_location *bl,
2089                     struct ui_file *tmp_error_stream,
2090                     int *disabled_breaks,
2091                     int *hw_breakpoint_error)
2092 {
2093   int val = 0;
2094
2095   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2096     return 0;
2097
2098   /* Note we don't initialize bl->target_info, as that wipes out
2099      the breakpoint location's shadow_contents if the breakpoint
2100      is still inserted at that location.  This in turn breaks
2101      target_read_memory which depends on these buffers when
2102      a memory read is requested at the breakpoint location:
2103      Once the target_info has been wiped, we fail to see that
2104      we have a breakpoint inserted at that address and thus
2105      read the breakpoint instead of returning the data saved in
2106      the breakpoint location's shadow contents.  */
2107   bl->target_info.placed_address = bl->address;
2108   bl->target_info.placed_address_space = bl->pspace->aspace;
2109   bl->target_info.length = bl->length;
2110
2111   /* When working with target-side conditions, we must pass all the conditions
2112      for the same breakpoint address down to the target since GDB will not
2113      insert those locations.  With a list of breakpoint conditions, the target
2114      can decide when to stop and notify GDB.  */
2115
2116   if (is_breakpoint (bl->owner))
2117     {
2118       build_target_condition_list (bl);
2119       /* Reset the condition modification marker.  */
2120       bl->needs_update = 0;
2121     }
2122
2123   if (bl->loc_type == bp_loc_software_breakpoint
2124       || bl->loc_type == bp_loc_hardware_breakpoint)
2125     {
2126       if (bl->owner->type != bp_hardware_breakpoint)
2127         {
2128           /* If the explicitly specified breakpoint type
2129              is not hardware breakpoint, check the memory map to see
2130              if the breakpoint address is in read only memory or not.
2131
2132              Two important cases are:
2133              - location type is not hardware breakpoint, memory
2134              is readonly.  We change the type of the location to
2135              hardware breakpoint.
2136              - location type is hardware breakpoint, memory is
2137              read-write.  This means we've previously made the
2138              location hardware one, but then the memory map changed,
2139              so we undo.
2140              
2141              When breakpoints are removed, remove_breakpoints will use
2142              location types we've just set here, the only possible
2143              problem is that memory map has changed during running
2144              program, but it's not going to work anyway with current
2145              gdb.  */
2146           struct mem_region *mr 
2147             = lookup_mem_region (bl->target_info.placed_address);
2148           
2149           if (mr)
2150             {
2151               if (automatic_hardware_breakpoints)
2152                 {
2153                   enum bp_loc_type new_type;
2154                   
2155                   if (mr->attrib.mode != MEM_RW)
2156                     new_type = bp_loc_hardware_breakpoint;
2157                   else 
2158                     new_type = bp_loc_software_breakpoint;
2159                   
2160                   if (new_type != bl->loc_type)
2161                     {
2162                       static int said = 0;
2163
2164                       bl->loc_type = new_type;
2165                       if (!said)
2166                         {
2167                           fprintf_filtered (gdb_stdout,
2168                                             _("Note: automatically using "
2169                                               "hardware breakpoints for "
2170                                               "read-only addresses.\n"));
2171                           said = 1;
2172                         }
2173                     }
2174                 }
2175               else if (bl->loc_type == bp_loc_software_breakpoint
2176                        && mr->attrib.mode != MEM_RW)        
2177                 warning (_("cannot set software breakpoint "
2178                            "at readonly address %s"),
2179                          paddress (bl->gdbarch, bl->address));
2180             }
2181         }
2182         
2183       /* First check to see if we have to handle an overlay.  */
2184       if (overlay_debugging == ovly_off
2185           || bl->section == NULL
2186           || !(section_is_overlay (bl->section)))
2187         {
2188           /* No overlay handling: just set the breakpoint.  */
2189
2190           val = bl->owner->ops->insert_location (bl);
2191         }
2192       else
2193         {
2194           /* This breakpoint is in an overlay section.
2195              Shall we set a breakpoint at the LMA?  */
2196           if (!overlay_events_enabled)
2197             {
2198               /* Yes -- overlay event support is not active, 
2199                  so we must try to set a breakpoint at the LMA.
2200                  This will not work for a hardware breakpoint.  */
2201               if (bl->loc_type == bp_loc_hardware_breakpoint)
2202                 warning (_("hardware breakpoint %d not supported in overlay!"),
2203                          bl->owner->number);
2204               else
2205                 {
2206                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2207                                                              bl->section);
2208                   /* Set a software (trap) breakpoint at the LMA.  */
2209                   bl->overlay_target_info = bl->target_info;
2210                   bl->overlay_target_info.placed_address = addr;
2211                   val = target_insert_breakpoint (bl->gdbarch,
2212                                                   &bl->overlay_target_info);
2213                   if (val != 0)
2214                     fprintf_unfiltered (tmp_error_stream,
2215                                         "Overlay breakpoint %d "
2216                                         "failed: in ROM?\n",
2217                                         bl->owner->number);
2218                 }
2219             }
2220           /* Shall we set a breakpoint at the VMA? */
2221           if (section_is_mapped (bl->section))
2222             {
2223               /* Yes.  This overlay section is mapped into memory.  */
2224               val = bl->owner->ops->insert_location (bl);
2225             }
2226           else
2227             {
2228               /* No.  This breakpoint will not be inserted.  
2229                  No error, but do not mark the bp as 'inserted'.  */
2230               return 0;
2231             }
2232         }
2233
2234       if (val)
2235         {
2236           /* Can't set the breakpoint.  */
2237           if (solib_name_from_address (bl->pspace, bl->address))
2238             {
2239               /* See also: disable_breakpoints_in_shlibs.  */
2240               val = 0;
2241               bl->shlib_disabled = 1;
2242               observer_notify_breakpoint_modified (bl->owner);
2243               if (!*disabled_breaks)
2244                 {
2245                   fprintf_unfiltered (tmp_error_stream, 
2246                                       "Cannot insert breakpoint %d.\n", 
2247                                       bl->owner->number);
2248                   fprintf_unfiltered (tmp_error_stream, 
2249                                       "Temporarily disabling shared "
2250                                       "library breakpoints:\n");
2251                 }
2252               *disabled_breaks = 1;
2253               fprintf_unfiltered (tmp_error_stream,
2254                                   "breakpoint #%d\n", bl->owner->number);
2255             }
2256           else
2257             {
2258               if (bl->loc_type == bp_loc_hardware_breakpoint)
2259                 {
2260                   *hw_breakpoint_error = 1;
2261                   fprintf_unfiltered (tmp_error_stream,
2262                                       "Cannot insert hardware "
2263                                       "breakpoint %d.\n",
2264                                       bl->owner->number);
2265                 }
2266               else
2267                 {
2268                   fprintf_unfiltered (tmp_error_stream, 
2269                                       "Cannot insert breakpoint %d.\n", 
2270                                       bl->owner->number);
2271                   fprintf_filtered (tmp_error_stream, 
2272                                     "Error accessing memory address ");
2273                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2274                                   tmp_error_stream);
2275                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2276                                     safe_strerror (val));
2277                 }
2278
2279             }
2280         }
2281       else
2282         bl->inserted = 1;
2283
2284       return val;
2285     }
2286
2287   else if (bl->loc_type == bp_loc_hardware_watchpoint
2288            /* NOTE drow/2003-09-08: This state only exists for removing
2289               watchpoints.  It's not clear that it's necessary...  */
2290            && bl->owner->disposition != disp_del_at_next_stop)
2291     {
2292       gdb_assert (bl->owner->ops != NULL
2293                   && bl->owner->ops->insert_location != NULL);
2294
2295       val = bl->owner->ops->insert_location (bl);
2296
2297       /* If trying to set a read-watchpoint, and it turns out it's not
2298          supported, try emulating one with an access watchpoint.  */
2299       if (val == 1 && bl->watchpoint_type == hw_read)
2300         {
2301           struct bp_location *loc, **loc_temp;
2302
2303           /* But don't try to insert it, if there's already another
2304              hw_access location that would be considered a duplicate
2305              of this one.  */
2306           ALL_BP_LOCATIONS (loc, loc_temp)
2307             if (loc != bl
2308                 && loc->watchpoint_type == hw_access
2309                 && watchpoint_locations_match (bl, loc))
2310               {
2311                 bl->duplicate = 1;
2312                 bl->inserted = 1;
2313                 bl->target_info = loc->target_info;
2314                 bl->watchpoint_type = hw_access;
2315                 val = 0;
2316                 break;
2317               }
2318
2319           if (val == 1)
2320             {
2321               bl->watchpoint_type = hw_access;
2322               val = bl->owner->ops->insert_location (bl);
2323
2324               if (val)
2325                 /* Back to the original value.  */
2326                 bl->watchpoint_type = hw_read;
2327             }
2328         }
2329
2330       bl->inserted = (val == 0);
2331     }
2332
2333   else if (bl->owner->type == bp_catchpoint)
2334     {
2335       gdb_assert (bl->owner->ops != NULL
2336                   && bl->owner->ops->insert_location != NULL);
2337
2338       val = bl->owner->ops->insert_location (bl);
2339       if (val)
2340         {
2341           bl->owner->enable_state = bp_disabled;
2342
2343           if (val == 1)
2344             warning (_("\
2345 Error inserting catchpoint %d: Your system does not support this type\n\
2346 of catchpoint."), bl->owner->number);
2347           else
2348             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2349         }
2350
2351       bl->inserted = (val == 0);
2352
2353       /* We've already printed an error message if there was a problem
2354          inserting this catchpoint, and we've disabled the catchpoint,
2355          so just return success.  */
2356       return 0;
2357     }
2358
2359   return 0;
2360 }
2361
2362 /* This function is called when program space PSPACE is about to be
2363    deleted.  It takes care of updating breakpoints to not reference
2364    PSPACE anymore.  */
2365
2366 void
2367 breakpoint_program_space_exit (struct program_space *pspace)
2368 {
2369   struct breakpoint *b, *b_temp;
2370   struct bp_location *loc, **loc_temp;
2371
2372   /* Remove any breakpoint that was set through this program space.  */
2373   ALL_BREAKPOINTS_SAFE (b, b_temp)
2374     {
2375       if (b->pspace == pspace)
2376         delete_breakpoint (b);
2377     }
2378
2379   /* Breakpoints set through other program spaces could have locations
2380      bound to PSPACE as well.  Remove those.  */
2381   ALL_BP_LOCATIONS (loc, loc_temp)
2382     {
2383       struct bp_location *tmp;
2384
2385       if (loc->pspace == pspace)
2386         {
2387           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2388           if (loc->owner->loc == loc)
2389             loc->owner->loc = loc->next;
2390           else
2391             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2392               if (tmp->next == loc)
2393                 {
2394                   tmp->next = loc->next;
2395                   break;
2396                 }
2397         }
2398     }
2399
2400   /* Now update the global location list to permanently delete the
2401      removed locations above.  */
2402   update_global_location_list (0);
2403 }
2404
2405 /* Make sure all breakpoints are inserted in inferior.
2406    Throws exception on any error.
2407    A breakpoint that is already inserted won't be inserted
2408    again, so calling this function twice is safe.  */
2409 void
2410 insert_breakpoints (void)
2411 {
2412   struct breakpoint *bpt;
2413
2414   ALL_BREAKPOINTS (bpt)
2415     if (is_hardware_watchpoint (bpt))
2416       {
2417         struct watchpoint *w = (struct watchpoint *) bpt;
2418
2419         update_watchpoint (w, 0 /* don't reparse.  */);
2420       }
2421
2422   update_global_location_list (1);
2423
2424   /* update_global_location_list does not insert breakpoints when
2425      always_inserted_mode is not enabled.  Explicitly insert them
2426      now.  */
2427   if (!breakpoints_always_inserted_mode ())
2428     insert_breakpoint_locations ();
2429 }
2430
2431 /* Invoke CALLBACK for each of bp_location.  */
2432
2433 void
2434 iterate_over_bp_locations (walk_bp_location_callback callback)
2435 {
2436   struct bp_location *loc, **loc_tmp;
2437
2438   ALL_BP_LOCATIONS (loc, loc_tmp)
2439     {
2440       callback (loc, NULL);
2441     }
2442 }
2443
2444 /* This is used when we need to synch breakpoint conditions between GDB and the
2445    target.  It is the case with deleting and disabling of breakpoints when using
2446    always-inserted mode.  */
2447
2448 static void
2449 update_inserted_breakpoint_locations (void)
2450 {
2451   struct bp_location *bl, **blp_tmp;
2452   int error_flag = 0;
2453   int val = 0;
2454   int disabled_breaks = 0;
2455   int hw_breakpoint_error = 0;
2456
2457   struct ui_file *tmp_error_stream = mem_fileopen ();
2458   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2459
2460   /* Explicitly mark the warning -- this will only be printed if
2461      there was an error.  */
2462   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2463
2464   save_current_space_and_thread ();
2465
2466   ALL_BP_LOCATIONS (bl, blp_tmp)
2467     {
2468       /* We only want to update software breakpoints and hardware
2469          breakpoints.  */
2470       if (!is_breakpoint (bl->owner))
2471         continue;
2472
2473       /* We only want to update locations that are already inserted
2474          and need updating.  This is to avoid unwanted insertion during
2475          deletion of breakpoints.  */
2476       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2477         continue;
2478
2479       switch_to_program_space_and_thread (bl->pspace);
2480
2481       /* For targets that support global breakpoints, there's no need
2482          to select an inferior to insert breakpoint to.  In fact, even
2483          if we aren't attached to any process yet, we should still
2484          insert breakpoints.  */
2485       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2486           && ptid_equal (inferior_ptid, null_ptid))
2487         continue;
2488
2489       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2490                                     &hw_breakpoint_error);
2491       if (val)
2492         error_flag = val;
2493     }
2494
2495   if (error_flag)
2496     {
2497       target_terminal_ours_for_output ();
2498       error_stream (tmp_error_stream);
2499     }
2500
2501   do_cleanups (cleanups);
2502 }
2503
2504 /* Used when starting or continuing the program.  */
2505
2506 static void
2507 insert_breakpoint_locations (void)
2508 {
2509   struct breakpoint *bpt;
2510   struct bp_location *bl, **blp_tmp;
2511   int error_flag = 0;
2512   int val = 0;
2513   int disabled_breaks = 0;
2514   int hw_breakpoint_error = 0;
2515
2516   struct ui_file *tmp_error_stream = mem_fileopen ();
2517   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2518   
2519   /* Explicitly mark the warning -- this will only be printed if
2520      there was an error.  */
2521   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2522
2523   save_current_space_and_thread ();
2524
2525   ALL_BP_LOCATIONS (bl, blp_tmp)
2526     {
2527       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2528         continue;
2529
2530       /* There is no point inserting thread-specific breakpoints if
2531          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2532          has BL->OWNER always non-NULL.  */
2533       if (bl->owner->thread != -1
2534           && !valid_thread_id (bl->owner->thread))
2535         continue;
2536
2537       switch_to_program_space_and_thread (bl->pspace);
2538
2539       /* For targets that support global breakpoints, there's no need
2540          to select an inferior to insert breakpoint to.  In fact, even
2541          if we aren't attached to any process yet, we should still
2542          insert breakpoints.  */
2543       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2544           && ptid_equal (inferior_ptid, null_ptid))
2545         continue;
2546
2547       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2548                                     &hw_breakpoint_error);
2549       if (val)
2550         error_flag = val;
2551     }
2552
2553   /* If we failed to insert all locations of a watchpoint, remove
2554      them, as half-inserted watchpoint is of limited use.  */
2555   ALL_BREAKPOINTS (bpt)  
2556     {
2557       int some_failed = 0;
2558       struct bp_location *loc;
2559
2560       if (!is_hardware_watchpoint (bpt))
2561         continue;
2562
2563       if (!breakpoint_enabled (bpt))
2564         continue;
2565
2566       if (bpt->disposition == disp_del_at_next_stop)
2567         continue;
2568       
2569       for (loc = bpt->loc; loc; loc = loc->next)
2570         if (!loc->inserted && should_be_inserted (loc))
2571           {
2572             some_failed = 1;
2573             break;
2574           }
2575       if (some_failed)
2576         {
2577           for (loc = bpt->loc; loc; loc = loc->next)
2578             if (loc->inserted)
2579               remove_breakpoint (loc, mark_uninserted);
2580
2581           hw_breakpoint_error = 1;
2582           fprintf_unfiltered (tmp_error_stream,
2583                               "Could not insert hardware watchpoint %d.\n", 
2584                               bpt->number);
2585           error_flag = -1;
2586         }
2587     }
2588
2589   if (error_flag)
2590     {
2591       /* If a hardware breakpoint or watchpoint was inserted, add a
2592          message about possibly exhausted resources.  */
2593       if (hw_breakpoint_error)
2594         {
2595           fprintf_unfiltered (tmp_error_stream, 
2596                               "Could not insert hardware breakpoints:\n\
2597 You may have requested too many hardware breakpoints/watchpoints.\n");
2598         }
2599       target_terminal_ours_for_output ();
2600       error_stream (tmp_error_stream);
2601     }
2602
2603   do_cleanups (cleanups);
2604 }
2605
2606 /* Used when the program stops.
2607    Returns zero if successful, or non-zero if there was a problem
2608    removing a breakpoint location.  */
2609
2610 int
2611 remove_breakpoints (void)
2612 {
2613   struct bp_location *bl, **blp_tmp;
2614   int val = 0;
2615
2616   ALL_BP_LOCATIONS (bl, blp_tmp)
2617   {
2618     if (bl->inserted && !is_tracepoint (bl->owner))
2619       val |= remove_breakpoint (bl, mark_uninserted);
2620   }
2621   return val;
2622 }
2623
2624 /* Remove breakpoints of process PID.  */
2625
2626 int
2627 remove_breakpoints_pid (int pid)
2628 {
2629   struct bp_location *bl, **blp_tmp;
2630   int val;
2631   struct inferior *inf = find_inferior_pid (pid);
2632
2633   ALL_BP_LOCATIONS (bl, blp_tmp)
2634   {
2635     if (bl->pspace != inf->pspace)
2636       continue;
2637
2638     if (bl->inserted)
2639       {
2640         val = remove_breakpoint (bl, mark_uninserted);
2641         if (val != 0)
2642           return val;
2643       }
2644   }
2645   return 0;
2646 }
2647
2648 int
2649 reattach_breakpoints (int pid)
2650 {
2651   struct cleanup *old_chain;
2652   struct bp_location *bl, **blp_tmp;
2653   int val;
2654   struct ui_file *tmp_error_stream;
2655   int dummy1 = 0, dummy2 = 0;
2656   struct inferior *inf;
2657   struct thread_info *tp;
2658
2659   tp = any_live_thread_of_process (pid);
2660   if (tp == NULL)
2661     return 1;
2662
2663   inf = find_inferior_pid (pid);
2664   old_chain = save_inferior_ptid ();
2665
2666   inferior_ptid = tp->ptid;
2667
2668   tmp_error_stream = mem_fileopen ();
2669   make_cleanup_ui_file_delete (tmp_error_stream);
2670
2671   ALL_BP_LOCATIONS (bl, blp_tmp)
2672   {
2673     if (bl->pspace != inf->pspace)
2674       continue;
2675
2676     if (bl->inserted)
2677       {
2678         bl->inserted = 0;
2679         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2680         if (val != 0)
2681           {
2682             do_cleanups (old_chain);
2683             return val;
2684           }
2685       }
2686   }
2687   do_cleanups (old_chain);
2688   return 0;
2689 }
2690
2691 static int internal_breakpoint_number = -1;
2692
2693 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2694    If INTERNAL is non-zero, the breakpoint number will be populated
2695    from internal_breakpoint_number and that variable decremented.
2696    Otherwise the breakpoint number will be populated from
2697    breakpoint_count and that value incremented.  Internal breakpoints
2698    do not set the internal var bpnum.  */
2699 static void
2700 set_breakpoint_number (int internal, struct breakpoint *b)
2701 {
2702   if (internal)
2703     b->number = internal_breakpoint_number--;
2704   else
2705     {
2706       set_breakpoint_count (breakpoint_count + 1);
2707       b->number = breakpoint_count;
2708     }
2709 }
2710
2711 static struct breakpoint *
2712 create_internal_breakpoint (struct gdbarch *gdbarch,
2713                             CORE_ADDR address, enum bptype type,
2714                             const struct breakpoint_ops *ops)
2715 {
2716   struct symtab_and_line sal;
2717   struct breakpoint *b;
2718
2719   init_sal (&sal);              /* Initialize to zeroes.  */
2720
2721   sal.pc = address;
2722   sal.section = find_pc_overlay (sal.pc);
2723   sal.pspace = current_program_space;
2724
2725   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2726   b->number = internal_breakpoint_number--;
2727   b->disposition = disp_donttouch;
2728
2729   return b;
2730 }
2731
2732 static const char *const longjmp_names[] =
2733   {
2734     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2735   };
2736 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2737
2738 /* Per-objfile data private to breakpoint.c.  */
2739 struct breakpoint_objfile_data
2740 {
2741   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2742   struct minimal_symbol *overlay_msym;
2743
2744   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2745   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2746
2747   /* Minimal symbol for "std::terminate()" (if any).  */
2748   struct minimal_symbol *terminate_msym;
2749
2750   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2751   struct minimal_symbol *exception_msym;
2752 };
2753
2754 static const struct objfile_data *breakpoint_objfile_key;
2755
2756 /* Minimal symbol not found sentinel.  */
2757 static struct minimal_symbol msym_not_found;
2758
2759 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2760
2761 static int
2762 msym_not_found_p (const struct minimal_symbol *msym)
2763 {
2764   return msym == &msym_not_found;
2765 }
2766
2767 /* Return per-objfile data needed by breakpoint.c.
2768    Allocate the data if necessary.  */
2769
2770 static struct breakpoint_objfile_data *
2771 get_breakpoint_objfile_data (struct objfile *objfile)
2772 {
2773   struct breakpoint_objfile_data *bp_objfile_data;
2774
2775   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2776   if (bp_objfile_data == NULL)
2777     {
2778       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2779                                        sizeof (*bp_objfile_data));
2780
2781       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2782       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2783     }
2784   return bp_objfile_data;
2785 }
2786
2787 static void
2788 create_overlay_event_breakpoint (void)
2789 {
2790   struct objfile *objfile;
2791   const char *const func_name = "_ovly_debug_event";
2792
2793   ALL_OBJFILES (objfile)
2794     {
2795       struct breakpoint *b;
2796       struct breakpoint_objfile_data *bp_objfile_data;
2797       CORE_ADDR addr;
2798
2799       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2800
2801       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2802         continue;
2803
2804       if (bp_objfile_data->overlay_msym == NULL)
2805         {
2806           struct minimal_symbol *m;
2807
2808           m = lookup_minimal_symbol_text (func_name, objfile);
2809           if (m == NULL)
2810             {
2811               /* Avoid future lookups in this objfile.  */
2812               bp_objfile_data->overlay_msym = &msym_not_found;
2813               continue;
2814             }
2815           bp_objfile_data->overlay_msym = m;
2816         }
2817
2818       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2819       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2820                                       bp_overlay_event,
2821                                       &internal_breakpoint_ops);
2822       b->addr_string = xstrdup (func_name);
2823
2824       if (overlay_debugging == ovly_auto)
2825         {
2826           b->enable_state = bp_enabled;
2827           overlay_events_enabled = 1;
2828         }
2829       else
2830        {
2831          b->enable_state = bp_disabled;
2832          overlay_events_enabled = 0;
2833        }
2834     }
2835   update_global_location_list (1);
2836 }
2837
2838 static void
2839 create_longjmp_master_breakpoint (void)
2840 {
2841   struct program_space *pspace;
2842   struct cleanup *old_chain;
2843
2844   old_chain = save_current_program_space ();
2845
2846   ALL_PSPACES (pspace)
2847   {
2848     struct objfile *objfile;
2849
2850     set_current_program_space (pspace);
2851
2852     ALL_OBJFILES (objfile)
2853     {
2854       int i;
2855       struct gdbarch *gdbarch;
2856       struct breakpoint_objfile_data *bp_objfile_data;
2857
2858       gdbarch = get_objfile_arch (objfile);
2859       if (!gdbarch_get_longjmp_target_p (gdbarch))
2860         continue;
2861
2862       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2863
2864       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2865         {
2866           struct breakpoint *b;
2867           const char *func_name;
2868           CORE_ADDR addr;
2869
2870           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2871             continue;
2872
2873           func_name = longjmp_names[i];
2874           if (bp_objfile_data->longjmp_msym[i] == NULL)
2875             {
2876               struct minimal_symbol *m;
2877
2878               m = lookup_minimal_symbol_text (func_name, objfile);
2879               if (m == NULL)
2880                 {
2881                   /* Prevent future lookups in this objfile.  */
2882                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2883                   continue;
2884                 }
2885               bp_objfile_data->longjmp_msym[i] = m;
2886             }
2887
2888           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2889           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2890                                           &internal_breakpoint_ops);
2891           b->addr_string = xstrdup (func_name);
2892           b->enable_state = bp_disabled;
2893         }
2894     }
2895   }
2896   update_global_location_list (1);
2897
2898   do_cleanups (old_chain);
2899 }
2900
2901 /* Create a master std::terminate breakpoint.  */
2902 static void
2903 create_std_terminate_master_breakpoint (void)
2904 {
2905   struct program_space *pspace;
2906   struct cleanup *old_chain;
2907   const char *const func_name = "std::terminate()";
2908
2909   old_chain = save_current_program_space ();
2910
2911   ALL_PSPACES (pspace)
2912   {
2913     struct objfile *objfile;
2914     CORE_ADDR addr;
2915
2916     set_current_program_space (pspace);
2917
2918     ALL_OBJFILES (objfile)
2919     {
2920       struct breakpoint *b;
2921       struct breakpoint_objfile_data *bp_objfile_data;
2922
2923       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2924
2925       if (msym_not_found_p (bp_objfile_data->terminate_msym))
2926         continue;
2927
2928       if (bp_objfile_data->terminate_msym == NULL)
2929         {
2930           struct minimal_symbol *m;
2931
2932           m = lookup_minimal_symbol (func_name, NULL, objfile);
2933           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
2934                             && MSYMBOL_TYPE (m) != mst_file_text))
2935             {
2936               /* Prevent future lookups in this objfile.  */
2937               bp_objfile_data->terminate_msym = &msym_not_found;
2938               continue;
2939             }
2940           bp_objfile_data->terminate_msym = m;
2941         }
2942
2943       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
2944       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2945                                       bp_std_terminate_master,
2946                                       &internal_breakpoint_ops);
2947       b->addr_string = xstrdup (func_name);
2948       b->enable_state = bp_disabled;
2949     }
2950   }
2951
2952   update_global_location_list (1);
2953
2954   do_cleanups (old_chain);
2955 }
2956
2957 /* Install a master breakpoint on the unwinder's debug hook.  */
2958
2959 static void
2960 create_exception_master_breakpoint (void)
2961 {
2962   struct objfile *objfile;
2963   const char *const func_name = "_Unwind_DebugHook";
2964
2965   ALL_OBJFILES (objfile)
2966     {
2967       struct breakpoint *b;
2968       struct gdbarch *gdbarch;
2969       struct breakpoint_objfile_data *bp_objfile_data;
2970       CORE_ADDR addr;
2971
2972       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2973
2974       if (msym_not_found_p (bp_objfile_data->exception_msym))
2975         continue;
2976
2977       gdbarch = get_objfile_arch (objfile);
2978
2979       if (bp_objfile_data->exception_msym == NULL)
2980         {
2981           struct minimal_symbol *debug_hook;
2982
2983           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
2984           if (debug_hook == NULL)
2985             {
2986               bp_objfile_data->exception_msym = &msym_not_found;
2987               continue;
2988             }
2989
2990           bp_objfile_data->exception_msym = debug_hook;
2991         }
2992
2993       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
2994       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
2995                                                  &current_target);
2996       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
2997                                       &internal_breakpoint_ops);
2998       b->addr_string = xstrdup (func_name);
2999       b->enable_state = bp_disabled;
3000     }
3001
3002   update_global_location_list (1);
3003 }
3004
3005 void
3006 update_breakpoints_after_exec (void)
3007 {
3008   struct breakpoint *b, *b_tmp;
3009   struct bp_location *bploc, **bplocp_tmp;
3010
3011   /* We're about to delete breakpoints from GDB's lists.  If the
3012      INSERTED flag is true, GDB will try to lift the breakpoints by
3013      writing the breakpoints' "shadow contents" back into memory.  The
3014      "shadow contents" are NOT valid after an exec, so GDB should not
3015      do that.  Instead, the target is responsible from marking
3016      breakpoints out as soon as it detects an exec.  We don't do that
3017      here instead, because there may be other attempts to delete
3018      breakpoints after detecting an exec and before reaching here.  */
3019   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3020     if (bploc->pspace == current_program_space)
3021       gdb_assert (!bploc->inserted);
3022
3023   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3024   {
3025     if (b->pspace != current_program_space)
3026       continue;
3027
3028     /* Solib breakpoints must be explicitly reset after an exec().  */
3029     if (b->type == bp_shlib_event)
3030       {
3031         delete_breakpoint (b);
3032         continue;
3033       }
3034
3035     /* JIT breakpoints must be explicitly reset after an exec().  */
3036     if (b->type == bp_jit_event)
3037       {
3038         delete_breakpoint (b);
3039         continue;
3040       }
3041
3042     /* Thread event breakpoints must be set anew after an exec(),
3043        as must overlay event and longjmp master breakpoints.  */
3044     if (b->type == bp_thread_event || b->type == bp_overlay_event
3045         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3046         || b->type == bp_exception_master)
3047       {
3048         delete_breakpoint (b);
3049         continue;
3050       }
3051
3052     /* Step-resume breakpoints are meaningless after an exec().  */
3053     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3054       {
3055         delete_breakpoint (b);
3056         continue;
3057       }
3058
3059     /* Longjmp and longjmp-resume breakpoints are also meaningless
3060        after an exec.  */
3061     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3062         || b->type == bp_exception || b->type == bp_exception_resume)
3063       {
3064         delete_breakpoint (b);
3065         continue;
3066       }
3067
3068     if (b->type == bp_catchpoint)
3069       {
3070         /* For now, none of the bp_catchpoint breakpoints need to
3071            do anything at this point.  In the future, if some of
3072            the catchpoints need to something, we will need to add
3073            a new method, and call this method from here.  */
3074         continue;
3075       }
3076
3077     /* bp_finish is a special case.  The only way we ought to be able
3078        to see one of these when an exec() has happened, is if the user
3079        caught a vfork, and then said "finish".  Ordinarily a finish just
3080        carries them to the call-site of the current callee, by setting
3081        a temporary bp there and resuming.  But in this case, the finish
3082        will carry them entirely through the vfork & exec.
3083
3084        We don't want to allow a bp_finish to remain inserted now.  But
3085        we can't safely delete it, 'cause finish_command has a handle to
3086        the bp on a bpstat, and will later want to delete it.  There's a
3087        chance (and I've seen it happen) that if we delete the bp_finish
3088        here, that its storage will get reused by the time finish_command
3089        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3090        We really must allow finish_command to delete a bp_finish.
3091
3092        In the absence of a general solution for the "how do we know
3093        it's safe to delete something others may have handles to?"
3094        problem, what we'll do here is just uninsert the bp_finish, and
3095        let finish_command delete it.
3096
3097        (We know the bp_finish is "doomed" in the sense that it's
3098        momentary, and will be deleted as soon as finish_command sees
3099        the inferior stopped.  So it doesn't matter that the bp's
3100        address is probably bogus in the new a.out, unlike e.g., the
3101        solib breakpoints.)  */
3102
3103     if (b->type == bp_finish)
3104       {
3105         continue;
3106       }
3107
3108     /* Without a symbolic address, we have little hope of the
3109        pre-exec() address meaning the same thing in the post-exec()
3110        a.out.  */
3111     if (b->addr_string == NULL)
3112       {
3113         delete_breakpoint (b);
3114         continue;
3115       }
3116   }
3117   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3118   create_overlay_event_breakpoint ();
3119   create_longjmp_master_breakpoint ();
3120   create_std_terminate_master_breakpoint ();
3121   create_exception_master_breakpoint ();
3122 }
3123
3124 int
3125 detach_breakpoints (int pid)
3126 {
3127   struct bp_location *bl, **blp_tmp;
3128   int val = 0;
3129   struct cleanup *old_chain = save_inferior_ptid ();
3130   struct inferior *inf = current_inferior ();
3131
3132   if (pid == PIDGET (inferior_ptid))
3133     error (_("Cannot detach breakpoints of inferior_ptid"));
3134
3135   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3136   inferior_ptid = pid_to_ptid (pid);
3137   ALL_BP_LOCATIONS (bl, blp_tmp)
3138   {
3139     if (bl->pspace != inf->pspace)
3140       continue;
3141
3142     if (bl->inserted)
3143       val |= remove_breakpoint_1 (bl, mark_inserted);
3144   }
3145
3146   /* Detach single-step breakpoints as well.  */
3147   detach_single_step_breakpoints ();
3148
3149   do_cleanups (old_chain);
3150   return val;
3151 }
3152
3153 /* Remove the breakpoint location BL from the current address space.
3154    Note that this is used to detach breakpoints from a child fork.
3155    When we get here, the child isn't in the inferior list, and neither
3156    do we have objects to represent its address space --- we should
3157    *not* look at bl->pspace->aspace here.  */
3158
3159 static int
3160 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3161 {
3162   int val;
3163
3164   /* BL is never in moribund_locations by our callers.  */
3165   gdb_assert (bl->owner != NULL);
3166
3167   if (bl->owner->enable_state == bp_permanent)
3168     /* Permanent breakpoints cannot be inserted or removed.  */
3169     return 0;
3170
3171   /* The type of none suggests that owner is actually deleted.
3172      This should not ever happen.  */
3173   gdb_assert (bl->owner->type != bp_none);
3174
3175   if (bl->loc_type == bp_loc_software_breakpoint
3176       || bl->loc_type == bp_loc_hardware_breakpoint)
3177     {
3178       /* "Normal" instruction breakpoint: either the standard
3179          trap-instruction bp (bp_breakpoint), or a
3180          bp_hardware_breakpoint.  */
3181
3182       /* First check to see if we have to handle an overlay.  */
3183       if (overlay_debugging == ovly_off
3184           || bl->section == NULL
3185           || !(section_is_overlay (bl->section)))
3186         {
3187           /* No overlay handling: just remove the breakpoint.  */
3188           val = bl->owner->ops->remove_location (bl);
3189         }
3190       else
3191         {
3192           /* This breakpoint is in an overlay section.
3193              Did we set a breakpoint at the LMA?  */
3194           if (!overlay_events_enabled)
3195               {
3196                 /* Yes -- overlay event support is not active, so we
3197                    should have set a breakpoint at the LMA.  Remove it.  
3198                 */
3199                 /* Ignore any failures: if the LMA is in ROM, we will
3200                    have already warned when we failed to insert it.  */
3201                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3202                   target_remove_hw_breakpoint (bl->gdbarch,
3203                                                &bl->overlay_target_info);
3204                 else
3205                   target_remove_breakpoint (bl->gdbarch,
3206                                             &bl->overlay_target_info);
3207               }
3208           /* Did we set a breakpoint at the VMA? 
3209              If so, we will have marked the breakpoint 'inserted'.  */
3210           if (bl->inserted)
3211             {
3212               /* Yes -- remove it.  Previously we did not bother to
3213                  remove the breakpoint if the section had been
3214                  unmapped, but let's not rely on that being safe.  We
3215                  don't know what the overlay manager might do.  */
3216
3217               /* However, we should remove *software* breakpoints only
3218                  if the section is still mapped, or else we overwrite
3219                  wrong code with the saved shadow contents.  */
3220               if (bl->loc_type == bp_loc_hardware_breakpoint
3221                   || section_is_mapped (bl->section))
3222                 val = bl->owner->ops->remove_location (bl);
3223               else
3224                 val = 0;
3225             }
3226           else
3227             {
3228               /* No -- not inserted, so no need to remove.  No error.  */
3229               val = 0;
3230             }
3231         }
3232
3233       /* In some cases, we might not be able to remove a breakpoint
3234          in a shared library that has already been removed, but we
3235          have not yet processed the shlib unload event.  */
3236       if (val && solib_name_from_address (bl->pspace, bl->address))
3237         val = 0;
3238
3239       if (val)
3240         return val;
3241       bl->inserted = (is == mark_inserted);
3242     }
3243   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3244     {
3245       gdb_assert (bl->owner->ops != NULL
3246                   && bl->owner->ops->remove_location != NULL);
3247
3248       bl->inserted = (is == mark_inserted);
3249       bl->owner->ops->remove_location (bl);
3250
3251       /* Failure to remove any of the hardware watchpoints comes here.  */
3252       if ((is == mark_uninserted) && (bl->inserted))
3253         warning (_("Could not remove hardware watchpoint %d."),
3254                  bl->owner->number);
3255     }
3256   else if (bl->owner->type == bp_catchpoint
3257            && breakpoint_enabled (bl->owner)
3258            && !bl->duplicate)
3259     {
3260       gdb_assert (bl->owner->ops != NULL
3261                   && bl->owner->ops->remove_location != NULL);
3262
3263       val = bl->owner->ops->remove_location (bl);
3264       if (val)
3265         return val;
3266
3267       bl->inserted = (is == mark_inserted);
3268     }
3269
3270   return 0;
3271 }
3272
3273 static int
3274 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3275 {
3276   int ret;
3277   struct cleanup *old_chain;
3278
3279   /* BL is never in moribund_locations by our callers.  */
3280   gdb_assert (bl->owner != NULL);
3281
3282   if (bl->owner->enable_state == bp_permanent)
3283     /* Permanent breakpoints cannot be inserted or removed.  */
3284     return 0;
3285
3286   /* The type of none suggests that owner is actually deleted.
3287      This should not ever happen.  */
3288   gdb_assert (bl->owner->type != bp_none);
3289
3290   old_chain = save_current_space_and_thread ();
3291
3292   switch_to_program_space_and_thread (bl->pspace);
3293
3294   ret = remove_breakpoint_1 (bl, is);
3295
3296   do_cleanups (old_chain);
3297   return ret;
3298 }
3299
3300 /* Clear the "inserted" flag in all breakpoints.  */
3301
3302 void
3303 mark_breakpoints_out (void)
3304 {
3305   struct bp_location *bl, **blp_tmp;
3306
3307   ALL_BP_LOCATIONS (bl, blp_tmp)
3308     if (bl->pspace == current_program_space)
3309       bl->inserted = 0;
3310 }
3311
3312 /* Clear the "inserted" flag in all breakpoints and delete any
3313    breakpoints which should go away between runs of the program.
3314
3315    Plus other such housekeeping that has to be done for breakpoints
3316    between runs.
3317
3318    Note: this function gets called at the end of a run (by
3319    generic_mourn_inferior) and when a run begins (by
3320    init_wait_for_inferior).  */
3321
3322
3323
3324 void
3325 breakpoint_init_inferior (enum inf_context context)
3326 {
3327   struct breakpoint *b, *b_tmp;
3328   struct bp_location *bl, **blp_tmp;
3329   int ix;
3330   struct program_space *pspace = current_program_space;
3331
3332   /* If breakpoint locations are shared across processes, then there's
3333      nothing to do.  */
3334   if (gdbarch_has_global_breakpoints (target_gdbarch))
3335     return;
3336
3337   ALL_BP_LOCATIONS (bl, blp_tmp)
3338   {
3339     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3340     if (bl->pspace == pspace
3341         && bl->owner->enable_state != bp_permanent)
3342       bl->inserted = 0;
3343   }
3344
3345   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3346   {
3347     if (b->loc && b->loc->pspace != pspace)
3348       continue;
3349
3350     switch (b->type)
3351       {
3352       case bp_call_dummy:
3353
3354         /* If the call dummy breakpoint is at the entry point it will
3355            cause problems when the inferior is rerun, so we better get
3356            rid of it.  */
3357
3358       case bp_watchpoint_scope:
3359
3360         /* Also get rid of scope breakpoints.  */
3361
3362       case bp_shlib_event:
3363
3364         /* Also remove solib event breakpoints.  Their addresses may
3365            have changed since the last time we ran the program.
3366            Actually we may now be debugging against different target;
3367            and so the solib backend that installed this breakpoint may
3368            not be used in by the target.  E.g.,
3369
3370            (gdb) file prog-linux
3371            (gdb) run               # native linux target
3372            ...
3373            (gdb) kill
3374            (gdb) file prog-win.exe
3375            (gdb) tar rem :9999     # remote Windows gdbserver.
3376         */
3377
3378       case bp_step_resume:
3379
3380         /* Also remove step-resume breakpoints.  */
3381
3382         delete_breakpoint (b);
3383         break;
3384
3385       case bp_watchpoint:
3386       case bp_hardware_watchpoint:
3387       case bp_read_watchpoint:
3388       case bp_access_watchpoint:
3389         {
3390           struct watchpoint *w = (struct watchpoint *) b;
3391
3392           /* Likewise for watchpoints on local expressions.  */
3393           if (w->exp_valid_block != NULL)
3394             delete_breakpoint (b);
3395           else if (context == inf_starting)
3396             {
3397               /* Reset val field to force reread of starting value in
3398                  insert_breakpoints.  */
3399               if (w->val)
3400                 value_free (w->val);
3401               w->val = NULL;
3402               w->val_valid = 0;
3403           }
3404         }
3405         break;
3406       default:
3407         break;
3408       }
3409   }
3410
3411   /* Get rid of the moribund locations.  */
3412   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3413     decref_bp_location (&bl);
3414   VEC_free (bp_location_p, moribund_locations);
3415 }
3416
3417 /* These functions concern about actual breakpoints inserted in the
3418    target --- to e.g. check if we need to do decr_pc adjustment or if
3419    we need to hop over the bkpt --- so we check for address space
3420    match, not program space.  */
3421
3422 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3423    exists at PC.  It returns ordinary_breakpoint_here if it's an
3424    ordinary breakpoint, or permanent_breakpoint_here if it's a
3425    permanent breakpoint.
3426    - When continuing from a location with an ordinary breakpoint, we
3427      actually single step once before calling insert_breakpoints.
3428    - When continuing from a location with a permanent breakpoint, we
3429      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3430      the target, to advance the PC past the breakpoint.  */
3431
3432 enum breakpoint_here
3433 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3434 {
3435   struct bp_location *bl, **blp_tmp;
3436   int any_breakpoint_here = 0;
3437
3438   ALL_BP_LOCATIONS (bl, blp_tmp)
3439     {
3440       if (bl->loc_type != bp_loc_software_breakpoint
3441           && bl->loc_type != bp_loc_hardware_breakpoint)
3442         continue;
3443
3444       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3445       if ((breakpoint_enabled (bl->owner)
3446            || bl->owner->enable_state == bp_permanent)
3447           && breakpoint_location_address_match (bl, aspace, pc))
3448         {
3449           if (overlay_debugging 
3450               && section_is_overlay (bl->section)
3451               && !section_is_mapped (bl->section))
3452             continue;           /* unmapped overlay -- can't be a match */
3453           else if (bl->owner->enable_state == bp_permanent)
3454             return permanent_breakpoint_here;
3455           else
3456             any_breakpoint_here = 1;
3457         }
3458     }
3459
3460   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3461 }
3462
3463 /* Return true if there's a moribund breakpoint at PC.  */
3464
3465 int
3466 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3467 {
3468   struct bp_location *loc;
3469   int ix;
3470
3471   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3472     if (breakpoint_location_address_match (loc, aspace, pc))
3473       return 1;
3474
3475   return 0;
3476 }
3477
3478 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3479    inserted using regular breakpoint_chain / bp_location array
3480    mechanism.  This does not check for single-step breakpoints, which
3481    are inserted and removed using direct target manipulation.  */
3482
3483 int
3484 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3485                                     CORE_ADDR pc)
3486 {
3487   struct bp_location *bl, **blp_tmp;
3488
3489   ALL_BP_LOCATIONS (bl, blp_tmp)
3490     {
3491       if (bl->loc_type != bp_loc_software_breakpoint
3492           && bl->loc_type != bp_loc_hardware_breakpoint)
3493         continue;
3494
3495       if (bl->inserted
3496           && breakpoint_location_address_match (bl, aspace, pc))
3497         {
3498           if (overlay_debugging 
3499               && section_is_overlay (bl->section)
3500               && !section_is_mapped (bl->section))
3501             continue;           /* unmapped overlay -- can't be a match */
3502           else
3503             return 1;
3504         }
3505     }
3506   return 0;
3507 }
3508
3509 /* Returns non-zero iff there's either regular breakpoint
3510    or a single step breakpoint inserted at PC.  */
3511
3512 int
3513 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3514 {
3515   if (regular_breakpoint_inserted_here_p (aspace, pc))
3516     return 1;
3517
3518   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3519     return 1;
3520
3521   return 0;
3522 }
3523
3524 /* This function returns non-zero iff there is a software breakpoint
3525    inserted at PC.  */
3526
3527 int
3528 software_breakpoint_inserted_here_p (struct address_space *aspace,
3529                                      CORE_ADDR pc)
3530 {
3531   struct bp_location *bl, **blp_tmp;
3532
3533   ALL_BP_LOCATIONS (bl, blp_tmp)
3534     {
3535       if (bl->loc_type != bp_loc_software_breakpoint)
3536         continue;
3537
3538       if (bl->inserted
3539           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3540                                        aspace, pc))
3541         {
3542           if (overlay_debugging 
3543               && section_is_overlay (bl->section)
3544               && !section_is_mapped (bl->section))
3545             continue;           /* unmapped overlay -- can't be a match */
3546           else
3547             return 1;
3548         }
3549     }
3550
3551   /* Also check for software single-step breakpoints.  */
3552   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3553     return 1;
3554
3555   return 0;
3556 }
3557
3558 int
3559 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3560                                        CORE_ADDR addr, ULONGEST len)
3561 {
3562   struct breakpoint *bpt;
3563
3564   ALL_BREAKPOINTS (bpt)
3565     {
3566       struct bp_location *loc;
3567
3568       if (bpt->type != bp_hardware_watchpoint
3569           && bpt->type != bp_access_watchpoint)
3570         continue;
3571
3572       if (!breakpoint_enabled (bpt))
3573         continue;
3574
3575       for (loc = bpt->loc; loc; loc = loc->next)
3576         if (loc->pspace->aspace == aspace && loc->inserted)
3577           {
3578             CORE_ADDR l, h;
3579
3580             /* Check for intersection.  */
3581             l = max (loc->address, addr);
3582             h = min (loc->address + loc->length, addr + len);
3583             if (l < h)
3584               return 1;
3585           }
3586     }
3587   return 0;
3588 }
3589
3590 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3591    PC is valid for process/thread PTID.  */
3592
3593 int
3594 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3595                          ptid_t ptid)
3596 {
3597   struct bp_location *bl, **blp_tmp;
3598   /* The thread and task IDs associated to PTID, computed lazily.  */
3599   int thread = -1;
3600   int task = 0;
3601   
3602   ALL_BP_LOCATIONS (bl, blp_tmp)
3603     {
3604       if (bl->loc_type != bp_loc_software_breakpoint
3605           && bl->loc_type != bp_loc_hardware_breakpoint)
3606         continue;
3607
3608       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3609       if (!breakpoint_enabled (bl->owner)
3610           && bl->owner->enable_state != bp_permanent)
3611         continue;
3612
3613       if (!breakpoint_location_address_match (bl, aspace, pc))
3614         continue;
3615
3616       if (bl->owner->thread != -1)
3617         {
3618           /* This is a thread-specific breakpoint.  Check that ptid
3619              matches that thread.  If thread hasn't been computed yet,
3620              it is now time to do so.  */
3621           if (thread == -1)
3622             thread = pid_to_thread_id (ptid);
3623           if (bl->owner->thread != thread)
3624             continue;
3625         }
3626
3627       if (bl->owner->task != 0)
3628         {
3629           /* This is a task-specific breakpoint.  Check that ptid
3630              matches that task.  If task hasn't been computed yet,
3631              it is now time to do so.  */
3632           if (task == 0)
3633             task = ada_get_task_number (ptid);
3634           if (bl->owner->task != task)
3635             continue;
3636         }
3637
3638       if (overlay_debugging 
3639           && section_is_overlay (bl->section)
3640           && !section_is_mapped (bl->section))
3641         continue;           /* unmapped overlay -- can't be a match */
3642
3643       return 1;
3644     }
3645
3646   return 0;
3647 }
3648 \f
3649
3650 /* bpstat stuff.  External routines' interfaces are documented
3651    in breakpoint.h.  */
3652
3653 int
3654 is_catchpoint (struct breakpoint *ep)
3655 {
3656   return (ep->type == bp_catchpoint);
3657 }
3658
3659 /* Frees any storage that is part of a bpstat.  Does not walk the
3660    'next' chain.  */
3661
3662 static void
3663 bpstat_free (bpstat bs)
3664 {
3665   if (bs->old_val != NULL)
3666     value_free (bs->old_val);
3667   decref_counted_command_line (&bs->commands);
3668   decref_bp_location (&bs->bp_location_at);
3669   xfree (bs);
3670 }
3671
3672 /* Clear a bpstat so that it says we are not at any breakpoint.
3673    Also free any storage that is part of a bpstat.  */
3674
3675 void
3676 bpstat_clear (bpstat *bsp)
3677 {
3678   bpstat p;
3679   bpstat q;
3680
3681   if (bsp == 0)
3682     return;
3683   p = *bsp;
3684   while (p != NULL)
3685     {
3686       q = p->next;
3687       bpstat_free (p);
3688       p = q;
3689     }
3690   *bsp = NULL;
3691 }
3692
3693 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3694    is part of the bpstat is copied as well.  */
3695
3696 bpstat
3697 bpstat_copy (bpstat bs)
3698 {
3699   bpstat p = NULL;
3700   bpstat tmp;
3701   bpstat retval = NULL;
3702
3703   if (bs == NULL)
3704     return bs;
3705
3706   for (; bs != NULL; bs = bs->next)
3707     {
3708       tmp = (bpstat) xmalloc (sizeof (*tmp));
3709       memcpy (tmp, bs, sizeof (*tmp));
3710       incref_counted_command_line (tmp->commands);
3711       incref_bp_location (tmp->bp_location_at);
3712       if (bs->old_val != NULL)
3713         {
3714           tmp->old_val = value_copy (bs->old_val);
3715           release_value (tmp->old_val);
3716         }
3717
3718       if (p == NULL)
3719         /* This is the first thing in the chain.  */
3720         retval = tmp;
3721       else
3722         p->next = tmp;
3723       p = tmp;
3724     }
3725   p->next = NULL;
3726   return retval;
3727 }
3728
3729 /* Find the bpstat associated with this breakpoint.  */
3730
3731 bpstat
3732 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3733 {
3734   if (bsp == NULL)
3735     return NULL;
3736
3737   for (; bsp != NULL; bsp = bsp->next)
3738     {
3739       if (bsp->breakpoint_at == breakpoint)
3740         return bsp;
3741     }
3742   return NULL;
3743 }
3744
3745 /* Put in *NUM the breakpoint number of the first breakpoint we are
3746    stopped at.  *BSP upon return is a bpstat which points to the
3747    remaining breakpoints stopped at (but which is not guaranteed to be
3748    good for anything but further calls to bpstat_num).
3749
3750    Return 0 if passed a bpstat which does not indicate any breakpoints.
3751    Return -1 if stopped at a breakpoint that has been deleted since
3752    we set it.
3753    Return 1 otherwise.  */
3754
3755 int
3756 bpstat_num (bpstat *bsp, int *num)
3757 {
3758   struct breakpoint *b;
3759
3760   if ((*bsp) == NULL)
3761     return 0;                   /* No more breakpoint values */
3762
3763   /* We assume we'll never have several bpstats that correspond to a
3764      single breakpoint -- otherwise, this function might return the
3765      same number more than once and this will look ugly.  */
3766   b = (*bsp)->breakpoint_at;
3767   *bsp = (*bsp)->next;
3768   if (b == NULL)
3769     return -1;                  /* breakpoint that's been deleted since */
3770
3771   *num = b->number;             /* We have its number */
3772   return 1;
3773 }
3774
3775 /* See breakpoint.h.  */
3776
3777 void
3778 bpstat_clear_actions (void)
3779 {
3780   struct thread_info *tp;
3781   bpstat bs;
3782
3783   if (ptid_equal (inferior_ptid, null_ptid))
3784     return;
3785
3786   tp = find_thread_ptid (inferior_ptid);
3787   if (tp == NULL)
3788     return;
3789
3790   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3791     {
3792       decref_counted_command_line (&bs->commands);
3793
3794       if (bs->old_val != NULL)
3795         {
3796           value_free (bs->old_val);
3797           bs->old_val = NULL;
3798         }
3799     }
3800 }
3801
3802 /* Called when a command is about to proceed the inferior.  */
3803
3804 static void
3805 breakpoint_about_to_proceed (void)
3806 {
3807   if (!ptid_equal (inferior_ptid, null_ptid))
3808     {
3809       struct thread_info *tp = inferior_thread ();
3810
3811       /* Allow inferior function calls in breakpoint commands to not
3812          interrupt the command list.  When the call finishes
3813          successfully, the inferior will be standing at the same
3814          breakpoint as if nothing happened.  */
3815       if (tp->control.in_infcall)
3816         return;
3817     }
3818
3819   breakpoint_proceeded = 1;
3820 }
3821
3822 /* Stub for cleaning up our state if we error-out of a breakpoint
3823    command.  */
3824 static void
3825 cleanup_executing_breakpoints (void *ignore)
3826 {
3827   executing_breakpoint_commands = 0;
3828 }
3829
3830 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3831    or its equivalent.  */
3832
3833 static int
3834 command_line_is_silent (struct command_line *cmd)
3835 {
3836   return cmd && (strcmp ("silent", cmd->line) == 0
3837                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3838 }
3839
3840 /* Execute all the commands associated with all the breakpoints at
3841    this location.  Any of these commands could cause the process to
3842    proceed beyond this point, etc.  We look out for such changes by
3843    checking the global "breakpoint_proceeded" after each command.
3844
3845    Returns true if a breakpoint command resumed the inferior.  In that
3846    case, it is the caller's responsibility to recall it again with the
3847    bpstat of the current thread.  */
3848
3849 static int
3850 bpstat_do_actions_1 (bpstat *bsp)
3851 {
3852   bpstat bs;
3853   struct cleanup *old_chain;
3854   int again = 0;
3855
3856   /* Avoid endless recursion if a `source' command is contained
3857      in bs->commands.  */
3858   if (executing_breakpoint_commands)
3859     return 0;
3860
3861   executing_breakpoint_commands = 1;
3862   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
3863
3864   prevent_dont_repeat ();
3865
3866   /* This pointer will iterate over the list of bpstat's.  */
3867   bs = *bsp;
3868
3869   breakpoint_proceeded = 0;
3870   for (; bs != NULL; bs = bs->next)
3871     {
3872       struct counted_command_line *ccmd;
3873       struct command_line *cmd;
3874       struct cleanup *this_cmd_tree_chain;
3875
3876       /* Take ownership of the BSP's command tree, if it has one.
3877
3878          The command tree could legitimately contain commands like
3879          'step' and 'next', which call clear_proceed_status, which
3880          frees stop_bpstat's command tree.  To make sure this doesn't
3881          free the tree we're executing out from under us, we need to
3882          take ownership of the tree ourselves.  Since a given bpstat's
3883          commands are only executed once, we don't need to copy it; we
3884          can clear the pointer in the bpstat, and make sure we free
3885          the tree when we're done.  */
3886       ccmd = bs->commands;
3887       bs->commands = NULL;
3888       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
3889       cmd = ccmd ? ccmd->commands : NULL;
3890       if (command_line_is_silent (cmd))
3891         {
3892           /* The action has been already done by bpstat_stop_status.  */
3893           cmd = cmd->next;
3894         }
3895
3896       while (cmd != NULL)
3897         {
3898           execute_control_command (cmd);
3899
3900           if (breakpoint_proceeded)
3901             break;
3902           else
3903             cmd = cmd->next;
3904         }
3905
3906       /* We can free this command tree now.  */
3907       do_cleanups (this_cmd_tree_chain);
3908
3909       if (breakpoint_proceeded)
3910         {
3911           if (target_can_async_p ())
3912             /* If we are in async mode, then the target might be still
3913                running, not stopped at any breakpoint, so nothing for
3914                us to do here -- just return to the event loop.  */
3915             ;
3916           else
3917             /* In sync mode, when execute_control_command returns
3918                we're already standing on the next breakpoint.
3919                Breakpoint commands for that stop were not run, since
3920                execute_command does not run breakpoint commands --
3921                only command_line_handler does, but that one is not
3922                involved in execution of breakpoint commands.  So, we
3923                can now execute breakpoint commands.  It should be
3924                noted that making execute_command do bpstat actions is
3925                not an option -- in this case we'll have recursive
3926                invocation of bpstat for each breakpoint with a
3927                command, and can easily blow up GDB stack.  Instead, we
3928                return true, which will trigger the caller to recall us
3929                with the new stop_bpstat.  */
3930             again = 1;
3931           break;
3932         }
3933     }
3934   do_cleanups (old_chain);
3935   return again;
3936 }
3937
3938 void
3939 bpstat_do_actions (void)
3940 {
3941   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
3942
3943   /* Do any commands attached to breakpoint we are stopped at.  */
3944   while (!ptid_equal (inferior_ptid, null_ptid)
3945          && target_has_execution
3946          && !is_exited (inferior_ptid)
3947          && !is_executing (inferior_ptid))
3948     /* Since in sync mode, bpstat_do_actions may resume the inferior,
3949        and only return when it is stopped at the next breakpoint, we
3950        keep doing breakpoint actions until it returns false to
3951        indicate the inferior was not resumed.  */
3952     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
3953       break;
3954
3955   discard_cleanups (cleanup_if_error);
3956 }
3957
3958 /* Print out the (old or new) value associated with a watchpoint.  */
3959
3960 static void
3961 watchpoint_value_print (struct value *val, struct ui_file *stream)
3962 {
3963   if (val == NULL)
3964     fprintf_unfiltered (stream, _("<unreadable>"));
3965   else
3966     {
3967       struct value_print_options opts;
3968       get_user_print_options (&opts);
3969       value_print (val, stream, &opts);
3970     }
3971 }
3972
3973 /* Generic routine for printing messages indicating why we
3974    stopped.  The behavior of this function depends on the value
3975    'print_it' in the bpstat structure.  Under some circumstances we
3976    may decide not to print anything here and delegate the task to
3977    normal_stop().  */
3978
3979 static enum print_stop_action
3980 print_bp_stop_message (bpstat bs)
3981 {
3982   switch (bs->print_it)
3983     {
3984     case print_it_noop:
3985       /* Nothing should be printed for this bpstat entry.  */
3986       return PRINT_UNKNOWN;
3987       break;
3988
3989     case print_it_done:
3990       /* We still want to print the frame, but we already printed the
3991          relevant messages.  */
3992       return PRINT_SRC_AND_LOC;
3993       break;
3994
3995     case print_it_normal:
3996       {
3997         struct breakpoint *b = bs->breakpoint_at;
3998
3999         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4000            which has since been deleted.  */
4001         if (b == NULL)
4002           return PRINT_UNKNOWN;
4003
4004         /* Normal case.  Call the breakpoint's print_it method.  */
4005         return b->ops->print_it (bs);
4006       }
4007       break;
4008
4009     default:
4010       internal_error (__FILE__, __LINE__,
4011                       _("print_bp_stop_message: unrecognized enum value"));
4012       break;
4013     }
4014 }
4015
4016 /* A helper function that prints a shared library stopped event.  */
4017
4018 static void
4019 print_solib_event (int is_catchpoint)
4020 {
4021   int any_deleted
4022     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4023   int any_added
4024     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4025
4026   if (!is_catchpoint)
4027     {
4028       if (any_added || any_deleted)
4029         ui_out_text (current_uiout,
4030                      _("Stopped due to shared library event:\n"));
4031       else
4032         ui_out_text (current_uiout,
4033                      _("Stopped due to shared library event (no "
4034                        "libraries added or removed)\n"));
4035     }
4036
4037   if (ui_out_is_mi_like_p (current_uiout))
4038     ui_out_field_string (current_uiout, "reason",
4039                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4040
4041   if (any_deleted)
4042     {
4043       struct cleanup *cleanup;
4044       char *name;
4045       int ix;
4046
4047       ui_out_text (current_uiout, _("  Inferior unloaded "));
4048       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4049                                                     "removed");
4050       for (ix = 0;
4051            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4052                         ix, name);
4053            ++ix)
4054         {
4055           if (ix > 0)
4056             ui_out_text (current_uiout, "    ");
4057           ui_out_field_string (current_uiout, "library", name);
4058           ui_out_text (current_uiout, "\n");
4059         }
4060
4061       do_cleanups (cleanup);
4062     }
4063
4064   if (any_added)
4065     {
4066       struct so_list *iter;
4067       int ix;
4068       struct cleanup *cleanup;
4069
4070       ui_out_text (current_uiout, _("  Inferior loaded "));
4071       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4072                                                     "added");
4073       for (ix = 0;
4074            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4075                         ix, iter);
4076            ++ix)
4077         {
4078           if (ix > 0)
4079             ui_out_text (current_uiout, "    ");
4080           ui_out_field_string (current_uiout, "library", iter->so_name);
4081           ui_out_text (current_uiout, "\n");
4082         }
4083
4084       do_cleanups (cleanup);
4085     }
4086 }
4087
4088 /* Print a message indicating what happened.  This is called from
4089    normal_stop().  The input to this routine is the head of the bpstat
4090    list - a list of the eventpoints that caused this stop.  KIND is
4091    the target_waitkind for the stopping event.  This
4092    routine calls the generic print routine for printing a message
4093    about reasons for stopping.  This will print (for example) the
4094    "Breakpoint n," part of the output.  The return value of this
4095    routine is one of:
4096
4097    PRINT_UNKNOWN: Means we printed nothing.
4098    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4099    code to print the location.  An example is 
4100    "Breakpoint 1, " which should be followed by
4101    the location.
4102    PRINT_SRC_ONLY: Means we printed something, but there is no need
4103    to also print the location part of the message.
4104    An example is the catch/throw messages, which
4105    don't require a location appended to the end.
4106    PRINT_NOTHING: We have done some printing and we don't need any 
4107    further info to be printed.  */
4108
4109 enum print_stop_action
4110 bpstat_print (bpstat bs, int kind)
4111 {
4112   int val;
4113
4114   /* Maybe another breakpoint in the chain caused us to stop.
4115      (Currently all watchpoints go on the bpstat whether hit or not.
4116      That probably could (should) be changed, provided care is taken
4117      with respect to bpstat_explains_signal).  */
4118   for (; bs; bs = bs->next)
4119     {
4120       val = print_bp_stop_message (bs);
4121       if (val == PRINT_SRC_ONLY 
4122           || val == PRINT_SRC_AND_LOC 
4123           || val == PRINT_NOTHING)
4124         return val;
4125     }
4126
4127   /* If we had hit a shared library event breakpoint,
4128      print_bp_stop_message would print out this message.  If we hit an
4129      OS-level shared library event, do the same thing.  */
4130   if (kind == TARGET_WAITKIND_LOADED)
4131     {
4132       print_solib_event (0);
4133       return PRINT_NOTHING;
4134     }
4135
4136   /* We reached the end of the chain, or we got a null BS to start
4137      with and nothing was printed.  */
4138   return PRINT_UNKNOWN;
4139 }
4140
4141 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4142    used inside a catch_errors to evaluate the breakpoint condition.
4143    The argument is a "struct expression *" that has been cast to a
4144    "char *" to make it pass through catch_errors.  */
4145
4146 static int
4147 breakpoint_cond_eval (void *exp)
4148 {
4149   struct value *mark = value_mark ();
4150   int i = !value_true (evaluate_expression ((struct expression *) exp));
4151
4152   value_free_to_mark (mark);
4153   return i;
4154 }
4155
4156 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4157
4158 static bpstat
4159 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4160 {
4161   bpstat bs;
4162
4163   bs = (bpstat) xmalloc (sizeof (*bs));
4164   bs->next = NULL;
4165   **bs_link_pointer = bs;
4166   *bs_link_pointer = &bs->next;
4167   bs->breakpoint_at = bl->owner;
4168   bs->bp_location_at = bl;
4169   incref_bp_location (bl);
4170   /* If the condition is false, etc., don't do the commands.  */
4171   bs->commands = NULL;
4172   bs->old_val = NULL;
4173   bs->print_it = print_it_normal;
4174   return bs;
4175 }
4176 \f
4177 /* The target has stopped with waitstatus WS.  Check if any hardware
4178    watchpoints have triggered, according to the target.  */
4179
4180 int
4181 watchpoints_triggered (struct target_waitstatus *ws)
4182 {
4183   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4184   CORE_ADDR addr;
4185   struct breakpoint *b;
4186
4187   if (!stopped_by_watchpoint)
4188     {
4189       /* We were not stopped by a watchpoint.  Mark all watchpoints
4190          as not triggered.  */
4191       ALL_BREAKPOINTS (b)
4192         if (is_hardware_watchpoint (b))
4193           {
4194             struct watchpoint *w = (struct watchpoint *) b;
4195
4196             w->watchpoint_triggered = watch_triggered_no;
4197           }
4198
4199       return 0;
4200     }
4201
4202   if (!target_stopped_data_address (&current_target, &addr))
4203     {
4204       /* We were stopped by a watchpoint, but we don't know where.
4205          Mark all watchpoints as unknown.  */
4206       ALL_BREAKPOINTS (b)
4207         if (is_hardware_watchpoint (b))
4208           {
4209             struct watchpoint *w = (struct watchpoint *) b;
4210
4211             w->watchpoint_triggered = watch_triggered_unknown;
4212           }
4213
4214       return stopped_by_watchpoint;
4215     }
4216
4217   /* The target could report the data address.  Mark watchpoints
4218      affected by this data address as triggered, and all others as not
4219      triggered.  */
4220
4221   ALL_BREAKPOINTS (b)
4222     if (is_hardware_watchpoint (b))
4223       {
4224         struct watchpoint *w = (struct watchpoint *) b;
4225         struct bp_location *loc;
4226
4227         w->watchpoint_triggered = watch_triggered_no;
4228         for (loc = b->loc; loc; loc = loc->next)
4229           {
4230             if (is_masked_watchpoint (b))
4231               {
4232                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4233                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4234
4235                 if (newaddr == start)
4236                   {
4237                     w->watchpoint_triggered = watch_triggered_yes;
4238                     break;
4239                   }
4240               }
4241             /* Exact match not required.  Within range is sufficient.  */
4242             else if (target_watchpoint_addr_within_range (&current_target,
4243                                                          addr, loc->address,
4244                                                          loc->length))
4245               {
4246                 w->watchpoint_triggered = watch_triggered_yes;
4247                 break;
4248               }
4249           }
4250       }
4251
4252   return 1;
4253 }
4254
4255 /* Possible return values for watchpoint_check (this can't be an enum
4256    because of check_errors).  */
4257 /* The watchpoint has been deleted.  */
4258 #define WP_DELETED 1
4259 /* The value has changed.  */
4260 #define WP_VALUE_CHANGED 2
4261 /* The value has not changed.  */
4262 #define WP_VALUE_NOT_CHANGED 3
4263 /* Ignore this watchpoint, no matter if the value changed or not.  */
4264 #define WP_IGNORE 4
4265
4266 #define BP_TEMPFLAG 1
4267 #define BP_HARDWAREFLAG 2
4268
4269 /* Evaluate watchpoint condition expression and check if its value
4270    changed.
4271
4272    P should be a pointer to struct bpstat, but is defined as a void *
4273    in order for this function to be usable with catch_errors.  */
4274
4275 static int
4276 watchpoint_check (void *p)
4277 {
4278   bpstat bs = (bpstat) p;
4279   struct watchpoint *b;
4280   struct frame_info *fr;
4281   int within_current_scope;
4282
4283   /* BS is built from an existing struct breakpoint.  */
4284   gdb_assert (bs->breakpoint_at != NULL);
4285   b = (struct watchpoint *) bs->breakpoint_at;
4286
4287   /* If this is a local watchpoint, we only want to check if the
4288      watchpoint frame is in scope if the current thread is the thread
4289      that was used to create the watchpoint.  */
4290   if (!watchpoint_in_thread_scope (b))
4291     return WP_IGNORE;
4292
4293   if (b->exp_valid_block == NULL)
4294     within_current_scope = 1;
4295   else
4296     {
4297       struct frame_info *frame = get_current_frame ();
4298       struct gdbarch *frame_arch = get_frame_arch (frame);
4299       CORE_ADDR frame_pc = get_frame_pc (frame);
4300
4301       /* in_function_epilogue_p() returns a non-zero value if we're
4302          still in the function but the stack frame has already been
4303          invalidated.  Since we can't rely on the values of local
4304          variables after the stack has been destroyed, we are treating
4305          the watchpoint in that state as `not changed' without further
4306          checking.  Don't mark watchpoints as changed if the current
4307          frame is in an epilogue - even if they are in some other
4308          frame, our view of the stack is likely to be wrong and
4309          frame_find_by_id could error out.  */
4310       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4311         return WP_IGNORE;
4312
4313       fr = frame_find_by_id (b->watchpoint_frame);
4314       within_current_scope = (fr != NULL);
4315
4316       /* If we've gotten confused in the unwinder, we might have
4317          returned a frame that can't describe this variable.  */
4318       if (within_current_scope)
4319         {
4320           struct symbol *function;
4321
4322           function = get_frame_function (fr);
4323           if (function == NULL
4324               || !contained_in (b->exp_valid_block,
4325                                 SYMBOL_BLOCK_VALUE (function)))
4326             within_current_scope = 0;
4327         }
4328
4329       if (within_current_scope)
4330         /* If we end up stopping, the current frame will get selected
4331            in normal_stop.  So this call to select_frame won't affect
4332            the user.  */
4333         select_frame (fr);
4334     }
4335
4336   if (within_current_scope)
4337     {
4338       /* We use value_{,free_to_}mark because it could be a *long*
4339          time before we return to the command level and call
4340          free_all_values.  We can't call free_all_values because we
4341          might be in the middle of evaluating a function call.  */
4342
4343       int pc = 0;
4344       struct value *mark;
4345       struct value *new_val;
4346
4347       if (is_masked_watchpoint (&b->base))
4348         /* Since we don't know the exact trigger address (from
4349            stopped_data_address), just tell the user we've triggered
4350            a mask watchpoint.  */
4351         return WP_VALUE_CHANGED;
4352
4353       mark = value_mark ();
4354       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4355
4356       /* We use value_equal_contents instead of value_equal because
4357          the latter coerces an array to a pointer, thus comparing just
4358          the address of the array instead of its contents.  This is
4359          not what we want.  */
4360       if ((b->val != NULL) != (new_val != NULL)
4361           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4362         {
4363           if (new_val != NULL)
4364             {
4365               release_value (new_val);
4366               value_free_to_mark (mark);
4367             }
4368           bs->old_val = b->val;
4369           b->val = new_val;
4370           b->val_valid = 1;
4371           return WP_VALUE_CHANGED;
4372         }
4373       else
4374         {
4375           /* Nothing changed.  */
4376           value_free_to_mark (mark);
4377           return WP_VALUE_NOT_CHANGED;
4378         }
4379     }
4380   else
4381     {
4382       struct ui_out *uiout = current_uiout;
4383
4384       /* This seems like the only logical thing to do because
4385          if we temporarily ignored the watchpoint, then when
4386          we reenter the block in which it is valid it contains
4387          garbage (in the case of a function, it may have two
4388          garbage values, one before and one after the prologue).
4389          So we can't even detect the first assignment to it and
4390          watch after that (since the garbage may or may not equal
4391          the first value assigned).  */
4392       /* We print all the stop information in
4393          breakpoint_ops->print_it, but in this case, by the time we
4394          call breakpoint_ops->print_it this bp will be deleted
4395          already.  So we have no choice but print the information
4396          here.  */
4397       if (ui_out_is_mi_like_p (uiout))
4398         ui_out_field_string
4399           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4400       ui_out_text (uiout, "\nWatchpoint ");
4401       ui_out_field_int (uiout, "wpnum", b->base.number);
4402       ui_out_text (uiout,
4403                    " deleted because the program has left the block in\n\
4404 which its expression is valid.\n");     
4405
4406       /* Make sure the watchpoint's commands aren't executed.  */
4407       decref_counted_command_line (&b->base.commands);
4408       watchpoint_del_at_next_stop (b);
4409
4410       return WP_DELETED;
4411     }
4412 }
4413
4414 /* Return true if it looks like target has stopped due to hitting
4415    breakpoint location BL.  This function does not check if we should
4416    stop, only if BL explains the stop.  */
4417
4418 static int
4419 bpstat_check_location (const struct bp_location *bl,
4420                        struct address_space *aspace, CORE_ADDR bp_addr,
4421                        const struct target_waitstatus *ws)
4422 {
4423   struct breakpoint *b = bl->owner;
4424
4425   /* BL is from an existing breakpoint.  */
4426   gdb_assert (b != NULL);
4427
4428   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4429 }
4430
4431 /* Determine if the watched values have actually changed, and we
4432    should stop.  If not, set BS->stop to 0.  */
4433
4434 static void
4435 bpstat_check_watchpoint (bpstat bs)
4436 {
4437   const struct bp_location *bl;
4438   struct watchpoint *b;
4439
4440   /* BS is built for existing struct breakpoint.  */
4441   bl = bs->bp_location_at;
4442   gdb_assert (bl != NULL);
4443   b = (struct watchpoint *) bs->breakpoint_at;
4444   gdb_assert (b != NULL);
4445
4446     {
4447       int must_check_value = 0;
4448       
4449       if (b->base.type == bp_watchpoint)
4450         /* For a software watchpoint, we must always check the
4451            watched value.  */
4452         must_check_value = 1;
4453       else if (b->watchpoint_triggered == watch_triggered_yes)
4454         /* We have a hardware watchpoint (read, write, or access)
4455            and the target earlier reported an address watched by
4456            this watchpoint.  */
4457         must_check_value = 1;
4458       else if (b->watchpoint_triggered == watch_triggered_unknown
4459                && b->base.type == bp_hardware_watchpoint)
4460         /* We were stopped by a hardware watchpoint, but the target could
4461            not report the data address.  We must check the watchpoint's
4462            value.  Access and read watchpoints are out of luck; without
4463            a data address, we can't figure it out.  */
4464         must_check_value = 1;
4465
4466       if (must_check_value)
4467         {
4468           char *message
4469             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4470                           b->base.number);
4471           struct cleanup *cleanups = make_cleanup (xfree, message);
4472           int e = catch_errors (watchpoint_check, bs, message,
4473                                 RETURN_MASK_ALL);
4474           do_cleanups (cleanups);
4475           switch (e)
4476             {
4477             case WP_DELETED:
4478               /* We've already printed what needs to be printed.  */
4479               bs->print_it = print_it_done;
4480               /* Stop.  */
4481               break;
4482             case WP_IGNORE:
4483               bs->print_it = print_it_noop;
4484               bs->stop = 0;
4485               break;
4486             case WP_VALUE_CHANGED:
4487               if (b->base.type == bp_read_watchpoint)
4488                 {
4489                   /* There are two cases to consider here:
4490
4491                      1. We're watching the triggered memory for reads.
4492                      In that case, trust the target, and always report
4493                      the watchpoint hit to the user.  Even though
4494                      reads don't cause value changes, the value may
4495                      have changed since the last time it was read, and
4496                      since we're not trapping writes, we will not see
4497                      those, and as such we should ignore our notion of
4498                      old value.
4499
4500                      2. We're watching the triggered memory for both
4501                      reads and writes.  There are two ways this may
4502                      happen:
4503
4504                      2.1. This is a target that can't break on data
4505                      reads only, but can break on accesses (reads or
4506                      writes), such as e.g., x86.  We detect this case
4507                      at the time we try to insert read watchpoints.
4508
4509                      2.2. Otherwise, the target supports read
4510                      watchpoints, but, the user set an access or write
4511                      watchpoint watching the same memory as this read
4512                      watchpoint.
4513
4514                      If we're watching memory writes as well as reads,
4515                      ignore watchpoint hits when we find that the
4516                      value hasn't changed, as reads don't cause
4517                      changes.  This still gives false positives when
4518                      the program writes the same value to memory as
4519                      what there was already in memory (we will confuse
4520                      it for a read), but it's much better than
4521                      nothing.  */
4522
4523                   int other_write_watchpoint = 0;
4524
4525                   if (bl->watchpoint_type == hw_read)
4526                     {
4527                       struct breakpoint *other_b;
4528
4529                       ALL_BREAKPOINTS (other_b)
4530                         if (other_b->type == bp_hardware_watchpoint
4531                             || other_b->type == bp_access_watchpoint)
4532                           {
4533                             struct watchpoint *other_w =
4534                               (struct watchpoint *) other_b;
4535
4536                             if (other_w->watchpoint_triggered
4537                                 == watch_triggered_yes)
4538                               {
4539                                 other_write_watchpoint = 1;
4540                                 break;
4541                               }
4542                           }
4543                     }
4544
4545                   if (other_write_watchpoint
4546                       || bl->watchpoint_type == hw_access)
4547                     {
4548                       /* We're watching the same memory for writes,
4549                          and the value changed since the last time we
4550                          updated it, so this trap must be for a write.
4551                          Ignore it.  */
4552                       bs->print_it = print_it_noop;
4553                       bs->stop = 0;
4554                     }
4555                 }
4556               break;
4557             case WP_VALUE_NOT_CHANGED:
4558               if (b->base.type == bp_hardware_watchpoint
4559                   || b->base.type == bp_watchpoint)
4560                 {
4561                   /* Don't stop: write watchpoints shouldn't fire if
4562                      the value hasn't changed.  */
4563                   bs->print_it = print_it_noop;
4564                   bs->stop = 0;
4565                 }
4566               /* Stop.  */
4567               break;
4568             default:
4569               /* Can't happen.  */
4570             case 0:
4571               /* Error from catch_errors.  */
4572               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
4573               watchpoint_del_at_next_stop (b);
4574               /* We've already printed what needs to be printed.  */
4575               bs->print_it = print_it_done;
4576               break;
4577             }
4578         }
4579       else      /* must_check_value == 0 */
4580         {
4581           /* This is a case where some watchpoint(s) triggered, but
4582              not at the address of this watchpoint, or else no
4583              watchpoint triggered after all.  So don't print
4584              anything for this watchpoint.  */
4585           bs->print_it = print_it_noop;
4586           bs->stop = 0;
4587         }
4588     }
4589 }
4590
4591
4592 /* Check conditions (condition proper, frame, thread and ignore count)
4593    of breakpoint referred to by BS.  If we should not stop for this
4594    breakpoint, set BS->stop to 0.  */
4595
4596 static void
4597 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4598 {
4599   int thread_id = pid_to_thread_id (ptid);
4600   const struct bp_location *bl;
4601   struct breakpoint *b;
4602
4603   /* BS is built for existing struct breakpoint.  */
4604   bl = bs->bp_location_at;
4605   gdb_assert (bl != NULL);
4606   b = bs->breakpoint_at;
4607   gdb_assert (b != NULL);
4608
4609   /* Even if the target evaluated the condition on its end and notified GDB, we
4610      need to do so again since GDB does not know if we stopped due to a
4611      breakpoint or a single step breakpoint.  */
4612
4613   if (frame_id_p (b->frame_id)
4614       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4615     bs->stop = 0;
4616   else if (bs->stop)
4617     {
4618       int value_is_zero = 0;
4619       struct expression *cond;
4620
4621       /* Evaluate Python breakpoints that have a "stop"
4622          method implemented.  */
4623       if (b->py_bp_object)
4624         bs->stop = gdbpy_should_stop (b->py_bp_object);
4625
4626       if (is_watchpoint (b))
4627         {
4628           struct watchpoint *w = (struct watchpoint *) b;
4629
4630           cond = w->cond_exp;
4631         }
4632       else
4633         cond = bl->cond;
4634
4635       if (cond && b->disposition != disp_del_at_next_stop)
4636         {
4637           int within_current_scope = 1;
4638           struct watchpoint * w;
4639
4640           /* We use value_mark and value_free_to_mark because it could
4641              be a long time before we return to the command level and
4642              call free_all_values.  We can't call free_all_values
4643              because we might be in the middle of evaluating a
4644              function call.  */
4645           struct value *mark = value_mark ();
4646
4647           if (is_watchpoint (b))
4648             w = (struct watchpoint *) b;
4649           else
4650             w = NULL;
4651
4652           /* Need to select the frame, with all that implies so that
4653              the conditions will have the right context.  Because we
4654              use the frame, we will not see an inlined function's
4655              variables when we arrive at a breakpoint at the start
4656              of the inlined function; the current frame will be the
4657              call site.  */
4658           if (w == NULL || w->cond_exp_valid_block == NULL)
4659             select_frame (get_current_frame ());
4660           else
4661             {
4662               struct frame_info *frame;
4663
4664               /* For local watchpoint expressions, which particular
4665                  instance of a local is being watched matters, so we
4666                  keep track of the frame to evaluate the expression
4667                  in.  To evaluate the condition however, it doesn't
4668                  really matter which instantiation of the function
4669                  where the condition makes sense triggers the
4670                  watchpoint.  This allows an expression like "watch
4671                  global if q > 10" set in `func', catch writes to
4672                  global on all threads that call `func', or catch
4673                  writes on all recursive calls of `func' by a single
4674                  thread.  We simply always evaluate the condition in
4675                  the innermost frame that's executing where it makes
4676                  sense to evaluate the condition.  It seems
4677                  intuitive.  */
4678               frame = block_innermost_frame (w->cond_exp_valid_block);
4679               if (frame != NULL)
4680                 select_frame (frame);
4681               else
4682                 within_current_scope = 0;
4683             }
4684           if (within_current_scope)
4685             value_is_zero
4686               = catch_errors (breakpoint_cond_eval, cond,
4687                               "Error in testing breakpoint condition:\n",
4688                               RETURN_MASK_ALL);
4689           else
4690             {
4691               warning (_("Watchpoint condition cannot be tested "
4692                          "in the current scope"));
4693               /* If we failed to set the right context for this
4694                  watchpoint, unconditionally report it.  */
4695               value_is_zero = 0;
4696             }
4697           /* FIXME-someday, should give breakpoint #.  */
4698           value_free_to_mark (mark);
4699         }
4700
4701       if (cond && value_is_zero)
4702         {
4703           bs->stop = 0;
4704         }
4705       else if (b->thread != -1 && b->thread != thread_id)
4706         {
4707           bs->stop = 0;
4708         }
4709       else if (b->ignore_count > 0)
4710         {
4711           b->ignore_count--;
4712           annotate_ignore_count_change ();
4713           bs->stop = 0;
4714           /* Increase the hit count even though we don't stop.  */
4715           ++(b->hit_count);
4716           observer_notify_breakpoint_modified (b);
4717         }       
4718     }
4719 }
4720
4721
4722 /* Get a bpstat associated with having just stopped at address
4723    BP_ADDR in thread PTID.
4724
4725    Determine whether we stopped at a breakpoint, etc, or whether we
4726    don't understand this stop.  Result is a chain of bpstat's such
4727    that:
4728
4729    if we don't understand the stop, the result is a null pointer.
4730
4731    if we understand why we stopped, the result is not null.
4732
4733    Each element of the chain refers to a particular breakpoint or
4734    watchpoint at which we have stopped.  (We may have stopped for
4735    several reasons concurrently.)
4736
4737    Each element of the chain has valid next, breakpoint_at,
4738    commands, FIXME??? fields.  */
4739
4740 bpstat
4741 bpstat_stop_status (struct address_space *aspace,
4742                     CORE_ADDR bp_addr, ptid_t ptid,
4743                     const struct target_waitstatus *ws)
4744 {
4745   struct breakpoint *b = NULL;
4746   struct bp_location *bl;
4747   struct bp_location *loc;
4748   /* First item of allocated bpstat's.  */
4749   bpstat bs_head = NULL, *bs_link = &bs_head;
4750   /* Pointer to the last thing in the chain currently.  */
4751   bpstat bs;
4752   int ix;
4753   int need_remove_insert;
4754   int removed_any;
4755
4756   /* First, build the bpstat chain with locations that explain a
4757      target stop, while being careful to not set the target running,
4758      as that may invalidate locations (in particular watchpoint
4759      locations are recreated).  Resuming will happen here with
4760      breakpoint conditions or watchpoint expressions that include
4761      inferior function calls.  */
4762
4763   ALL_BREAKPOINTS (b)
4764     {
4765       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4766         continue;
4767
4768       for (bl = b->loc; bl != NULL; bl = bl->next)
4769         {
4770           /* For hardware watchpoints, we look only at the first
4771              location.  The watchpoint_check function will work on the
4772              entire expression, not the individual locations.  For
4773              read watchpoints, the watchpoints_triggered function has
4774              checked all locations already.  */
4775           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4776             break;
4777
4778           if (bl->shlib_disabled)
4779             continue;
4780
4781           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
4782             continue;
4783
4784           /* Come here if it's a watchpoint, or if the break address
4785              matches.  */
4786
4787           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4788                                                    explain stop.  */
4789
4790           /* Assume we stop.  Should we find a watchpoint that is not
4791              actually triggered, or if the condition of the breakpoint
4792              evaluates as false, we'll reset 'stop' to 0.  */
4793           bs->stop = 1;
4794           bs->print = 1;
4795
4796           /* If this is a scope breakpoint, mark the associated
4797              watchpoint as triggered so that we will handle the
4798              out-of-scope event.  We'll get to the watchpoint next
4799              iteration.  */
4800           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4801             {
4802               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4803
4804               w->watchpoint_triggered = watch_triggered_yes;
4805             }
4806         }
4807     }
4808
4809   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4810     {
4811       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4812         {
4813           bs = bpstat_alloc (loc, &bs_link);
4814           /* For hits of moribund locations, we should just proceed.  */
4815           bs->stop = 0;
4816           bs->print = 0;
4817           bs->print_it = print_it_noop;
4818         }
4819     }
4820
4821   /* A bit of special processing for shlib breakpoints.  We need to
4822      process solib loading here, so that the lists of loaded and
4823      unloaded libraries are correct before we handle "catch load" and
4824      "catch unload".  */
4825   for (bs = bs_head; bs != NULL; bs = bs->next)
4826     {
4827       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
4828         {
4829           handle_solib_event ();
4830           break;
4831         }
4832     }
4833
4834   /* Now go through the locations that caused the target to stop, and
4835      check whether we're interested in reporting this stop to higher
4836      layers, or whether we should resume the target transparently.  */
4837
4838   removed_any = 0;
4839
4840   for (bs = bs_head; bs != NULL; bs = bs->next)
4841     {
4842       if (!bs->stop)
4843         continue;
4844
4845       b = bs->breakpoint_at;
4846       b->ops->check_status (bs);
4847       if (bs->stop)
4848         {
4849           bpstat_check_breakpoint_conditions (bs, ptid);
4850
4851           if (bs->stop)
4852             {
4853               ++(b->hit_count);
4854               observer_notify_breakpoint_modified (b);
4855
4856               /* We will stop here.  */
4857               if (b->disposition == disp_disable)
4858                 {
4859                   --(b->enable_count);
4860                   if (b->enable_count <= 0
4861                       && b->enable_state != bp_permanent)
4862                     b->enable_state = bp_disabled;
4863                   removed_any = 1;
4864                 }
4865               if (b->silent)
4866                 bs->print = 0;
4867               bs->commands = b->commands;
4868               incref_counted_command_line (bs->commands);
4869               if (command_line_is_silent (bs->commands
4870                                           ? bs->commands->commands : NULL))
4871                 bs->print = 0;
4872             }
4873
4874         }
4875
4876       /* Print nothing for this entry if we don't stop or don't
4877          print.  */
4878       if (!bs->stop || !bs->print)
4879         bs->print_it = print_it_noop;
4880     }
4881
4882   /* If we aren't stopping, the value of some hardware watchpoint may
4883      not have changed, but the intermediate memory locations we are
4884      watching may have.  Don't bother if we're stopping; this will get
4885      done later.  */
4886   need_remove_insert = 0;
4887   if (! bpstat_causes_stop (bs_head))
4888     for (bs = bs_head; bs != NULL; bs = bs->next)
4889       if (!bs->stop
4890           && bs->breakpoint_at
4891           && is_hardware_watchpoint (bs->breakpoint_at))
4892         {
4893           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
4894
4895           update_watchpoint (w, 0 /* don't reparse.  */);
4896           need_remove_insert = 1;
4897         }
4898
4899   if (need_remove_insert)
4900     update_global_location_list (1);
4901   else if (removed_any)
4902     update_global_location_list (0);
4903
4904   return bs_head;
4905 }
4906
4907 static void
4908 handle_jit_event (void)
4909 {
4910   struct frame_info *frame;
4911   struct gdbarch *gdbarch;
4912
4913   /* Switch terminal for any messages produced by
4914      breakpoint_re_set.  */
4915   target_terminal_ours_for_output ();
4916
4917   frame = get_current_frame ();
4918   gdbarch = get_frame_arch (frame);
4919
4920   jit_event_handler (gdbarch);
4921
4922   target_terminal_inferior ();
4923 }
4924
4925 /* Handle an solib event by calling solib_add.  */
4926
4927 void
4928 handle_solib_event (void)
4929 {
4930   clear_program_space_solib_cache (current_inferior ()->pspace);
4931
4932   /* Check for any newly added shared libraries if we're supposed to
4933      be adding them automatically.  Switch terminal for any messages
4934      produced by breakpoint_re_set.  */
4935   target_terminal_ours_for_output ();
4936 #ifdef SOLIB_ADD
4937   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
4938 #else
4939   solib_add (NULL, 0, &current_target, auto_solib_add);
4940 #endif
4941   target_terminal_inferior ();
4942 }
4943
4944 /* Prepare WHAT final decision for infrun.  */
4945
4946 /* Decide what infrun needs to do with this bpstat.  */
4947
4948 struct bpstat_what
4949 bpstat_what (bpstat bs_head)
4950 {
4951   struct bpstat_what retval;
4952   int jit_event = 0;
4953   bpstat bs;
4954
4955   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
4956   retval.call_dummy = STOP_NONE;
4957   retval.is_longjmp = 0;
4958
4959   for (bs = bs_head; bs != NULL; bs = bs->next)
4960     {
4961       /* Extract this BS's action.  After processing each BS, we check
4962          if its action overrides all we've seem so far.  */
4963       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
4964       enum bptype bptype;
4965
4966       if (bs->breakpoint_at == NULL)
4967         {
4968           /* I suspect this can happen if it was a momentary
4969              breakpoint which has since been deleted.  */
4970           bptype = bp_none;
4971         }
4972       else
4973         bptype = bs->breakpoint_at->type;
4974
4975       switch (bptype)
4976         {
4977         case bp_none:
4978           break;
4979         case bp_breakpoint:
4980         case bp_hardware_breakpoint:
4981         case bp_until:
4982         case bp_finish:
4983         case bp_shlib_event:
4984           if (bs->stop)
4985             {
4986               if (bs->print)
4987                 this_action = BPSTAT_WHAT_STOP_NOISY;
4988               else
4989                 this_action = BPSTAT_WHAT_STOP_SILENT;
4990             }
4991           else
4992             this_action = BPSTAT_WHAT_SINGLE;
4993           break;
4994         case bp_watchpoint:
4995         case bp_hardware_watchpoint:
4996         case bp_read_watchpoint:
4997         case bp_access_watchpoint:
4998           if (bs->stop)
4999             {
5000               if (bs->print)
5001                 this_action = BPSTAT_WHAT_STOP_NOISY;
5002               else
5003                 this_action = BPSTAT_WHAT_STOP_SILENT;
5004             }
5005           else
5006             {
5007               /* There was a watchpoint, but we're not stopping.
5008                  This requires no further action.  */
5009             }
5010           break;
5011         case bp_longjmp:
5012         case bp_exception:
5013           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5014           retval.is_longjmp = bptype == bp_longjmp;
5015           break;
5016         case bp_longjmp_resume:
5017         case bp_exception_resume:
5018           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5019           retval.is_longjmp = bptype == bp_longjmp_resume;
5020           break;
5021         case bp_step_resume:
5022           if (bs->stop)
5023             this_action = BPSTAT_WHAT_STEP_RESUME;
5024           else
5025             {
5026               /* It is for the wrong frame.  */
5027               this_action = BPSTAT_WHAT_SINGLE;
5028             }
5029           break;
5030         case bp_hp_step_resume:
5031           if (bs->stop)
5032             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5033           else
5034             {
5035               /* It is for the wrong frame.  */
5036               this_action = BPSTAT_WHAT_SINGLE;
5037             }
5038           break;
5039         case bp_watchpoint_scope:
5040         case bp_thread_event:
5041         case bp_overlay_event:
5042         case bp_longjmp_master:
5043         case bp_std_terminate_master:
5044         case bp_exception_master:
5045           this_action = BPSTAT_WHAT_SINGLE;
5046           break;
5047         case bp_catchpoint:
5048           if (bs->stop)
5049             {
5050               if (bs->print)
5051                 this_action = BPSTAT_WHAT_STOP_NOISY;
5052               else
5053                 this_action = BPSTAT_WHAT_STOP_SILENT;
5054             }
5055           else
5056             {
5057               /* There was a catchpoint, but we're not stopping.
5058                  This requires no further action.  */
5059             }
5060           break;
5061         case bp_jit_event:
5062           jit_event = 1;
5063           this_action = BPSTAT_WHAT_SINGLE;
5064           break;
5065         case bp_call_dummy:
5066           /* Make sure the action is stop (silent or noisy),
5067              so infrun.c pops the dummy frame.  */
5068           retval.call_dummy = STOP_STACK_DUMMY;
5069           this_action = BPSTAT_WHAT_STOP_SILENT;
5070           break;
5071         case bp_std_terminate:
5072           /* Make sure the action is stop (silent or noisy),
5073              so infrun.c pops the dummy frame.  */
5074           retval.call_dummy = STOP_STD_TERMINATE;
5075           this_action = BPSTAT_WHAT_STOP_SILENT;
5076           break;
5077         case bp_tracepoint:
5078         case bp_fast_tracepoint:
5079         case bp_static_tracepoint:
5080           /* Tracepoint hits should not be reported back to GDB, and
5081              if one got through somehow, it should have been filtered
5082              out already.  */
5083           internal_error (__FILE__, __LINE__,
5084                           _("bpstat_what: tracepoint encountered"));
5085           break;
5086         case bp_gnu_ifunc_resolver:
5087           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5088           this_action = BPSTAT_WHAT_SINGLE;
5089           break;
5090         case bp_gnu_ifunc_resolver_return:
5091           /* The breakpoint will be removed, execution will restart from the
5092              PC of the former breakpoint.  */
5093           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5094           break;
5095         default:
5096           internal_error (__FILE__, __LINE__,
5097                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5098         }
5099
5100       retval.main_action = max (retval.main_action, this_action);
5101     }
5102
5103   /* These operations may affect the bs->breakpoint_at state so they are
5104      delayed after MAIN_ACTION is decided above.  */
5105
5106   if (jit_event)
5107     {
5108       if (debug_infrun)
5109         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5110
5111       handle_jit_event ();
5112     }
5113
5114   for (bs = bs_head; bs != NULL; bs = bs->next)
5115     {
5116       struct breakpoint *b = bs->breakpoint_at;
5117
5118       if (b == NULL)
5119         continue;
5120       switch (b->type)
5121         {
5122         case bp_gnu_ifunc_resolver:
5123           gnu_ifunc_resolver_stop (b);
5124           break;
5125         case bp_gnu_ifunc_resolver_return:
5126           gnu_ifunc_resolver_return_stop (b);
5127           break;
5128         }
5129     }
5130
5131   return retval;
5132 }
5133
5134 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5135    without hardware support).  This isn't related to a specific bpstat,
5136    just to things like whether watchpoints are set.  */
5137
5138 int
5139 bpstat_should_step (void)
5140 {
5141   struct breakpoint *b;
5142
5143   ALL_BREAKPOINTS (b)
5144     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5145       return 1;
5146   return 0;
5147 }
5148
5149 int
5150 bpstat_causes_stop (bpstat bs)
5151 {
5152   for (; bs != NULL; bs = bs->next)
5153     if (bs->stop)
5154       return 1;
5155
5156   return 0;
5157 }
5158
5159 \f
5160
5161 /* Compute a string of spaces suitable to indent the next line
5162    so it starts at the position corresponding to the table column
5163    named COL_NAME in the currently active table of UIOUT.  */
5164
5165 static char *
5166 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5167 {
5168   static char wrap_indent[80];
5169   int i, total_width, width, align;
5170   char *text;
5171
5172   total_width = 0;
5173   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5174     {
5175       if (strcmp (text, col_name) == 0)
5176         {
5177           gdb_assert (total_width < sizeof wrap_indent);
5178           memset (wrap_indent, ' ', total_width);
5179           wrap_indent[total_width] = 0;
5180
5181           return wrap_indent;
5182         }
5183
5184       total_width += width + 1;
5185     }
5186
5187   return NULL;
5188 }
5189
5190 /* Determine if the locations of this breakpoint will have their conditions
5191    evaluated by the target, host or a mix of both.  Returns the following:
5192
5193     "host": Host evals condition.
5194     "host or target": Host or Target evals condition.
5195     "target": Target evals condition.
5196 */
5197
5198 static const char *
5199 bp_condition_evaluator (struct breakpoint *b)
5200 {
5201   struct bp_location *bl;
5202   char host_evals = 0;
5203   char target_evals = 0;
5204
5205   if (!b)
5206     return NULL;
5207
5208   if (!is_breakpoint (b))
5209     return NULL;
5210
5211   if (gdb_evaluates_breakpoint_condition_p ()
5212       || !target_supports_evaluation_of_breakpoint_conditions ())
5213     return condition_evaluation_host;
5214
5215   for (bl = b->loc; bl; bl = bl->next)
5216     {
5217       if (bl->cond_bytecode)
5218         target_evals++;
5219       else
5220         host_evals++;
5221     }
5222
5223   if (host_evals && target_evals)
5224     return condition_evaluation_both;
5225   else if (target_evals)
5226     return condition_evaluation_target;
5227   else
5228     return condition_evaluation_host;
5229 }
5230
5231 /* Determine the breakpoint location's condition evaluator.  This is
5232    similar to bp_condition_evaluator, but for locations.  */
5233
5234 static const char *
5235 bp_location_condition_evaluator (struct bp_location *bl)
5236 {
5237   if (bl && !is_breakpoint (bl->owner))
5238     return NULL;
5239
5240   if (gdb_evaluates_breakpoint_condition_p ()
5241       || !target_supports_evaluation_of_breakpoint_conditions ())
5242     return condition_evaluation_host;
5243
5244   if (bl && bl->cond_bytecode)
5245     return condition_evaluation_target;
5246   else
5247     return condition_evaluation_host;
5248 }
5249
5250 /* Print the LOC location out of the list of B->LOC locations.  */
5251
5252 static void
5253 print_breakpoint_location (struct breakpoint *b,
5254                            struct bp_location *loc)
5255 {
5256   struct ui_out *uiout = current_uiout;
5257   struct cleanup *old_chain = save_current_program_space ();
5258
5259   if (loc != NULL && loc->shlib_disabled)
5260     loc = NULL;
5261
5262   if (loc != NULL)
5263     set_current_program_space (loc->pspace);
5264
5265   if (b->display_canonical)
5266     ui_out_field_string (uiout, "what", b->addr_string);
5267   else if (loc && loc->source_file)
5268     {
5269       struct symbol *sym 
5270         = find_pc_sect_function (loc->address, loc->section);
5271       if (sym)
5272         {
5273           ui_out_text (uiout, "in ");
5274           ui_out_field_string (uiout, "func",
5275                                SYMBOL_PRINT_NAME (sym));
5276           ui_out_text (uiout, " ");
5277           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5278           ui_out_text (uiout, "at ");
5279         }
5280       ui_out_field_string (uiout, "file", loc->source_file);
5281       ui_out_text (uiout, ":");
5282       
5283       if (ui_out_is_mi_like_p (uiout))
5284         {
5285           struct symtab_and_line sal = find_pc_line (loc->address, 0);
5286           char *fullname = symtab_to_fullname (sal.symtab);
5287           
5288           if (fullname)
5289             ui_out_field_string (uiout, "fullname", fullname);
5290         }
5291       
5292       ui_out_field_int (uiout, "line", loc->line_number);
5293     }
5294   else if (loc)
5295     {
5296       struct ui_file *stb = mem_fileopen ();
5297       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5298
5299       print_address_symbolic (loc->gdbarch, loc->address, stb,
5300                               demangle, "");
5301       ui_out_field_stream (uiout, "at", stb);
5302
5303       do_cleanups (stb_chain);
5304     }
5305   else
5306     ui_out_field_string (uiout, "pending", b->addr_string);
5307
5308   if (loc && is_breakpoint (b)
5309       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5310       && bp_condition_evaluator (b) == condition_evaluation_both)
5311     {
5312       ui_out_text (uiout, " (");
5313       ui_out_field_string (uiout, "evaluated-by",
5314                            bp_location_condition_evaluator (loc));
5315       ui_out_text (uiout, ")");
5316     }
5317
5318   do_cleanups (old_chain);
5319 }
5320
5321 static const char *
5322 bptype_string (enum bptype type)
5323 {
5324   struct ep_type_description
5325     {
5326       enum bptype type;
5327       char *description;
5328     };
5329   static struct ep_type_description bptypes[] =
5330   {
5331     {bp_none, "?deleted?"},
5332     {bp_breakpoint, "breakpoint"},
5333     {bp_hardware_breakpoint, "hw breakpoint"},
5334     {bp_until, "until"},
5335     {bp_finish, "finish"},
5336     {bp_watchpoint, "watchpoint"},
5337     {bp_hardware_watchpoint, "hw watchpoint"},
5338     {bp_read_watchpoint, "read watchpoint"},
5339     {bp_access_watchpoint, "acc watchpoint"},
5340     {bp_longjmp, "longjmp"},
5341     {bp_longjmp_resume, "longjmp resume"},
5342     {bp_exception, "exception"},
5343     {bp_exception_resume, "exception resume"},
5344     {bp_step_resume, "step resume"},
5345     {bp_hp_step_resume, "high-priority step resume"},
5346     {bp_watchpoint_scope, "watchpoint scope"},
5347     {bp_call_dummy, "call dummy"},
5348     {bp_std_terminate, "std::terminate"},
5349     {bp_shlib_event, "shlib events"},
5350     {bp_thread_event, "thread events"},
5351     {bp_overlay_event, "overlay events"},
5352     {bp_longjmp_master, "longjmp master"},
5353     {bp_std_terminate_master, "std::terminate master"},
5354     {bp_exception_master, "exception master"},
5355     {bp_catchpoint, "catchpoint"},
5356     {bp_tracepoint, "tracepoint"},
5357     {bp_fast_tracepoint, "fast tracepoint"},
5358     {bp_static_tracepoint, "static tracepoint"},
5359     {bp_jit_event, "jit events"},
5360     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5361     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5362   };
5363
5364   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5365       || ((int) type != bptypes[(int) type].type))
5366     internal_error (__FILE__, __LINE__,
5367                     _("bptypes table does not describe type #%d."),
5368                     (int) type);
5369
5370   return bptypes[(int) type].description;
5371 }
5372
5373 /* Print B to gdb_stdout.  */
5374
5375 static void
5376 print_one_breakpoint_location (struct breakpoint *b,
5377                                struct bp_location *loc,
5378                                int loc_number,
5379                                struct bp_location **last_loc,
5380                                int allflag)
5381 {
5382   struct command_line *l;
5383   static char bpenables[] = "nynny";
5384
5385   struct ui_out *uiout = current_uiout;
5386   int header_of_multiple = 0;
5387   int part_of_multiple = (loc != NULL);
5388   struct value_print_options opts;
5389
5390   get_user_print_options (&opts);
5391
5392   gdb_assert (!loc || loc_number != 0);
5393   /* See comment in print_one_breakpoint concerning treatment of
5394      breakpoints with single disabled location.  */
5395   if (loc == NULL 
5396       && (b->loc != NULL 
5397           && (b->loc->next != NULL || !b->loc->enabled)))
5398     header_of_multiple = 1;
5399   if (loc == NULL)
5400     loc = b->loc;
5401
5402   annotate_record ();
5403
5404   /* 1 */
5405   annotate_field (0);
5406   if (part_of_multiple)
5407     {
5408       char *formatted;
5409       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5410       ui_out_field_string (uiout, "number", formatted);
5411       xfree (formatted);
5412     }
5413   else
5414     {
5415       ui_out_field_int (uiout, "number", b->number);
5416     }
5417
5418   /* 2 */
5419   annotate_field (1);
5420   if (part_of_multiple)
5421     ui_out_field_skip (uiout, "type");
5422   else
5423     ui_out_field_string (uiout, "type", bptype_string (b->type));
5424
5425   /* 3 */
5426   annotate_field (2);
5427   if (part_of_multiple)
5428     ui_out_field_skip (uiout, "disp");
5429   else
5430     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5431
5432
5433   /* 4 */
5434   annotate_field (3);
5435   if (part_of_multiple)
5436     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5437   else
5438     ui_out_field_fmt (uiout, "enabled", "%c", 
5439                       bpenables[(int) b->enable_state]);
5440   ui_out_spaces (uiout, 2);
5441
5442   
5443   /* 5 and 6 */
5444   if (b->ops != NULL && b->ops->print_one != NULL)
5445     {
5446       /* Although the print_one can possibly print all locations,
5447          calling it here is not likely to get any nice result.  So,
5448          make sure there's just one location.  */
5449       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5450       b->ops->print_one (b, last_loc);
5451     }
5452   else
5453     switch (b->type)
5454       {
5455       case bp_none:
5456         internal_error (__FILE__, __LINE__,
5457                         _("print_one_breakpoint: bp_none encountered\n"));
5458         break;
5459
5460       case bp_watchpoint:
5461       case bp_hardware_watchpoint:
5462       case bp_read_watchpoint:
5463       case bp_access_watchpoint:
5464         {
5465           struct watchpoint *w = (struct watchpoint *) b;
5466
5467           /* Field 4, the address, is omitted (which makes the columns
5468              not line up too nicely with the headers, but the effect
5469              is relatively readable).  */
5470           if (opts.addressprint)
5471             ui_out_field_skip (uiout, "addr");
5472           annotate_field (5);
5473           ui_out_field_string (uiout, "what", w->exp_string);
5474         }
5475         break;
5476
5477       case bp_breakpoint:
5478       case bp_hardware_breakpoint:
5479       case bp_until:
5480       case bp_finish:
5481       case bp_longjmp:
5482       case bp_longjmp_resume:
5483       case bp_exception:
5484       case bp_exception_resume:
5485       case bp_step_resume:
5486       case bp_hp_step_resume:
5487       case bp_watchpoint_scope:
5488       case bp_call_dummy:
5489       case bp_std_terminate:
5490       case bp_shlib_event:
5491       case bp_thread_event:
5492       case bp_overlay_event:
5493       case bp_longjmp_master:
5494       case bp_std_terminate_master:
5495       case bp_exception_master:
5496       case bp_tracepoint:
5497       case bp_fast_tracepoint:
5498       case bp_static_tracepoint:
5499       case bp_jit_event:
5500       case bp_gnu_ifunc_resolver:
5501       case bp_gnu_ifunc_resolver_return:
5502         if (opts.addressprint)
5503           {
5504             annotate_field (4);
5505             if (header_of_multiple)
5506               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5507             else if (b->loc == NULL || loc->shlib_disabled)
5508               ui_out_field_string (uiout, "addr", "<PENDING>");
5509             else
5510               ui_out_field_core_addr (uiout, "addr",
5511                                       loc->gdbarch, loc->address);
5512           }
5513         annotate_field (5);
5514         if (!header_of_multiple)
5515           print_breakpoint_location (b, loc);
5516         if (b->loc)
5517           *last_loc = b->loc;
5518         break;
5519       }
5520
5521
5522   /* For backward compatibility, don't display inferiors unless there
5523      are several.  */
5524   if (loc != NULL
5525       && !header_of_multiple
5526       && (allflag
5527           || (!gdbarch_has_global_breakpoints (target_gdbarch)
5528               && (number_of_program_spaces () > 1
5529                   || number_of_inferiors () > 1)
5530               /* LOC is for existing B, it cannot be in
5531                  moribund_locations and thus having NULL OWNER.  */
5532               && loc->owner->type != bp_catchpoint)))
5533     {
5534       struct inferior *inf;
5535       int first = 1;
5536
5537       for (inf = inferior_list; inf != NULL; inf = inf->next)
5538         {
5539           if (inf->pspace == loc->pspace)
5540             {
5541               if (first)
5542                 {
5543                   first = 0;
5544                   ui_out_text (uiout, " inf ");
5545                 }
5546               else
5547                 ui_out_text (uiout, ", ");
5548               ui_out_text (uiout, plongest (inf->num));
5549             }
5550         }
5551     }
5552
5553   if (!part_of_multiple)
5554     {
5555       if (b->thread != -1)
5556         {
5557           /* FIXME: This seems to be redundant and lost here; see the
5558              "stop only in" line a little further down.  */
5559           ui_out_text (uiout, " thread ");
5560           ui_out_field_int (uiout, "thread", b->thread);
5561         }
5562       else if (b->task != 0)
5563         {
5564           ui_out_text (uiout, " task ");
5565           ui_out_field_int (uiout, "task", b->task);
5566         }
5567     }
5568
5569   ui_out_text (uiout, "\n");
5570
5571   if (!part_of_multiple)
5572     b->ops->print_one_detail (b, uiout);
5573
5574   if (part_of_multiple && frame_id_p (b->frame_id))
5575     {
5576       annotate_field (6);
5577       ui_out_text (uiout, "\tstop only in stack frame at ");
5578       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
5579          the frame ID.  */
5580       ui_out_field_core_addr (uiout, "frame",
5581                               b->gdbarch, b->frame_id.stack_addr);
5582       ui_out_text (uiout, "\n");
5583     }
5584   
5585   if (!part_of_multiple && b->cond_string)
5586     {
5587       annotate_field (7);
5588       if (is_tracepoint (b))
5589         ui_out_text (uiout, "\ttrace only if ");
5590       else
5591         ui_out_text (uiout, "\tstop only if ");
5592       ui_out_field_string (uiout, "cond", b->cond_string);
5593
5594       /* Print whether the target is doing the breakpoint's condition
5595          evaluation.  If GDB is doing the evaluation, don't print anything.  */
5596       if (is_breakpoint (b)
5597           && breakpoint_condition_evaluation_mode ()
5598           == condition_evaluation_target)
5599         {
5600           ui_out_text (uiout, " (");
5601           ui_out_field_string (uiout, "evaluated-by",
5602                                bp_condition_evaluator (b));
5603           ui_out_text (uiout, " evals)");
5604         }
5605       ui_out_text (uiout, "\n");
5606     }
5607
5608   if (!part_of_multiple && b->thread != -1)
5609     {
5610       /* FIXME should make an annotation for this.  */
5611       ui_out_text (uiout, "\tstop only in thread ");
5612       ui_out_field_int (uiout, "thread", b->thread);
5613       ui_out_text (uiout, "\n");
5614     }
5615   
5616   if (!part_of_multiple && b->hit_count)
5617     {
5618       /* FIXME should make an annotation for this.  */
5619       if (is_catchpoint (b))
5620         ui_out_text (uiout, "\tcatchpoint");
5621       else if (is_tracepoint (b))
5622         ui_out_text (uiout, "\ttracepoint");
5623       else
5624         ui_out_text (uiout, "\tbreakpoint");
5625       ui_out_text (uiout, " already hit ");
5626       ui_out_field_int (uiout, "times", b->hit_count);
5627       if (b->hit_count == 1)
5628         ui_out_text (uiout, " time\n");
5629       else
5630         ui_out_text (uiout, " times\n");
5631     }
5632   
5633   /* Output the count also if it is zero, but only if this is mi.
5634      FIXME: Should have a better test for this.  */
5635   if (ui_out_is_mi_like_p (uiout))
5636     if (!part_of_multiple && b->hit_count == 0)
5637       ui_out_field_int (uiout, "times", b->hit_count);
5638
5639   if (!part_of_multiple && b->ignore_count)
5640     {
5641       annotate_field (8);
5642       ui_out_text (uiout, "\tignore next ");
5643       ui_out_field_int (uiout, "ignore", b->ignore_count);
5644       ui_out_text (uiout, " hits\n");
5645     }
5646
5647   /* Note that an enable count of 1 corresponds to "enable once"
5648      behavior, which is reported by the combination of enablement and
5649      disposition, so we don't need to mention it here.  */
5650   if (!part_of_multiple && b->enable_count > 1)
5651     {
5652       annotate_field (8);
5653       ui_out_text (uiout, "\tdisable after ");
5654       /* Tweak the wording to clarify that ignore and enable counts
5655          are distinct, and have additive effect.  */
5656       if (b->ignore_count)
5657         ui_out_text (uiout, "additional ");
5658       else
5659         ui_out_text (uiout, "next ");
5660       ui_out_field_int (uiout, "enable", b->enable_count);
5661       ui_out_text (uiout, " hits\n");
5662     }
5663
5664   if (!part_of_multiple && is_tracepoint (b))
5665     {
5666       struct tracepoint *tp = (struct tracepoint *) b;
5667
5668       if (tp->traceframe_usage)
5669         {
5670           ui_out_text (uiout, "\ttrace buffer usage ");
5671           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
5672           ui_out_text (uiout, " bytes\n");
5673         }
5674     }
5675   
5676   l = b->commands ? b->commands->commands : NULL;
5677   if (!part_of_multiple && l)
5678     {
5679       struct cleanup *script_chain;
5680
5681       annotate_field (9);
5682       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
5683       print_command_lines (uiout, l, 4);
5684       do_cleanups (script_chain);
5685     }
5686
5687   if (is_tracepoint (b))
5688     {
5689       struct tracepoint *t = (struct tracepoint *) b;
5690
5691       if (!part_of_multiple && t->pass_count)
5692         {
5693           annotate_field (10);
5694           ui_out_text (uiout, "\tpass count ");
5695           ui_out_field_int (uiout, "pass", t->pass_count);
5696           ui_out_text (uiout, " \n");
5697         }
5698     }
5699
5700   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5701     {
5702       if (is_watchpoint (b))
5703         {
5704           struct watchpoint *w = (struct watchpoint *) b;
5705
5706           ui_out_field_string (uiout, "original-location", w->exp_string);
5707         }
5708       else if (b->addr_string)
5709         ui_out_field_string (uiout, "original-location", b->addr_string);
5710     }
5711 }
5712
5713 static void
5714 print_one_breakpoint (struct breakpoint *b,
5715                       struct bp_location **last_loc, 
5716                       int allflag)
5717 {
5718   struct cleanup *bkpt_chain;
5719   struct ui_out *uiout = current_uiout;
5720
5721   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5722
5723   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5724   do_cleanups (bkpt_chain);
5725
5726   /* If this breakpoint has custom print function,
5727      it's already printed.  Otherwise, print individual
5728      locations, if any.  */
5729   if (b->ops == NULL || b->ops->print_one == NULL)
5730     {
5731       /* If breakpoint has a single location that is disabled, we
5732          print it as if it had several locations, since otherwise it's
5733          hard to represent "breakpoint enabled, location disabled"
5734          situation.
5735
5736          Note that while hardware watchpoints have several locations
5737          internally, that's not a property exposed to user.  */
5738       if (b->loc 
5739           && !is_hardware_watchpoint (b)
5740           && (b->loc->next || !b->loc->enabled))
5741         {
5742           struct bp_location *loc;
5743           int n = 1;
5744
5745           for (loc = b->loc; loc; loc = loc->next, ++n)
5746             {
5747               struct cleanup *inner2 =
5748                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5749               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5750               do_cleanups (inner2);
5751             }
5752         }
5753     }
5754 }
5755
5756 static int
5757 breakpoint_address_bits (struct breakpoint *b)
5758 {
5759   int print_address_bits = 0;
5760   struct bp_location *loc;
5761
5762   for (loc = b->loc; loc; loc = loc->next)
5763     {
5764       int addr_bit;
5765
5766       /* Software watchpoints that aren't watching memory don't have
5767          an address to print.  */
5768       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5769         continue;
5770
5771       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5772       if (addr_bit > print_address_bits)
5773         print_address_bits = addr_bit;
5774     }
5775
5776   return print_address_bits;
5777 }
5778
5779 struct captured_breakpoint_query_args
5780   {
5781     int bnum;
5782   };
5783
5784 static int
5785 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5786 {
5787   struct captured_breakpoint_query_args *args = data;
5788   struct breakpoint *b;
5789   struct bp_location *dummy_loc = NULL;
5790
5791   ALL_BREAKPOINTS (b)
5792     {
5793       if (args->bnum == b->number)
5794         {
5795           print_one_breakpoint (b, &dummy_loc, 0);
5796           return GDB_RC_OK;
5797         }
5798     }
5799   return GDB_RC_NONE;
5800 }
5801
5802 enum gdb_rc
5803 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5804                       char **error_message)
5805 {
5806   struct captured_breakpoint_query_args args;
5807
5808   args.bnum = bnum;
5809   /* For the moment we don't trust print_one_breakpoint() to not throw
5810      an error.  */
5811   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5812                                  error_message, RETURN_MASK_ALL) < 0)
5813     return GDB_RC_FAIL;
5814   else
5815     return GDB_RC_OK;
5816 }
5817
5818 /* Return true if this breakpoint was set by the user, false if it is
5819    internal or momentary.  */
5820
5821 int
5822 user_breakpoint_p (struct breakpoint *b)
5823 {
5824   return b->number > 0;
5825 }
5826
5827 /* Print information on user settable breakpoint (watchpoint, etc)
5828    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5829    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5830    FILTER is non-NULL, call it on each breakpoint and only include the
5831    ones for which it returns non-zero.  Return the total number of
5832    breakpoints listed.  */
5833
5834 static int
5835 breakpoint_1 (char *args, int allflag, 
5836               int (*filter) (const struct breakpoint *))
5837 {
5838   struct breakpoint *b;
5839   struct bp_location *last_loc = NULL;
5840   int nr_printable_breakpoints;
5841   struct cleanup *bkpttbl_chain;
5842   struct value_print_options opts;
5843   int print_address_bits = 0;
5844   int print_type_col_width = 14;
5845   struct ui_out *uiout = current_uiout;
5846
5847   get_user_print_options (&opts);
5848
5849   /* Compute the number of rows in the table, as well as the size
5850      required for address fields.  */
5851   nr_printable_breakpoints = 0;
5852   ALL_BREAKPOINTS (b)
5853     {
5854       /* If we have a filter, only list the breakpoints it accepts.  */
5855       if (filter && !filter (b))
5856         continue;
5857
5858       /* If we have an "args" string, it is a list of breakpoints to 
5859          accept.  Skip the others.  */
5860       if (args != NULL && *args != '\0')
5861         {
5862           if (allflag && parse_and_eval_long (args) != b->number)
5863             continue;
5864           if (!allflag && !number_is_in_list (args, b->number))
5865             continue;
5866         }
5867
5868       if (allflag || user_breakpoint_p (b))
5869         {
5870           int addr_bit, type_len;
5871
5872           addr_bit = breakpoint_address_bits (b);
5873           if (addr_bit > print_address_bits)
5874             print_address_bits = addr_bit;
5875
5876           type_len = strlen (bptype_string (b->type));
5877           if (type_len > print_type_col_width)
5878             print_type_col_width = type_len;
5879
5880           nr_printable_breakpoints++;
5881         }
5882     }
5883
5884   if (opts.addressprint)
5885     bkpttbl_chain 
5886       = make_cleanup_ui_out_table_begin_end (uiout, 6,
5887                                              nr_printable_breakpoints,
5888                                              "BreakpointTable");
5889   else
5890     bkpttbl_chain 
5891       = make_cleanup_ui_out_table_begin_end (uiout, 5,
5892                                              nr_printable_breakpoints,
5893                                              "BreakpointTable");
5894
5895   if (nr_printable_breakpoints > 0)
5896     annotate_breakpoints_headers ();
5897   if (nr_printable_breakpoints > 0)
5898     annotate_field (0);
5899   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
5900   if (nr_printable_breakpoints > 0)
5901     annotate_field (1);
5902   ui_out_table_header (uiout, print_type_col_width, ui_left,
5903                        "type", "Type");                         /* 2 */
5904   if (nr_printable_breakpoints > 0)
5905     annotate_field (2);
5906   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
5907   if (nr_printable_breakpoints > 0)
5908     annotate_field (3);
5909   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
5910   if (opts.addressprint)
5911     {
5912       if (nr_printable_breakpoints > 0)
5913         annotate_field (4);
5914       if (print_address_bits <= 32)
5915         ui_out_table_header (uiout, 10, ui_left, 
5916                              "addr", "Address");                /* 5 */
5917       else
5918         ui_out_table_header (uiout, 18, ui_left, 
5919                              "addr", "Address");                /* 5 */
5920     }
5921   if (nr_printable_breakpoints > 0)
5922     annotate_field (5);
5923   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
5924   ui_out_table_body (uiout);
5925   if (nr_printable_breakpoints > 0)
5926     annotate_breakpoints_table ();
5927
5928   ALL_BREAKPOINTS (b)
5929     {
5930       QUIT;
5931       /* If we have a filter, only list the breakpoints it accepts.  */
5932       if (filter && !filter (b))
5933         continue;
5934
5935       /* If we have an "args" string, it is a list of breakpoints to 
5936          accept.  Skip the others.  */
5937
5938       if (args != NULL && *args != '\0')
5939         {
5940           if (allflag)  /* maintenance info breakpoint */
5941             {
5942               if (parse_and_eval_long (args) != b->number)
5943                 continue;
5944             }
5945           else          /* all others */
5946             {
5947               if (!number_is_in_list (args, b->number))
5948                 continue;
5949             }
5950         }
5951       /* We only print out user settable breakpoints unless the
5952          allflag is set.  */
5953       if (allflag || user_breakpoint_p (b))
5954         print_one_breakpoint (b, &last_loc, allflag);
5955     }
5956
5957   do_cleanups (bkpttbl_chain);
5958
5959   if (nr_printable_breakpoints == 0)
5960     {
5961       /* If there's a filter, let the caller decide how to report
5962          empty list.  */
5963       if (!filter)
5964         {
5965           if (args == NULL || *args == '\0')
5966             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
5967           else
5968             ui_out_message (uiout, 0, 
5969                             "No breakpoint or watchpoint matching '%s'.\n",
5970                             args);
5971         }
5972     }
5973   else
5974     {
5975       if (last_loc && !server_command)
5976         set_next_address (last_loc->gdbarch, last_loc->address);
5977     }
5978
5979   /* FIXME?  Should this be moved up so that it is only called when
5980      there have been breakpoints? */
5981   annotate_breakpoints_table_end ();
5982
5983   return nr_printable_breakpoints;
5984 }
5985
5986 /* Display the value of default-collect in a way that is generally
5987    compatible with the breakpoint list.  */
5988
5989 static void
5990 default_collect_info (void)
5991 {
5992   struct ui_out *uiout = current_uiout;
5993
5994   /* If it has no value (which is frequently the case), say nothing; a
5995      message like "No default-collect." gets in user's face when it's
5996      not wanted.  */
5997   if (!*default_collect)
5998     return;
5999
6000   /* The following phrase lines up nicely with per-tracepoint collect
6001      actions.  */
6002   ui_out_text (uiout, "default collect ");
6003   ui_out_field_string (uiout, "default-collect", default_collect);
6004   ui_out_text (uiout, " \n");
6005 }
6006   
6007 static void
6008 breakpoints_info (char *args, int from_tty)
6009 {
6010   breakpoint_1 (args, 0, NULL);
6011
6012   default_collect_info ();
6013 }
6014
6015 static void
6016 watchpoints_info (char *args, int from_tty)
6017 {
6018   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6019   struct ui_out *uiout = current_uiout;
6020
6021   if (num_printed == 0)
6022     {
6023       if (args == NULL || *args == '\0')
6024         ui_out_message (uiout, 0, "No watchpoints.\n");
6025       else
6026         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6027     }
6028 }
6029
6030 static void
6031 maintenance_info_breakpoints (char *args, int from_tty)
6032 {
6033   breakpoint_1 (args, 1, NULL);
6034
6035   default_collect_info ();
6036 }
6037
6038 static int
6039 breakpoint_has_pc (struct breakpoint *b,
6040                    struct program_space *pspace,
6041                    CORE_ADDR pc, struct obj_section *section)
6042 {
6043   struct bp_location *bl = b->loc;
6044
6045   for (; bl; bl = bl->next)
6046     {
6047       if (bl->pspace == pspace
6048           && bl->address == pc
6049           && (!overlay_debugging || bl->section == section))
6050         return 1;         
6051     }
6052   return 0;
6053 }
6054
6055 /* Print a message describing any user-breakpoints set at PC.  This
6056    concerns with logical breakpoints, so we match program spaces, not
6057    address spaces.  */
6058
6059 static void
6060 describe_other_breakpoints (struct gdbarch *gdbarch,
6061                             struct program_space *pspace, CORE_ADDR pc,
6062                             struct obj_section *section, int thread)
6063 {
6064   int others = 0;
6065   struct breakpoint *b;
6066
6067   ALL_BREAKPOINTS (b)
6068     others += (user_breakpoint_p (b)
6069                && breakpoint_has_pc (b, pspace, pc, section));
6070   if (others > 0)
6071     {
6072       if (others == 1)
6073         printf_filtered (_("Note: breakpoint "));
6074       else /* if (others == ???) */
6075         printf_filtered (_("Note: breakpoints "));
6076       ALL_BREAKPOINTS (b)
6077         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6078           {
6079             others--;
6080             printf_filtered ("%d", b->number);
6081             if (b->thread == -1 && thread != -1)
6082               printf_filtered (" (all threads)");
6083             else if (b->thread != -1)
6084               printf_filtered (" (thread %d)", b->thread);
6085             printf_filtered ("%s%s ",
6086                              ((b->enable_state == bp_disabled
6087                                || b->enable_state == bp_call_disabled)
6088                               ? " (disabled)"
6089                               : b->enable_state == bp_permanent 
6090                               ? " (permanent)"
6091                               : ""),
6092                              (others > 1) ? "," 
6093                              : ((others == 1) ? " and" : ""));
6094           }
6095       printf_filtered (_("also set at pc "));
6096       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6097       printf_filtered (".\n");
6098     }
6099 }
6100 \f
6101
6102 /* Return true iff it is meaningful to use the address member of
6103    BPT.  For some breakpoint types, the address member is irrelevant
6104    and it makes no sense to attempt to compare it to other addresses
6105    (or use it for any other purpose either).
6106
6107    More specifically, each of the following breakpoint types will
6108    always have a zero valued address and we don't want to mark
6109    breakpoints of any of these types to be a duplicate of an actual
6110    breakpoint at address zero:
6111
6112       bp_watchpoint
6113       bp_catchpoint
6114
6115 */
6116
6117 static int
6118 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6119 {
6120   enum bptype type = bpt->type;
6121
6122   return (type != bp_watchpoint && type != bp_catchpoint);
6123 }
6124
6125 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6126    true if LOC1 and LOC2 represent the same watchpoint location.  */
6127
6128 static int
6129 watchpoint_locations_match (struct bp_location *loc1, 
6130                             struct bp_location *loc2)
6131 {
6132   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6133   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6134
6135   /* Both of them must exist.  */
6136   gdb_assert (w1 != NULL);
6137   gdb_assert (w2 != NULL);
6138
6139   /* If the target can evaluate the condition expression in hardware,
6140      then we we need to insert both watchpoints even if they are at
6141      the same place.  Otherwise the watchpoint will only trigger when
6142      the condition of whichever watchpoint was inserted evaluates to
6143      true, not giving a chance for GDB to check the condition of the
6144      other watchpoint.  */
6145   if ((w1->cond_exp
6146        && target_can_accel_watchpoint_condition (loc1->address, 
6147                                                  loc1->length,
6148                                                  loc1->watchpoint_type,
6149                                                  w1->cond_exp))
6150       || (w2->cond_exp
6151           && target_can_accel_watchpoint_condition (loc2->address, 
6152                                                     loc2->length,
6153                                                     loc2->watchpoint_type,
6154                                                     w2->cond_exp)))
6155     return 0;
6156
6157   /* Note that this checks the owner's type, not the location's.  In
6158      case the target does not support read watchpoints, but does
6159      support access watchpoints, we'll have bp_read_watchpoint
6160      watchpoints with hw_access locations.  Those should be considered
6161      duplicates of hw_read locations.  The hw_read locations will
6162      become hw_access locations later.  */
6163   return (loc1->owner->type == loc2->owner->type
6164           && loc1->pspace->aspace == loc2->pspace->aspace
6165           && loc1->address == loc2->address
6166           && loc1->length == loc2->length);
6167 }
6168
6169 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6170    same breakpoint location.  In most targets, this can only be true
6171    if ASPACE1 matches ASPACE2.  On targets that have global
6172    breakpoints, the address space doesn't really matter.  */
6173
6174 static int
6175 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6176                           struct address_space *aspace2, CORE_ADDR addr2)
6177 {
6178   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6179            || aspace1 == aspace2)
6180           && addr1 == addr2);
6181 }
6182
6183 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6184    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6185    matches ASPACE2.  On targets that have global breakpoints, the address
6186    space doesn't really matter.  */
6187
6188 static int
6189 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6190                                 int len1, struct address_space *aspace2,
6191                                 CORE_ADDR addr2)
6192 {
6193   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6194            || aspace1 == aspace2)
6195           && addr2 >= addr1 && addr2 < addr1 + len1);
6196 }
6197
6198 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6199    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6200    matches the breakpoint's address space.  On targets that have global
6201    breakpoints, the address space doesn't really matter.  */
6202
6203 static int
6204 breakpoint_location_address_match (struct bp_location *bl,
6205                                    struct address_space *aspace,
6206                                    CORE_ADDR addr)
6207 {
6208   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6209                                     aspace, addr)
6210           || (bl->length
6211               && breakpoint_address_match_range (bl->pspace->aspace,
6212                                                  bl->address, bl->length,
6213                                                  aspace, addr)));
6214 }
6215
6216 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6217    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6218    true, otherwise returns false.  */
6219
6220 static int
6221 tracepoint_locations_match (struct bp_location *loc1,
6222                             struct bp_location *loc2)
6223 {
6224   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6225     /* Since tracepoint locations are never duplicated with others', tracepoint
6226        locations at the same address of different tracepoints are regarded as
6227        different locations.  */
6228     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6229   else
6230     return 0;
6231 }
6232
6233 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6234    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6235    represent the same location.  */
6236
6237 static int
6238 breakpoint_locations_match (struct bp_location *loc1, 
6239                             struct bp_location *loc2)
6240 {
6241   int hw_point1, hw_point2;
6242
6243   /* Both of them must not be in moribund_locations.  */
6244   gdb_assert (loc1->owner != NULL);
6245   gdb_assert (loc2->owner != NULL);
6246
6247   hw_point1 = is_hardware_watchpoint (loc1->owner);
6248   hw_point2 = is_hardware_watchpoint (loc2->owner);
6249
6250   if (hw_point1 != hw_point2)
6251     return 0;
6252   else if (hw_point1)
6253     return watchpoint_locations_match (loc1, loc2);
6254   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6255     return tracepoint_locations_match (loc1, loc2);
6256   else
6257     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6258     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6259                                      loc2->pspace->aspace, loc2->address)
6260             && loc1->length == loc2->length);
6261 }
6262
6263 static void
6264 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6265                                int bnum, int have_bnum)
6266 {
6267   /* The longest string possibly returned by hex_string_custom
6268      is 50 chars.  These must be at least that big for safety.  */
6269   char astr1[64];
6270   char astr2[64];
6271
6272   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6273   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6274   if (have_bnum)
6275     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6276              bnum, astr1, astr2);
6277   else
6278     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6279 }
6280
6281 /* Adjust a breakpoint's address to account for architectural
6282    constraints on breakpoint placement.  Return the adjusted address.
6283    Note: Very few targets require this kind of adjustment.  For most
6284    targets, this function is simply the identity function.  */
6285
6286 static CORE_ADDR
6287 adjust_breakpoint_address (struct gdbarch *gdbarch,
6288                            CORE_ADDR bpaddr, enum bptype bptype)
6289 {
6290   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6291     {
6292       /* Very few targets need any kind of breakpoint adjustment.  */
6293       return bpaddr;
6294     }
6295   else if (bptype == bp_watchpoint
6296            || bptype == bp_hardware_watchpoint
6297            || bptype == bp_read_watchpoint
6298            || bptype == bp_access_watchpoint
6299            || bptype == bp_catchpoint)
6300     {
6301       /* Watchpoints and the various bp_catch_* eventpoints should not
6302          have their addresses modified.  */
6303       return bpaddr;
6304     }
6305   else
6306     {
6307       CORE_ADDR adjusted_bpaddr;
6308
6309       /* Some targets have architectural constraints on the placement
6310          of breakpoint instructions.  Obtain the adjusted address.  */
6311       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6312
6313       /* An adjusted breakpoint address can significantly alter
6314          a user's expectations.  Print a warning if an adjustment
6315          is required.  */
6316       if (adjusted_bpaddr != bpaddr)
6317         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6318
6319       return adjusted_bpaddr;
6320     }
6321 }
6322
6323 void
6324 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6325                   struct breakpoint *owner)
6326 {
6327   memset (loc, 0, sizeof (*loc));
6328
6329   gdb_assert (ops != NULL);
6330
6331   loc->ops = ops;
6332   loc->owner = owner;
6333   loc->cond = NULL;
6334   loc->cond_bytecode = NULL;
6335   loc->shlib_disabled = 0;
6336   loc->enabled = 1;
6337
6338   switch (owner->type)
6339     {
6340     case bp_breakpoint:
6341     case bp_until:
6342     case bp_finish:
6343     case bp_longjmp:
6344     case bp_longjmp_resume:
6345     case bp_exception:
6346     case bp_exception_resume:
6347     case bp_step_resume:
6348     case bp_hp_step_resume:
6349     case bp_watchpoint_scope:
6350     case bp_call_dummy:
6351     case bp_std_terminate:
6352     case bp_shlib_event:
6353     case bp_thread_event:
6354     case bp_overlay_event:
6355     case bp_jit_event:
6356     case bp_longjmp_master:
6357     case bp_std_terminate_master:
6358     case bp_exception_master:
6359     case bp_gnu_ifunc_resolver:
6360     case bp_gnu_ifunc_resolver_return:
6361       loc->loc_type = bp_loc_software_breakpoint;
6362       mark_breakpoint_location_modified (loc);
6363       break;
6364     case bp_hardware_breakpoint:
6365       loc->loc_type = bp_loc_hardware_breakpoint;
6366       mark_breakpoint_location_modified (loc);
6367       break;
6368     case bp_hardware_watchpoint:
6369     case bp_read_watchpoint:
6370     case bp_access_watchpoint:
6371       loc->loc_type = bp_loc_hardware_watchpoint;
6372       break;
6373     case bp_watchpoint:
6374     case bp_catchpoint:
6375     case bp_tracepoint:
6376     case bp_fast_tracepoint:
6377     case bp_static_tracepoint:
6378       loc->loc_type = bp_loc_other;
6379       break;
6380     default:
6381       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6382     }
6383
6384   loc->refc = 1;
6385 }
6386
6387 /* Allocate a struct bp_location.  */
6388
6389 static struct bp_location *
6390 allocate_bp_location (struct breakpoint *bpt)
6391 {
6392   return bpt->ops->allocate_location (bpt);
6393 }
6394
6395 static void
6396 free_bp_location (struct bp_location *loc)
6397 {
6398   loc->ops->dtor (loc);
6399   xfree (loc);
6400 }
6401
6402 /* Increment reference count.  */
6403
6404 static void
6405 incref_bp_location (struct bp_location *bl)
6406 {
6407   ++bl->refc;
6408 }
6409
6410 /* Decrement reference count.  If the reference count reaches 0,
6411    destroy the bp_location.  Sets *BLP to NULL.  */
6412
6413 static void
6414 decref_bp_location (struct bp_location **blp)
6415 {
6416   gdb_assert ((*blp)->refc > 0);
6417
6418   if (--(*blp)->refc == 0)
6419     free_bp_location (*blp);
6420   *blp = NULL;
6421 }
6422
6423 /* Add breakpoint B at the end of the global breakpoint chain.  */
6424
6425 static void
6426 add_to_breakpoint_chain (struct breakpoint *b)
6427 {
6428   struct breakpoint *b1;
6429
6430   /* Add this breakpoint to the end of the chain so that a list of
6431      breakpoints will come out in order of increasing numbers.  */
6432
6433   b1 = breakpoint_chain;
6434   if (b1 == 0)
6435     breakpoint_chain = b;
6436   else
6437     {
6438       while (b1->next)
6439         b1 = b1->next;
6440       b1->next = b;
6441     }
6442 }
6443
6444 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6445
6446 static void
6447 init_raw_breakpoint_without_location (struct breakpoint *b,
6448                                       struct gdbarch *gdbarch,
6449                                       enum bptype bptype,
6450                                       const struct breakpoint_ops *ops)
6451 {
6452   memset (b, 0, sizeof (*b));
6453
6454   gdb_assert (ops != NULL);
6455
6456   b->ops = ops;
6457   b->type = bptype;
6458   b->gdbarch = gdbarch;
6459   b->language = current_language->la_language;
6460   b->input_radix = input_radix;
6461   b->thread = -1;
6462   b->enable_state = bp_enabled;
6463   b->next = 0;
6464   b->silent = 0;
6465   b->ignore_count = 0;
6466   b->commands = NULL;
6467   b->frame_id = null_frame_id;
6468   b->condition_not_parsed = 0;
6469   b->py_bp_object = NULL;
6470   b->related_breakpoint = b;
6471 }
6472
6473 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6474    that has type BPTYPE and has no locations as yet.  */
6475
6476 static struct breakpoint *
6477 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6478                                      enum bptype bptype,
6479                                      const struct breakpoint_ops *ops)
6480 {
6481   struct breakpoint *b = XNEW (struct breakpoint);
6482
6483   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6484   add_to_breakpoint_chain (b);
6485   return b;
6486 }
6487
6488 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6489    resolutions should be made as the user specified the location explicitly
6490    enough.  */
6491
6492 static void
6493 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
6494 {
6495   gdb_assert (loc->owner != NULL);
6496
6497   if (loc->owner->type == bp_breakpoint
6498       || loc->owner->type == bp_hardware_breakpoint
6499       || is_tracepoint (loc->owner))
6500     {
6501       int is_gnu_ifunc;
6502       const char *function_name;
6503
6504       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
6505                                           NULL, NULL, &is_gnu_ifunc);
6506
6507       if (is_gnu_ifunc && !explicit_loc)
6508         {
6509           struct breakpoint *b = loc->owner;
6510
6511           gdb_assert (loc->pspace == current_program_space);
6512           if (gnu_ifunc_resolve_name (function_name,
6513                                       &loc->requested_address))
6514             {
6515               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
6516               loc->address = adjust_breakpoint_address (loc->gdbarch,
6517                                                         loc->requested_address,
6518                                                         b->type);
6519             }
6520           else if (b->type == bp_breakpoint && b->loc == loc
6521                    && loc->next == NULL && b->related_breakpoint == b)
6522             {
6523               /* Create only the whole new breakpoint of this type but do not
6524                  mess more complicated breakpoints with multiple locations.  */
6525               b->type = bp_gnu_ifunc_resolver;
6526             }
6527         }
6528
6529       if (function_name)
6530         loc->function_name = xstrdup (function_name);
6531     }
6532 }
6533
6534 /* Attempt to determine architecture of location identified by SAL.  */
6535 struct gdbarch *
6536 get_sal_arch (struct symtab_and_line sal)
6537 {
6538   if (sal.section)
6539     return get_objfile_arch (sal.section->objfile);
6540   if (sal.symtab)
6541     return get_objfile_arch (sal.symtab->objfile);
6542
6543   return NULL;
6544 }
6545
6546 /* Low level routine for partially initializing a breakpoint of type
6547    BPTYPE.  The newly created breakpoint's address, section, source
6548    file name, and line number are provided by SAL.
6549
6550    It is expected that the caller will complete the initialization of
6551    the newly created breakpoint struct as well as output any status
6552    information regarding the creation of a new breakpoint.  */
6553
6554 static void
6555 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
6556                      struct symtab_and_line sal, enum bptype bptype,
6557                      const struct breakpoint_ops *ops)
6558 {
6559   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6560
6561   add_location_to_breakpoint (b, &sal);
6562
6563   if (bptype != bp_catchpoint)
6564     gdb_assert (sal.pspace != NULL);
6565
6566   /* Store the program space that was used to set the breakpoint,
6567      except for ordinary breakpoints, which are independent of the
6568      program space.  */
6569   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
6570     b->pspace = sal.pspace;
6571
6572   breakpoints_changed ();
6573 }
6574
6575 /* set_raw_breakpoint is a low level routine for allocating and
6576    partially initializing a breakpoint of type BPTYPE.  The newly
6577    created breakpoint's address, section, source file name, and line
6578    number are provided by SAL.  The newly created and partially
6579    initialized breakpoint is added to the breakpoint chain and
6580    is also returned as the value of this function.
6581
6582    It is expected that the caller will complete the initialization of
6583    the newly created breakpoint struct as well as output any status
6584    information regarding the creation of a new breakpoint.  In
6585    particular, set_raw_breakpoint does NOT set the breakpoint
6586    number!  Care should be taken to not allow an error to occur
6587    prior to completing the initialization of the breakpoint.  If this
6588    should happen, a bogus breakpoint will be left on the chain.  */
6589
6590 struct breakpoint *
6591 set_raw_breakpoint (struct gdbarch *gdbarch,
6592                     struct symtab_and_line sal, enum bptype bptype,
6593                     const struct breakpoint_ops *ops)
6594 {
6595   struct breakpoint *b = XNEW (struct breakpoint);
6596
6597   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
6598   add_to_breakpoint_chain (b);
6599   return b;
6600 }
6601
6602
6603 /* Note that the breakpoint object B describes a permanent breakpoint
6604    instruction, hard-wired into the inferior's code.  */
6605 void
6606 make_breakpoint_permanent (struct breakpoint *b)
6607 {
6608   struct bp_location *bl;
6609
6610   b->enable_state = bp_permanent;
6611
6612   /* By definition, permanent breakpoints are already present in the
6613      code.  Mark all locations as inserted.  For now,
6614      make_breakpoint_permanent is called in just one place, so it's
6615      hard to say if it's reasonable to have permanent breakpoint with
6616      multiple locations or not, but it's easy to implement.  */
6617   for (bl = b->loc; bl; bl = bl->next)
6618     bl->inserted = 1;
6619 }
6620
6621 /* Call this routine when stepping and nexting to enable a breakpoint
6622    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
6623    initiated the operation.  */
6624
6625 void
6626 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
6627 {
6628   struct breakpoint *b, *b_tmp;
6629   int thread = tp->num;
6630
6631   /* To avoid having to rescan all objfile symbols at every step,
6632      we maintain a list of continually-inserted but always disabled
6633      longjmp "master" breakpoints.  Here, we simply create momentary
6634      clones of those and enable them for the requested thread.  */
6635   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6636     if (b->pspace == current_program_space
6637         && (b->type == bp_longjmp_master
6638             || b->type == bp_exception_master))
6639       {
6640         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
6641         struct breakpoint *clone;
6642
6643         clone = momentary_breakpoint_from_master (b, type,
6644                                                   &momentary_breakpoint_ops);
6645         clone->thread = thread;
6646       }
6647
6648   tp->initiating_frame = frame;
6649 }
6650
6651 /* Delete all longjmp breakpoints from THREAD.  */
6652 void
6653 delete_longjmp_breakpoint (int thread)
6654 {
6655   struct breakpoint *b, *b_tmp;
6656
6657   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6658     if (b->type == bp_longjmp || b->type == bp_exception)
6659       {
6660         if (b->thread == thread)
6661           delete_breakpoint (b);
6662       }
6663 }
6664
6665 void
6666 delete_longjmp_breakpoint_at_next_stop (int thread)
6667 {
6668   struct breakpoint *b, *b_tmp;
6669
6670   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6671     if (b->type == bp_longjmp || b->type == bp_exception)
6672       {
6673         if (b->thread == thread)
6674           b->disposition = disp_del_at_next_stop;
6675       }
6676 }
6677
6678 void
6679 enable_overlay_breakpoints (void)
6680 {
6681   struct breakpoint *b;
6682
6683   ALL_BREAKPOINTS (b)
6684     if (b->type == bp_overlay_event)
6685     {
6686       b->enable_state = bp_enabled;
6687       update_global_location_list (1);
6688       overlay_events_enabled = 1;
6689     }
6690 }
6691
6692 void
6693 disable_overlay_breakpoints (void)
6694 {
6695   struct breakpoint *b;
6696
6697   ALL_BREAKPOINTS (b)
6698     if (b->type == bp_overlay_event)
6699     {
6700       b->enable_state = bp_disabled;
6701       update_global_location_list (0);
6702       overlay_events_enabled = 0;
6703     }
6704 }
6705
6706 /* Set an active std::terminate breakpoint for each std::terminate
6707    master breakpoint.  */
6708 void
6709 set_std_terminate_breakpoint (void)
6710 {
6711   struct breakpoint *b, *b_tmp;
6712
6713   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6714     if (b->pspace == current_program_space
6715         && b->type == bp_std_terminate_master)
6716       {
6717         momentary_breakpoint_from_master (b, bp_std_terminate,
6718                                           &momentary_breakpoint_ops);
6719       }
6720 }
6721
6722 /* Delete all the std::terminate breakpoints.  */
6723 void
6724 delete_std_terminate_breakpoint (void)
6725 {
6726   struct breakpoint *b, *b_tmp;
6727
6728   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6729     if (b->type == bp_std_terminate)
6730       delete_breakpoint (b);
6731 }
6732
6733 struct breakpoint *
6734 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6735 {
6736   struct breakpoint *b;
6737
6738   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6739                                   &internal_breakpoint_ops);
6740
6741   b->enable_state = bp_enabled;
6742   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6743   b->addr_string
6744     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6745
6746   update_global_location_list_nothrow (1);
6747
6748   return b;
6749 }
6750
6751 void
6752 remove_thread_event_breakpoints (void)
6753 {
6754   struct breakpoint *b, *b_tmp;
6755
6756   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6757     if (b->type == bp_thread_event
6758         && b->loc->pspace == current_program_space)
6759       delete_breakpoint (b);
6760 }
6761
6762 struct lang_and_radix
6763   {
6764     enum language lang;
6765     int radix;
6766   };
6767
6768 /* Create a breakpoint for JIT code registration and unregistration.  */
6769
6770 struct breakpoint *
6771 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6772 {
6773   struct breakpoint *b;
6774
6775   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
6776                                   &internal_breakpoint_ops);
6777   update_global_location_list_nothrow (1);
6778   return b;
6779 }
6780
6781 /* Remove JIT code registration and unregistration breakpoint(s).  */
6782
6783 void
6784 remove_jit_event_breakpoints (void)
6785 {
6786   struct breakpoint *b, *b_tmp;
6787
6788   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6789     if (b->type == bp_jit_event
6790         && b->loc->pspace == current_program_space)
6791       delete_breakpoint (b);
6792 }
6793
6794 void
6795 remove_solib_event_breakpoints (void)
6796 {
6797   struct breakpoint *b, *b_tmp;
6798
6799   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6800     if (b->type == bp_shlib_event
6801         && b->loc->pspace == current_program_space)
6802       delete_breakpoint (b);
6803 }
6804
6805 struct breakpoint *
6806 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6807 {
6808   struct breakpoint *b;
6809
6810   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
6811                                   &internal_breakpoint_ops);
6812   update_global_location_list_nothrow (1);
6813   return b;
6814 }
6815
6816 /* Disable any breakpoints that are on code in shared libraries.  Only
6817    apply to enabled breakpoints, disabled ones can just stay disabled.  */
6818
6819 void
6820 disable_breakpoints_in_shlibs (void)
6821 {
6822   struct bp_location *loc, **locp_tmp;
6823
6824   ALL_BP_LOCATIONS (loc, locp_tmp)
6825   {
6826     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6827     struct breakpoint *b = loc->owner;
6828
6829     /* We apply the check to all breakpoints, including disabled for
6830        those with loc->duplicate set.  This is so that when breakpoint
6831        becomes enabled, or the duplicate is removed, gdb will try to
6832        insert all breakpoints.  If we don't set shlib_disabled here,
6833        we'll try to insert those breakpoints and fail.  */
6834     if (((b->type == bp_breakpoint)
6835          || (b->type == bp_jit_event)
6836          || (b->type == bp_hardware_breakpoint)
6837          || (is_tracepoint (b)))
6838         && loc->pspace == current_program_space
6839         && !loc->shlib_disabled
6840 #ifdef PC_SOLIB
6841         && PC_SOLIB (loc->address)
6842 #else
6843         && solib_name_from_address (loc->pspace, loc->address)
6844 #endif
6845         )
6846       {
6847         loc->shlib_disabled = 1;
6848       }
6849   }
6850 }
6851
6852 /* Disable any breakpoints and tracepoints that are in an unloaded shared
6853    library.  Only apply to enabled breakpoints, disabled ones can just stay
6854    disabled.  */
6855
6856 static void
6857 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
6858 {
6859   struct bp_location *loc, **locp_tmp;
6860   int disabled_shlib_breaks = 0;
6861
6862   /* SunOS a.out shared libraries are always mapped, so do not
6863      disable breakpoints; they will only be reported as unloaded
6864      through clear_solib when GDB discards its shared library
6865      list.  See clear_solib for more information.  */
6866   if (exec_bfd != NULL
6867       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
6868     return;
6869
6870   ALL_BP_LOCATIONS (loc, locp_tmp)
6871   {
6872     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6873     struct breakpoint *b = loc->owner;
6874
6875     if (solib->pspace == loc->pspace
6876         && !loc->shlib_disabled
6877         && (((b->type == bp_breakpoint
6878               || b->type == bp_jit_event
6879               || b->type == bp_hardware_breakpoint)
6880              && (loc->loc_type == bp_loc_hardware_breakpoint
6881                  || loc->loc_type == bp_loc_software_breakpoint))
6882             || is_tracepoint (b))
6883         && solib_contains_address_p (solib, loc->address))
6884       {
6885         loc->shlib_disabled = 1;
6886         /* At this point, we cannot rely on remove_breakpoint
6887            succeeding so we must mark the breakpoint as not inserted
6888            to prevent future errors occurring in remove_breakpoints.  */
6889         loc->inserted = 0;
6890
6891         /* This may cause duplicate notifications for the same breakpoint.  */
6892         observer_notify_breakpoint_modified (b);
6893
6894         if (!disabled_shlib_breaks)
6895           {
6896             target_terminal_ours_for_output ();
6897             warning (_("Temporarily disabling breakpoints "
6898                        "for unloaded shared library \"%s\""),
6899                      solib->so_name);
6900           }
6901         disabled_shlib_breaks = 1;
6902       }
6903   }
6904 }
6905
6906 /* FORK & VFORK catchpoints.  */
6907
6908 /* An instance of this type is used to represent a fork or vfork
6909    catchpoint.  It includes a "struct breakpoint" as a kind of base
6910    class; users downcast to "struct breakpoint *" when needed.  A
6911    breakpoint is really of this type iff its ops pointer points to
6912    CATCH_FORK_BREAKPOINT_OPS.  */
6913
6914 struct fork_catchpoint
6915 {
6916   /* The base class.  */
6917   struct breakpoint base;
6918
6919   /* Process id of a child process whose forking triggered this
6920      catchpoint.  This field is only valid immediately after this
6921      catchpoint has triggered.  */
6922   ptid_t forked_inferior_pid;
6923 };
6924
6925 /* Implement the "insert" breakpoint_ops method for fork
6926    catchpoints.  */
6927
6928 static int
6929 insert_catch_fork (struct bp_location *bl)
6930 {
6931   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
6932 }
6933
6934 /* Implement the "remove" breakpoint_ops method for fork
6935    catchpoints.  */
6936
6937 static int
6938 remove_catch_fork (struct bp_location *bl)
6939 {
6940   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
6941 }
6942
6943 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
6944    catchpoints.  */
6945
6946 static int
6947 breakpoint_hit_catch_fork (const struct bp_location *bl,
6948                            struct address_space *aspace, CORE_ADDR bp_addr,
6949                            const struct target_waitstatus *ws)
6950 {
6951   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6952
6953   if (ws->kind != TARGET_WAITKIND_FORKED)
6954     return 0;
6955
6956   c->forked_inferior_pid = ws->value.related_pid;
6957   return 1;
6958 }
6959
6960 /* Implement the "print_it" breakpoint_ops method for fork
6961    catchpoints.  */
6962
6963 static enum print_stop_action
6964 print_it_catch_fork (bpstat bs)
6965 {
6966   struct ui_out *uiout = current_uiout;
6967   struct breakpoint *b = bs->breakpoint_at;
6968   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
6969
6970   annotate_catchpoint (b->number);
6971   if (b->disposition == disp_del)
6972     ui_out_text (uiout, "\nTemporary catchpoint ");
6973   else
6974     ui_out_text (uiout, "\nCatchpoint ");
6975   if (ui_out_is_mi_like_p (uiout))
6976     {
6977       ui_out_field_string (uiout, "reason",
6978                            async_reason_lookup (EXEC_ASYNC_FORK));
6979       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6980     }
6981   ui_out_field_int (uiout, "bkptno", b->number);
6982   ui_out_text (uiout, " (forked process ");
6983   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6984   ui_out_text (uiout, "), ");
6985   return PRINT_SRC_AND_LOC;
6986 }
6987
6988 /* Implement the "print_one" breakpoint_ops method for fork
6989    catchpoints.  */
6990
6991 static void
6992 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
6993 {
6994   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6995   struct value_print_options opts;
6996   struct ui_out *uiout = current_uiout;
6997
6998   get_user_print_options (&opts);
6999
7000   /* Field 4, the address, is omitted (which makes the columns not
7001      line up too nicely with the headers, but the effect is relatively
7002      readable).  */
7003   if (opts.addressprint)
7004     ui_out_field_skip (uiout, "addr");
7005   annotate_field (5);
7006   ui_out_text (uiout, "fork");
7007   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7008     {
7009       ui_out_text (uiout, ", process ");
7010       ui_out_field_int (uiout, "what",
7011                         ptid_get_pid (c->forked_inferior_pid));
7012       ui_out_spaces (uiout, 1);
7013     }
7014 }
7015
7016 /* Implement the "print_mention" breakpoint_ops method for fork
7017    catchpoints.  */
7018
7019 static void
7020 print_mention_catch_fork (struct breakpoint *b)
7021 {
7022   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7023 }
7024
7025 /* Implement the "print_recreate" breakpoint_ops method for fork
7026    catchpoints.  */
7027
7028 static void
7029 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7030 {
7031   fprintf_unfiltered (fp, "catch fork");
7032   print_recreate_thread (b, fp);
7033 }
7034
7035 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7036
7037 static struct breakpoint_ops catch_fork_breakpoint_ops;
7038
7039 /* Implement the "insert" breakpoint_ops method for vfork
7040    catchpoints.  */
7041
7042 static int
7043 insert_catch_vfork (struct bp_location *bl)
7044 {
7045   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7046 }
7047
7048 /* Implement the "remove" breakpoint_ops method for vfork
7049    catchpoints.  */
7050
7051 static int
7052 remove_catch_vfork (struct bp_location *bl)
7053 {
7054   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7055 }
7056
7057 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7058    catchpoints.  */
7059
7060 static int
7061 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7062                             struct address_space *aspace, CORE_ADDR bp_addr,
7063                             const struct target_waitstatus *ws)
7064 {
7065   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7066
7067   if (ws->kind != TARGET_WAITKIND_VFORKED)
7068     return 0;
7069
7070   c->forked_inferior_pid = ws->value.related_pid;
7071   return 1;
7072 }
7073
7074 /* Implement the "print_it" breakpoint_ops method for vfork
7075    catchpoints.  */
7076
7077 static enum print_stop_action
7078 print_it_catch_vfork (bpstat bs)
7079 {
7080   struct ui_out *uiout = current_uiout;
7081   struct breakpoint *b = bs->breakpoint_at;
7082   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7083
7084   annotate_catchpoint (b->number);
7085   if (b->disposition == disp_del)
7086     ui_out_text (uiout, "\nTemporary catchpoint ");
7087   else
7088     ui_out_text (uiout, "\nCatchpoint ");
7089   if (ui_out_is_mi_like_p (uiout))
7090     {
7091       ui_out_field_string (uiout, "reason",
7092                            async_reason_lookup (EXEC_ASYNC_VFORK));
7093       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7094     }
7095   ui_out_field_int (uiout, "bkptno", b->number);
7096   ui_out_text (uiout, " (vforked process ");
7097   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7098   ui_out_text (uiout, "), ");
7099   return PRINT_SRC_AND_LOC;
7100 }
7101
7102 /* Implement the "print_one" breakpoint_ops method for vfork
7103    catchpoints.  */
7104
7105 static void
7106 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7107 {
7108   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7109   struct value_print_options opts;
7110   struct ui_out *uiout = current_uiout;
7111
7112   get_user_print_options (&opts);
7113   /* Field 4, the address, is omitted (which makes the columns not
7114      line up too nicely with the headers, but the effect is relatively
7115      readable).  */
7116   if (opts.addressprint)
7117     ui_out_field_skip (uiout, "addr");
7118   annotate_field (5);
7119   ui_out_text (uiout, "vfork");
7120   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7121     {
7122       ui_out_text (uiout, ", process ");
7123       ui_out_field_int (uiout, "what",
7124                         ptid_get_pid (c->forked_inferior_pid));
7125       ui_out_spaces (uiout, 1);
7126     }
7127 }
7128
7129 /* Implement the "print_mention" breakpoint_ops method for vfork
7130    catchpoints.  */
7131
7132 static void
7133 print_mention_catch_vfork (struct breakpoint *b)
7134 {
7135   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7136 }
7137
7138 /* Implement the "print_recreate" breakpoint_ops method for vfork
7139    catchpoints.  */
7140
7141 static void
7142 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7143 {
7144   fprintf_unfiltered (fp, "catch vfork");
7145   print_recreate_thread (b, fp);
7146 }
7147
7148 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7149
7150 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7151
7152 /* An instance of this type is used to represent an solib catchpoint.
7153    It includes a "struct breakpoint" as a kind of base class; users
7154    downcast to "struct breakpoint *" when needed.  A breakpoint is
7155    really of this type iff its ops pointer points to
7156    CATCH_SOLIB_BREAKPOINT_OPS.  */
7157
7158 struct solib_catchpoint
7159 {
7160   /* The base class.  */
7161   struct breakpoint base;
7162
7163   /* True for "catch load", false for "catch unload".  */
7164   unsigned char is_load;
7165
7166   /* Regular expression to match, if any.  COMPILED is only valid when
7167      REGEX is non-NULL.  */
7168   char *regex;
7169   regex_t compiled;
7170 };
7171
7172 static void
7173 dtor_catch_solib (struct breakpoint *b)
7174 {
7175   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7176
7177   if (self->regex)
7178     regfree (&self->compiled);
7179   xfree (self->regex);
7180
7181   base_breakpoint_ops.dtor (b);
7182 }
7183
7184 static int
7185 insert_catch_solib (struct bp_location *ignore)
7186 {
7187   return 0;
7188 }
7189
7190 static int
7191 remove_catch_solib (struct bp_location *ignore)
7192 {
7193   return 0;
7194 }
7195
7196 static int
7197 breakpoint_hit_catch_solib (const struct bp_location *bl,
7198                             struct address_space *aspace,
7199                             CORE_ADDR bp_addr,
7200                             const struct target_waitstatus *ws)
7201 {
7202   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7203   struct breakpoint *other;
7204
7205   if (ws->kind == TARGET_WAITKIND_LOADED)
7206     return 1;
7207
7208   ALL_BREAKPOINTS (other)
7209   {
7210     struct bp_location *other_bl;
7211
7212     if (other == bl->owner)
7213       continue;
7214
7215     if (other->type != bp_shlib_event)
7216       continue;
7217
7218     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7219       continue;
7220
7221     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7222       {
7223         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7224           return 1;
7225       }
7226   }
7227
7228   return 0;
7229 }
7230
7231 static void
7232 check_status_catch_solib (struct bpstats *bs)
7233 {
7234   struct solib_catchpoint *self
7235     = (struct solib_catchpoint *) bs->breakpoint_at;
7236   int ix;
7237
7238   if (self->is_load)
7239     {
7240       struct so_list *iter;
7241
7242       for (ix = 0;
7243            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7244                         ix, iter);
7245            ++ix)
7246         {
7247           if (!self->regex
7248               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7249             return;
7250         }
7251     }
7252   else
7253     {
7254       char *iter;
7255
7256       for (ix = 0;
7257            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7258                         ix, iter);
7259            ++ix)
7260         {
7261           if (!self->regex
7262               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7263             return;
7264         }
7265     }
7266
7267   bs->stop = 0;
7268   bs->print_it = print_it_noop;
7269 }
7270
7271 static enum print_stop_action
7272 print_it_catch_solib (bpstat bs)
7273 {
7274   struct breakpoint *b = bs->breakpoint_at;
7275   struct ui_out *uiout = current_uiout;
7276
7277   annotate_catchpoint (b->number);
7278   if (b->disposition == disp_del)
7279     ui_out_text (uiout, "\nTemporary catchpoint ");
7280   else
7281     ui_out_text (uiout, "\nCatchpoint ");
7282   ui_out_field_int (uiout, "bkptno", b->number);
7283   ui_out_text (uiout, "\n");
7284   if (ui_out_is_mi_like_p (uiout))
7285     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7286   print_solib_event (1);
7287   return PRINT_SRC_AND_LOC;
7288 }
7289
7290 static void
7291 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7292 {
7293   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7294   struct value_print_options opts;
7295   struct ui_out *uiout = current_uiout;
7296   char *msg;
7297
7298   get_user_print_options (&opts);
7299   /* Field 4, the address, is omitted (which makes the columns not
7300      line up too nicely with the headers, but the effect is relatively
7301      readable).  */
7302   if (opts.addressprint)
7303     {
7304       annotate_field (4);
7305       ui_out_field_skip (uiout, "addr");
7306     }
7307
7308   annotate_field (5);
7309   if (self->is_load)
7310     {
7311       if (self->regex)
7312         msg = xstrprintf (_("load of library matching %s"), self->regex);
7313       else
7314         msg = xstrdup (_("load of library"));
7315     }
7316   else
7317     {
7318       if (self->regex)
7319         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7320       else
7321         msg = xstrdup (_("unload of library"));
7322     }
7323   ui_out_field_string (uiout, "what", msg);
7324   xfree (msg);
7325 }
7326
7327 static void
7328 print_mention_catch_solib (struct breakpoint *b)
7329 {
7330   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7331
7332   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7333                    self->is_load ? "load" : "unload");
7334 }
7335
7336 static void
7337 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7338 {
7339   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7340
7341   fprintf_unfiltered (fp, "%s %s",
7342                       b->disposition == disp_del ? "tcatch" : "catch",
7343                       self->is_load ? "load" : "unload");
7344   if (self->regex)
7345     fprintf_unfiltered (fp, " %s", self->regex);
7346   fprintf_unfiltered (fp, "\n");
7347 }
7348
7349 static struct breakpoint_ops catch_solib_breakpoint_ops;
7350
7351 /* A helper function that does all the work for "catch load" and
7352    "catch unload".  */
7353
7354 static void
7355 catch_load_or_unload (char *arg, int from_tty, int is_load,
7356                       struct cmd_list_element *command)
7357 {
7358   struct solib_catchpoint *c;
7359   struct gdbarch *gdbarch = get_current_arch ();
7360   int tempflag;
7361   regex_t compiled;
7362   struct cleanup *cleanup;
7363
7364   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7365
7366   if (!arg)
7367     arg = "";
7368   arg = skip_spaces (arg);
7369
7370   c = XCNEW (struct solib_catchpoint);
7371   cleanup = make_cleanup (xfree, c);
7372
7373   if (*arg != '\0')
7374     {
7375       int errcode;
7376
7377       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7378       if (errcode != 0)
7379         {
7380           char *err = get_regcomp_error (errcode, &c->compiled);
7381
7382           make_cleanup (xfree, err);
7383           error (_("Invalid regexp (%s): %s"), err, arg);
7384         }
7385       c->regex = xstrdup (arg);
7386     }
7387
7388   c->is_load = is_load;
7389   init_catchpoint (&c->base, gdbarch, tempflag, NULL,
7390                    &catch_solib_breakpoint_ops);
7391
7392   discard_cleanups (cleanup);
7393   install_breakpoint (0, &c->base, 1);
7394 }
7395
7396 static void
7397 catch_load_command_1 (char *arg, int from_tty,
7398                       struct cmd_list_element *command)
7399 {
7400   catch_load_or_unload (arg, from_tty, 1, command);
7401 }
7402
7403 static void
7404 catch_unload_command_1 (char *arg, int from_tty,
7405                         struct cmd_list_element *command)
7406 {
7407   catch_load_or_unload (arg, from_tty, 0, command);
7408 }
7409
7410 DEF_VEC_I(int);
7411
7412 /* An instance of this type is used to represent a syscall catchpoint.
7413    It includes a "struct breakpoint" as a kind of base class; users
7414    downcast to "struct breakpoint *" when needed.  A breakpoint is
7415    really of this type iff its ops pointer points to
7416    CATCH_SYSCALL_BREAKPOINT_OPS.  */
7417
7418 struct syscall_catchpoint
7419 {
7420   /* The base class.  */
7421   struct breakpoint base;
7422
7423   /* Syscall numbers used for the 'catch syscall' feature.  If no
7424      syscall has been specified for filtering, its value is NULL.
7425      Otherwise, it holds a list of all syscalls to be caught.  The
7426      list elements are allocated with xmalloc.  */
7427   VEC(int) *syscalls_to_be_caught;
7428 };
7429
7430 /* Implement the "dtor" breakpoint_ops method for syscall
7431    catchpoints.  */
7432
7433 static void
7434 dtor_catch_syscall (struct breakpoint *b)
7435 {
7436   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7437
7438   VEC_free (int, c->syscalls_to_be_caught);
7439
7440   base_breakpoint_ops.dtor (b);
7441 }
7442
7443 static const struct inferior_data *catch_syscall_inferior_data = NULL;
7444
7445 struct catch_syscall_inferior_data
7446 {
7447   /* We keep a count of the number of times the user has requested a
7448      particular syscall to be tracked, and pass this information to the
7449      target.  This lets capable targets implement filtering directly.  */
7450
7451   /* Number of times that "any" syscall is requested.  */
7452   int any_syscall_count;
7453
7454   /* Count of each system call.  */
7455   VEC(int) *syscalls_counts;
7456
7457   /* This counts all syscall catch requests, so we can readily determine
7458      if any catching is necessary.  */
7459   int total_syscalls_count;
7460 };
7461
7462 static struct catch_syscall_inferior_data*
7463 get_catch_syscall_inferior_data (struct inferior *inf)
7464 {
7465   struct catch_syscall_inferior_data *inf_data;
7466
7467   inf_data = inferior_data (inf, catch_syscall_inferior_data);
7468   if (inf_data == NULL)
7469     {
7470       inf_data = XZALLOC (struct catch_syscall_inferior_data);
7471       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
7472     }
7473
7474   return inf_data;
7475 }
7476
7477 static void
7478 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
7479 {
7480   xfree (arg);
7481 }
7482
7483
7484 /* Implement the "insert" breakpoint_ops method for syscall
7485    catchpoints.  */
7486
7487 static int
7488 insert_catch_syscall (struct bp_location *bl)
7489 {
7490   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7491   struct inferior *inf = current_inferior ();
7492   struct catch_syscall_inferior_data *inf_data
7493     = get_catch_syscall_inferior_data (inf);
7494
7495   ++inf_data->total_syscalls_count;
7496   if (!c->syscalls_to_be_caught)
7497     ++inf_data->any_syscall_count;
7498   else
7499     {
7500       int i, iter;
7501
7502       for (i = 0;
7503            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7504            i++)
7505         {
7506           int elem;
7507
7508           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7509             {
7510               int old_size = VEC_length (int, inf_data->syscalls_counts);
7511               uintptr_t vec_addr_offset
7512                 = old_size * ((uintptr_t) sizeof (int));
7513               uintptr_t vec_addr;
7514               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
7515               vec_addr = ((uintptr_t) VEC_address (int,
7516                                                   inf_data->syscalls_counts)
7517                           + vec_addr_offset);
7518               memset ((void *) vec_addr, 0,
7519                       (iter + 1 - old_size) * sizeof (int));
7520             }
7521           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7522           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
7523         }
7524     }
7525
7526   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7527                                         inf_data->total_syscalls_count != 0,
7528                                         inf_data->any_syscall_count,
7529                                         VEC_length (int,
7530                                                     inf_data->syscalls_counts),
7531                                         VEC_address (int,
7532                                                      inf_data->syscalls_counts));
7533 }
7534
7535 /* Implement the "remove" breakpoint_ops method for syscall
7536    catchpoints.  */
7537
7538 static int
7539 remove_catch_syscall (struct bp_location *bl)
7540 {
7541   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7542   struct inferior *inf = current_inferior ();
7543   struct catch_syscall_inferior_data *inf_data
7544     = get_catch_syscall_inferior_data (inf);
7545
7546   --inf_data->total_syscalls_count;
7547   if (!c->syscalls_to_be_caught)
7548     --inf_data->any_syscall_count;
7549   else
7550     {
7551       int i, iter;
7552
7553       for (i = 0;
7554            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7555            i++)
7556         {
7557           int elem;
7558           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7559             /* Shouldn't happen.  */
7560             continue;
7561           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7562           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
7563         }
7564     }
7565
7566   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7567                                         inf_data->total_syscalls_count != 0,
7568                                         inf_data->any_syscall_count,
7569                                         VEC_length (int,
7570                                                     inf_data->syscalls_counts),
7571                                         VEC_address (int,
7572                                                      inf_data->syscalls_counts));
7573 }
7574
7575 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
7576    catchpoints.  */
7577
7578 static int
7579 breakpoint_hit_catch_syscall (const struct bp_location *bl,
7580                               struct address_space *aspace, CORE_ADDR bp_addr,
7581                               const struct target_waitstatus *ws)
7582 {
7583   /* We must check if we are catching specific syscalls in this
7584      breakpoint.  If we are, then we must guarantee that the called
7585      syscall is the same syscall we are catching.  */
7586   int syscall_number = 0;
7587   const struct syscall_catchpoint *c
7588     = (const struct syscall_catchpoint *) bl->owner;
7589
7590   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
7591       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
7592     return 0;
7593
7594   syscall_number = ws->value.syscall_number;
7595
7596   /* Now, checking if the syscall is the same.  */
7597   if (c->syscalls_to_be_caught)
7598     {
7599       int i, iter;
7600
7601       for (i = 0;
7602            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7603            i++)
7604         if (syscall_number == iter)
7605           break;
7606       /* Not the same.  */
7607       if (!iter)
7608         return 0;
7609     }
7610
7611   return 1;
7612 }
7613
7614 /* Implement the "print_it" breakpoint_ops method for syscall
7615    catchpoints.  */
7616
7617 static enum print_stop_action
7618 print_it_catch_syscall (bpstat bs)
7619 {
7620   struct ui_out *uiout = current_uiout;
7621   struct breakpoint *b = bs->breakpoint_at;
7622   /* These are needed because we want to know in which state a
7623      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
7624      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
7625      must print "called syscall" or "returned from syscall".  */
7626   ptid_t ptid;
7627   struct target_waitstatus last;
7628   struct syscall s;
7629   char *syscall_id;
7630
7631   get_last_target_status (&ptid, &last);
7632
7633   get_syscall_by_number (last.value.syscall_number, &s);
7634
7635   annotate_catchpoint (b->number);
7636
7637   if (b->disposition == disp_del)
7638     ui_out_text (uiout, "\nTemporary catchpoint ");
7639   else
7640     ui_out_text (uiout, "\nCatchpoint ");
7641   if (ui_out_is_mi_like_p (uiout))
7642     {
7643       ui_out_field_string (uiout, "reason",
7644                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
7645                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
7646                                                 : EXEC_ASYNC_SYSCALL_RETURN));
7647       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7648     }
7649   ui_out_field_int (uiout, "bkptno", b->number);
7650
7651   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
7652     ui_out_text (uiout, " (call to syscall ");
7653   else
7654     ui_out_text (uiout, " (returned from syscall ");
7655
7656   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
7657     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
7658   if (s.name != NULL)
7659     ui_out_field_string (uiout, "syscall-name", s.name);
7660
7661   ui_out_text (uiout, "), ");
7662
7663   return PRINT_SRC_AND_LOC;
7664 }
7665
7666 /* Implement the "print_one" breakpoint_ops method for syscall
7667    catchpoints.  */
7668
7669 static void
7670 print_one_catch_syscall (struct breakpoint *b,
7671                          struct bp_location **last_loc)
7672 {
7673   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7674   struct value_print_options opts;
7675   struct ui_out *uiout = current_uiout;
7676
7677   get_user_print_options (&opts);
7678   /* Field 4, the address, is omitted (which makes the columns not
7679      line up too nicely with the headers, but the effect is relatively
7680      readable).  */
7681   if (opts.addressprint)
7682     ui_out_field_skip (uiout, "addr");
7683   annotate_field (5);
7684
7685   if (c->syscalls_to_be_caught
7686       && VEC_length (int, c->syscalls_to_be_caught) > 1)
7687     ui_out_text (uiout, "syscalls \"");
7688   else
7689     ui_out_text (uiout, "syscall \"");
7690
7691   if (c->syscalls_to_be_caught)
7692     {
7693       int i, iter;
7694       char *text = xstrprintf ("%s", "");
7695
7696       for (i = 0;
7697            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7698            i++)
7699         {
7700           char *x = text;
7701           struct syscall s;
7702           get_syscall_by_number (iter, &s);
7703
7704           if (s.name != NULL)
7705             text = xstrprintf ("%s%s, ", text, s.name);
7706           else
7707             text = xstrprintf ("%s%d, ", text, iter);
7708
7709           /* We have to xfree the last 'text' (now stored at 'x')
7710              because xstrprintf dynamically allocates new space for it
7711              on every call.  */
7712           xfree (x);
7713         }
7714       /* Remove the last comma.  */
7715       text[strlen (text) - 2] = '\0';
7716       ui_out_field_string (uiout, "what", text);
7717     }
7718   else
7719     ui_out_field_string (uiout, "what", "<any syscall>");
7720   ui_out_text (uiout, "\" ");
7721 }
7722
7723 /* Implement the "print_mention" breakpoint_ops method for syscall
7724    catchpoints.  */
7725
7726 static void
7727 print_mention_catch_syscall (struct breakpoint *b)
7728 {
7729   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7730
7731   if (c->syscalls_to_be_caught)
7732     {
7733       int i, iter;
7734
7735       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
7736         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
7737       else
7738         printf_filtered (_("Catchpoint %d (syscall"), b->number);
7739
7740       for (i = 0;
7741            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7742            i++)
7743         {
7744           struct syscall s;
7745           get_syscall_by_number (iter, &s);
7746
7747           if (s.name)
7748             printf_filtered (" '%s' [%d]", s.name, s.number);
7749           else
7750             printf_filtered (" %d", s.number);
7751         }
7752       printf_filtered (")");
7753     }
7754   else
7755     printf_filtered (_("Catchpoint %d (any syscall)"),
7756                      b->number);
7757 }
7758
7759 /* Implement the "print_recreate" breakpoint_ops method for syscall
7760    catchpoints.  */
7761
7762 static void
7763 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
7764 {
7765   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7766
7767   fprintf_unfiltered (fp, "catch syscall");
7768
7769   if (c->syscalls_to_be_caught)
7770     {
7771       int i, iter;
7772
7773       for (i = 0;
7774            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7775            i++)
7776         {
7777           struct syscall s;
7778
7779           get_syscall_by_number (iter, &s);
7780           if (s.name)
7781             fprintf_unfiltered (fp, " %s", s.name);
7782           else
7783             fprintf_unfiltered (fp, " %d", s.number);
7784         }
7785     }
7786   print_recreate_thread (b, fp);
7787 }
7788
7789 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
7790
7791 static struct breakpoint_ops catch_syscall_breakpoint_ops;
7792
7793 /* Returns non-zero if 'b' is a syscall catchpoint.  */
7794
7795 static int
7796 syscall_catchpoint_p (struct breakpoint *b)
7797 {
7798   return (b->ops == &catch_syscall_breakpoint_ops);
7799 }
7800
7801 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
7802    is non-zero, then make the breakpoint temporary.  If COND_STRING is
7803    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
7804    the breakpoint_ops structure associated to the catchpoint.  */
7805
7806 static void
7807 init_catchpoint (struct breakpoint *b,
7808                  struct gdbarch *gdbarch, int tempflag,
7809                  char *cond_string,
7810                  const struct breakpoint_ops *ops)
7811 {
7812   struct symtab_and_line sal;
7813
7814   init_sal (&sal);
7815   sal.pspace = current_program_space;
7816
7817   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
7818
7819   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
7820   b->disposition = tempflag ? disp_del : disp_donttouch;
7821 }
7822
7823 void
7824 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
7825 {
7826   add_to_breakpoint_chain (b);
7827   set_breakpoint_number (internal, b);
7828   if (!internal)
7829     mention (b);
7830   observer_notify_breakpoint_created (b);
7831
7832   if (update_gll)
7833     update_global_location_list (1);
7834 }
7835
7836 static void
7837 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
7838                                     int tempflag, char *cond_string,
7839                                     const struct breakpoint_ops *ops)
7840 {
7841   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
7842
7843   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
7844
7845   c->forked_inferior_pid = null_ptid;
7846
7847   install_breakpoint (0, &c->base, 1);
7848 }
7849
7850 /* Exec catchpoints.  */
7851
7852 /* An instance of this type is used to represent an exec catchpoint.
7853    It includes a "struct breakpoint" as a kind of base class; users
7854    downcast to "struct breakpoint *" when needed.  A breakpoint is
7855    really of this type iff its ops pointer points to
7856    CATCH_EXEC_BREAKPOINT_OPS.  */
7857
7858 struct exec_catchpoint
7859 {
7860   /* The base class.  */
7861   struct breakpoint base;
7862
7863   /* Filename of a program whose exec triggered this catchpoint.
7864      This field is only valid immediately after this catchpoint has
7865      triggered.  */
7866   char *exec_pathname;
7867 };
7868
7869 /* Implement the "dtor" breakpoint_ops method for exec
7870    catchpoints.  */
7871
7872 static void
7873 dtor_catch_exec (struct breakpoint *b)
7874 {
7875   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7876
7877   xfree (c->exec_pathname);
7878
7879   base_breakpoint_ops.dtor (b);
7880 }
7881
7882 static int
7883 insert_catch_exec (struct bp_location *bl)
7884 {
7885   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
7886 }
7887
7888 static int
7889 remove_catch_exec (struct bp_location *bl)
7890 {
7891   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
7892 }
7893
7894 static int
7895 breakpoint_hit_catch_exec (const struct bp_location *bl,
7896                            struct address_space *aspace, CORE_ADDR bp_addr,
7897                            const struct target_waitstatus *ws)
7898 {
7899   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
7900
7901   if (ws->kind != TARGET_WAITKIND_EXECD)
7902     return 0;
7903
7904   c->exec_pathname = xstrdup (ws->value.execd_pathname);
7905   return 1;
7906 }
7907
7908 static enum print_stop_action
7909 print_it_catch_exec (bpstat bs)
7910 {
7911   struct ui_out *uiout = current_uiout;
7912   struct breakpoint *b = bs->breakpoint_at;
7913   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7914
7915   annotate_catchpoint (b->number);
7916   if (b->disposition == disp_del)
7917     ui_out_text (uiout, "\nTemporary catchpoint ");
7918   else
7919     ui_out_text (uiout, "\nCatchpoint ");
7920   if (ui_out_is_mi_like_p (uiout))
7921     {
7922       ui_out_field_string (uiout, "reason",
7923                            async_reason_lookup (EXEC_ASYNC_EXEC));
7924       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7925     }
7926   ui_out_field_int (uiout, "bkptno", b->number);
7927   ui_out_text (uiout, " (exec'd ");
7928   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
7929   ui_out_text (uiout, "), ");
7930
7931   return PRINT_SRC_AND_LOC;
7932 }
7933
7934 static void
7935 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
7936 {
7937   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7938   struct value_print_options opts;
7939   struct ui_out *uiout = current_uiout;
7940
7941   get_user_print_options (&opts);
7942
7943   /* Field 4, the address, is omitted (which makes the columns
7944      not line up too nicely with the headers, but the effect
7945      is relatively readable).  */
7946   if (opts.addressprint)
7947     ui_out_field_skip (uiout, "addr");
7948   annotate_field (5);
7949   ui_out_text (uiout, "exec");
7950   if (c->exec_pathname != NULL)
7951     {
7952       ui_out_text (uiout, ", program \"");
7953       ui_out_field_string (uiout, "what", c->exec_pathname);
7954       ui_out_text (uiout, "\" ");
7955     }
7956 }
7957
7958 static void
7959 print_mention_catch_exec (struct breakpoint *b)
7960 {
7961   printf_filtered (_("Catchpoint %d (exec)"), b->number);
7962 }
7963
7964 /* Implement the "print_recreate" breakpoint_ops method for exec
7965    catchpoints.  */
7966
7967 static void
7968 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
7969 {
7970   fprintf_unfiltered (fp, "catch exec");
7971   print_recreate_thread (b, fp);
7972 }
7973
7974 static struct breakpoint_ops catch_exec_breakpoint_ops;
7975
7976 static void
7977 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
7978                                  const struct breakpoint_ops *ops)
7979 {
7980   struct syscall_catchpoint *c;
7981   struct gdbarch *gdbarch = get_current_arch ();
7982
7983   c = XNEW (struct syscall_catchpoint);
7984   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
7985   c->syscalls_to_be_caught = filter;
7986
7987   install_breakpoint (0, &c->base, 1);
7988 }
7989
7990 static int
7991 hw_breakpoint_used_count (void)
7992 {
7993   int i = 0;
7994   struct breakpoint *b;
7995   struct bp_location *bl;
7996
7997   ALL_BREAKPOINTS (b)
7998   {
7999     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8000       for (bl = b->loc; bl; bl = bl->next)
8001         {
8002           /* Special types of hardware breakpoints may use more than
8003              one register.  */
8004           i += b->ops->resources_needed (bl);
8005         }
8006   }
8007
8008   return i;
8009 }
8010
8011 /* Returns the resources B would use if it were a hardware
8012    watchpoint.  */
8013
8014 static int
8015 hw_watchpoint_use_count (struct breakpoint *b)
8016 {
8017   int i = 0;
8018   struct bp_location *bl;
8019
8020   if (!breakpoint_enabled (b))
8021     return 0;
8022
8023   for (bl = b->loc; bl; bl = bl->next)
8024     {
8025       /* Special types of hardware watchpoints may use more than
8026          one register.  */
8027       i += b->ops->resources_needed (bl);
8028     }
8029
8030   return i;
8031 }
8032
8033 /* Returns the sum the used resources of all hardware watchpoints of
8034    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8035    the sum of the used resources of all hardware watchpoints of other
8036    types _not_ TYPE.  */
8037
8038 static int
8039 hw_watchpoint_used_count_others (struct breakpoint *except,
8040                                  enum bptype type, int *other_type_used)
8041 {
8042   int i = 0;
8043   struct breakpoint *b;
8044
8045   *other_type_used = 0;
8046   ALL_BREAKPOINTS (b)
8047     {
8048       if (b == except)
8049         continue;
8050       if (!breakpoint_enabled (b))
8051         continue;
8052
8053       if (b->type == type)
8054         i += hw_watchpoint_use_count (b);
8055       else if (is_hardware_watchpoint (b))
8056         *other_type_used = 1;
8057     }
8058
8059   return i;
8060 }
8061
8062 void
8063 disable_watchpoints_before_interactive_call_start (void)
8064 {
8065   struct breakpoint *b;
8066
8067   ALL_BREAKPOINTS (b)
8068   {
8069     if (is_watchpoint (b) && breakpoint_enabled (b))
8070       {
8071         b->enable_state = bp_call_disabled;
8072         update_global_location_list (0);
8073       }
8074   }
8075 }
8076
8077 void
8078 enable_watchpoints_after_interactive_call_stop (void)
8079 {
8080   struct breakpoint *b;
8081
8082   ALL_BREAKPOINTS (b)
8083   {
8084     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8085       {
8086         b->enable_state = bp_enabled;
8087         update_global_location_list (1);
8088       }
8089   }
8090 }
8091
8092 void
8093 disable_breakpoints_before_startup (void)
8094 {
8095   current_program_space->executing_startup = 1;
8096   update_global_location_list (0);
8097 }
8098
8099 void
8100 enable_breakpoints_after_startup (void)
8101 {
8102   current_program_space->executing_startup = 0;
8103   breakpoint_re_set ();
8104 }
8105
8106
8107 /* Set a breakpoint that will evaporate an end of command
8108    at address specified by SAL.
8109    Restrict it to frame FRAME if FRAME is nonzero.  */
8110
8111 struct breakpoint *
8112 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8113                           struct frame_id frame_id, enum bptype type)
8114 {
8115   struct breakpoint *b;
8116
8117   /* If FRAME_ID is valid, it should be a real frame, not an inlined
8118      one.  */
8119   gdb_assert (!frame_id_inlined_p (frame_id));
8120
8121   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8122   b->enable_state = bp_enabled;
8123   b->disposition = disp_donttouch;
8124   b->frame_id = frame_id;
8125
8126   /* If we're debugging a multi-threaded program, then we want
8127      momentary breakpoints to be active in only a single thread of
8128      control.  */
8129   if (in_thread_list (inferior_ptid))
8130     b->thread = pid_to_thread_id (inferior_ptid);
8131
8132   update_global_location_list_nothrow (1);
8133
8134   return b;
8135 }
8136
8137 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8138    The new breakpoint will have type TYPE, and use OPS as it
8139    breakpoint_ops.  */
8140
8141 static struct breakpoint *
8142 momentary_breakpoint_from_master (struct breakpoint *orig,
8143                                   enum bptype type,
8144                                   const struct breakpoint_ops *ops)
8145 {
8146   struct breakpoint *copy;
8147
8148   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8149   copy->loc = allocate_bp_location (copy);
8150   set_breakpoint_location_function (copy->loc, 1);
8151
8152   copy->loc->gdbarch = orig->loc->gdbarch;
8153   copy->loc->requested_address = orig->loc->requested_address;
8154   copy->loc->address = orig->loc->address;
8155   copy->loc->section = orig->loc->section;
8156   copy->loc->pspace = orig->loc->pspace;
8157   copy->loc->probe = orig->loc->probe;
8158
8159   if (orig->loc->source_file != NULL)
8160     copy->loc->source_file = xstrdup (orig->loc->source_file);
8161
8162   copy->loc->line_number = orig->loc->line_number;
8163   copy->frame_id = orig->frame_id;
8164   copy->thread = orig->thread;
8165   copy->pspace = orig->pspace;
8166
8167   copy->enable_state = bp_enabled;
8168   copy->disposition = disp_donttouch;
8169   copy->number = internal_breakpoint_number--;
8170
8171   update_global_location_list_nothrow (0);
8172   return copy;
8173 }
8174
8175 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8176    ORIG is NULL.  */
8177
8178 struct breakpoint *
8179 clone_momentary_breakpoint (struct breakpoint *orig)
8180 {
8181   /* If there's nothing to clone, then return nothing.  */
8182   if (orig == NULL)
8183     return NULL;
8184
8185   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8186 }
8187
8188 struct breakpoint *
8189 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8190                                 enum bptype type)
8191 {
8192   struct symtab_and_line sal;
8193
8194   sal = find_pc_line (pc, 0);
8195   sal.pc = pc;
8196   sal.section = find_pc_overlay (pc);
8197   sal.explicit_pc = 1;
8198
8199   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8200 }
8201 \f
8202
8203 /* Tell the user we have just set a breakpoint B.  */
8204
8205 static void
8206 mention (struct breakpoint *b)
8207 {
8208   b->ops->print_mention (b);
8209   if (ui_out_is_mi_like_p (current_uiout))
8210     return;
8211   printf_filtered ("\n");
8212 }
8213 \f
8214
8215 static struct bp_location *
8216 add_location_to_breakpoint (struct breakpoint *b,
8217                             const struct symtab_and_line *sal)
8218 {
8219   struct bp_location *loc, **tmp;
8220   CORE_ADDR adjusted_address;
8221   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8222
8223   if (loc_gdbarch == NULL)
8224     loc_gdbarch = b->gdbarch;
8225
8226   /* Adjust the breakpoint's address prior to allocating a location.
8227      Once we call allocate_bp_location(), that mostly uninitialized
8228      location will be placed on the location chain.  Adjustment of the
8229      breakpoint may cause target_read_memory() to be called and we do
8230      not want its scan of the location chain to find a breakpoint and
8231      location that's only been partially initialized.  */
8232   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8233                                                 sal->pc, b->type);
8234
8235   loc = allocate_bp_location (b);
8236   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
8237     ;
8238   *tmp = loc;
8239
8240   loc->requested_address = sal->pc;
8241   loc->address = adjusted_address;
8242   loc->pspace = sal->pspace;
8243   loc->probe = sal->probe;
8244   gdb_assert (loc->pspace != NULL);
8245   loc->section = sal->section;
8246   loc->gdbarch = loc_gdbarch;
8247
8248   if (sal->symtab != NULL)
8249     loc->source_file = xstrdup (sal->symtab->filename);
8250   loc->line_number = sal->line;
8251
8252   set_breakpoint_location_function (loc,
8253                                     sal->explicit_pc || sal->explicit_line);
8254   return loc;
8255 }
8256 \f
8257
8258 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8259    return 0 otherwise.  */
8260
8261 static int
8262 bp_loc_is_permanent (struct bp_location *loc)
8263 {
8264   int len;
8265   CORE_ADDR addr;
8266   const gdb_byte *bpoint;
8267   gdb_byte *target_mem;
8268   struct cleanup *cleanup;
8269   int retval = 0;
8270
8271   gdb_assert (loc != NULL);
8272
8273   addr = loc->address;
8274   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8275
8276   /* Software breakpoints unsupported?  */
8277   if (bpoint == NULL)
8278     return 0;
8279
8280   target_mem = alloca (len);
8281
8282   /* Enable the automatic memory restoration from breakpoints while
8283      we read the memory.  Otherwise we could say about our temporary
8284      breakpoints they are permanent.  */
8285   cleanup = save_current_space_and_thread ();
8286
8287   switch_to_program_space_and_thread (loc->pspace);
8288   make_show_memory_breakpoints_cleanup (0);
8289
8290   if (target_read_memory (loc->address, target_mem, len) == 0
8291       && memcmp (target_mem, bpoint, len) == 0)
8292     retval = 1;
8293
8294   do_cleanups (cleanup);
8295
8296   return retval;
8297 }
8298
8299
8300
8301 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
8302    as textual description of the location, and COND_STRING
8303    as condition expression.  */
8304
8305 static void
8306 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8307                      struct symtabs_and_lines sals, char *addr_string,
8308                      char *filter, char *cond_string,
8309                      enum bptype type, enum bpdisp disposition,
8310                      int thread, int task, int ignore_count,
8311                      const struct breakpoint_ops *ops, int from_tty,
8312                      int enabled, int internal, unsigned flags,
8313                      int display_canonical)
8314 {
8315   int i;
8316
8317   if (type == bp_hardware_breakpoint)
8318     {
8319       int target_resources_ok;
8320
8321       i = hw_breakpoint_used_count ();
8322       target_resources_ok =
8323         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8324                                             i + 1, 0);
8325       if (target_resources_ok == 0)
8326         error (_("No hardware breakpoint support in the target."));
8327       else if (target_resources_ok < 0)
8328         error (_("Hardware breakpoints used exceeds limit."));
8329     }
8330
8331   gdb_assert (sals.nelts > 0);
8332
8333   for (i = 0; i < sals.nelts; ++i)
8334     {
8335       struct symtab_and_line sal = sals.sals[i];
8336       struct bp_location *loc;
8337
8338       if (from_tty)
8339         {
8340           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8341           if (!loc_gdbarch)
8342             loc_gdbarch = gdbarch;
8343
8344           describe_other_breakpoints (loc_gdbarch,
8345                                       sal.pspace, sal.pc, sal.section, thread);
8346         }
8347
8348       if (i == 0)
8349         {
8350           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8351           b->thread = thread;
8352           b->task = task;
8353   
8354           b->cond_string = cond_string;
8355           b->ignore_count = ignore_count;
8356           b->enable_state = enabled ? bp_enabled : bp_disabled;
8357           b->disposition = disposition;
8358
8359           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8360             b->loc->inserted = 1;
8361
8362           if (type == bp_static_tracepoint)
8363             {
8364               struct tracepoint *t = (struct tracepoint *) b;
8365               struct static_tracepoint_marker marker;
8366
8367               if (strace_marker_p (b))
8368                 {
8369                   /* We already know the marker exists, otherwise, we
8370                      wouldn't see a sal for it.  */
8371                   char *p = &addr_string[3];
8372                   char *endp;
8373                   char *marker_str;
8374
8375                   p = skip_spaces (p);
8376
8377                   endp = skip_to_space (p);
8378
8379                   marker_str = savestring (p, endp - p);
8380                   t->static_trace_marker_id = marker_str;
8381
8382                   printf_filtered (_("Probed static tracepoint "
8383                                      "marker \"%s\"\n"),
8384                                    t->static_trace_marker_id);
8385                 }
8386               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8387                 {
8388                   t->static_trace_marker_id = xstrdup (marker.str_id);
8389                   release_static_tracepoint_marker (&marker);
8390
8391                   printf_filtered (_("Probed static tracepoint "
8392                                      "marker \"%s\"\n"),
8393                                    t->static_trace_marker_id);
8394                 }
8395               else
8396                 warning (_("Couldn't determine the static "
8397                            "tracepoint marker to probe"));
8398             }
8399
8400           loc = b->loc;
8401         }
8402       else
8403         {
8404           loc = add_location_to_breakpoint (b, &sal);
8405           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8406             loc->inserted = 1;
8407         }
8408
8409       if (bp_loc_is_permanent (loc))
8410         make_breakpoint_permanent (b);
8411
8412       if (b->cond_string)
8413         {
8414           char *arg = b->cond_string;
8415           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
8416           if (*arg)
8417               error (_("Garbage %s follows condition"), arg);
8418         }
8419     }   
8420
8421   b->display_canonical = display_canonical;
8422   if (addr_string)
8423     b->addr_string = addr_string;
8424   else
8425     /* addr_string has to be used or breakpoint_re_set will delete
8426        me.  */
8427     b->addr_string
8428       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
8429   b->filter = filter;
8430 }
8431
8432 static void
8433 create_breakpoint_sal (struct gdbarch *gdbarch,
8434                        struct symtabs_and_lines sals, char *addr_string,
8435                        char *filter, char *cond_string,
8436                        enum bptype type, enum bpdisp disposition,
8437                        int thread, int task, int ignore_count,
8438                        const struct breakpoint_ops *ops, int from_tty,
8439                        int enabled, int internal, unsigned flags,
8440                        int display_canonical)
8441 {
8442   struct breakpoint *b;
8443   struct cleanup *old_chain;
8444
8445   if (is_tracepoint_type (type))
8446     {
8447       struct tracepoint *t;
8448
8449       t = XCNEW (struct tracepoint);
8450       b = &t->base;
8451     }
8452   else
8453     b = XNEW (struct breakpoint);
8454
8455   old_chain = make_cleanup (xfree, b);
8456
8457   init_breakpoint_sal (b, gdbarch,
8458                        sals, addr_string,
8459                        filter, cond_string,
8460                        type, disposition,
8461                        thread, task, ignore_count,
8462                        ops, from_tty,
8463                        enabled, internal, flags,
8464                        display_canonical);
8465   discard_cleanups (old_chain);
8466
8467   install_breakpoint (internal, b, 0);
8468 }
8469
8470 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8471    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8472    value.  COND_STRING, if not NULL, specified the condition to be
8473    used for all breakpoints.  Essentially the only case where
8474    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8475    function.  In that case, it's still not possible to specify
8476    separate conditions for different overloaded functions, so
8477    we take just a single condition string.
8478    
8479    NOTE: If the function succeeds, the caller is expected to cleanup
8480    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8481    array contents).  If the function fails (error() is called), the
8482    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8483    COND and SALS arrays and each of those arrays contents.  */
8484
8485 static void
8486 create_breakpoints_sal (struct gdbarch *gdbarch,
8487                         struct linespec_result *canonical,
8488                         char *cond_string,
8489                         enum bptype type, enum bpdisp disposition,
8490                         int thread, int task, int ignore_count,
8491                         const struct breakpoint_ops *ops, int from_tty,
8492                         int enabled, int internal, unsigned flags)
8493 {
8494   int i;
8495   struct linespec_sals *lsal;
8496
8497   if (canonical->pre_expanded)
8498     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
8499
8500   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
8501     {
8502       /* Note that 'addr_string' can be NULL in the case of a plain
8503          'break', without arguments.  */
8504       char *addr_string = (canonical->addr_string
8505                            ? xstrdup (canonical->addr_string)
8506                            : NULL);
8507       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
8508       struct cleanup *inner = make_cleanup (xfree, addr_string);
8509
8510       make_cleanup (xfree, filter_string);
8511       create_breakpoint_sal (gdbarch, lsal->sals,
8512                              addr_string,
8513                              filter_string,
8514                              cond_string, type, disposition,
8515                              thread, task, ignore_count, ops,
8516                              from_tty, enabled, internal, flags,
8517                              canonical->special_display);
8518       discard_cleanups (inner);
8519     }
8520 }
8521
8522 /* Parse ADDRESS which is assumed to be a SAL specification possibly
8523    followed by conditionals.  On return, SALS contains an array of SAL
8524    addresses found.  ADDR_STRING contains a vector of (canonical)
8525    address strings.  ADDRESS points to the end of the SAL.
8526
8527    The array and the line spec strings are allocated on the heap, it is
8528    the caller's responsibility to free them.  */
8529
8530 static void
8531 parse_breakpoint_sals (char **address,
8532                        struct linespec_result *canonical)
8533 {
8534   char *addr_start = *address;
8535
8536   /* If no arg given, or if first arg is 'if ', use the default
8537      breakpoint.  */
8538   if ((*address) == NULL
8539       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
8540     {
8541       /* The last displayed codepoint, if it's valid, is our default breakpoint
8542          address.  */
8543       if (last_displayed_sal_is_valid ())
8544         {
8545           struct linespec_sals lsal;
8546           struct symtab_and_line sal;
8547
8548           init_sal (&sal);              /* Initialize to zeroes.  */
8549           lsal.sals.sals = (struct symtab_and_line *)
8550             xmalloc (sizeof (struct symtab_and_line));
8551
8552           /* Set sal's pspace, pc, symtab, and line to the values
8553              corresponding to the last call to print_frame_info.  */
8554           get_last_displayed_sal (&sal);
8555           sal.section = find_pc_overlay (sal.pc);
8556
8557           /* "break" without arguments is equivalent to "break *PC"
8558              where PC is the last displayed codepoint's address.  So
8559              make sure to set sal.explicit_pc to prevent GDB from
8560              trying to expand the list of sals to include all other
8561              instances with the same symtab and line.  */
8562           sal.explicit_pc = 1;
8563
8564           lsal.sals.sals[0] = sal;
8565           lsal.sals.nelts = 1;
8566           lsal.canonical = NULL;
8567
8568           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
8569         }
8570       else
8571         error (_("No default breakpoint address now."));
8572     }
8573   else
8574     {
8575       /* Force almost all breakpoints to be in terms of the
8576          current_source_symtab (which is decode_line_1's default).
8577          This should produce the results we want almost all of the
8578          time while leaving default_breakpoint_* alone.  */
8579       if (last_displayed_sal_is_valid ())
8580         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8581                           get_last_displayed_symtab (),
8582                           get_last_displayed_line (),
8583                           canonical, NULL, NULL);
8584       else
8585         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8586                           (struct symtab *) NULL, 0,
8587                           canonical, NULL, NULL);
8588     }
8589 }
8590
8591
8592 /* Convert each SAL into a real PC.  Verify that the PC can be
8593    inserted as a breakpoint.  If it can't throw an error.  */
8594
8595 static void
8596 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
8597 {    
8598   int i;
8599
8600   for (i = 0; i < sals->nelts; i++)
8601     resolve_sal_pc (&sals->sals[i]);
8602 }
8603
8604 /* Fast tracepoints may have restrictions on valid locations.  For
8605    instance, a fast tracepoint using a jump instead of a trap will
8606    likely have to overwrite more bytes than a trap would, and so can
8607    only be placed where the instruction is longer than the jump, or a
8608    multi-instruction sequence does not have a jump into the middle of
8609    it, etc.  */
8610
8611 static void
8612 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8613                             struct symtabs_and_lines *sals)
8614 {
8615   int i, rslt;
8616   struct symtab_and_line *sal;
8617   char *msg;
8618   struct cleanup *old_chain;
8619
8620   for (i = 0; i < sals->nelts; i++)
8621     {
8622       struct gdbarch *sarch;
8623
8624       sal = &sals->sals[i];
8625
8626       sarch = get_sal_arch (*sal);
8627       /* We fall back to GDBARCH if there is no architecture
8628          associated with SAL.  */
8629       if (sarch == NULL)
8630         sarch = gdbarch;
8631       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
8632                                                NULL, &msg);
8633       old_chain = make_cleanup (xfree, msg);
8634
8635       if (!rslt)
8636         error (_("May not have a fast tracepoint at 0x%s%s"),
8637                paddress (sarch, sal->pc), (msg ? msg : ""));
8638
8639       do_cleanups (old_chain);
8640     }
8641 }
8642
8643 /* Given TOK, a string specification of condition and thread, as
8644    accepted by the 'break' command, extract the condition
8645    string and thread number and set *COND_STRING and *THREAD.
8646    PC identifies the context at which the condition should be parsed.
8647    If no condition is found, *COND_STRING is set to NULL.
8648    If no thread is found, *THREAD is set to -1.  */
8649 static void 
8650 find_condition_and_thread (char *tok, CORE_ADDR pc, 
8651                            char **cond_string, int *thread, int *task)
8652 {
8653   *cond_string = NULL;
8654   *thread = -1;
8655   while (tok && *tok)
8656     {
8657       char *end_tok;
8658       int toklen;
8659       char *cond_start = NULL;
8660       char *cond_end = NULL;
8661
8662       tok = skip_spaces (tok);
8663       
8664       end_tok = skip_to_space (tok);
8665       
8666       toklen = end_tok - tok;
8667       
8668       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8669         {
8670           struct expression *expr;
8671
8672           tok = cond_start = end_tok + 1;
8673           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
8674           xfree (expr);
8675           cond_end = tok;
8676           *cond_string = savestring (cond_start, 
8677                                      cond_end - cond_start);
8678         }
8679       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8680         {
8681           char *tmptok;
8682           
8683           tok = end_tok + 1;
8684           tmptok = tok;
8685           *thread = strtol (tok, &tok, 0);
8686           if (tok == tmptok)
8687             error (_("Junk after thread keyword."));
8688           if (!valid_thread_id (*thread))
8689             error (_("Unknown thread %d."), *thread);
8690         }
8691       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
8692         {
8693           char *tmptok;
8694
8695           tok = end_tok + 1;
8696           tmptok = tok;
8697           *task = strtol (tok, &tok, 0);
8698           if (tok == tmptok)
8699             error (_("Junk after task keyword."));
8700           if (!valid_task_id (*task))
8701             error (_("Unknown task %d."), *task);
8702         }
8703       else
8704         error (_("Junk at end of arguments."));
8705     }
8706 }
8707
8708 /* Decode a static tracepoint marker spec.  */
8709
8710 static struct symtabs_and_lines
8711 decode_static_tracepoint_spec (char **arg_p)
8712 {
8713   VEC(static_tracepoint_marker_p) *markers = NULL;
8714   struct symtabs_and_lines sals;
8715   struct symtab_and_line sal;
8716   struct symbol *sym;
8717   struct cleanup *old_chain;
8718   char *p = &(*arg_p)[3];
8719   char *endp;
8720   char *marker_str;
8721   int i;
8722
8723   p = skip_spaces (p);
8724
8725   endp = skip_to_space (p);
8726
8727   marker_str = savestring (p, endp - p);
8728   old_chain = make_cleanup (xfree, marker_str);
8729
8730   markers = target_static_tracepoint_markers_by_strid (marker_str);
8731   if (VEC_empty(static_tracepoint_marker_p, markers))
8732     error (_("No known static tracepoint marker named %s"), marker_str);
8733
8734   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
8735   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
8736
8737   for (i = 0; i < sals.nelts; i++)
8738     {
8739       struct static_tracepoint_marker *marker;
8740
8741       marker = VEC_index (static_tracepoint_marker_p, markers, i);
8742
8743       init_sal (&sals.sals[i]);
8744
8745       sals.sals[i] = find_pc_line (marker->address, 0);
8746       sals.sals[i].pc = marker->address;
8747
8748       release_static_tracepoint_marker (marker);
8749     }
8750
8751   do_cleanups (old_chain);
8752
8753   *arg_p = endp;
8754   return sals;
8755 }
8756
8757 /* Set a breakpoint.  This function is shared between CLI and MI
8758    functions for setting a breakpoint.  This function has two major
8759    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
8760    parameter.  If non-zero, the function will parse arg, extracting
8761    breakpoint location, address and thread.  Otherwise, ARG is just
8762    the location of breakpoint, with condition and thread specified by
8763    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
8764    the breakpoint number will be allocated from the internal
8765    breakpoint count.  Returns true if any breakpoint was created;
8766    false otherwise.  */
8767
8768 int
8769 create_breakpoint (struct gdbarch *gdbarch,
8770                    char *arg, char *cond_string, int thread,
8771                    int parse_condition_and_thread,
8772                    int tempflag, enum bptype type_wanted,
8773                    int ignore_count,
8774                    enum auto_boolean pending_break_support,
8775                    const struct breakpoint_ops *ops,
8776                    int from_tty, int enabled, int internal,
8777                    unsigned flags)
8778 {
8779   volatile struct gdb_exception e;
8780   char *copy_arg = NULL;
8781   char *addr_start = arg;
8782   struct linespec_result canonical;
8783   struct cleanup *old_chain;
8784   struct cleanup *bkpt_chain = NULL;
8785   int i;
8786   int pending = 0;
8787   int task = 0;
8788   int prev_bkpt_count = breakpoint_count;
8789
8790   gdb_assert (ops != NULL);
8791
8792   init_linespec_result (&canonical);
8793
8794   TRY_CATCH (e, RETURN_MASK_ALL)
8795     {
8796       ops->create_sals_from_address (&arg, &canonical, type_wanted,
8797                                      addr_start, &copy_arg);
8798     }
8799
8800   /* If caller is interested in rc value from parse, set value.  */
8801   switch (e.reason)
8802     {
8803     case GDB_NO_ERROR:
8804       if (VEC_empty (linespec_sals, canonical.sals))
8805         return 0;
8806       break;
8807     case RETURN_ERROR:
8808       switch (e.error)
8809         {
8810         case NOT_FOUND_ERROR:
8811
8812           /* If pending breakpoint support is turned off, throw
8813              error.  */
8814
8815           if (pending_break_support == AUTO_BOOLEAN_FALSE)
8816             throw_exception (e);
8817
8818           exception_print (gdb_stderr, e);
8819
8820           /* If pending breakpoint support is auto query and the user
8821              selects no, then simply return the error code.  */
8822           if (pending_break_support == AUTO_BOOLEAN_AUTO
8823               && !nquery (_("Make %s pending on future shared library load? "),
8824                           bptype_string (type_wanted)))
8825             return 0;
8826
8827           /* At this point, either the user was queried about setting
8828              a pending breakpoint and selected yes, or pending
8829              breakpoint behavior is on and thus a pending breakpoint
8830              is defaulted on behalf of the user.  */
8831           {
8832             struct linespec_sals lsal;
8833
8834             copy_arg = xstrdup (addr_start);
8835             lsal.canonical = xstrdup (copy_arg);
8836             lsal.sals.nelts = 1;
8837             lsal.sals.sals = XNEW (struct symtab_and_line);
8838             init_sal (&lsal.sals.sals[0]);
8839             pending = 1;
8840             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
8841           }
8842           break;
8843         default:
8844           throw_exception (e);
8845         }
8846       break;
8847     default:
8848       throw_exception (e);
8849     }
8850
8851   /* Create a chain of things that always need to be cleaned up.  */
8852   old_chain = make_cleanup_destroy_linespec_result (&canonical);
8853
8854   /* ----------------------------- SNIP -----------------------------
8855      Anything added to the cleanup chain beyond this point is assumed
8856      to be part of a breakpoint.  If the breakpoint create succeeds
8857      then the memory is not reclaimed.  */
8858   bkpt_chain = make_cleanup (null_cleanup, 0);
8859
8860   /* Resolve all line numbers to PC's and verify that the addresses
8861      are ok for the target.  */
8862   if (!pending)
8863     {
8864       int ix;
8865       struct linespec_sals *iter;
8866
8867       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8868         breakpoint_sals_to_pc (&iter->sals);
8869     }
8870
8871   /* Fast tracepoints may have additional restrictions on location.  */
8872   if (!pending && type_wanted == bp_fast_tracepoint)
8873     {
8874       int ix;
8875       struct linespec_sals *iter;
8876
8877       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8878         check_fast_tracepoint_sals (gdbarch, &iter->sals);
8879     }
8880
8881   /* Verify that condition can be parsed, before setting any
8882      breakpoints.  Allocate a separate condition expression for each
8883      breakpoint.  */
8884   if (!pending)
8885     {
8886       struct linespec_sals *lsal;
8887
8888       lsal = VEC_index (linespec_sals, canonical.sals, 0);
8889
8890       if (parse_condition_and_thread)
8891         {
8892             /* Here we only parse 'arg' to separate condition
8893                from thread number, so parsing in context of first
8894                sal is OK.  When setting the breakpoint we'll 
8895                re-parse it in context of each sal.  */
8896             cond_string = NULL;
8897             thread = -1;
8898             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
8899                                        &thread, &task);
8900             if (cond_string)
8901                 make_cleanup (xfree, cond_string);
8902         }
8903       else
8904         {
8905             /* Create a private copy of condition string.  */
8906             if (cond_string)
8907             {
8908                 cond_string = xstrdup (cond_string);
8909                 make_cleanup (xfree, cond_string);
8910             }
8911         }
8912
8913       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
8914                                    cond_string, type_wanted,
8915                                    tempflag ? disp_del : disp_donttouch,
8916                                    thread, task, ignore_count, ops,
8917                                    from_tty, enabled, internal, flags);
8918     }
8919   else
8920     {
8921       struct breakpoint *b;
8922
8923       make_cleanup (xfree, copy_arg);
8924
8925       if (is_tracepoint_type (type_wanted))
8926         {
8927           struct tracepoint *t;
8928
8929           t = XCNEW (struct tracepoint);
8930           b = &t->base;
8931         }
8932       else
8933         b = XNEW (struct breakpoint);
8934
8935       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
8936
8937       b->addr_string = copy_arg;
8938       b->cond_string = NULL;
8939       b->ignore_count = ignore_count;
8940       b->disposition = tempflag ? disp_del : disp_donttouch;
8941       b->condition_not_parsed = 1;
8942       b->enable_state = enabled ? bp_enabled : bp_disabled;
8943       if ((type_wanted != bp_breakpoint
8944            && type_wanted != bp_hardware_breakpoint) || thread != -1)
8945         b->pspace = current_program_space;
8946
8947       install_breakpoint (internal, b, 0);
8948     }
8949   
8950   if (VEC_length (linespec_sals, canonical.sals) > 1)
8951     {
8952       warning (_("Multiple breakpoints were set.\nUse the "
8953                  "\"delete\" command to delete unwanted breakpoints."));
8954       prev_breakpoint_count = prev_bkpt_count;
8955     }
8956
8957   /* That's it.  Discard the cleanups for data inserted into the
8958      breakpoint.  */
8959   discard_cleanups (bkpt_chain);
8960   /* But cleanup everything else.  */
8961   do_cleanups (old_chain);
8962
8963   /* error call may happen here - have BKPT_CHAIN already discarded.  */
8964   update_global_location_list (1);
8965
8966   return 1;
8967 }
8968
8969 /* Set a breakpoint.
8970    ARG is a string describing breakpoint address,
8971    condition, and thread.
8972    FLAG specifies if a breakpoint is hardware on,
8973    and if breakpoint is temporary, using BP_HARDWARE_FLAG
8974    and BP_TEMPFLAG.  */
8975
8976 static void
8977 break_command_1 (char *arg, int flag, int from_tty)
8978 {
8979   int tempflag = flag & BP_TEMPFLAG;
8980   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
8981                              ? bp_hardware_breakpoint
8982                              : bp_breakpoint);
8983   struct breakpoint_ops *ops;
8984   const char *arg_cp = arg;
8985
8986   /* Matching breakpoints on probes.  */
8987   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
8988     ops = &bkpt_probe_breakpoint_ops;
8989   else
8990     ops = &bkpt_breakpoint_ops;
8991
8992   create_breakpoint (get_current_arch (),
8993                      arg,
8994                      NULL, 0, 1 /* parse arg */,
8995                      tempflag, type_wanted,
8996                      0 /* Ignore count */,
8997                      pending_break_support,
8998                      ops,
8999                      from_tty,
9000                      1 /* enabled */,
9001                      0 /* internal */,
9002                      0);
9003 }
9004
9005 /* Helper function for break_command_1 and disassemble_command.  */
9006
9007 void
9008 resolve_sal_pc (struct symtab_and_line *sal)
9009 {
9010   CORE_ADDR pc;
9011
9012   if (sal->pc == 0 && sal->symtab != NULL)
9013     {
9014       if (!find_line_pc (sal->symtab, sal->line, &pc))
9015         error (_("No line %d in file \"%s\"."),
9016                sal->line, sal->symtab->filename);
9017       sal->pc = pc;
9018
9019       /* If this SAL corresponds to a breakpoint inserted using a line
9020          number, then skip the function prologue if necessary.  */
9021       if (sal->explicit_line)
9022         skip_prologue_sal (sal);
9023     }
9024
9025   if (sal->section == 0 && sal->symtab != NULL)
9026     {
9027       struct blockvector *bv;
9028       struct block *b;
9029       struct symbol *sym;
9030
9031       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9032       if (bv != NULL)
9033         {
9034           sym = block_linkage_function (b);
9035           if (sym != NULL)
9036             {
9037               fixup_symbol_section (sym, sal->symtab->objfile);
9038               sal->section = SYMBOL_OBJ_SECTION (sym);
9039             }
9040           else
9041             {
9042               /* It really is worthwhile to have the section, so we'll
9043                  just have to look harder. This case can be executed
9044                  if we have line numbers but no functions (as can
9045                  happen in assembly source).  */
9046
9047               struct minimal_symbol *msym;
9048               struct cleanup *old_chain = save_current_space_and_thread ();
9049
9050               switch_to_program_space_and_thread (sal->pspace);
9051
9052               msym = lookup_minimal_symbol_by_pc (sal->pc);
9053               if (msym)
9054                 sal->section = SYMBOL_OBJ_SECTION (msym);
9055
9056               do_cleanups (old_chain);
9057             }
9058         }
9059     }
9060 }
9061
9062 void
9063 break_command (char *arg, int from_tty)
9064 {
9065   break_command_1 (arg, 0, from_tty);
9066 }
9067
9068 void
9069 tbreak_command (char *arg, int from_tty)
9070 {
9071   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9072 }
9073
9074 static void
9075 hbreak_command (char *arg, int from_tty)
9076 {
9077   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9078 }
9079
9080 static void
9081 thbreak_command (char *arg, int from_tty)
9082 {
9083   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9084 }
9085
9086 static void
9087 stop_command (char *arg, int from_tty)
9088 {
9089   printf_filtered (_("Specify the type of breakpoint to set.\n\
9090 Usage: stop in <function | address>\n\
9091        stop at <line>\n"));
9092 }
9093
9094 static void
9095 stopin_command (char *arg, int from_tty)
9096 {
9097   int badInput = 0;
9098
9099   if (arg == (char *) NULL)
9100     badInput = 1;
9101   else if (*arg != '*')
9102     {
9103       char *argptr = arg;
9104       int hasColon = 0;
9105
9106       /* Look for a ':'.  If this is a line number specification, then
9107          say it is bad, otherwise, it should be an address or
9108          function/method name.  */
9109       while (*argptr && !hasColon)
9110         {
9111           hasColon = (*argptr == ':');
9112           argptr++;
9113         }
9114
9115       if (hasColon)
9116         badInput = (*argptr != ':');    /* Not a class::method */
9117       else
9118         badInput = isdigit (*arg);      /* a simple line number */
9119     }
9120
9121   if (badInput)
9122     printf_filtered (_("Usage: stop in <function | address>\n"));
9123   else
9124     break_command_1 (arg, 0, from_tty);
9125 }
9126
9127 static void
9128 stopat_command (char *arg, int from_tty)
9129 {
9130   int badInput = 0;
9131
9132   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9133     badInput = 1;
9134   else
9135     {
9136       char *argptr = arg;
9137       int hasColon = 0;
9138
9139       /* Look for a ':'.  If there is a '::' then get out, otherwise
9140          it is probably a line number.  */
9141       while (*argptr && !hasColon)
9142         {
9143           hasColon = (*argptr == ':');
9144           argptr++;
9145         }
9146
9147       if (hasColon)
9148         badInput = (*argptr == ':');    /* we have class::method */
9149       else
9150         badInput = !isdigit (*arg);     /* not a line number */
9151     }
9152
9153   if (badInput)
9154     printf_filtered (_("Usage: stop at <line>\n"));
9155   else
9156     break_command_1 (arg, 0, from_tty);
9157 }
9158
9159 /* Implement the "breakpoint_hit" breakpoint_ops method for
9160    ranged breakpoints.  */
9161
9162 static int
9163 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9164                                   struct address_space *aspace,
9165                                   CORE_ADDR bp_addr,
9166                                   const struct target_waitstatus *ws)
9167 {
9168   if (ws->kind != TARGET_WAITKIND_STOPPED
9169       || ws->value.sig != TARGET_SIGNAL_TRAP)
9170     return 0;
9171
9172   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9173                                          bl->length, aspace, bp_addr);
9174 }
9175
9176 /* Implement the "resources_needed" breakpoint_ops method for
9177    ranged breakpoints.  */
9178
9179 static int
9180 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9181 {
9182   return target_ranged_break_num_registers ();
9183 }
9184
9185 /* Implement the "print_it" breakpoint_ops method for
9186    ranged breakpoints.  */
9187
9188 static enum print_stop_action
9189 print_it_ranged_breakpoint (bpstat bs)
9190 {
9191   struct breakpoint *b = bs->breakpoint_at;
9192   struct bp_location *bl = b->loc;
9193   struct ui_out *uiout = current_uiout;
9194
9195   gdb_assert (b->type == bp_hardware_breakpoint);
9196
9197   /* Ranged breakpoints have only one location.  */
9198   gdb_assert (bl && bl->next == NULL);
9199
9200   annotate_breakpoint (b->number);
9201   if (b->disposition == disp_del)
9202     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
9203   else
9204     ui_out_text (uiout, "\nRanged breakpoint ");
9205   if (ui_out_is_mi_like_p (uiout))
9206     {
9207       ui_out_field_string (uiout, "reason",
9208                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9209       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9210     }
9211   ui_out_field_int (uiout, "bkptno", b->number);
9212   ui_out_text (uiout, ", ");
9213
9214   return PRINT_SRC_AND_LOC;
9215 }
9216
9217 /* Implement the "print_one" breakpoint_ops method for
9218    ranged breakpoints.  */
9219
9220 static void
9221 print_one_ranged_breakpoint (struct breakpoint *b,
9222                              struct bp_location **last_loc)
9223 {
9224   struct bp_location *bl = b->loc;
9225   struct value_print_options opts;
9226   struct ui_out *uiout = current_uiout;
9227
9228   /* Ranged breakpoints have only one location.  */
9229   gdb_assert (bl && bl->next == NULL);
9230
9231   get_user_print_options (&opts);
9232
9233   if (opts.addressprint)
9234     /* We don't print the address range here, it will be printed later
9235        by print_one_detail_ranged_breakpoint.  */
9236     ui_out_field_skip (uiout, "addr");
9237   annotate_field (5);
9238   print_breakpoint_location (b, bl);
9239   *last_loc = bl;
9240 }
9241
9242 /* Implement the "print_one_detail" breakpoint_ops method for
9243    ranged breakpoints.  */
9244
9245 static void
9246 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9247                                     struct ui_out *uiout)
9248 {
9249   CORE_ADDR address_start, address_end;
9250   struct bp_location *bl = b->loc;
9251   struct ui_file *stb = mem_fileopen ();
9252   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
9253
9254   gdb_assert (bl);
9255
9256   address_start = bl->address;
9257   address_end = address_start + bl->length - 1;
9258
9259   ui_out_text (uiout, "\taddress range: ");
9260   fprintf_unfiltered (stb, "[%s, %s]",
9261                       print_core_address (bl->gdbarch, address_start),
9262                       print_core_address (bl->gdbarch, address_end));
9263   ui_out_field_stream (uiout, "addr", stb);
9264   ui_out_text (uiout, "\n");
9265
9266   do_cleanups (cleanup);
9267 }
9268
9269 /* Implement the "print_mention" breakpoint_ops method for
9270    ranged breakpoints.  */
9271
9272 static void
9273 print_mention_ranged_breakpoint (struct breakpoint *b)
9274 {
9275   struct bp_location *bl = b->loc;
9276   struct ui_out *uiout = current_uiout;
9277
9278   gdb_assert (bl);
9279   gdb_assert (b->type == bp_hardware_breakpoint);
9280
9281   if (ui_out_is_mi_like_p (uiout))
9282     return;
9283
9284   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9285                    b->number, paddress (bl->gdbarch, bl->address),
9286                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9287 }
9288
9289 /* Implement the "print_recreate" breakpoint_ops method for
9290    ranged breakpoints.  */
9291
9292 static void
9293 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9294 {
9295   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
9296                       b->addr_string_range_end);
9297   print_recreate_thread (b, fp);
9298 }
9299
9300 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9301
9302 static struct breakpoint_ops ranged_breakpoint_ops;
9303
9304 /* Find the address where the end of the breakpoint range should be
9305    placed, given the SAL of the end of the range.  This is so that if
9306    the user provides a line number, the end of the range is set to the
9307    last instruction of the given line.  */
9308
9309 static CORE_ADDR
9310 find_breakpoint_range_end (struct symtab_and_line sal)
9311 {
9312   CORE_ADDR end;
9313
9314   /* If the user provided a PC value, use it.  Otherwise,
9315      find the address of the end of the given location.  */
9316   if (sal.explicit_pc)
9317     end = sal.pc;
9318   else
9319     {
9320       int ret;
9321       CORE_ADDR start;
9322
9323       ret = find_line_pc_range (sal, &start, &end);
9324       if (!ret)
9325         error (_("Could not find location of the end of the range."));
9326
9327       /* find_line_pc_range returns the start of the next line.  */
9328       end--;
9329     }
9330
9331   return end;
9332 }
9333
9334 /* Implement the "break-range" CLI command.  */
9335
9336 static void
9337 break_range_command (char *arg, int from_tty)
9338 {
9339   char *arg_start, *addr_string_start, *addr_string_end;
9340   struct linespec_result canonical_start, canonical_end;
9341   int bp_count, can_use_bp, length;
9342   CORE_ADDR end;
9343   struct breakpoint *b;
9344   struct symtab_and_line sal_start, sal_end;
9345   struct cleanup *cleanup_bkpt;
9346   struct linespec_sals *lsal_start, *lsal_end;
9347
9348   /* We don't support software ranged breakpoints.  */
9349   if (target_ranged_break_num_registers () < 0)
9350     error (_("This target does not support hardware ranged breakpoints."));
9351
9352   bp_count = hw_breakpoint_used_count ();
9353   bp_count += target_ranged_break_num_registers ();
9354   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9355                                                    bp_count, 0);
9356   if (can_use_bp < 0)
9357     error (_("Hardware breakpoints used exceeds limit."));
9358
9359   arg = skip_spaces (arg);
9360   if (arg == NULL || arg[0] == '\0')
9361     error(_("No address range specified."));
9362
9363   init_linespec_result (&canonical_start);
9364
9365   arg_start = arg;
9366   parse_breakpoint_sals (&arg, &canonical_start);
9367
9368   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
9369
9370   if (arg[0] != ',')
9371     error (_("Too few arguments."));
9372   else if (VEC_empty (linespec_sals, canonical_start.sals))
9373     error (_("Could not find location of the beginning of the range."));
9374
9375   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
9376
9377   if (VEC_length (linespec_sals, canonical_start.sals) > 1
9378       || lsal_start->sals.nelts != 1)
9379     error (_("Cannot create a ranged breakpoint with multiple locations."));
9380
9381   sal_start = lsal_start->sals.sals[0];
9382   addr_string_start = savestring (arg_start, arg - arg_start);
9383   make_cleanup (xfree, addr_string_start);
9384
9385   arg++;        /* Skip the comma.  */
9386   arg = skip_spaces (arg);
9387
9388   /* Parse the end location.  */
9389
9390   init_linespec_result (&canonical_end);
9391   arg_start = arg;
9392
9393   /* We call decode_line_full directly here instead of using
9394      parse_breakpoint_sals because we need to specify the start location's
9395      symtab and line as the default symtab and line for the end of the
9396      range.  This makes it possible to have ranges like "foo.c:27, +14",
9397      where +14 means 14 lines from the start location.  */
9398   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
9399                     sal_start.symtab, sal_start.line,
9400                     &canonical_end, NULL, NULL);
9401
9402   make_cleanup_destroy_linespec_result (&canonical_end);
9403
9404   if (VEC_empty (linespec_sals, canonical_end.sals))
9405     error (_("Could not find location of the end of the range."));
9406
9407   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
9408   if (VEC_length (linespec_sals, canonical_end.sals) > 1
9409       || lsal_end->sals.nelts != 1)
9410     error (_("Cannot create a ranged breakpoint with multiple locations."));
9411
9412   sal_end = lsal_end->sals.sals[0];
9413   addr_string_end = savestring (arg_start, arg - arg_start);
9414   make_cleanup (xfree, addr_string_end);
9415
9416   end = find_breakpoint_range_end (sal_end);
9417   if (sal_start.pc > end)
9418     error (_("Invalid address range, end precedes start."));
9419
9420   length = end - sal_start.pc + 1;
9421   if (length < 0)
9422     /* Length overflowed.  */
9423     error (_("Address range too large."));
9424   else if (length == 1)
9425     {
9426       /* This range is simple enough to be handled by
9427          the `hbreak' command.  */
9428       hbreak_command (addr_string_start, 1);
9429
9430       do_cleanups (cleanup_bkpt);
9431
9432       return;
9433     }
9434
9435   /* Now set up the breakpoint.  */
9436   b = set_raw_breakpoint (get_current_arch (), sal_start,
9437                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9438   set_breakpoint_count (breakpoint_count + 1);
9439   b->number = breakpoint_count;
9440   b->disposition = disp_donttouch;
9441   b->addr_string = xstrdup (addr_string_start);
9442   b->addr_string_range_end = xstrdup (addr_string_end);
9443   b->loc->length = length;
9444
9445   do_cleanups (cleanup_bkpt);
9446
9447   mention (b);
9448   observer_notify_breakpoint_created (b);
9449   update_global_location_list (1);
9450 }
9451
9452 /*  Return non-zero if EXP is verified as constant.  Returned zero
9453     means EXP is variable.  Also the constant detection may fail for
9454     some constant expressions and in such case still falsely return
9455     zero.  */
9456
9457 static int
9458 watchpoint_exp_is_const (const struct expression *exp)
9459 {
9460   int i = exp->nelts;
9461
9462   while (i > 0)
9463     {
9464       int oplenp, argsp;
9465
9466       /* We are only interested in the descriptor of each element.  */
9467       operator_length (exp, i, &oplenp, &argsp);
9468       i -= oplenp;
9469
9470       switch (exp->elts[i].opcode)
9471         {
9472         case BINOP_ADD:
9473         case BINOP_SUB:
9474         case BINOP_MUL:
9475         case BINOP_DIV:
9476         case BINOP_REM:
9477         case BINOP_MOD:
9478         case BINOP_LSH:
9479         case BINOP_RSH:
9480         case BINOP_LOGICAL_AND:
9481         case BINOP_LOGICAL_OR:
9482         case BINOP_BITWISE_AND:
9483         case BINOP_BITWISE_IOR:
9484         case BINOP_BITWISE_XOR:
9485         case BINOP_EQUAL:
9486         case BINOP_NOTEQUAL:
9487         case BINOP_LESS:
9488         case BINOP_GTR:
9489         case BINOP_LEQ:
9490         case BINOP_GEQ:
9491         case BINOP_REPEAT:
9492         case BINOP_COMMA:
9493         case BINOP_EXP:
9494         case BINOP_MIN:
9495         case BINOP_MAX:
9496         case BINOP_INTDIV:
9497         case BINOP_CONCAT:
9498         case BINOP_IN:
9499         case BINOP_RANGE:
9500         case TERNOP_COND:
9501         case TERNOP_SLICE:
9502         case TERNOP_SLICE_COUNT:
9503
9504         case OP_LONG:
9505         case OP_DOUBLE:
9506         case OP_DECFLOAT:
9507         case OP_LAST:
9508         case OP_COMPLEX:
9509         case OP_STRING:
9510         case OP_BITSTRING:
9511         case OP_ARRAY:
9512         case OP_TYPE:
9513         case OP_NAME:
9514         case OP_OBJC_NSSTRING:
9515
9516         case UNOP_NEG:
9517         case UNOP_LOGICAL_NOT:
9518         case UNOP_COMPLEMENT:
9519         case UNOP_ADDR:
9520         case UNOP_HIGH:
9521         case UNOP_CAST:
9522           /* Unary, binary and ternary operators: We have to check
9523              their operands.  If they are constant, then so is the
9524              result of that operation.  For instance, if A and B are
9525              determined to be constants, then so is "A + B".
9526
9527              UNOP_IND is one exception to the rule above, because the
9528              value of *ADDR is not necessarily a constant, even when
9529              ADDR is.  */
9530           break;
9531
9532         case OP_VAR_VALUE:
9533           /* Check whether the associated symbol is a constant.
9534
9535              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9536              possible that a buggy compiler could mark a variable as
9537              constant even when it is not, and TYPE_CONST would return
9538              true in this case, while SYMBOL_CLASS wouldn't.
9539
9540              We also have to check for function symbols because they
9541              are always constant.  */
9542           {
9543             struct symbol *s = exp->elts[i + 2].symbol;
9544
9545             if (SYMBOL_CLASS (s) != LOC_BLOCK
9546                 && SYMBOL_CLASS (s) != LOC_CONST
9547                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
9548               return 0;
9549             break;
9550           }
9551
9552         /* The default action is to return 0 because we are using
9553            the optimistic approach here: If we don't know something,
9554            then it is not a constant.  */
9555         default:
9556           return 0;
9557         }
9558     }
9559
9560   return 1;
9561 }
9562
9563 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
9564
9565 static void
9566 dtor_watchpoint (struct breakpoint *self)
9567 {
9568   struct watchpoint *w = (struct watchpoint *) self;
9569
9570   xfree (w->cond_exp);
9571   xfree (w->exp);
9572   xfree (w->exp_string);
9573   xfree (w->exp_string_reparse);
9574   value_free (w->val);
9575
9576   base_breakpoint_ops.dtor (self);
9577 }
9578
9579 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
9580
9581 static void
9582 re_set_watchpoint (struct breakpoint *b)
9583 {
9584   struct watchpoint *w = (struct watchpoint *) b;
9585
9586   /* Watchpoint can be either on expression using entirely global
9587      variables, or it can be on local variables.
9588
9589      Watchpoints of the first kind are never auto-deleted, and even
9590      persist across program restarts.  Since they can use variables
9591      from shared libraries, we need to reparse expression as libraries
9592      are loaded and unloaded.
9593
9594      Watchpoints on local variables can also change meaning as result
9595      of solib event.  For example, if a watchpoint uses both a local
9596      and a global variables in expression, it's a local watchpoint,
9597      but unloading of a shared library will make the expression
9598      invalid.  This is not a very common use case, but we still
9599      re-evaluate expression, to avoid surprises to the user.
9600
9601      Note that for local watchpoints, we re-evaluate it only if
9602      watchpoints frame id is still valid.  If it's not, it means the
9603      watchpoint is out of scope and will be deleted soon.  In fact,
9604      I'm not sure we'll ever be called in this case.
9605
9606      If a local watchpoint's frame id is still valid, then
9607      w->exp_valid_block is likewise valid, and we can safely use it.
9608
9609      Don't do anything about disabled watchpoints, since they will be
9610      reevaluated again when enabled.  */
9611   update_watchpoint (w, 1 /* reparse */);
9612 }
9613
9614 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
9615
9616 static int
9617 insert_watchpoint (struct bp_location *bl)
9618 {
9619   struct watchpoint *w = (struct watchpoint *) bl->owner;
9620   int length = w->exact ? 1 : bl->length;
9621
9622   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9623                                    w->cond_exp);
9624 }
9625
9626 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
9627
9628 static int
9629 remove_watchpoint (struct bp_location *bl)
9630 {
9631   struct watchpoint *w = (struct watchpoint *) bl->owner;
9632   int length = w->exact ? 1 : bl->length;
9633
9634   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9635                                    w->cond_exp);
9636 }
9637
9638 static int
9639 breakpoint_hit_watchpoint (const struct bp_location *bl,
9640                            struct address_space *aspace, CORE_ADDR bp_addr,
9641                            const struct target_waitstatus *ws)
9642 {
9643   struct breakpoint *b = bl->owner;
9644   struct watchpoint *w = (struct watchpoint *) b;
9645
9646   /* Continuable hardware watchpoints are treated as non-existent if the
9647      reason we stopped wasn't a hardware watchpoint (we didn't stop on
9648      some data address).  Otherwise gdb won't stop on a break instruction
9649      in the code (not from a breakpoint) when a hardware watchpoint has
9650      been defined.  Also skip watchpoints which we know did not trigger
9651      (did not match the data address).  */
9652   if (is_hardware_watchpoint (b)
9653       && w->watchpoint_triggered == watch_triggered_no)
9654     return 0;
9655
9656   return 1;
9657 }
9658
9659 static void
9660 check_status_watchpoint (bpstat bs)
9661 {
9662   gdb_assert (is_watchpoint (bs->breakpoint_at));
9663
9664   bpstat_check_watchpoint (bs);
9665 }
9666
9667 /* Implement the "resources_needed" breakpoint_ops method for
9668    hardware watchpoints.  */
9669
9670 static int
9671 resources_needed_watchpoint (const struct bp_location *bl)
9672 {
9673   struct watchpoint *w = (struct watchpoint *) bl->owner;
9674   int length = w->exact? 1 : bl->length;
9675
9676   return target_region_ok_for_hw_watchpoint (bl->address, length);
9677 }
9678
9679 /* Implement the "works_in_software_mode" breakpoint_ops method for
9680    hardware watchpoints.  */
9681
9682 static int
9683 works_in_software_mode_watchpoint (const struct breakpoint *b)
9684 {
9685   /* Read and access watchpoints only work with hardware support.  */
9686   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
9687 }
9688
9689 static enum print_stop_action
9690 print_it_watchpoint (bpstat bs)
9691 {
9692   struct cleanup *old_chain;
9693   struct breakpoint *b;
9694   const struct bp_location *bl;
9695   struct ui_file *stb;
9696   enum print_stop_action result;
9697   struct watchpoint *w;
9698   struct ui_out *uiout = current_uiout;
9699
9700   gdb_assert (bs->bp_location_at != NULL);
9701
9702   bl = bs->bp_location_at;
9703   b = bs->breakpoint_at;
9704   w = (struct watchpoint *) b;
9705
9706   stb = mem_fileopen ();
9707   old_chain = make_cleanup_ui_file_delete (stb);
9708
9709   switch (b->type)
9710     {
9711     case bp_watchpoint:
9712     case bp_hardware_watchpoint:
9713       annotate_watchpoint (b->number);
9714       if (ui_out_is_mi_like_p (uiout))
9715         ui_out_field_string
9716           (uiout, "reason",
9717            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9718       mention (b);
9719       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9720       ui_out_text (uiout, "\nOld value = ");
9721       watchpoint_value_print (bs->old_val, stb);
9722       ui_out_field_stream (uiout, "old", stb);
9723       ui_out_text (uiout, "\nNew value = ");
9724       watchpoint_value_print (w->val, stb);
9725       ui_out_field_stream (uiout, "new", stb);
9726       ui_out_text (uiout, "\n");
9727       /* More than one watchpoint may have been triggered.  */
9728       result = PRINT_UNKNOWN;
9729       break;
9730
9731     case bp_read_watchpoint:
9732       if (ui_out_is_mi_like_p (uiout))
9733         ui_out_field_string
9734           (uiout, "reason",
9735            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9736       mention (b);
9737       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9738       ui_out_text (uiout, "\nValue = ");
9739       watchpoint_value_print (w->val, stb);
9740       ui_out_field_stream (uiout, "value", stb);
9741       ui_out_text (uiout, "\n");
9742       result = PRINT_UNKNOWN;
9743       break;
9744
9745     case bp_access_watchpoint:
9746       if (bs->old_val != NULL)
9747         {
9748           annotate_watchpoint (b->number);
9749           if (ui_out_is_mi_like_p (uiout))
9750             ui_out_field_string
9751               (uiout, "reason",
9752                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9753           mention (b);
9754           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9755           ui_out_text (uiout, "\nOld value = ");
9756           watchpoint_value_print (bs->old_val, stb);
9757           ui_out_field_stream (uiout, "old", stb);
9758           ui_out_text (uiout, "\nNew value = ");
9759         }
9760       else
9761         {
9762           mention (b);
9763           if (ui_out_is_mi_like_p (uiout))
9764             ui_out_field_string
9765               (uiout, "reason",
9766                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9767           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9768           ui_out_text (uiout, "\nValue = ");
9769         }
9770       watchpoint_value_print (w->val, stb);
9771       ui_out_field_stream (uiout, "new", stb);
9772       ui_out_text (uiout, "\n");
9773       result = PRINT_UNKNOWN;
9774       break;
9775     default:
9776       result = PRINT_UNKNOWN;
9777     }
9778
9779   do_cleanups (old_chain);
9780   return result;
9781 }
9782
9783 /* Implement the "print_mention" breakpoint_ops method for hardware
9784    watchpoints.  */
9785
9786 static void
9787 print_mention_watchpoint (struct breakpoint *b)
9788 {
9789   struct cleanup *ui_out_chain;
9790   struct watchpoint *w = (struct watchpoint *) b;
9791   struct ui_out *uiout = current_uiout;
9792
9793   switch (b->type)
9794     {
9795     case bp_watchpoint:
9796       ui_out_text (uiout, "Watchpoint ");
9797       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9798       break;
9799     case bp_hardware_watchpoint:
9800       ui_out_text (uiout, "Hardware watchpoint ");
9801       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9802       break;
9803     case bp_read_watchpoint:
9804       ui_out_text (uiout, "Hardware read watchpoint ");
9805       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9806       break;
9807     case bp_access_watchpoint:
9808       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
9809       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9810       break;
9811     default:
9812       internal_error (__FILE__, __LINE__,
9813                       _("Invalid hardware watchpoint type."));
9814     }
9815
9816   ui_out_field_int (uiout, "number", b->number);
9817   ui_out_text (uiout, ": ");
9818   ui_out_field_string (uiout, "exp", w->exp_string);
9819   do_cleanups (ui_out_chain);
9820 }
9821
9822 /* Implement the "print_recreate" breakpoint_ops method for
9823    watchpoints.  */
9824
9825 static void
9826 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
9827 {
9828   struct watchpoint *w = (struct watchpoint *) b;
9829
9830   switch (b->type)
9831     {
9832     case bp_watchpoint:
9833     case bp_hardware_watchpoint:
9834       fprintf_unfiltered (fp, "watch");
9835       break;
9836     case bp_read_watchpoint:
9837       fprintf_unfiltered (fp, "rwatch");
9838       break;
9839     case bp_access_watchpoint:
9840       fprintf_unfiltered (fp, "awatch");
9841       break;
9842     default:
9843       internal_error (__FILE__, __LINE__,
9844                       _("Invalid watchpoint type."));
9845     }
9846
9847   fprintf_unfiltered (fp, " %s", w->exp_string);
9848   print_recreate_thread (b, fp);
9849 }
9850
9851 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
9852
9853 static struct breakpoint_ops watchpoint_breakpoint_ops;
9854
9855 /* Implement the "insert" breakpoint_ops method for
9856    masked hardware watchpoints.  */
9857
9858 static int
9859 insert_masked_watchpoint (struct bp_location *bl)
9860 {
9861   struct watchpoint *w = (struct watchpoint *) bl->owner;
9862
9863   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
9864                                         bl->watchpoint_type);
9865 }
9866
9867 /* Implement the "remove" breakpoint_ops method for
9868    masked hardware watchpoints.  */
9869
9870 static int
9871 remove_masked_watchpoint (struct bp_location *bl)
9872 {
9873   struct watchpoint *w = (struct watchpoint *) bl->owner;
9874
9875   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
9876                                         bl->watchpoint_type);
9877 }
9878
9879 /* Implement the "resources_needed" breakpoint_ops method for
9880    masked hardware watchpoints.  */
9881
9882 static int
9883 resources_needed_masked_watchpoint (const struct bp_location *bl)
9884 {
9885   struct watchpoint *w = (struct watchpoint *) bl->owner;
9886
9887   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
9888 }
9889
9890 /* Implement the "works_in_software_mode" breakpoint_ops method for
9891    masked hardware watchpoints.  */
9892
9893 static int
9894 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
9895 {
9896   return 0;
9897 }
9898
9899 /* Implement the "print_it" breakpoint_ops method for
9900    masked hardware watchpoints.  */
9901
9902 static enum print_stop_action
9903 print_it_masked_watchpoint (bpstat bs)
9904 {
9905   struct breakpoint *b = bs->breakpoint_at;
9906   struct ui_out *uiout = current_uiout;
9907
9908   /* Masked watchpoints have only one location.  */
9909   gdb_assert (b->loc && b->loc->next == NULL);
9910
9911   switch (b->type)
9912     {
9913     case bp_hardware_watchpoint:
9914       annotate_watchpoint (b->number);
9915       if (ui_out_is_mi_like_p (uiout))
9916         ui_out_field_string
9917           (uiout, "reason",
9918            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9919       break;
9920
9921     case bp_read_watchpoint:
9922       if (ui_out_is_mi_like_p (uiout))
9923         ui_out_field_string
9924           (uiout, "reason",
9925            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9926       break;
9927
9928     case bp_access_watchpoint:
9929       if (ui_out_is_mi_like_p (uiout))
9930         ui_out_field_string
9931           (uiout, "reason",
9932            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9933       break;
9934     default:
9935       internal_error (__FILE__, __LINE__,
9936                       _("Invalid hardware watchpoint type."));
9937     }
9938
9939   mention (b);
9940   ui_out_text (uiout, _("\n\
9941 Check the underlying instruction at PC for the memory\n\
9942 address and value which triggered this watchpoint.\n"));
9943   ui_out_text (uiout, "\n");
9944
9945   /* More than one watchpoint may have been triggered.  */
9946   return PRINT_UNKNOWN;
9947 }
9948
9949 /* Implement the "print_one_detail" breakpoint_ops method for
9950    masked hardware watchpoints.  */
9951
9952 static void
9953 print_one_detail_masked_watchpoint (const struct breakpoint *b,
9954                                     struct ui_out *uiout)
9955 {
9956   struct watchpoint *w = (struct watchpoint *) b;
9957
9958   /* Masked watchpoints have only one location.  */
9959   gdb_assert (b->loc && b->loc->next == NULL);
9960
9961   ui_out_text (uiout, "\tmask ");
9962   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
9963   ui_out_text (uiout, "\n");
9964 }
9965
9966 /* Implement the "print_mention" breakpoint_ops method for
9967    masked hardware watchpoints.  */
9968
9969 static void
9970 print_mention_masked_watchpoint (struct breakpoint *b)
9971 {
9972   struct watchpoint *w = (struct watchpoint *) b;
9973   struct ui_out *uiout = current_uiout;
9974   struct cleanup *ui_out_chain;
9975
9976   switch (b->type)
9977     {
9978     case bp_hardware_watchpoint:
9979       ui_out_text (uiout, "Masked hardware watchpoint ");
9980       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9981       break;
9982     case bp_read_watchpoint:
9983       ui_out_text (uiout, "Masked hardware read watchpoint ");
9984       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9985       break;
9986     case bp_access_watchpoint:
9987       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
9988       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9989       break;
9990     default:
9991       internal_error (__FILE__, __LINE__,
9992                       _("Invalid hardware watchpoint type."));
9993     }
9994
9995   ui_out_field_int (uiout, "number", b->number);
9996   ui_out_text (uiout, ": ");
9997   ui_out_field_string (uiout, "exp", w->exp_string);
9998   do_cleanups (ui_out_chain);
9999 }
10000
10001 /* Implement the "print_recreate" breakpoint_ops method for
10002    masked hardware watchpoints.  */
10003
10004 static void
10005 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10006 {
10007   struct watchpoint *w = (struct watchpoint *) b;
10008   char tmp[40];
10009
10010   switch (b->type)
10011     {
10012     case bp_hardware_watchpoint:
10013       fprintf_unfiltered (fp, "watch");
10014       break;
10015     case bp_read_watchpoint:
10016       fprintf_unfiltered (fp, "rwatch");
10017       break;
10018     case bp_access_watchpoint:
10019       fprintf_unfiltered (fp, "awatch");
10020       break;
10021     default:
10022       internal_error (__FILE__, __LINE__,
10023                       _("Invalid hardware watchpoint type."));
10024     }
10025
10026   sprintf_vma (tmp, w->hw_wp_mask);
10027   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10028   print_recreate_thread (b, fp);
10029 }
10030
10031 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10032
10033 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10034
10035 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10036
10037 static int
10038 is_masked_watchpoint (const struct breakpoint *b)
10039 {
10040   return b->ops == &masked_watchpoint_breakpoint_ops;
10041 }
10042
10043 /* accessflag:  hw_write:  watch write, 
10044                 hw_read:   watch read, 
10045                 hw_access: watch access (read or write) */
10046 static void
10047 watch_command_1 (char *arg, int accessflag, int from_tty,
10048                  int just_location, int internal)
10049 {
10050   volatile struct gdb_exception e;
10051   struct breakpoint *b, *scope_breakpoint = NULL;
10052   struct expression *exp;
10053   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10054   struct value *val, *mark, *result;
10055   struct frame_info *frame;
10056   char *exp_start = NULL;
10057   char *exp_end = NULL;
10058   char *tok, *end_tok;
10059   int toklen = -1;
10060   char *cond_start = NULL;
10061   char *cond_end = NULL;
10062   enum bptype bp_type;
10063   int thread = -1;
10064   int pc = 0;
10065   /* Flag to indicate whether we are going to use masks for
10066      the hardware watchpoint.  */
10067   int use_mask = 0;
10068   CORE_ADDR mask = 0;
10069   struct watchpoint *w;
10070
10071   /* Make sure that we actually have parameters to parse.  */
10072   if (arg != NULL && arg[0] != '\0')
10073     {
10074       char *value_start;
10075
10076       /* Look for "parameter value" pairs at the end
10077          of the arguments string.  */
10078       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
10079         {
10080           /* Skip whitespace at the end of the argument list.  */
10081           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10082             tok--;
10083
10084           /* Find the beginning of the last token.
10085              This is the value of the parameter.  */
10086           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10087             tok--;
10088           value_start = tok + 1;
10089
10090           /* Skip whitespace.  */
10091           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10092             tok--;
10093
10094           end_tok = tok;
10095
10096           /* Find the beginning of the second to last token.
10097              This is the parameter itself.  */
10098           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10099             tok--;
10100           tok++;
10101           toklen = end_tok - tok + 1;
10102
10103           if (toklen == 6 && !strncmp (tok, "thread", 6))
10104             {
10105               /* At this point we've found a "thread" token, which means
10106                  the user is trying to set a watchpoint that triggers
10107                  only in a specific thread.  */
10108               char *endp;
10109
10110               if (thread != -1)
10111                 error(_("You can specify only one thread."));
10112
10113               /* Extract the thread ID from the next token.  */
10114               thread = strtol (value_start, &endp, 0);
10115
10116               /* Check if the user provided a valid numeric value for the
10117                  thread ID.  */
10118               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10119                 error (_("Invalid thread ID specification %s."), value_start);
10120
10121               /* Check if the thread actually exists.  */
10122               if (!valid_thread_id (thread))
10123                 error (_("Unknown thread %d."), thread);
10124             }
10125           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10126             {
10127               /* We've found a "mask" token, which means the user wants to
10128                  create a hardware watchpoint that is going to have the mask
10129                  facility.  */
10130               struct value *mask_value, *mark;
10131
10132               if (use_mask)
10133                 error(_("You can specify only one mask."));
10134
10135               use_mask = just_location = 1;
10136
10137               mark = value_mark ();
10138               mask_value = parse_to_comma_and_eval (&value_start);
10139               mask = value_as_address (mask_value);
10140               value_free_to_mark (mark);
10141             }
10142           else
10143             /* We didn't recognize what we found.  We should stop here.  */
10144             break;
10145
10146           /* Truncate the string and get rid of the "parameter value" pair before
10147              the arguments string is parsed by the parse_exp_1 function.  */
10148           *tok = '\0';
10149         }
10150     }
10151
10152   /* Parse the rest of the arguments.  */
10153   innermost_block = NULL;
10154   exp_start = arg;
10155   exp = parse_exp_1 (&arg, 0, 0);
10156   exp_end = arg;
10157   /* Remove trailing whitespace from the expression before saving it.
10158      This makes the eventual display of the expression string a bit
10159      prettier.  */
10160   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10161     --exp_end;
10162
10163   /* Checking if the expression is not constant.  */
10164   if (watchpoint_exp_is_const (exp))
10165     {
10166       int len;
10167
10168       len = exp_end - exp_start;
10169       while (len > 0 && isspace (exp_start[len - 1]))
10170         len--;
10171       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10172     }
10173
10174   exp_valid_block = innermost_block;
10175   mark = value_mark ();
10176   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10177
10178   if (just_location)
10179     {
10180       int ret;
10181
10182       exp_valid_block = NULL;
10183       val = value_addr (result);
10184       release_value (val);
10185       value_free_to_mark (mark);
10186
10187       if (use_mask)
10188         {
10189           ret = target_masked_watch_num_registers (value_as_address (val),
10190                                                    mask);
10191           if (ret == -1)
10192             error (_("This target does not support masked watchpoints."));
10193           else if (ret == -2)
10194             error (_("Invalid mask or memory region."));
10195         }
10196     }
10197   else if (val != NULL)
10198     release_value (val);
10199
10200   tok = skip_spaces (arg);
10201   end_tok = skip_to_space (tok);
10202
10203   toklen = end_tok - tok;
10204   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10205     {
10206       struct expression *cond;
10207
10208       innermost_block = NULL;
10209       tok = cond_start = end_tok + 1;
10210       cond = parse_exp_1 (&tok, 0, 0);
10211
10212       /* The watchpoint expression may not be local, but the condition
10213          may still be.  E.g.: `watch global if local > 0'.  */
10214       cond_exp_valid_block = innermost_block;
10215
10216       xfree (cond);
10217       cond_end = tok;
10218     }
10219   if (*tok)
10220     error (_("Junk at end of command."));
10221
10222   if (accessflag == hw_read)
10223     bp_type = bp_read_watchpoint;
10224   else if (accessflag == hw_access)
10225     bp_type = bp_access_watchpoint;
10226   else
10227     bp_type = bp_hardware_watchpoint;
10228
10229   frame = block_innermost_frame (exp_valid_block);
10230
10231   /* If the expression is "local", then set up a "watchpoint scope"
10232      breakpoint at the point where we've left the scope of the watchpoint
10233      expression.  Create the scope breakpoint before the watchpoint, so
10234      that we will encounter it first in bpstat_stop_status.  */
10235   if (exp_valid_block && frame)
10236     {
10237       if (frame_id_p (frame_unwind_caller_id (frame)))
10238         {
10239           scope_breakpoint
10240             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
10241                                           frame_unwind_caller_pc (frame),
10242                                           bp_watchpoint_scope,
10243                                           &momentary_breakpoint_ops);
10244
10245           scope_breakpoint->enable_state = bp_enabled;
10246
10247           /* Automatically delete the breakpoint when it hits.  */
10248           scope_breakpoint->disposition = disp_del;
10249
10250           /* Only break in the proper frame (help with recursion).  */
10251           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
10252
10253           /* Set the address at which we will stop.  */
10254           scope_breakpoint->loc->gdbarch
10255             = frame_unwind_caller_arch (frame);
10256           scope_breakpoint->loc->requested_address
10257             = frame_unwind_caller_pc (frame);
10258           scope_breakpoint->loc->address
10259             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10260                                          scope_breakpoint->loc->requested_address,
10261                                          scope_breakpoint->type);
10262         }
10263     }
10264
10265   /* Now set up the breakpoint.  */
10266
10267   w = XCNEW (struct watchpoint);
10268   b = &w->base;
10269   if (use_mask)
10270     init_raw_breakpoint_without_location (b, NULL, bp_type,
10271                                           &masked_watchpoint_breakpoint_ops);
10272   else
10273     init_raw_breakpoint_without_location (b, NULL, bp_type,
10274                                           &watchpoint_breakpoint_ops);
10275   b->thread = thread;
10276   b->disposition = disp_donttouch;
10277   b->pspace = current_program_space;
10278   w->exp = exp;
10279   w->exp_valid_block = exp_valid_block;
10280   w->cond_exp_valid_block = cond_exp_valid_block;
10281   if (just_location)
10282     {
10283       struct type *t = value_type (val);
10284       CORE_ADDR addr = value_as_address (val);
10285       char *name;
10286
10287       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
10288       name = type_to_string (t);
10289
10290       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
10291                                           core_addr_to_string (addr));
10292       xfree (name);
10293
10294       w->exp_string = xstrprintf ("-location %.*s",
10295                                   (int) (exp_end - exp_start), exp_start);
10296
10297       /* The above expression is in C.  */
10298       b->language = language_c;
10299     }
10300   else
10301     w->exp_string = savestring (exp_start, exp_end - exp_start);
10302
10303   if (use_mask)
10304     {
10305       w->hw_wp_mask = mask;
10306     }
10307   else
10308     {
10309       w->val = val;
10310       w->val_valid = 1;
10311     }
10312
10313   if (cond_start)
10314     b->cond_string = savestring (cond_start, cond_end - cond_start);
10315   else
10316     b->cond_string = 0;
10317
10318   if (frame)
10319     {
10320       w->watchpoint_frame = get_frame_id (frame);
10321       w->watchpoint_thread = inferior_ptid;
10322     }
10323   else
10324     {
10325       w->watchpoint_frame = null_frame_id;
10326       w->watchpoint_thread = null_ptid;
10327     }
10328
10329   if (scope_breakpoint != NULL)
10330     {
10331       /* The scope breakpoint is related to the watchpoint.  We will
10332          need to act on them together.  */
10333       b->related_breakpoint = scope_breakpoint;
10334       scope_breakpoint->related_breakpoint = b;
10335     }
10336
10337   if (!just_location)
10338     value_free_to_mark (mark);
10339
10340   TRY_CATCH (e, RETURN_MASK_ALL)
10341     {
10342       /* Finally update the new watchpoint.  This creates the locations
10343          that should be inserted.  */
10344       update_watchpoint (w, 1);
10345     }
10346   if (e.reason < 0)
10347     {
10348       delete_breakpoint (b);
10349       throw_exception (e);
10350     }
10351
10352   install_breakpoint (internal, b, 1);
10353 }
10354
10355 /* Return count of debug registers needed to watch the given expression.
10356    If the watchpoint cannot be handled in hardware return zero.  */
10357
10358 static int
10359 can_use_hardware_watchpoint (struct value *v)
10360 {
10361   int found_memory_cnt = 0;
10362   struct value *head = v;
10363
10364   /* Did the user specifically forbid us to use hardware watchpoints? */
10365   if (!can_use_hw_watchpoints)
10366     return 0;
10367
10368   /* Make sure that the value of the expression depends only upon
10369      memory contents, and values computed from them within GDB.  If we
10370      find any register references or function calls, we can't use a
10371      hardware watchpoint.
10372
10373      The idea here is that evaluating an expression generates a series
10374      of values, one holding the value of every subexpression.  (The
10375      expression a*b+c has five subexpressions: a, b, a*b, c, and
10376      a*b+c.)  GDB's values hold almost enough information to establish
10377      the criteria given above --- they identify memory lvalues,
10378      register lvalues, computed values, etcetera.  So we can evaluate
10379      the expression, and then scan the chain of values that leaves
10380      behind to decide whether we can detect any possible change to the
10381      expression's final value using only hardware watchpoints.
10382
10383      However, I don't think that the values returned by inferior
10384      function calls are special in any way.  So this function may not
10385      notice that an expression involving an inferior function call
10386      can't be watched with hardware watchpoints.  FIXME.  */
10387   for (; v; v = value_next (v))
10388     {
10389       if (VALUE_LVAL (v) == lval_memory)
10390         {
10391           if (v != head && value_lazy (v))
10392             /* A lazy memory lvalue in the chain is one that GDB never
10393                needed to fetch; we either just used its address (e.g.,
10394                `a' in `a.b') or we never needed it at all (e.g., `a'
10395                in `a,b').  This doesn't apply to HEAD; if that is
10396                lazy then it was not readable, but watch it anyway.  */
10397             ;
10398           else
10399             {
10400               /* Ahh, memory we actually used!  Check if we can cover
10401                  it with hardware watchpoints.  */
10402               struct type *vtype = check_typedef (value_type (v));
10403
10404               /* We only watch structs and arrays if user asked for it
10405                  explicitly, never if they just happen to appear in a
10406                  middle of some value chain.  */
10407               if (v == head
10408                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10409                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10410                 {
10411                   CORE_ADDR vaddr = value_address (v);
10412                   int len;
10413                   int num_regs;
10414
10415                   len = (target_exact_watchpoints
10416                          && is_scalar_type_recursive (vtype))?
10417                     1 : TYPE_LENGTH (value_type (v));
10418
10419                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10420                   if (!num_regs)
10421                     return 0;
10422                   else
10423                     found_memory_cnt += num_regs;
10424                 }
10425             }
10426         }
10427       else if (VALUE_LVAL (v) != not_lval
10428                && deprecated_value_modifiable (v) == 0)
10429         return 0;       /* These are values from the history (e.g., $1).  */
10430       else if (VALUE_LVAL (v) == lval_register)
10431         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10432     }
10433
10434   /* The expression itself looks suitable for using a hardware
10435      watchpoint, but give the target machine a chance to reject it.  */
10436   return found_memory_cnt;
10437 }
10438
10439 void
10440 watch_command_wrapper (char *arg, int from_tty, int internal)
10441 {
10442   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10443 }
10444
10445 /* A helper function that looks for an argument at the start of a
10446    string.  The argument must also either be at the end of the string,
10447    or be followed by whitespace.  Returns 1 if it finds the argument,
10448    0 otherwise.  If the argument is found, it updates *STR.  */
10449
10450 static int
10451 check_for_argument (char **str, char *arg, int arg_len)
10452 {
10453   if (strncmp (*str, arg, arg_len) == 0
10454       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
10455     {
10456       *str += arg_len;
10457       return 1;
10458     }
10459   return 0;
10460 }
10461
10462 /* A helper function that looks for the "-location" argument and then
10463    calls watch_command_1.  */
10464
10465 static void
10466 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
10467 {
10468   int just_location = 0;
10469
10470   if (arg
10471       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10472           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10473     {
10474       arg = skip_spaces (arg);
10475       just_location = 1;
10476     }
10477
10478   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10479 }
10480
10481 static void
10482 watch_command (char *arg, int from_tty)
10483 {
10484   watch_maybe_just_location (arg, hw_write, from_tty);
10485 }
10486
10487 void
10488 rwatch_command_wrapper (char *arg, int from_tty, int internal)
10489 {
10490   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10491 }
10492
10493 static void
10494 rwatch_command (char *arg, int from_tty)
10495 {
10496   watch_maybe_just_location (arg, hw_read, from_tty);
10497 }
10498
10499 void
10500 awatch_command_wrapper (char *arg, int from_tty, int internal)
10501 {
10502   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10503 }
10504
10505 static void
10506 awatch_command (char *arg, int from_tty)
10507 {
10508   watch_maybe_just_location (arg, hw_access, from_tty);
10509 }
10510 \f
10511
10512 /* Helper routines for the until_command routine in infcmd.c.  Here
10513    because it uses the mechanisms of breakpoints.  */
10514
10515 struct until_break_command_continuation_args
10516 {
10517   struct breakpoint *breakpoint;
10518   struct breakpoint *breakpoint2;
10519   int thread_num;
10520 };
10521
10522 /* This function is called by fetch_inferior_event via the
10523    cmd_continuation pointer, to complete the until command.  It takes
10524    care of cleaning up the temporary breakpoints set up by the until
10525    command.  */
10526 static void
10527 until_break_command_continuation (void *arg, int err)
10528 {
10529   struct until_break_command_continuation_args *a = arg;
10530
10531   delete_breakpoint (a->breakpoint);
10532   if (a->breakpoint2)
10533     delete_breakpoint (a->breakpoint2);
10534   delete_longjmp_breakpoint (a->thread_num);
10535 }
10536
10537 void
10538 until_break_command (char *arg, int from_tty, int anywhere)
10539 {
10540   struct symtabs_and_lines sals;
10541   struct symtab_and_line sal;
10542   struct frame_info *frame = get_selected_frame (NULL);
10543   struct gdbarch *frame_gdbarch = get_frame_arch (frame);
10544   struct frame_id stack_frame_id = get_stack_frame_id (frame);
10545   struct frame_id caller_frame_id = frame_unwind_caller_id (frame);
10546   struct breakpoint *breakpoint;
10547   struct breakpoint *breakpoint2 = NULL;
10548   struct cleanup *old_chain;
10549   int thread;
10550   struct thread_info *tp;
10551
10552   clear_proceed_status ();
10553
10554   /* Set a breakpoint where the user wants it and at return from
10555      this function.  */
10556
10557   if (last_displayed_sal_is_valid ())
10558     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10559                           get_last_displayed_symtab (),
10560                           get_last_displayed_line ());
10561   else
10562     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10563                           (struct symtab *) NULL, 0);
10564
10565   if (sals.nelts != 1)
10566     error (_("Couldn't get information on specified line."));
10567
10568   sal = sals.sals[0];
10569   xfree (sals.sals);    /* malloc'd, so freed.  */
10570
10571   if (*arg)
10572     error (_("Junk at end of arguments."));
10573
10574   resolve_sal_pc (&sal);
10575
10576   tp = inferior_thread ();
10577   thread = tp->num;
10578
10579   old_chain = make_cleanup (null_cleanup, NULL);
10580
10581   /* Installing a breakpoint invalidates the frame chain (as it may
10582      need to switch threads), so do any frame handling first.  */
10583
10584   /* Keep within the current frame, or in frames called by the current
10585      one.  */
10586
10587   if (frame_id_p (caller_frame_id))
10588     {
10589       struct symtab_and_line sal2;
10590
10591       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10592       sal2.pc = frame_unwind_caller_pc (frame);
10593       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
10594                                               sal2,
10595                                               caller_frame_id,
10596                                               bp_until);
10597       make_cleanup_delete_breakpoint (breakpoint2);
10598
10599       set_longjmp_breakpoint (tp, caller_frame_id);
10600       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
10601     }
10602
10603   /* set_momentary_breakpoint could invalidate FRAME.  */
10604   frame = NULL;
10605
10606   if (anywhere)
10607     /* If the user told us to continue until a specified location,
10608        we don't specify a frame at which we need to stop.  */
10609     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10610                                            null_frame_id, bp_until);
10611   else
10612     /* Otherwise, specify the selected frame, because we want to stop
10613        only at the very same frame.  */
10614     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10615                                            stack_frame_id, bp_until);
10616   make_cleanup_delete_breakpoint (breakpoint);
10617
10618   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
10619
10620   /* If we are running asynchronously, and proceed call above has
10621      actually managed to start the target, arrange for breakpoints to
10622      be deleted when the target stops.  Otherwise, we're already
10623      stopped and delete breakpoints via cleanup chain.  */
10624
10625   if (target_can_async_p () && is_running (inferior_ptid))
10626     {
10627       struct until_break_command_continuation_args *args;
10628       args = xmalloc (sizeof (*args));
10629
10630       args->breakpoint = breakpoint;
10631       args->breakpoint2 = breakpoint2;
10632       args->thread_num = thread;
10633
10634       discard_cleanups (old_chain);
10635       add_continuation (inferior_thread (),
10636                         until_break_command_continuation, args,
10637                         xfree);
10638     }
10639   else
10640     do_cleanups (old_chain);
10641 }
10642
10643 /* This function attempts to parse an optional "if <cond>" clause
10644    from the arg string.  If one is not found, it returns NULL.
10645
10646    Else, it returns a pointer to the condition string.  (It does not
10647    attempt to evaluate the string against a particular block.)  And,
10648    it updates arg to point to the first character following the parsed
10649    if clause in the arg string.  */
10650
10651 static char *
10652 ep_parse_optional_if_clause (char **arg)
10653 {
10654   char *cond_string;
10655
10656   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
10657     return NULL;
10658
10659   /* Skip the "if" keyword.  */
10660   (*arg) += 2;
10661
10662   /* Skip any extra leading whitespace, and record the start of the
10663      condition string.  */
10664   *arg = skip_spaces (*arg);
10665   cond_string = *arg;
10666
10667   /* Assume that the condition occupies the remainder of the arg
10668      string.  */
10669   (*arg) += strlen (cond_string);
10670
10671   return cond_string;
10672 }
10673
10674 /* Commands to deal with catching events, such as signals, exceptions,
10675    process start/exit, etc.  */
10676
10677 typedef enum
10678 {
10679   catch_fork_temporary, catch_vfork_temporary,
10680   catch_fork_permanent, catch_vfork_permanent
10681 }
10682 catch_fork_kind;
10683
10684 static void
10685 catch_fork_command_1 (char *arg, int from_tty, 
10686                       struct cmd_list_element *command)
10687 {
10688   struct gdbarch *gdbarch = get_current_arch ();
10689   char *cond_string = NULL;
10690   catch_fork_kind fork_kind;
10691   int tempflag;
10692
10693   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
10694   tempflag = (fork_kind == catch_fork_temporary
10695               || fork_kind == catch_vfork_temporary);
10696
10697   if (!arg)
10698     arg = "";
10699   arg = skip_spaces (arg);
10700
10701   /* The allowed syntax is:
10702      catch [v]fork
10703      catch [v]fork if <cond>
10704
10705      First, check if there's an if clause.  */
10706   cond_string = ep_parse_optional_if_clause (&arg);
10707
10708   if ((*arg != '\0') && !isspace (*arg))
10709     error (_("Junk at end of arguments."));
10710
10711   /* If this target supports it, create a fork or vfork catchpoint
10712      and enable reporting of such events.  */
10713   switch (fork_kind)
10714     {
10715     case catch_fork_temporary:
10716     case catch_fork_permanent:
10717       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10718                                           &catch_fork_breakpoint_ops);
10719       break;
10720     case catch_vfork_temporary:
10721     case catch_vfork_permanent:
10722       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10723                                           &catch_vfork_breakpoint_ops);
10724       break;
10725     default:
10726       error (_("unsupported or unknown fork kind; cannot catch it"));
10727       break;
10728     }
10729 }
10730
10731 static void
10732 catch_exec_command_1 (char *arg, int from_tty, 
10733                       struct cmd_list_element *command)
10734 {
10735   struct exec_catchpoint *c;
10736   struct gdbarch *gdbarch = get_current_arch ();
10737   int tempflag;
10738   char *cond_string = NULL;
10739
10740   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10741
10742   if (!arg)
10743     arg = "";
10744   arg = skip_spaces (arg);
10745
10746   /* The allowed syntax is:
10747      catch exec
10748      catch exec if <cond>
10749
10750      First, check if there's an if clause.  */
10751   cond_string = ep_parse_optional_if_clause (&arg);
10752
10753   if ((*arg != '\0') && !isspace (*arg))
10754     error (_("Junk at end of arguments."));
10755
10756   c = XNEW (struct exec_catchpoint);
10757   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
10758                    &catch_exec_breakpoint_ops);
10759   c->exec_pathname = NULL;
10760
10761   install_breakpoint (0, &c->base, 1);
10762 }
10763
10764 static enum print_stop_action
10765 print_it_exception_catchpoint (bpstat bs)
10766 {
10767   struct ui_out *uiout = current_uiout;
10768   struct breakpoint *b = bs->breakpoint_at;
10769   int bp_temp, bp_throw;
10770
10771   annotate_catchpoint (b->number);
10772
10773   bp_throw = strstr (b->addr_string, "throw") != NULL;
10774   if (b->loc->address != b->loc->requested_address)
10775     breakpoint_adjustment_warning (b->loc->requested_address,
10776                                    b->loc->address,
10777                                    b->number, 1);
10778   bp_temp = b->disposition == disp_del;
10779   ui_out_text (uiout, 
10780                bp_temp ? "Temporary catchpoint "
10781                        : "Catchpoint ");
10782   if (!ui_out_is_mi_like_p (uiout))
10783     ui_out_field_int (uiout, "bkptno", b->number);
10784   ui_out_text (uiout,
10785                bp_throw ? " (exception thrown), "
10786                         : " (exception caught), ");
10787   if (ui_out_is_mi_like_p (uiout))
10788     {
10789       ui_out_field_string (uiout, "reason", 
10790                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10791       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10792       ui_out_field_int (uiout, "bkptno", b->number);
10793     }
10794   return PRINT_SRC_AND_LOC;
10795 }
10796
10797 static void
10798 print_one_exception_catchpoint (struct breakpoint *b, 
10799                                 struct bp_location **last_loc)
10800 {
10801   struct value_print_options opts;
10802   struct ui_out *uiout = current_uiout;
10803
10804   get_user_print_options (&opts);
10805   if (opts.addressprint)
10806     {
10807       annotate_field (4);
10808       if (b->loc == NULL || b->loc->shlib_disabled)
10809         ui_out_field_string (uiout, "addr", "<PENDING>");
10810       else
10811         ui_out_field_core_addr (uiout, "addr",
10812                                 b->loc->gdbarch, b->loc->address);
10813     }
10814   annotate_field (5);
10815   if (b->loc)
10816     *last_loc = b->loc;
10817   if (strstr (b->addr_string, "throw") != NULL)
10818     ui_out_field_string (uiout, "what", "exception throw");
10819   else
10820     ui_out_field_string (uiout, "what", "exception catch");
10821 }
10822
10823 static void
10824 print_mention_exception_catchpoint (struct breakpoint *b)
10825 {
10826   struct ui_out *uiout = current_uiout;
10827   int bp_temp;
10828   int bp_throw;
10829
10830   bp_temp = b->disposition == disp_del;
10831   bp_throw = strstr (b->addr_string, "throw") != NULL;
10832   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
10833                               : _("Catchpoint "));
10834   ui_out_field_int (uiout, "bkptno", b->number);
10835   ui_out_text (uiout, bp_throw ? _(" (throw)")
10836                                : _(" (catch)"));
10837 }
10838
10839 /* Implement the "print_recreate" breakpoint_ops method for throw and
10840    catch catchpoints.  */
10841
10842 static void
10843 print_recreate_exception_catchpoint (struct breakpoint *b, 
10844                                      struct ui_file *fp)
10845 {
10846   int bp_temp;
10847   int bp_throw;
10848
10849   bp_temp = b->disposition == disp_del;
10850   bp_throw = strstr (b->addr_string, "throw") != NULL;
10851   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
10852   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
10853   print_recreate_thread (b, fp);
10854 }
10855
10856 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
10857
10858 static int
10859 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
10860                           enum exception_event_kind ex_event, int from_tty)
10861 {
10862   char *trigger_func_name;
10863  
10864   if (ex_event == EX_EVENT_CATCH)
10865     trigger_func_name = "__cxa_begin_catch";
10866   else
10867     trigger_func_name = "__cxa_throw";
10868
10869   create_breakpoint (get_current_arch (),
10870                      trigger_func_name, cond_string, -1,
10871                      0 /* condition and thread are valid.  */,
10872                      tempflag, bp_breakpoint,
10873                      0,
10874                      AUTO_BOOLEAN_TRUE /* pending */,
10875                      &gnu_v3_exception_catchpoint_ops, from_tty,
10876                      1 /* enabled */,
10877                      0 /* internal */,
10878                      0);
10879
10880   return 1;
10881 }
10882
10883 /* Deal with "catch catch" and "catch throw" commands.  */
10884
10885 static void
10886 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
10887                            int tempflag, int from_tty)
10888 {
10889   char *cond_string = NULL;
10890
10891   if (!arg)
10892     arg = "";
10893   arg = skip_spaces (arg);
10894
10895   cond_string = ep_parse_optional_if_clause (&arg);
10896
10897   if ((*arg != '\0') && !isspace (*arg))
10898     error (_("Junk at end of arguments."));
10899
10900   if (ex_event != EX_EVENT_THROW
10901       && ex_event != EX_EVENT_CATCH)
10902     error (_("Unsupported or unknown exception event; cannot catch it"));
10903
10904   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
10905     return;
10906
10907   warning (_("Unsupported with this platform/compiler combination."));
10908 }
10909
10910 /* Implementation of "catch catch" command.  */
10911
10912 static void
10913 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
10914 {
10915   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10916
10917   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
10918 }
10919
10920 /* Implementation of "catch throw" command.  */
10921
10922 static void
10923 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
10924 {
10925   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10926
10927   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
10928 }
10929
10930 void
10931 init_ada_exception_breakpoint (struct breakpoint *b,
10932                                struct gdbarch *gdbarch,
10933                                struct symtab_and_line sal,
10934                                char *addr_string,
10935                                const struct breakpoint_ops *ops,
10936                                int tempflag,
10937                                int from_tty)
10938 {
10939   if (from_tty)
10940     {
10941       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
10942       if (!loc_gdbarch)
10943         loc_gdbarch = gdbarch;
10944
10945       describe_other_breakpoints (loc_gdbarch,
10946                                   sal.pspace, sal.pc, sal.section, -1);
10947       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
10948          version for exception catchpoints, because two catchpoints
10949          used for different exception names will use the same address.
10950          In this case, a "breakpoint ... also set at..." warning is
10951          unproductive.  Besides, the warning phrasing is also a bit
10952          inappropriate, we should use the word catchpoint, and tell
10953          the user what type of catchpoint it is.  The above is good
10954          enough for now, though.  */
10955     }
10956
10957   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
10958
10959   b->enable_state = bp_enabled;
10960   b->disposition = tempflag ? disp_del : disp_donttouch;
10961   b->addr_string = addr_string;
10962   b->language = language_ada;
10963 }
10964
10965 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
10966    filter list, or NULL if no filtering is required.  */
10967 static VEC(int) *
10968 catch_syscall_split_args (char *arg)
10969 {
10970   VEC(int) *result = NULL;
10971   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
10972
10973   while (*arg != '\0')
10974     {
10975       int i, syscall_number;
10976       char *endptr;
10977       char cur_name[128];
10978       struct syscall s;
10979
10980       /* Skip whitespace.  */
10981       while (isspace (*arg))
10982         arg++;
10983
10984       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
10985         cur_name[i] = arg[i];
10986       cur_name[i] = '\0';
10987       arg += i;
10988
10989       /* Check if the user provided a syscall name or a number.  */
10990       syscall_number = (int) strtol (cur_name, &endptr, 0);
10991       if (*endptr == '\0')
10992         get_syscall_by_number (syscall_number, &s);
10993       else
10994         {
10995           /* We have a name.  Let's check if it's valid and convert it
10996              to a number.  */
10997           get_syscall_by_name (cur_name, &s);
10998
10999           if (s.number == UNKNOWN_SYSCALL)
11000             /* Here we have to issue an error instead of a warning,
11001                because GDB cannot do anything useful if there's no
11002                syscall number to be caught.  */
11003             error (_("Unknown syscall name '%s'."), cur_name);
11004         }
11005
11006       /* Ok, it's valid.  */
11007       VEC_safe_push (int, result, s.number);
11008     }
11009
11010   discard_cleanups (cleanup);
11011   return result;
11012 }
11013
11014 /* Implement the "catch syscall" command.  */
11015
11016 static void
11017 catch_syscall_command_1 (char *arg, int from_tty, 
11018                          struct cmd_list_element *command)
11019 {
11020   int tempflag;
11021   VEC(int) *filter;
11022   struct syscall s;
11023   struct gdbarch *gdbarch = get_current_arch ();
11024
11025   /* Checking if the feature if supported.  */
11026   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11027     error (_("The feature 'catch syscall' is not supported on \
11028 this architecture yet."));
11029
11030   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11031
11032   arg = skip_spaces (arg);
11033
11034   /* We need to do this first "dummy" translation in order
11035      to get the syscall XML file loaded or, most important,
11036      to display a warning to the user if there's no XML file
11037      for his/her architecture.  */
11038   get_syscall_by_number (0, &s);
11039
11040   /* The allowed syntax is:
11041      catch syscall
11042      catch syscall <name | number> [<name | number> ... <name | number>]
11043
11044      Let's check if there's a syscall name.  */
11045
11046   if (arg != NULL)
11047     filter = catch_syscall_split_args (arg);
11048   else
11049     filter = NULL;
11050
11051   create_syscall_event_catchpoint (tempflag, filter,
11052                                    &catch_syscall_breakpoint_ops);
11053 }
11054
11055 static void
11056 catch_command (char *arg, int from_tty)
11057 {
11058   error (_("Catch requires an event name."));
11059 }
11060 \f
11061
11062 static void
11063 tcatch_command (char *arg, int from_tty)
11064 {
11065   error (_("Catch requires an event name."));
11066 }
11067
11068 /* A qsort comparison function that sorts breakpoints in order.  */
11069
11070 static int
11071 compare_breakpoints (const void *a, const void *b)
11072 {
11073   const breakpoint_p *ba = a;
11074   uintptr_t ua = (uintptr_t) *ba;
11075   const breakpoint_p *bb = b;
11076   uintptr_t ub = (uintptr_t) *bb;
11077
11078   if ((*ba)->number < (*bb)->number)
11079     return -1;
11080   else if ((*ba)->number > (*bb)->number)
11081     return 1;
11082
11083   /* Now sort by address, in case we see, e..g, two breakpoints with
11084      the number 0.  */
11085   if (ua < ub)
11086     return -1;
11087   return ub > ub ? 1 : 0;
11088 }
11089
11090 /* Delete breakpoints by address or line.  */
11091
11092 static void
11093 clear_command (char *arg, int from_tty)
11094 {
11095   struct breakpoint *b, *prev;
11096   VEC(breakpoint_p) *found = 0;
11097   int ix;
11098   int default_match;
11099   struct symtabs_and_lines sals;
11100   struct symtab_and_line sal;
11101   int i;
11102   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11103
11104   if (arg)
11105     {
11106       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
11107                                      | DECODE_LINE_LIST_MODE));
11108       default_match = 0;
11109     }
11110   else
11111     {
11112       sals.sals = (struct symtab_and_line *)
11113         xmalloc (sizeof (struct symtab_and_line));
11114       make_cleanup (xfree, sals.sals);
11115       init_sal (&sal);          /* Initialize to zeroes.  */
11116
11117       /* Set sal's line, symtab, pc, and pspace to the values
11118          corresponding to the last call to print_frame_info.  If the
11119          codepoint is not valid, this will set all the fields to 0.  */
11120       get_last_displayed_sal (&sal);
11121       if (sal.symtab == 0)
11122         error (_("No source file specified."));
11123
11124       sals.sals[0] = sal;
11125       sals.nelts = 1;
11126
11127       default_match = 1;
11128     }
11129
11130   /* We don't call resolve_sal_pc here.  That's not as bad as it
11131      seems, because all existing breakpoints typically have both
11132      file/line and pc set.  So, if clear is given file/line, we can
11133      match this to existing breakpoint without obtaining pc at all.
11134
11135      We only support clearing given the address explicitly 
11136      present in breakpoint table.  Say, we've set breakpoint 
11137      at file:line.  There were several PC values for that file:line,
11138      due to optimization, all in one block.
11139
11140      We've picked one PC value.  If "clear" is issued with another
11141      PC corresponding to the same file:line, the breakpoint won't
11142      be cleared.  We probably can still clear the breakpoint, but 
11143      since the other PC value is never presented to user, user
11144      can only find it by guessing, and it does not seem important
11145      to support that.  */
11146
11147   /* For each line spec given, delete bps which correspond to it.  Do
11148      it in two passes, solely to preserve the current behavior that
11149      from_tty is forced true if we delete more than one
11150      breakpoint.  */
11151
11152   found = NULL;
11153   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11154   for (i = 0; i < sals.nelts; i++)
11155     {
11156       int is_abs, sal_name_len;
11157
11158       /* If exact pc given, clear bpts at that pc.
11159          If line given (pc == 0), clear all bpts on specified line.
11160          If defaulting, clear all bpts on default line
11161          or at default pc.
11162
11163          defaulting    sal.pc != 0    tests to do
11164
11165          0              1             pc
11166          1              1             pc _and_ line
11167          0              0             line
11168          1              0             <can't happen> */
11169
11170       sal = sals.sals[i];
11171       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
11172       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
11173
11174       /* Find all matching breakpoints and add them to 'found'.  */
11175       ALL_BREAKPOINTS (b)
11176         {
11177           int match = 0;
11178           /* Are we going to delete b?  */
11179           if (b->type != bp_none && !is_watchpoint (b))
11180             {
11181               struct bp_location *loc = b->loc;
11182               for (; loc; loc = loc->next)
11183                 {
11184                   /* If the user specified file:line, don't allow a PC
11185                      match.  This matches historical gdb behavior.  */
11186                   int pc_match = (!sal.explicit_line
11187                                   && sal.pc
11188                                   && (loc->pspace == sal.pspace)
11189                                   && (loc->address == sal.pc)
11190                                   && (!section_is_overlay (loc->section)
11191                                       || loc->section == sal.section));
11192                   int line_match = 0;
11193
11194                   if ((default_match || sal.explicit_line)
11195                       && loc->source_file != NULL
11196                       && sal.symtab != NULL
11197                       && sal.pspace == loc->pspace
11198                       && loc->line_number == sal.line)
11199                     {
11200                       if (filename_cmp (loc->source_file,
11201                                         sal.symtab->filename) == 0)
11202                         line_match = 1;
11203                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
11204                                && compare_filenames_for_search (loc->source_file,
11205                                                                 sal.symtab->filename,
11206                                                                 sal_name_len))
11207                         line_match = 1;
11208                     }
11209
11210                   if (pc_match || line_match)
11211                     {
11212                       match = 1;
11213                       break;
11214                     }
11215                 }
11216             }
11217
11218           if (match)
11219             VEC_safe_push(breakpoint_p, found, b);
11220         }
11221     }
11222
11223   /* Now go thru the 'found' chain and delete them.  */
11224   if (VEC_empty(breakpoint_p, found))
11225     {
11226       if (arg)
11227         error (_("No breakpoint at %s."), arg);
11228       else
11229         error (_("No breakpoint at this line."));
11230     }
11231
11232   /* Remove duplicates from the vec.  */
11233   qsort (VEC_address (breakpoint_p, found),
11234          VEC_length (breakpoint_p, found),
11235          sizeof (breakpoint_p),
11236          compare_breakpoints);
11237   prev = VEC_index (breakpoint_p, found, 0);
11238   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11239     {
11240       if (b == prev)
11241         {
11242           VEC_ordered_remove (breakpoint_p, found, ix);
11243           --ix;
11244         }
11245     }
11246
11247   if (VEC_length(breakpoint_p, found) > 1)
11248     from_tty = 1;       /* Always report if deleted more than one.  */
11249   if (from_tty)
11250     {
11251       if (VEC_length(breakpoint_p, found) == 1)
11252         printf_unfiltered (_("Deleted breakpoint "));
11253       else
11254         printf_unfiltered (_("Deleted breakpoints "));
11255     }
11256   breakpoints_changed ();
11257
11258   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11259     {
11260       if (from_tty)
11261         printf_unfiltered ("%d ", b->number);
11262       delete_breakpoint (b);
11263     }
11264   if (from_tty)
11265     putchar_unfiltered ('\n');
11266
11267   do_cleanups (cleanups);
11268 }
11269 \f
11270 /* Delete breakpoint in BS if they are `delete' breakpoints and
11271    all breakpoints that are marked for deletion, whether hit or not.
11272    This is called after any breakpoint is hit, or after errors.  */
11273
11274 void
11275 breakpoint_auto_delete (bpstat bs)
11276 {
11277   struct breakpoint *b, *b_tmp;
11278
11279   for (; bs; bs = bs->next)
11280     if (bs->breakpoint_at
11281         && bs->breakpoint_at->disposition == disp_del
11282         && bs->stop)
11283       delete_breakpoint (bs->breakpoint_at);
11284
11285   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11286   {
11287     if (b->disposition == disp_del_at_next_stop)
11288       delete_breakpoint (b);
11289   }
11290 }
11291
11292 /* A comparison function for bp_location AP and BP being interfaced to
11293    qsort.  Sort elements primarily by their ADDRESS (no matter what
11294    does breakpoint_address_is_meaningful say for its OWNER),
11295    secondarily by ordering first bp_permanent OWNERed elements and
11296    terciarily just ensuring the array is sorted stable way despite
11297    qsort being an unstable algorithm.  */
11298
11299 static int
11300 bp_location_compare (const void *ap, const void *bp)
11301 {
11302   struct bp_location *a = *(void **) ap;
11303   struct bp_location *b = *(void **) bp;
11304   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11305   int a_perm = a->owner->enable_state == bp_permanent;
11306   int b_perm = b->owner->enable_state == bp_permanent;
11307
11308   if (a->address != b->address)
11309     return (a->address > b->address) - (a->address < b->address);
11310
11311   /* Sort locations at the same address by their pspace number, keeping
11312      locations of the same inferior (in a multi-inferior environment)
11313      grouped.  */
11314
11315   if (a->pspace->num != b->pspace->num)
11316     return ((a->pspace->num > b->pspace->num)
11317             - (a->pspace->num < b->pspace->num));
11318
11319   /* Sort permanent breakpoints first.  */
11320   if (a_perm != b_perm)
11321     return (a_perm < b_perm) - (a_perm > b_perm);
11322
11323   /* Make the internal GDB representation stable across GDB runs
11324      where A and B memory inside GDB can differ.  Breakpoint locations of
11325      the same type at the same address can be sorted in arbitrary order.  */
11326
11327   if (a->owner->number != b->owner->number)
11328     return ((a->owner->number > b->owner->number)
11329             - (a->owner->number < b->owner->number));
11330
11331   return (a > b) - (a < b);
11332 }
11333
11334 /* Set bp_location_placed_address_before_address_max and
11335    bp_location_shadow_len_after_address_max according to the current
11336    content of the bp_location array.  */
11337
11338 static void
11339 bp_location_target_extensions_update (void)
11340 {
11341   struct bp_location *bl, **blp_tmp;
11342
11343   bp_location_placed_address_before_address_max = 0;
11344   bp_location_shadow_len_after_address_max = 0;
11345
11346   ALL_BP_LOCATIONS (bl, blp_tmp)
11347     {
11348       CORE_ADDR start, end, addr;
11349
11350       if (!bp_location_has_shadow (bl))
11351         continue;
11352
11353       start = bl->target_info.placed_address;
11354       end = start + bl->target_info.shadow_len;
11355
11356       gdb_assert (bl->address >= start);
11357       addr = bl->address - start;
11358       if (addr > bp_location_placed_address_before_address_max)
11359         bp_location_placed_address_before_address_max = addr;
11360
11361       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11362
11363       gdb_assert (bl->address < end);
11364       addr = end - bl->address;
11365       if (addr > bp_location_shadow_len_after_address_max)
11366         bp_location_shadow_len_after_address_max = addr;
11367     }
11368 }
11369
11370 /* Download tracepoint locations if they haven't been.  */
11371
11372 static void
11373 download_tracepoint_locations (void)
11374 {
11375   struct bp_location *bl, **blp_tmp;
11376   struct cleanup *old_chain;
11377
11378   if (!target_can_download_tracepoint ())
11379     return;
11380
11381   old_chain = save_current_space_and_thread ();
11382
11383   ALL_BP_LOCATIONS (bl, blp_tmp)
11384     {
11385       struct tracepoint *t;
11386
11387       if (!is_tracepoint (bl->owner))
11388         continue;
11389
11390       if ((bl->owner->type == bp_fast_tracepoint
11391            ? !may_insert_fast_tracepoints
11392            : !may_insert_tracepoints))
11393         continue;
11394
11395       /* In tracepoint, locations are _never_ duplicated, so
11396          should_be_inserted is equivalent to
11397          unduplicated_should_be_inserted.  */
11398       if (!should_be_inserted (bl) || bl->inserted)
11399         continue;
11400
11401       switch_to_program_space_and_thread (bl->pspace);
11402
11403       target_download_tracepoint (bl);
11404
11405       bl->inserted = 1;
11406       t = (struct tracepoint *) bl->owner;
11407       t->number_on_target = bl->owner->number;
11408     }
11409
11410   do_cleanups (old_chain);
11411 }
11412
11413 /* Swap the insertion/duplication state between two locations.  */
11414
11415 static void
11416 swap_insertion (struct bp_location *left, struct bp_location *right)
11417 {
11418   const int left_inserted = left->inserted;
11419   const int left_duplicate = left->duplicate;
11420   const int left_needs_update = left->needs_update;
11421   const struct bp_target_info left_target_info = left->target_info;
11422
11423   /* Locations of tracepoints can never be duplicated.  */
11424   if (is_tracepoint (left->owner))
11425     gdb_assert (!left->duplicate);
11426   if (is_tracepoint (right->owner))
11427     gdb_assert (!right->duplicate);
11428
11429   left->inserted = right->inserted;
11430   left->duplicate = right->duplicate;
11431   left->needs_update = right->needs_update;
11432   left->target_info = right->target_info;
11433   right->inserted = left_inserted;
11434   right->duplicate = left_duplicate;
11435   right->needs_update = left_needs_update;
11436   right->target_info = left_target_info;
11437 }
11438
11439 /* Force the re-insertion of the locations at ADDRESS.  This is called
11440    once a new/deleted/modified duplicate location is found and we are evaluating
11441    conditions on the target's side.  Such conditions need to be updated on
11442    the target.  */
11443
11444 static void
11445 force_breakpoint_reinsertion (struct bp_location *bl)
11446 {
11447   struct bp_location **locp = NULL, **loc2p;
11448   struct bp_location *loc;
11449   CORE_ADDR address = 0;
11450   int pspace_num;
11451
11452   address = bl->address;
11453   pspace_num = bl->pspace->num;
11454
11455   /* This is only meaningful if the target is
11456      evaluating conditions and if the user has
11457      opted for condition evaluation on the target's
11458      side.  */
11459   if (gdb_evaluates_breakpoint_condition_p ()
11460       || !target_supports_evaluation_of_breakpoint_conditions ())
11461     return;
11462
11463   /* Flag all breakpoint locations with this address and
11464      the same program space as the location
11465      as "its condition has changed".  We need to
11466      update the conditions on the target's side.  */
11467   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11468     {
11469       loc = *loc2p;
11470
11471       if (!is_breakpoint (loc->owner)
11472           || pspace_num != loc->pspace->num)
11473         continue;
11474
11475       /* Flag the location appropriately.  We use a different state to
11476          let everyone know that we already updated the set of locations
11477          with addr bl->address and program space bl->pspace.  This is so
11478          we don't have to keep calling these functions just to mark locations
11479          that have already been marked.  */
11480       loc->condition_changed = condition_updated;
11481
11482       /* Free the agent expression bytecode as well.  We will compute
11483          it later on.  */
11484       if (loc->cond_bytecode)
11485         {
11486           free_agent_expr (loc->cond_bytecode);
11487           loc->cond_bytecode = NULL;
11488         }
11489     }
11490 }
11491
11492 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
11493    into the inferior, only remove already-inserted locations that no
11494    longer should be inserted.  Functions that delete a breakpoint or
11495    breakpoints should pass false, so that deleting a breakpoint
11496    doesn't have the side effect of inserting the locations of other
11497    breakpoints that are marked not-inserted, but should_be_inserted
11498    returns true on them.
11499
11500    This behaviour is useful is situations close to tear-down -- e.g.,
11501    after an exec, while the target still has execution, but breakpoint
11502    shadows of the previous executable image should *NOT* be restored
11503    to the new image; or before detaching, where the target still has
11504    execution and wants to delete breakpoints from GDB's lists, and all
11505    breakpoints had already been removed from the inferior.  */
11506
11507 static void
11508 update_global_location_list (int should_insert)
11509 {
11510   struct breakpoint *b;
11511   struct bp_location **locp, *loc;
11512   struct cleanup *cleanups;
11513   /* Last breakpoint location address that was marked for update.  */
11514   CORE_ADDR last_addr = 0;
11515   /* Last breakpoint location program space that was marked for update.  */
11516   int last_pspace_num = -1;
11517
11518   /* Used in the duplicates detection below.  When iterating over all
11519      bp_locations, points to the first bp_location of a given address.
11520      Breakpoints and watchpoints of different types are never
11521      duplicates of each other.  Keep one pointer for each type of
11522      breakpoint/watchpoint, so we only need to loop over all locations
11523      once.  */
11524   struct bp_location *bp_loc_first;  /* breakpoint */
11525   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11526   struct bp_location *awp_loc_first; /* access watchpoint */
11527   struct bp_location *rwp_loc_first; /* read watchpoint */
11528
11529   /* Saved former bp_location array which we compare against the newly
11530      built bp_location from the current state of ALL_BREAKPOINTS.  */
11531   struct bp_location **old_location, **old_locp;
11532   unsigned old_location_count;
11533
11534   old_location = bp_location;
11535   old_location_count = bp_location_count;
11536   bp_location = NULL;
11537   bp_location_count = 0;
11538   cleanups = make_cleanup (xfree, old_location);
11539
11540   ALL_BREAKPOINTS (b)
11541     for (loc = b->loc; loc; loc = loc->next)
11542       bp_location_count++;
11543
11544   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
11545   locp = bp_location;
11546   ALL_BREAKPOINTS (b)
11547     for (loc = b->loc; loc; loc = loc->next)
11548       *locp++ = loc;
11549   qsort (bp_location, bp_location_count, sizeof (*bp_location),
11550          bp_location_compare);
11551
11552   bp_location_target_extensions_update ();
11553
11554   /* Identify bp_location instances that are no longer present in the
11555      new list, and therefore should be freed.  Note that it's not
11556      necessary that those locations should be removed from inferior --
11557      if there's another location at the same address (previously
11558      marked as duplicate), we don't need to remove/insert the
11559      location.
11560      
11561      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11562      and former bp_location array state respectively.  */
11563
11564   locp = bp_location;
11565   for (old_locp = old_location; old_locp < old_location + old_location_count;
11566        old_locp++)
11567     {
11568       struct bp_location *old_loc = *old_locp;
11569       struct bp_location **loc2p;
11570
11571       /* Tells if 'old_loc' is found among the new locations.  If
11572          not, we have to free it.  */
11573       int found_object = 0;
11574       /* Tells if the location should remain inserted in the target.  */
11575       int keep_in_target = 0;
11576       int removed = 0;
11577
11578       /* Skip LOCP entries which will definitely never be needed.
11579          Stop either at or being the one matching OLD_LOC.  */
11580       while (locp < bp_location + bp_location_count
11581              && (*locp)->address < old_loc->address)
11582         locp++;
11583
11584       for (loc2p = locp;
11585            (loc2p < bp_location + bp_location_count
11586             && (*loc2p)->address == old_loc->address);
11587            loc2p++)
11588         {
11589           /* Check if this is a new/duplicated location or a duplicated
11590              location that had its condition modified.  If so, we want to send
11591              its condition to the target if evaluation of conditions is taking
11592              place there.  */
11593           if ((*loc2p)->condition_changed == condition_modified
11594               && (last_addr != old_loc->address
11595                   || last_pspace_num != old_loc->pspace->num))
11596             {
11597               force_breakpoint_reinsertion (*loc2p);
11598               last_pspace_num = old_loc->pspace->num;
11599             }
11600
11601           if (*loc2p == old_loc)
11602             found_object = 1;
11603         }
11604
11605       /* We have already handled this address, update it so that we don't
11606          have to go through updates again.  */
11607       last_addr = old_loc->address;
11608
11609       /* Target-side condition evaluation: Handle deleted locations.  */
11610       if (!found_object)
11611         force_breakpoint_reinsertion (old_loc);
11612
11613       /* If this location is no longer present, and inserted, look if
11614          there's maybe a new location at the same address.  If so,
11615          mark that one inserted, and don't remove this one.  This is
11616          needed so that we don't have a time window where a breakpoint
11617          at certain location is not inserted.  */
11618
11619       if (old_loc->inserted)
11620         {
11621           /* If the location is inserted now, we might have to remove
11622              it.  */
11623
11624           if (found_object && should_be_inserted (old_loc))
11625             {
11626               /* The location is still present in the location list,
11627                  and still should be inserted.  Don't do anything.  */
11628               keep_in_target = 1;
11629             }
11630           else
11631             {
11632               /* This location still exists, but it won't be kept in the
11633                  target since it may have been disabled.  We proceed to
11634                  remove its target-side condition.  */
11635
11636               /* The location is either no longer present, or got
11637                  disabled.  See if there's another location at the
11638                  same address, in which case we don't need to remove
11639                  this one from the target.  */
11640
11641               /* OLD_LOC comes from existing struct breakpoint.  */
11642               if (breakpoint_address_is_meaningful (old_loc->owner))
11643                 {
11644                   for (loc2p = locp;
11645                        (loc2p < bp_location + bp_location_count
11646                         && (*loc2p)->address == old_loc->address);
11647                        loc2p++)
11648                     {
11649                       struct bp_location *loc2 = *loc2p;
11650
11651                       if (breakpoint_locations_match (loc2, old_loc))
11652                         {
11653                           /* Read watchpoint locations are switched to
11654                              access watchpoints, if the former are not
11655                              supported, but the latter are.  */
11656                           if (is_hardware_watchpoint (old_loc->owner))
11657                             {
11658                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11659                               loc2->watchpoint_type = old_loc->watchpoint_type;
11660                             }
11661
11662                           /* loc2 is a duplicated location. We need to check
11663                              if it should be inserted in case it will be
11664                              unduplicated.  */
11665                           if (loc2 != old_loc
11666                               && unduplicated_should_be_inserted (loc2))
11667                             {
11668                               swap_insertion (old_loc, loc2);
11669                               keep_in_target = 1;
11670                               break;
11671                             }
11672                         }
11673                     }
11674                 }
11675             }
11676
11677           if (!keep_in_target)
11678             {
11679               if (remove_breakpoint (old_loc, mark_uninserted))
11680                 {
11681                   /* This is just about all we can do.  We could keep
11682                      this location on the global list, and try to
11683                      remove it next time, but there's no particular
11684                      reason why we will succeed next time.
11685                      
11686                      Note that at this point, old_loc->owner is still
11687                      valid, as delete_breakpoint frees the breakpoint
11688                      only after calling us.  */
11689                   printf_filtered (_("warning: Error removing "
11690                                      "breakpoint %d\n"), 
11691                                    old_loc->owner->number);
11692                 }
11693               removed = 1;
11694             }
11695         }
11696
11697       if (!found_object)
11698         {
11699           if (removed && non_stop
11700               && breakpoint_address_is_meaningful (old_loc->owner)
11701               && !is_hardware_watchpoint (old_loc->owner))
11702             {
11703               /* This location was removed from the target.  In
11704                  non-stop mode, a race condition is possible where
11705                  we've removed a breakpoint, but stop events for that
11706                  breakpoint are already queued and will arrive later.
11707                  We apply an heuristic to be able to distinguish such
11708                  SIGTRAPs from other random SIGTRAPs: we keep this
11709                  breakpoint location for a bit, and will retire it
11710                  after we see some number of events.  The theory here
11711                  is that reporting of events should, "on the average",
11712                  be fair, so after a while we'll see events from all
11713                  threads that have anything of interest, and no longer
11714                  need to keep this breakpoint location around.  We
11715                  don't hold locations forever so to reduce chances of
11716                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11717                  SIGTRAP.
11718
11719                  The heuristic failing can be disastrous on
11720                  decr_pc_after_break targets.
11721
11722                  On decr_pc_after_break targets, like e.g., x86-linux,
11723                  if we fail to recognize a late breakpoint SIGTRAP,
11724                  because events_till_retirement has reached 0 too
11725                  soon, we'll fail to do the PC adjustment, and report
11726                  a random SIGTRAP to the user.  When the user resumes
11727                  the inferior, it will most likely immediately crash
11728                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11729                  corrupted, because of being resumed e.g., in the
11730                  middle of a multi-byte instruction, or skipped a
11731                  one-byte instruction.  This was actually seen happen
11732                  on native x86-linux, and should be less rare on
11733                  targets that do not support new thread events, like
11734                  remote, due to the heuristic depending on
11735                  thread_count.
11736
11737                  Mistaking a random SIGTRAP for a breakpoint trap
11738                  causes similar symptoms (PC adjustment applied when
11739                  it shouldn't), but then again, playing with SIGTRAPs
11740                  behind the debugger's back is asking for trouble.
11741
11742                  Since hardware watchpoint traps are always
11743                  distinguishable from other traps, so we don't need to
11744                  apply keep hardware watchpoint moribund locations
11745                  around.  We simply always ignore hardware watchpoint
11746                  traps we can no longer explain.  */
11747
11748               old_loc->events_till_retirement = 3 * (thread_count () + 1);
11749               old_loc->owner = NULL;
11750
11751               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
11752             }
11753           else
11754             {
11755               old_loc->owner = NULL;
11756               decref_bp_location (&old_loc);
11757             }
11758         }
11759     }
11760
11761   /* Rescan breakpoints at the same address and section, marking the
11762      first one as "first" and any others as "duplicates".  This is so
11763      that the bpt instruction is only inserted once.  If we have a
11764      permanent breakpoint at the same place as BPT, make that one the
11765      official one, and the rest as duplicates.  Permanent breakpoints
11766      are sorted first for the same address.
11767
11768      Do the same for hardware watchpoints, but also considering the
11769      watchpoint's type (regular/access/read) and length.  */
11770
11771   bp_loc_first = NULL;
11772   wp_loc_first = NULL;
11773   awp_loc_first = NULL;
11774   rwp_loc_first = NULL;
11775   ALL_BP_LOCATIONS (loc, locp)
11776     {
11777       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11778          non-NULL.  */
11779       struct bp_location **loc_first_p;
11780       b = loc->owner;
11781
11782       if (!should_be_inserted (loc)
11783           || !breakpoint_address_is_meaningful (b)
11784           /* Don't detect duplicate for tracepoint locations because they are
11785            never duplicated.  See the comments in field `duplicate' of
11786            `struct bp_location'.  */
11787           || is_tracepoint (b))
11788         {
11789           /* Clear the condition modification flag.  */
11790           loc->condition_changed = condition_unchanged;
11791           continue;
11792         }
11793
11794       /* Permanent breakpoint should always be inserted.  */
11795       if (b->enable_state == bp_permanent && ! loc->inserted)
11796         internal_error (__FILE__, __LINE__,
11797                         _("allegedly permanent breakpoint is not "
11798                         "actually inserted"));
11799
11800       if (b->type == bp_hardware_watchpoint)
11801         loc_first_p = &wp_loc_first;
11802       else if (b->type == bp_read_watchpoint)
11803         loc_first_p = &rwp_loc_first;
11804       else if (b->type == bp_access_watchpoint)
11805         loc_first_p = &awp_loc_first;
11806       else
11807         loc_first_p = &bp_loc_first;
11808
11809       if (*loc_first_p == NULL
11810           || (overlay_debugging && loc->section != (*loc_first_p)->section)
11811           || !breakpoint_locations_match (loc, *loc_first_p))
11812         {
11813           *loc_first_p = loc;
11814           loc->duplicate = 0;
11815
11816           if (is_breakpoint (loc->owner) && loc->condition_changed)
11817             {
11818               loc->needs_update = 1;
11819               /* Clear the condition modification flag.  */
11820               loc->condition_changed = condition_unchanged;
11821             }
11822           continue;
11823         }
11824
11825
11826       /* This and the above ensure the invariant that the first location
11827          is not duplicated, and is the inserted one.
11828          All following are marked as duplicated, and are not inserted.  */
11829       if (loc->inserted)
11830         swap_insertion (loc, *loc_first_p);
11831       loc->duplicate = 1;
11832
11833       /* Clear the condition modification flag.  */
11834       loc->condition_changed = condition_unchanged;
11835
11836       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
11837           && b->enable_state != bp_permanent)
11838         internal_error (__FILE__, __LINE__,
11839                         _("another breakpoint was inserted on top of "
11840                         "a permanent breakpoint"));
11841     }
11842
11843   if (breakpoints_always_inserted_mode ()
11844       && (have_live_inferiors ()
11845           || (gdbarch_has_global_breakpoints (target_gdbarch))))
11846     {
11847       if (should_insert)
11848         insert_breakpoint_locations ();
11849       else
11850         {
11851           /* Though should_insert is false, we may need to update conditions
11852              on the target's side if it is evaluating such conditions.  We
11853              only update conditions for locations that are marked
11854              "needs_update".  */
11855           update_inserted_breakpoint_locations ();
11856         }
11857     }
11858
11859   if (should_insert)
11860     download_tracepoint_locations ();
11861
11862   do_cleanups (cleanups);
11863 }
11864
11865 void
11866 breakpoint_retire_moribund (void)
11867 {
11868   struct bp_location *loc;
11869   int ix;
11870
11871   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
11872     if (--(loc->events_till_retirement) == 0)
11873       {
11874         decref_bp_location (&loc);
11875         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
11876         --ix;
11877       }
11878 }
11879
11880 static void
11881 update_global_location_list_nothrow (int inserting)
11882 {
11883   volatile struct gdb_exception e;
11884
11885   TRY_CATCH (e, RETURN_MASK_ERROR)
11886     update_global_location_list (inserting);
11887 }
11888
11889 /* Clear BKP from a BPS.  */
11890
11891 static void
11892 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
11893 {
11894   bpstat bs;
11895
11896   for (bs = bps; bs; bs = bs->next)
11897     if (bs->breakpoint_at == bpt)
11898       {
11899         bs->breakpoint_at = NULL;
11900         bs->old_val = NULL;
11901         /* bs->commands will be freed later.  */
11902       }
11903 }
11904
11905 /* Callback for iterate_over_threads.  */
11906 static int
11907 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11908 {
11909   struct breakpoint *bpt = data;
11910
11911   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11912   return 0;
11913 }
11914
11915 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
11916    callbacks.  */
11917
11918 static void
11919 say_where (struct breakpoint *b)
11920 {
11921   struct ui_out *uiout = current_uiout;
11922   struct value_print_options opts;
11923
11924   get_user_print_options (&opts);
11925
11926   /* i18n: cagney/2005-02-11: Below needs to be merged into a
11927      single string.  */
11928   if (b->loc == NULL)
11929     {
11930       printf_filtered (_(" (%s) pending."), b->addr_string);
11931     }
11932   else
11933     {
11934       if (opts.addressprint || b->loc->source_file == NULL)
11935         {
11936           printf_filtered (" at ");
11937           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
11938                           gdb_stdout);
11939         }
11940       if (b->loc->source_file)
11941         {
11942           /* If there is a single location, we can print the location
11943              more nicely.  */
11944           if (b->loc->next == NULL)
11945             printf_filtered (": file %s, line %d.",
11946                              b->loc->source_file, b->loc->line_number);
11947           else
11948             /* This is not ideal, but each location may have a
11949                different file name, and this at least reflects the
11950                real situation somewhat.  */
11951             printf_filtered (": %s.", b->addr_string);
11952         }
11953
11954       if (b->loc->next)
11955         {
11956           struct bp_location *loc = b->loc;
11957           int n = 0;
11958           for (; loc; loc = loc->next)
11959             ++n;
11960           printf_filtered (" (%d locations)", n);
11961         }
11962     }
11963 }
11964
11965 /* Default bp_location_ops methods.  */
11966
11967 static void
11968 bp_location_dtor (struct bp_location *self)
11969 {
11970   xfree (self->cond);
11971   if (self->cond_bytecode)
11972     free_agent_expr (self->cond_bytecode);
11973   xfree (self->function_name);
11974   xfree (self->source_file);
11975 }
11976
11977 static const struct bp_location_ops bp_location_ops =
11978 {
11979   bp_location_dtor
11980 };
11981
11982 /* Default breakpoint_ops methods all breakpoint_ops ultimately
11983    inherit from.  */
11984
11985 static void
11986 base_breakpoint_dtor (struct breakpoint *self)
11987 {
11988   decref_counted_command_line (&self->commands);
11989   xfree (self->cond_string);
11990   xfree (self->addr_string);
11991   xfree (self->filter);
11992   xfree (self->addr_string_range_end);
11993 }
11994
11995 static struct bp_location *
11996 base_breakpoint_allocate_location (struct breakpoint *self)
11997 {
11998   struct bp_location *loc;
11999
12000   loc = XNEW (struct bp_location);
12001   init_bp_location (loc, &bp_location_ops, self);
12002   return loc;
12003 }
12004
12005 static void
12006 base_breakpoint_re_set (struct breakpoint *b)
12007 {
12008   /* Nothing to re-set. */
12009 }
12010
12011 #define internal_error_pure_virtual_called() \
12012   gdb_assert_not_reached ("pure virtual function called")
12013
12014 static int
12015 base_breakpoint_insert_location (struct bp_location *bl)
12016 {
12017   internal_error_pure_virtual_called ();
12018 }
12019
12020 static int
12021 base_breakpoint_remove_location (struct bp_location *bl)
12022 {
12023   internal_error_pure_virtual_called ();
12024 }
12025
12026 static int
12027 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12028                                 struct address_space *aspace,
12029                                 CORE_ADDR bp_addr,
12030                                 const struct target_waitstatus *ws)
12031 {
12032   internal_error_pure_virtual_called ();
12033 }
12034
12035 static void
12036 base_breakpoint_check_status (bpstat bs)
12037 {
12038   /* Always stop.   */
12039 }
12040
12041 /* A "works_in_software_mode" breakpoint_ops method that just internal
12042    errors.  */
12043
12044 static int
12045 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12046 {
12047   internal_error_pure_virtual_called ();
12048 }
12049
12050 /* A "resources_needed" breakpoint_ops method that just internal
12051    errors.  */
12052
12053 static int
12054 base_breakpoint_resources_needed (const struct bp_location *bl)
12055 {
12056   internal_error_pure_virtual_called ();
12057 }
12058
12059 static enum print_stop_action
12060 base_breakpoint_print_it (bpstat bs)
12061 {
12062   internal_error_pure_virtual_called ();
12063 }
12064
12065 static void
12066 base_breakpoint_print_one_detail (const struct breakpoint *self,
12067                                   struct ui_out *uiout)
12068 {
12069   /* nothing */
12070 }
12071
12072 static void
12073 base_breakpoint_print_mention (struct breakpoint *b)
12074 {
12075   internal_error_pure_virtual_called ();
12076 }
12077
12078 static void
12079 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12080 {
12081   internal_error_pure_virtual_called ();
12082 }
12083
12084 static void
12085 base_breakpoint_create_sals_from_address (char **arg,
12086                                           struct linespec_result *canonical,
12087                                           enum bptype type_wanted,
12088                                           char *addr_start,
12089                                           char **copy_arg)
12090 {
12091   internal_error_pure_virtual_called ();
12092 }
12093
12094 static void
12095 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12096                                         struct linespec_result *c,
12097                                         struct linespec_sals *lsal,
12098                                         char *cond_string,
12099                                         enum bptype type_wanted,
12100                                         enum bpdisp disposition,
12101                                         int thread,
12102                                         int task, int ignore_count,
12103                                         const struct breakpoint_ops *o,
12104                                         int from_tty, int enabled,
12105                                         int internal, unsigned flags)
12106 {
12107   internal_error_pure_virtual_called ();
12108 }
12109
12110 static void
12111 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12112                                  struct symtabs_and_lines *sals)
12113 {
12114   internal_error_pure_virtual_called ();
12115 }
12116
12117 static struct breakpoint_ops base_breakpoint_ops =
12118 {
12119   base_breakpoint_dtor,
12120   base_breakpoint_allocate_location,
12121   base_breakpoint_re_set,
12122   base_breakpoint_insert_location,
12123   base_breakpoint_remove_location,
12124   base_breakpoint_breakpoint_hit,
12125   base_breakpoint_check_status,
12126   base_breakpoint_resources_needed,
12127   base_breakpoint_works_in_software_mode,
12128   base_breakpoint_print_it,
12129   NULL,
12130   base_breakpoint_print_one_detail,
12131   base_breakpoint_print_mention,
12132   base_breakpoint_print_recreate,
12133   base_breakpoint_create_sals_from_address,
12134   base_breakpoint_create_breakpoints_sal,
12135   base_breakpoint_decode_linespec,
12136 };
12137
12138 /* Default breakpoint_ops methods.  */
12139
12140 static void
12141 bkpt_re_set (struct breakpoint *b)
12142 {
12143   /* FIXME: is this still reachable?  */
12144   if (b->addr_string == NULL)
12145     {
12146       /* Anything without a string can't be re-set.  */
12147       delete_breakpoint (b);
12148       return;
12149     }
12150
12151   breakpoint_re_set_default (b);
12152 }
12153
12154 static int
12155 bkpt_insert_location (struct bp_location *bl)
12156 {
12157   if (bl->loc_type == bp_loc_hardware_breakpoint)
12158     return target_insert_hw_breakpoint (bl->gdbarch,
12159                                         &bl->target_info);
12160   else
12161     return target_insert_breakpoint (bl->gdbarch,
12162                                      &bl->target_info);
12163 }
12164
12165 static int
12166 bkpt_remove_location (struct bp_location *bl)
12167 {
12168   if (bl->loc_type == bp_loc_hardware_breakpoint)
12169     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12170   else
12171     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12172 }
12173
12174 static int
12175 bkpt_breakpoint_hit (const struct bp_location *bl,
12176                      struct address_space *aspace, CORE_ADDR bp_addr,
12177                      const struct target_waitstatus *ws)
12178 {
12179   struct breakpoint *b = bl->owner;
12180
12181   if (ws->kind != TARGET_WAITKIND_STOPPED
12182       || ws->value.sig != TARGET_SIGNAL_TRAP)
12183     return 0;
12184
12185   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12186                                  aspace, bp_addr))
12187     return 0;
12188
12189   if (overlay_debugging         /* unmapped overlay section */
12190       && section_is_overlay (bl->section)
12191       && !section_is_mapped (bl->section))
12192     return 0;
12193
12194   return 1;
12195 }
12196
12197 static int
12198 bkpt_resources_needed (const struct bp_location *bl)
12199 {
12200   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12201
12202   return 1;
12203 }
12204
12205 static enum print_stop_action
12206 bkpt_print_it (bpstat bs)
12207 {
12208   struct breakpoint *b;
12209   const struct bp_location *bl;
12210   int bp_temp;
12211   struct ui_out *uiout = current_uiout;
12212
12213   gdb_assert (bs->bp_location_at != NULL);
12214
12215   bl = bs->bp_location_at;
12216   b = bs->breakpoint_at;
12217
12218   bp_temp = b->disposition == disp_del;
12219   if (bl->address != bl->requested_address)
12220     breakpoint_adjustment_warning (bl->requested_address,
12221                                    bl->address,
12222                                    b->number, 1);
12223   annotate_breakpoint (b->number);
12224   if (bp_temp)
12225     ui_out_text (uiout, "\nTemporary breakpoint ");
12226   else
12227     ui_out_text (uiout, "\nBreakpoint ");
12228   if (ui_out_is_mi_like_p (uiout))
12229     {
12230       ui_out_field_string (uiout, "reason",
12231                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12232       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12233     }
12234   ui_out_field_int (uiout, "bkptno", b->number);
12235   ui_out_text (uiout, ", ");
12236
12237   return PRINT_SRC_AND_LOC;
12238 }
12239
12240 static void
12241 bkpt_print_mention (struct breakpoint *b)
12242 {
12243   if (ui_out_is_mi_like_p (current_uiout))
12244     return;
12245
12246   switch (b->type)
12247     {
12248     case bp_breakpoint:
12249     case bp_gnu_ifunc_resolver:
12250       if (b->disposition == disp_del)
12251         printf_filtered (_("Temporary breakpoint"));
12252       else
12253         printf_filtered (_("Breakpoint"));
12254       printf_filtered (_(" %d"), b->number);
12255       if (b->type == bp_gnu_ifunc_resolver)
12256         printf_filtered (_(" at gnu-indirect-function resolver"));
12257       break;
12258     case bp_hardware_breakpoint:
12259       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12260       break;
12261     }
12262
12263   say_where (b);
12264 }
12265
12266 static void
12267 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12268 {
12269   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12270     fprintf_unfiltered (fp, "tbreak");
12271   else if (tp->type == bp_breakpoint)
12272     fprintf_unfiltered (fp, "break");
12273   else if (tp->type == bp_hardware_breakpoint
12274            && tp->disposition == disp_del)
12275     fprintf_unfiltered (fp, "thbreak");
12276   else if (tp->type == bp_hardware_breakpoint)
12277     fprintf_unfiltered (fp, "hbreak");
12278   else
12279     internal_error (__FILE__, __LINE__,
12280                     _("unhandled breakpoint type %d"), (int) tp->type);
12281
12282   fprintf_unfiltered (fp, " %s", tp->addr_string);
12283   print_recreate_thread (tp, fp);
12284 }
12285
12286 static void
12287 bkpt_create_sals_from_address (char **arg,
12288                                struct linespec_result *canonical,
12289                                enum bptype type_wanted,
12290                                char *addr_start, char **copy_arg)
12291 {
12292   create_sals_from_address_default (arg, canonical, type_wanted,
12293                                     addr_start, copy_arg);
12294 }
12295
12296 static void
12297 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12298                              struct linespec_result *canonical,
12299                              struct linespec_sals *lsal,
12300                              char *cond_string,
12301                              enum bptype type_wanted,
12302                              enum bpdisp disposition,
12303                              int thread,
12304                              int task, int ignore_count,
12305                              const struct breakpoint_ops *ops,
12306                              int from_tty, int enabled,
12307                              int internal, unsigned flags)
12308 {
12309   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12310                                   cond_string, type_wanted,
12311                                   disposition, thread, task,
12312                                   ignore_count, ops, from_tty,
12313                                   enabled, internal, flags);
12314 }
12315
12316 static void
12317 bkpt_decode_linespec (struct breakpoint *b, char **s,
12318                       struct symtabs_and_lines *sals)
12319 {
12320   decode_linespec_default (b, s, sals);
12321 }
12322
12323 /* Virtual table for internal breakpoints.  */
12324
12325 static void
12326 internal_bkpt_re_set (struct breakpoint *b)
12327 {
12328   switch (b->type)
12329     {
12330       /* Delete overlay event and longjmp master breakpoints; they
12331          will be reset later by breakpoint_re_set.  */
12332     case bp_overlay_event:
12333     case bp_longjmp_master:
12334     case bp_std_terminate_master:
12335     case bp_exception_master:
12336       delete_breakpoint (b);
12337       break;
12338
12339       /* This breakpoint is special, it's set up when the inferior
12340          starts and we really don't want to touch it.  */
12341     case bp_shlib_event:
12342
12343       /* Like bp_shlib_event, this breakpoint type is special.  Once
12344          it is set up, we do not want to touch it.  */
12345     case bp_thread_event:
12346       break;
12347     }
12348 }
12349
12350 static void
12351 internal_bkpt_check_status (bpstat bs)
12352 {
12353   if (bs->breakpoint_at->type == bp_shlib_event)
12354     {
12355       /* If requested, stop when the dynamic linker notifies GDB of
12356          events.  This allows the user to get control and place
12357          breakpoints in initializer routines for dynamically loaded
12358          objects (among other things).  */
12359       bs->stop = stop_on_solib_events;
12360       bs->print = stop_on_solib_events;
12361     }
12362   else
12363     bs->stop = 0;
12364 }
12365
12366 static enum print_stop_action
12367 internal_bkpt_print_it (bpstat bs)
12368 {
12369   struct ui_out *uiout = current_uiout;
12370   struct breakpoint *b;
12371
12372   b = bs->breakpoint_at;
12373
12374   switch (b->type)
12375     {
12376     case bp_shlib_event:
12377       /* Did we stop because the user set the stop_on_solib_events
12378          variable?  (If so, we report this as a generic, "Stopped due
12379          to shlib event" message.) */
12380       print_solib_event (0);
12381       break;
12382
12383     case bp_thread_event:
12384       /* Not sure how we will get here.
12385          GDB should not stop for these breakpoints.  */
12386       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12387       break;
12388
12389     case bp_overlay_event:
12390       /* By analogy with the thread event, GDB should not stop for these.  */
12391       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12392       break;
12393
12394     case bp_longjmp_master:
12395       /* These should never be enabled.  */
12396       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12397       break;
12398
12399     case bp_std_terminate_master:
12400       /* These should never be enabled.  */
12401       printf_filtered (_("std::terminate Master Breakpoint: "
12402                          "gdb should not stop!\n"));
12403       break;
12404
12405     case bp_exception_master:
12406       /* These should never be enabled.  */
12407       printf_filtered (_("Exception Master Breakpoint: "
12408                          "gdb should not stop!\n"));
12409       break;
12410     }
12411
12412   return PRINT_NOTHING;
12413 }
12414
12415 static void
12416 internal_bkpt_print_mention (struct breakpoint *b)
12417 {
12418   /* Nothing to mention.  These breakpoints are internal.  */
12419 }
12420
12421 /* Virtual table for momentary breakpoints  */
12422
12423 static void
12424 momentary_bkpt_re_set (struct breakpoint *b)
12425 {
12426   /* Keep temporary breakpoints, which can be encountered when we step
12427      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
12428      Otherwise these should have been blown away via the cleanup chain
12429      or by breakpoint_init_inferior when we rerun the executable.  */
12430 }
12431
12432 static void
12433 momentary_bkpt_check_status (bpstat bs)
12434 {
12435   /* Nothing.  The point of these breakpoints is causing a stop.  */
12436 }
12437
12438 static enum print_stop_action
12439 momentary_bkpt_print_it (bpstat bs)
12440 {
12441   struct ui_out *uiout = current_uiout;
12442
12443   if (ui_out_is_mi_like_p (uiout))
12444     {
12445       struct breakpoint *b = bs->breakpoint_at;
12446
12447       switch (b->type)
12448         {
12449         case bp_finish:
12450           ui_out_field_string
12451             (uiout, "reason",
12452              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
12453           break;
12454
12455         case bp_until:
12456           ui_out_field_string
12457             (uiout, "reason",
12458              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
12459           break;
12460         }
12461     }
12462
12463   return PRINT_UNKNOWN;
12464 }
12465
12466 static void
12467 momentary_bkpt_print_mention (struct breakpoint *b)
12468 {
12469   /* Nothing to mention.  These breakpoints are internal.  */
12470 }
12471
12472 /* Specific methods for probe breakpoints.  */
12473
12474 static int
12475 bkpt_probe_insert_location (struct bp_location *bl)
12476 {
12477   int v = bkpt_insert_location (bl);
12478
12479   if (v == 0)
12480     {
12481       /* The insertion was successful, now let's set the probe's semaphore
12482          if needed.  */
12483       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
12484     }
12485
12486   return v;
12487 }
12488
12489 static int
12490 bkpt_probe_remove_location (struct bp_location *bl)
12491 {
12492   /* Let's clear the semaphore before removing the location.  */
12493   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
12494
12495   return bkpt_remove_location (bl);
12496 }
12497
12498 static void
12499 bkpt_probe_create_sals_from_address (char **arg,
12500                                      struct linespec_result *canonical,
12501                                      enum bptype type_wanted,
12502                                      char *addr_start, char **copy_arg)
12503 {
12504   struct linespec_sals lsal;
12505
12506   lsal.sals = parse_probes (arg, canonical);
12507
12508   *copy_arg = xstrdup (canonical->addr_string);
12509   lsal.canonical = xstrdup (*copy_arg);
12510
12511   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12512 }
12513
12514 static void
12515 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
12516                             struct symtabs_and_lines *sals)
12517 {
12518   *sals = parse_probes (s, NULL);
12519   if (!sals->sals)
12520     error (_("probe not found"));
12521 }
12522
12523 /* The breakpoint_ops structure to be used in tracepoints.  */
12524
12525 static void
12526 tracepoint_re_set (struct breakpoint *b)
12527 {
12528   breakpoint_re_set_default (b);
12529 }
12530
12531 static int
12532 tracepoint_breakpoint_hit (const struct bp_location *bl,
12533                            struct address_space *aspace, CORE_ADDR bp_addr,
12534                            const struct target_waitstatus *ws)
12535 {
12536   /* By definition, the inferior does not report stops at
12537      tracepoints.  */
12538   return 0;
12539 }
12540
12541 static void
12542 tracepoint_print_one_detail (const struct breakpoint *self,
12543                              struct ui_out *uiout)
12544 {
12545   struct tracepoint *tp = (struct tracepoint *) self;
12546   if (tp->static_trace_marker_id)
12547     {
12548       gdb_assert (self->type == bp_static_tracepoint);
12549
12550       ui_out_text (uiout, "\tmarker id is ");
12551       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
12552                            tp->static_trace_marker_id);
12553       ui_out_text (uiout, "\n");
12554     }
12555 }
12556
12557 static void
12558 tracepoint_print_mention (struct breakpoint *b)
12559 {
12560   if (ui_out_is_mi_like_p (current_uiout))
12561     return;
12562
12563   switch (b->type)
12564     {
12565     case bp_tracepoint:
12566       printf_filtered (_("Tracepoint"));
12567       printf_filtered (_(" %d"), b->number);
12568       break;
12569     case bp_fast_tracepoint:
12570       printf_filtered (_("Fast tracepoint"));
12571       printf_filtered (_(" %d"), b->number);
12572       break;
12573     case bp_static_tracepoint:
12574       printf_filtered (_("Static tracepoint"));
12575       printf_filtered (_(" %d"), b->number);
12576       break;
12577     default:
12578       internal_error (__FILE__, __LINE__,
12579                       _("unhandled tracepoint type %d"), (int) b->type);
12580     }
12581
12582   say_where (b);
12583 }
12584
12585 static void
12586 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12587 {
12588   struct tracepoint *tp = (struct tracepoint *) self;
12589
12590   if (self->type == bp_fast_tracepoint)
12591     fprintf_unfiltered (fp, "ftrace");
12592   if (self->type == bp_static_tracepoint)
12593     fprintf_unfiltered (fp, "strace");
12594   else if (self->type == bp_tracepoint)
12595     fprintf_unfiltered (fp, "trace");
12596   else
12597     internal_error (__FILE__, __LINE__,
12598                     _("unhandled tracepoint type %d"), (int) self->type);
12599
12600   fprintf_unfiltered (fp, " %s", self->addr_string);
12601   print_recreate_thread (self, fp);
12602
12603   if (tp->pass_count)
12604     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12605 }
12606
12607 static void
12608 tracepoint_create_sals_from_address (char **arg,
12609                                      struct linespec_result *canonical,
12610                                      enum bptype type_wanted,
12611                                      char *addr_start, char **copy_arg)
12612 {
12613   create_sals_from_address_default (arg, canonical, type_wanted,
12614                                     addr_start, copy_arg);
12615 }
12616
12617 static void
12618 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12619                                    struct linespec_result *canonical,
12620                                    struct linespec_sals *lsal,
12621                                    char *cond_string,
12622                                    enum bptype type_wanted,
12623                                    enum bpdisp disposition,
12624                                    int thread,
12625                                    int task, int ignore_count,
12626                                    const struct breakpoint_ops *ops,
12627                                    int from_tty, int enabled,
12628                                    int internal, unsigned flags)
12629 {
12630   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12631                                   cond_string, type_wanted,
12632                                   disposition, thread, task,
12633                                   ignore_count, ops, from_tty,
12634                                   enabled, internal, flags);
12635 }
12636
12637 static void
12638 tracepoint_decode_linespec (struct breakpoint *b, char **s,
12639                             struct symtabs_and_lines *sals)
12640 {
12641   decode_linespec_default (b, s, sals);
12642 }
12643
12644 struct breakpoint_ops tracepoint_breakpoint_ops;
12645
12646 /* The breakpoint_ops structure to be use on tracepoints placed in a
12647    static probe.  */
12648
12649 static void
12650 tracepoint_probe_create_sals_from_address (char **arg,
12651                                            struct linespec_result *canonical,
12652                                            enum bptype type_wanted,
12653                                            char *addr_start, char **copy_arg)
12654 {
12655   /* We use the same method for breakpoint on probes.  */
12656   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
12657                                        addr_start, copy_arg);
12658 }
12659
12660 static void
12661 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
12662                                   struct symtabs_and_lines *sals)
12663 {
12664   /* We use the same method for breakpoint on probes.  */
12665   bkpt_probe_decode_linespec (b, s, sals);
12666 }
12667
12668 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
12669
12670 /* The breakpoint_ops structure to be used on static tracepoints with
12671    markers (`-m').  */
12672
12673 static void
12674 strace_marker_create_sals_from_address (char **arg,
12675                                         struct linespec_result *canonical,
12676                                         enum bptype type_wanted,
12677                                         char *addr_start, char **copy_arg)
12678 {
12679   struct linespec_sals lsal;
12680
12681   lsal.sals = decode_static_tracepoint_spec (arg);
12682
12683   *copy_arg = savestring (addr_start, *arg - addr_start);
12684
12685   canonical->addr_string = xstrdup (*copy_arg);
12686   lsal.canonical = xstrdup (*copy_arg);
12687   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12688 }
12689
12690 static void
12691 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12692                                       struct linespec_result *canonical,
12693                                       struct linespec_sals *lsal,
12694                                       char *cond_string,
12695                                       enum bptype type_wanted,
12696                                       enum bpdisp disposition,
12697                                       int thread,
12698                                       int task, int ignore_count,
12699                                       const struct breakpoint_ops *ops,
12700                                       int from_tty, int enabled,
12701                                       int internal, unsigned flags)
12702 {
12703   int i;
12704
12705   /* If the user is creating a static tracepoint by marker id
12706      (strace -m MARKER_ID), then store the sals index, so that
12707      breakpoint_re_set can try to match up which of the newly
12708      found markers corresponds to this one, and, don't try to
12709      expand multiple locations for each sal, given than SALS
12710      already should contain all sals for MARKER_ID.  */
12711
12712   for (i = 0; i < lsal->sals.nelts; ++i)
12713     {
12714       struct symtabs_and_lines expanded;
12715       struct tracepoint *tp;
12716       struct cleanup *old_chain;
12717       char *addr_string;
12718
12719       expanded.nelts = 1;
12720       expanded.sals = &lsal->sals.sals[i];
12721
12722       addr_string = xstrdup (canonical->addr_string);
12723       old_chain = make_cleanup (xfree, addr_string);
12724
12725       tp = XCNEW (struct tracepoint);
12726       init_breakpoint_sal (&tp->base, gdbarch, expanded,
12727                            addr_string, NULL,
12728                            cond_string, type_wanted, disposition,
12729                            thread, task, ignore_count, ops,
12730                            from_tty, enabled, internal, flags,
12731                            canonical->special_display);
12732       /* Given that its possible to have multiple markers with
12733          the same string id, if the user is creating a static
12734          tracepoint by marker id ("strace -m MARKER_ID"), then
12735          store the sals index, so that breakpoint_re_set can
12736          try to match up which of the newly found markers
12737          corresponds to this one  */
12738       tp->static_trace_marker_id_idx = i;
12739
12740       install_breakpoint (internal, &tp->base, 0);
12741
12742       discard_cleanups (old_chain);
12743     }
12744 }
12745
12746 static void
12747 strace_marker_decode_linespec (struct breakpoint *b, char **s,
12748                                struct symtabs_and_lines *sals)
12749 {
12750   struct tracepoint *tp = (struct tracepoint *) b;
12751
12752   *sals = decode_static_tracepoint_spec (s);
12753   if (sals->nelts > tp->static_trace_marker_id_idx)
12754     {
12755       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
12756       sals->nelts = 1;
12757     }
12758   else
12759     error (_("marker %s not found"), tp->static_trace_marker_id);
12760 }
12761
12762 static struct breakpoint_ops strace_marker_breakpoint_ops;
12763
12764 static int
12765 strace_marker_p (struct breakpoint *b)
12766 {
12767   return b->ops == &strace_marker_breakpoint_ops;
12768 }
12769
12770 /* Delete a breakpoint and clean up all traces of it in the data
12771    structures.  */
12772
12773 void
12774 delete_breakpoint (struct breakpoint *bpt)
12775 {
12776   struct breakpoint *b;
12777
12778   gdb_assert (bpt != NULL);
12779
12780   /* Has this bp already been deleted?  This can happen because
12781      multiple lists can hold pointers to bp's.  bpstat lists are
12782      especial culprits.
12783
12784      One example of this happening is a watchpoint's scope bp.  When
12785      the scope bp triggers, we notice that the watchpoint is out of
12786      scope, and delete it.  We also delete its scope bp.  But the
12787      scope bp is marked "auto-deleting", and is already on a bpstat.
12788      That bpstat is then checked for auto-deleting bp's, which are
12789      deleted.
12790
12791      A real solution to this problem might involve reference counts in
12792      bp's, and/or giving them pointers back to their referencing
12793      bpstat's, and teaching delete_breakpoint to only free a bp's
12794      storage when no more references were extent.  A cheaper bandaid
12795      was chosen.  */
12796   if (bpt->type == bp_none)
12797     return;
12798
12799   /* At least avoid this stale reference until the reference counting
12800      of breakpoints gets resolved.  */
12801   if (bpt->related_breakpoint != bpt)
12802     {
12803       struct breakpoint *related;
12804       struct watchpoint *w;
12805
12806       if (bpt->type == bp_watchpoint_scope)
12807         w = (struct watchpoint *) bpt->related_breakpoint;
12808       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12809         w = (struct watchpoint *) bpt;
12810       else
12811         w = NULL;
12812       if (w != NULL)
12813         watchpoint_del_at_next_stop (w);
12814
12815       /* Unlink bpt from the bpt->related_breakpoint ring.  */
12816       for (related = bpt; related->related_breakpoint != bpt;
12817            related = related->related_breakpoint);
12818       related->related_breakpoint = bpt->related_breakpoint;
12819       bpt->related_breakpoint = bpt;
12820     }
12821
12822   /* watch_command_1 creates a watchpoint but only sets its number if
12823      update_watchpoint succeeds in creating its bp_locations.  If there's
12824      a problem in that process, we'll be asked to delete the half-created
12825      watchpoint.  In that case, don't announce the deletion.  */
12826   if (bpt->number)
12827     observer_notify_breakpoint_deleted (bpt);
12828
12829   if (breakpoint_chain == bpt)
12830     breakpoint_chain = bpt->next;
12831
12832   ALL_BREAKPOINTS (b)
12833     if (b->next == bpt)
12834     {
12835       b->next = bpt->next;
12836       break;
12837     }
12838
12839   /* Be sure no bpstat's are pointing at the breakpoint after it's
12840      been freed.  */
12841   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
12842      in all threads for now.  Note that we cannot just remove bpstats
12843      pointing at bpt from the stop_bpstat list entirely, as breakpoint
12844      commands are associated with the bpstat; if we remove it here,
12845      then the later call to bpstat_do_actions (&stop_bpstat); in
12846      event-top.c won't do anything, and temporary breakpoints with
12847      commands won't work.  */
12848
12849   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12850
12851   /* Now that breakpoint is removed from breakpoint list, update the
12852      global location list.  This will remove locations that used to
12853      belong to this breakpoint.  Do this before freeing the breakpoint
12854      itself, since remove_breakpoint looks at location's owner.  It
12855      might be better design to have location completely
12856      self-contained, but it's not the case now.  */
12857   update_global_location_list (0);
12858
12859   bpt->ops->dtor (bpt);
12860   /* On the chance that someone will soon try again to delete this
12861      same bp, we mark it as deleted before freeing its storage.  */
12862   bpt->type = bp_none;
12863   xfree (bpt);
12864 }
12865
12866 static void
12867 do_delete_breakpoint_cleanup (void *b)
12868 {
12869   delete_breakpoint (b);
12870 }
12871
12872 struct cleanup *
12873 make_cleanup_delete_breakpoint (struct breakpoint *b)
12874 {
12875   return make_cleanup (do_delete_breakpoint_cleanup, b);
12876 }
12877
12878 /* Iterator function to call a user-provided callback function once
12879    for each of B and its related breakpoints.  */
12880
12881 static void
12882 iterate_over_related_breakpoints (struct breakpoint *b,
12883                                   void (*function) (struct breakpoint *,
12884                                                     void *),
12885                                   void *data)
12886 {
12887   struct breakpoint *related;
12888
12889   related = b;
12890   do
12891     {
12892       struct breakpoint *next;
12893
12894       /* FUNCTION may delete RELATED.  */
12895       next = related->related_breakpoint;
12896
12897       if (next == related)
12898         {
12899           /* RELATED is the last ring entry.  */
12900           function (related, data);
12901
12902           /* FUNCTION may have deleted it, so we'd never reach back to
12903              B.  There's nothing left to do anyway, so just break
12904              out.  */
12905           break;
12906         }
12907       else
12908         function (related, data);
12909
12910       related = next;
12911     }
12912   while (related != b);
12913 }
12914
12915 static void
12916 do_delete_breakpoint (struct breakpoint *b, void *ignore)
12917 {
12918   delete_breakpoint (b);
12919 }
12920
12921 /* A callback for map_breakpoint_numbers that calls
12922    delete_breakpoint.  */
12923
12924 static void
12925 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
12926 {
12927   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
12928 }
12929
12930 void
12931 delete_command (char *arg, int from_tty)
12932 {
12933   struct breakpoint *b, *b_tmp;
12934
12935   dont_repeat ();
12936
12937   if (arg == 0)
12938     {
12939       int breaks_to_delete = 0;
12940
12941       /* Delete all breakpoints if no argument.  Do not delete
12942          internal breakpoints, these have to be deleted with an
12943          explicit breakpoint number argument.  */
12944       ALL_BREAKPOINTS (b)
12945         if (user_breakpoint_p (b))
12946           {
12947             breaks_to_delete = 1;
12948             break;
12949           }
12950
12951       /* Ask user only if there are some breakpoints to delete.  */
12952       if (!from_tty
12953           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12954         {
12955           ALL_BREAKPOINTS_SAFE (b, b_tmp)
12956             if (user_breakpoint_p (b))
12957               delete_breakpoint (b);
12958         }
12959     }
12960   else
12961     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
12962 }
12963
12964 static int
12965 all_locations_are_pending (struct bp_location *loc)
12966 {
12967   for (; loc; loc = loc->next)
12968     if (!loc->shlib_disabled
12969         && !loc->pspace->executing_startup)
12970       return 0;
12971   return 1;
12972 }
12973
12974 /* Subroutine of update_breakpoint_locations to simplify it.
12975    Return non-zero if multiple fns in list LOC have the same name.
12976    Null names are ignored.  */
12977
12978 static int
12979 ambiguous_names_p (struct bp_location *loc)
12980 {
12981   struct bp_location *l;
12982   htab_t htab = htab_create_alloc (13, htab_hash_string,
12983                                    (int (*) (const void *, 
12984                                              const void *)) streq,
12985                                    NULL, xcalloc, xfree);
12986
12987   for (l = loc; l != NULL; l = l->next)
12988     {
12989       const char **slot;
12990       const char *name = l->function_name;
12991
12992       /* Allow for some names to be NULL, ignore them.  */
12993       if (name == NULL)
12994         continue;
12995
12996       slot = (const char **) htab_find_slot (htab, (const void *) name,
12997                                              INSERT);
12998       /* NOTE: We can assume slot != NULL here because xcalloc never
12999          returns NULL.  */
13000       if (*slot != NULL)
13001         {
13002           htab_delete (htab);
13003           return 1;
13004         }
13005       *slot = name;
13006     }
13007
13008   htab_delete (htab);
13009   return 0;
13010 }
13011
13012 /* When symbols change, it probably means the sources changed as well,
13013    and it might mean the static tracepoint markers are no longer at
13014    the same address or line numbers they used to be at last we
13015    checked.  Losing your static tracepoints whenever you rebuild is
13016    undesirable.  This function tries to resync/rematch gdb static
13017    tracepoints with the markers on the target, for static tracepoints
13018    that have not been set by marker id.  Static tracepoint that have
13019    been set by marker id are reset by marker id in breakpoint_re_set.
13020    The heuristic is:
13021
13022    1) For a tracepoint set at a specific address, look for a marker at
13023    the old PC.  If one is found there, assume to be the same marker.
13024    If the name / string id of the marker found is different from the
13025    previous known name, assume that means the user renamed the marker
13026    in the sources, and output a warning.
13027
13028    2) For a tracepoint set at a given line number, look for a marker
13029    at the new address of the old line number.  If one is found there,
13030    assume to be the same marker.  If the name / string id of the
13031    marker found is different from the previous known name, assume that
13032    means the user renamed the marker in the sources, and output a
13033    warning.
13034
13035    3) If a marker is no longer found at the same address or line, it
13036    may mean the marker no longer exists.  But it may also just mean
13037    the code changed a bit.  Maybe the user added a few lines of code
13038    that made the marker move up or down (in line number terms).  Ask
13039    the target for info about the marker with the string id as we knew
13040    it.  If found, update line number and address in the matching
13041    static tracepoint.  This will get confused if there's more than one
13042    marker with the same ID (possible in UST, although unadvised
13043    precisely because it confuses tools).  */
13044
13045 static struct symtab_and_line
13046 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13047 {
13048   struct tracepoint *tp = (struct tracepoint *) b;
13049   struct static_tracepoint_marker marker;
13050   CORE_ADDR pc;
13051   int i;
13052
13053   pc = sal.pc;
13054   if (sal.line)
13055     find_line_pc (sal.symtab, sal.line, &pc);
13056
13057   if (target_static_tracepoint_marker_at (pc, &marker))
13058     {
13059       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13060         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13061                  b->number,
13062                  tp->static_trace_marker_id, marker.str_id);
13063
13064       xfree (tp->static_trace_marker_id);
13065       tp->static_trace_marker_id = xstrdup (marker.str_id);
13066       release_static_tracepoint_marker (&marker);
13067
13068       return sal;
13069     }
13070
13071   /* Old marker wasn't found on target at lineno.  Try looking it up
13072      by string ID.  */
13073   if (!sal.explicit_pc
13074       && sal.line != 0
13075       && sal.symtab != NULL
13076       && tp->static_trace_marker_id != NULL)
13077     {
13078       VEC(static_tracepoint_marker_p) *markers;
13079
13080       markers
13081         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13082
13083       if (!VEC_empty(static_tracepoint_marker_p, markers))
13084         {
13085           struct symtab_and_line sal2;
13086           struct symbol *sym;
13087           struct static_tracepoint_marker *tpmarker;
13088           struct ui_out *uiout = current_uiout;
13089
13090           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13091
13092           xfree (tp->static_trace_marker_id);
13093           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13094
13095           warning (_("marker for static tracepoint %d (%s) not "
13096                      "found at previous line number"),
13097                    b->number, tp->static_trace_marker_id);
13098
13099           init_sal (&sal2);
13100
13101           sal2.pc = tpmarker->address;
13102
13103           sal2 = find_pc_line (tpmarker->address, 0);
13104           sym = find_pc_sect_function (tpmarker->address, NULL);
13105           ui_out_text (uiout, "Now in ");
13106           if (sym)
13107             {
13108               ui_out_field_string (uiout, "func",
13109                                    SYMBOL_PRINT_NAME (sym));
13110               ui_out_text (uiout, " at ");
13111             }
13112           ui_out_field_string (uiout, "file", sal2.symtab->filename);
13113           ui_out_text (uiout, ":");
13114
13115           if (ui_out_is_mi_like_p (uiout))
13116             {
13117               char *fullname = symtab_to_fullname (sal2.symtab);
13118
13119               if (fullname)
13120                 ui_out_field_string (uiout, "fullname", fullname);
13121             }
13122
13123           ui_out_field_int (uiout, "line", sal2.line);
13124           ui_out_text (uiout, "\n");
13125
13126           b->loc->line_number = sal2.line;
13127
13128           xfree (b->loc->source_file);
13129           if (sym)
13130             b->loc->source_file = xstrdup (sal2.symtab->filename);
13131           else
13132             b->loc->source_file = NULL;
13133
13134           xfree (b->addr_string);
13135           b->addr_string = xstrprintf ("%s:%d",
13136                                        sal2.symtab->filename,
13137                                        b->loc->line_number);
13138
13139           /* Might be nice to check if function changed, and warn if
13140              so.  */
13141
13142           release_static_tracepoint_marker (tpmarker);
13143         }
13144     }
13145   return sal;
13146 }
13147
13148 /* Returns 1 iff locations A and B are sufficiently same that
13149    we don't need to report breakpoint as changed.  */
13150
13151 static int
13152 locations_are_equal (struct bp_location *a, struct bp_location *b)
13153 {
13154   while (a && b)
13155     {
13156       if (a->address != b->address)
13157         return 0;
13158
13159       if (a->shlib_disabled != b->shlib_disabled)
13160         return 0;
13161
13162       if (a->enabled != b->enabled)
13163         return 0;
13164
13165       a = a->next;
13166       b = b->next;
13167     }
13168
13169   if ((a == NULL) != (b == NULL))
13170     return 0;
13171
13172   return 1;
13173 }
13174
13175 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13176    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13177    a ranged breakpoint.  */
13178
13179 void
13180 update_breakpoint_locations (struct breakpoint *b,
13181                              struct symtabs_and_lines sals,
13182                              struct symtabs_and_lines sals_end)
13183 {
13184   int i;
13185   struct bp_location *existing_locations = b->loc;
13186
13187   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13188     {
13189       /* Ranged breakpoints have only one start location and one end
13190          location.  */
13191       b->enable_state = bp_disabled;
13192       update_global_location_list (1);
13193       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13194                            "multiple locations found\n"),
13195                          b->number);
13196       return;
13197     }
13198
13199   /* If there's no new locations, and all existing locations are
13200      pending, don't do anything.  This optimizes the common case where
13201      all locations are in the same shared library, that was unloaded.
13202      We'd like to retain the location, so that when the library is
13203      loaded again, we don't loose the enabled/disabled status of the
13204      individual locations.  */
13205   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13206     return;
13207
13208   b->loc = NULL;
13209
13210   for (i = 0; i < sals.nelts; ++i)
13211     {
13212       struct bp_location *new_loc;
13213
13214       switch_to_program_space_and_thread (sals.sals[i].pspace);
13215
13216       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13217
13218       /* Reparse conditions, they might contain references to the
13219          old symtab.  */
13220       if (b->cond_string != NULL)
13221         {
13222           char *s;
13223           volatile struct gdb_exception e;
13224
13225           s = b->cond_string;
13226           TRY_CATCH (e, RETURN_MASK_ERROR)
13227             {
13228               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
13229                                            0);
13230             }
13231           if (e.reason < 0)
13232             {
13233               warning (_("failed to reevaluate condition "
13234                          "for breakpoint %d: %s"), 
13235                        b->number, e.message);
13236               new_loc->enabled = 0;
13237             }
13238         }
13239
13240       if (sals_end.nelts)
13241         {
13242           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
13243
13244           new_loc->length = end - sals.sals[0].pc + 1;
13245         }
13246     }
13247
13248   /* Update locations of permanent breakpoints.  */
13249   if (b->enable_state == bp_permanent)
13250     make_breakpoint_permanent (b);
13251
13252   /* If possible, carry over 'disable' status from existing
13253      breakpoints.  */
13254   {
13255     struct bp_location *e = existing_locations;
13256     /* If there are multiple breakpoints with the same function name,
13257        e.g. for inline functions, comparing function names won't work.
13258        Instead compare pc addresses; this is just a heuristic as things
13259        may have moved, but in practice it gives the correct answer
13260        often enough until a better solution is found.  */
13261     int have_ambiguous_names = ambiguous_names_p (b->loc);
13262
13263     for (; e; e = e->next)
13264       {
13265         if (!e->enabled && e->function_name)
13266           {
13267             struct bp_location *l = b->loc;
13268             if (have_ambiguous_names)
13269               {
13270                 for (; l; l = l->next)
13271                   if (breakpoint_locations_match (e, l))
13272                     {
13273                       l->enabled = 0;
13274                       break;
13275                     }
13276               }
13277             else
13278               {
13279                 for (; l; l = l->next)
13280                   if (l->function_name
13281                       && strcmp (e->function_name, l->function_name) == 0)
13282                     {
13283                       l->enabled = 0;
13284                       break;
13285                     }
13286               }
13287           }
13288       }
13289   }
13290
13291   if (!locations_are_equal (existing_locations, b->loc))
13292     observer_notify_breakpoint_modified (b);
13293
13294   update_global_location_list (1);
13295 }
13296
13297 /* Find the SaL locations corresponding to the given ADDR_STRING.
13298    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13299
13300 static struct symtabs_and_lines
13301 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
13302 {
13303   char *s;
13304   struct symtabs_and_lines sals = {0};
13305   volatile struct gdb_exception e;
13306
13307   gdb_assert (b->ops != NULL);
13308   s = addr_string;
13309
13310   TRY_CATCH (e, RETURN_MASK_ERROR)
13311     {
13312       b->ops->decode_linespec (b, &s, &sals);
13313     }
13314   if (e.reason < 0)
13315     {
13316       int not_found_and_ok = 0;
13317       /* For pending breakpoints, it's expected that parsing will
13318          fail until the right shared library is loaded.  User has
13319          already told to create pending breakpoints and don't need
13320          extra messages.  If breakpoint is in bp_shlib_disabled
13321          state, then user already saw the message about that
13322          breakpoint being disabled, and don't want to see more
13323          errors.  */
13324       if (e.error == NOT_FOUND_ERROR
13325           && (b->condition_not_parsed 
13326               || (b->loc && b->loc->shlib_disabled)
13327               || (b->loc && b->loc->pspace->executing_startup)
13328               || b->enable_state == bp_disabled))
13329         not_found_and_ok = 1;
13330
13331       if (!not_found_and_ok)
13332         {
13333           /* We surely don't want to warn about the same breakpoint
13334              10 times.  One solution, implemented here, is disable
13335              the breakpoint on error.  Another solution would be to
13336              have separate 'warning emitted' flag.  Since this
13337              happens only when a binary has changed, I don't know
13338              which approach is better.  */
13339           b->enable_state = bp_disabled;
13340           throw_exception (e);
13341         }
13342     }
13343
13344   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
13345     {
13346       int i;
13347
13348       for (i = 0; i < sals.nelts; ++i)
13349         resolve_sal_pc (&sals.sals[i]);
13350       if (b->condition_not_parsed && s && s[0])
13351         {
13352           char *cond_string = 0;
13353           int thread = -1;
13354           int task = 0;
13355
13356           find_condition_and_thread (s, sals.sals[0].pc,
13357                                      &cond_string, &thread, &task);
13358           if (cond_string)
13359             b->cond_string = cond_string;
13360           b->thread = thread;
13361           b->task = task;
13362           b->condition_not_parsed = 0;
13363         }
13364
13365       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13366         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
13367
13368       *found = 1;
13369     }
13370   else
13371     *found = 0;
13372
13373   return sals;
13374 }
13375
13376 /* The default re_set method, for typical hardware or software
13377    breakpoints.  Reevaluate the breakpoint and recreate its
13378    locations.  */
13379
13380 static void
13381 breakpoint_re_set_default (struct breakpoint *b)
13382 {
13383   int found;
13384   struct symtabs_and_lines sals, sals_end;
13385   struct symtabs_and_lines expanded = {0};
13386   struct symtabs_and_lines expanded_end = {0};
13387
13388   sals = addr_string_to_sals (b, b->addr_string, &found);
13389   if (found)
13390     {
13391       make_cleanup (xfree, sals.sals);
13392       expanded = sals;
13393     }
13394
13395   if (b->addr_string_range_end)
13396     {
13397       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
13398       if (found)
13399         {
13400           make_cleanup (xfree, sals_end.sals);
13401           expanded_end = sals_end;
13402         }
13403     }
13404
13405   update_breakpoint_locations (b, expanded, expanded_end);
13406 }
13407
13408 /* Default method for creating SALs from an address string.  It basically
13409    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13410
13411 static void
13412 create_sals_from_address_default (char **arg,
13413                                   struct linespec_result *canonical,
13414                                   enum bptype type_wanted,
13415                                   char *addr_start, char **copy_arg)
13416 {
13417   parse_breakpoint_sals (arg, canonical);
13418 }
13419
13420 /* Call create_breakpoints_sal for the given arguments.  This is the default
13421    function for the `create_breakpoints_sal' method of
13422    breakpoint_ops.  */
13423
13424 static void
13425 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13426                                 struct linespec_result *canonical,
13427                                 struct linespec_sals *lsal,
13428                                 char *cond_string,
13429                                 enum bptype type_wanted,
13430                                 enum bpdisp disposition,
13431                                 int thread,
13432                                 int task, int ignore_count,
13433                                 const struct breakpoint_ops *ops,
13434                                 int from_tty, int enabled,
13435                                 int internal, unsigned flags)
13436 {
13437   create_breakpoints_sal (gdbarch, canonical, cond_string,
13438                           type_wanted, disposition,
13439                           thread, task, ignore_count, ops, from_tty,
13440                           enabled, internal, flags);
13441 }
13442
13443 /* Decode the line represented by S by calling decode_line_full.  This is the
13444    default function for the `decode_linespec' method of breakpoint_ops.  */
13445
13446 static void
13447 decode_linespec_default (struct breakpoint *b, char **s,
13448                          struct symtabs_and_lines *sals)
13449 {
13450   struct linespec_result canonical;
13451
13452   init_linespec_result (&canonical);
13453   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
13454                     (struct symtab *) NULL, 0,
13455                     &canonical, multiple_symbols_all,
13456                     b->filter);
13457
13458   /* We should get 0 or 1 resulting SALs.  */
13459   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
13460
13461   if (VEC_length (linespec_sals, canonical.sals) > 0)
13462     {
13463       struct linespec_sals *lsal;
13464
13465       lsal = VEC_index (linespec_sals, canonical.sals, 0);
13466       *sals = lsal->sals;
13467       /* Arrange it so the destructor does not free the
13468          contents.  */
13469       lsal->sals.sals = NULL;
13470     }
13471
13472   destroy_linespec_result (&canonical);
13473 }
13474
13475 /* Prepare the global context for a re-set of breakpoint B.  */
13476
13477 static struct cleanup *
13478 prepare_re_set_context (struct breakpoint *b)
13479 {
13480   struct cleanup *cleanups;
13481
13482   input_radix = b->input_radix;
13483   cleanups = save_current_space_and_thread ();
13484   if (b->pspace != NULL)
13485     switch_to_program_space_and_thread (b->pspace);
13486   set_language (b->language);
13487
13488   return cleanups;
13489 }
13490
13491 /* Reset a breakpoint given it's struct breakpoint * BINT.
13492    The value we return ends up being the return value from catch_errors.
13493    Unused in this case.  */
13494
13495 static int
13496 breakpoint_re_set_one (void *bint)
13497 {
13498   /* Get past catch_errs.  */
13499   struct breakpoint *b = (struct breakpoint *) bint;
13500   struct cleanup *cleanups;
13501
13502   cleanups = prepare_re_set_context (b);
13503   b->ops->re_set (b);
13504   do_cleanups (cleanups);
13505   return 0;
13506 }
13507
13508 /* Re-set all breakpoints after symbols have been re-loaded.  */
13509 void
13510 breakpoint_re_set (void)
13511 {
13512   struct breakpoint *b, *b_tmp;
13513   enum language save_language;
13514   int save_input_radix;
13515   struct cleanup *old_chain;
13516
13517   save_language = current_language->la_language;
13518   save_input_radix = input_radix;
13519   old_chain = save_current_program_space ();
13520
13521   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13522   {
13523     /* Format possible error msg.  */
13524     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
13525                                 b->number);
13526     struct cleanup *cleanups = make_cleanup (xfree, message);
13527     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
13528     do_cleanups (cleanups);
13529   }
13530   set_language (save_language);
13531   input_radix = save_input_radix;
13532
13533   jit_breakpoint_re_set ();
13534
13535   do_cleanups (old_chain);
13536
13537   create_overlay_event_breakpoint ();
13538   create_longjmp_master_breakpoint ();
13539   create_std_terminate_master_breakpoint ();
13540   create_exception_master_breakpoint ();
13541
13542   /* While we're at it, reset the skip list too.  */
13543   skip_re_set ();
13544 }
13545 \f
13546 /* Reset the thread number of this breakpoint:
13547
13548    - If the breakpoint is for all threads, leave it as-is.
13549    - Else, reset it to the current thread for inferior_ptid.  */
13550 void
13551 breakpoint_re_set_thread (struct breakpoint *b)
13552 {
13553   if (b->thread != -1)
13554     {
13555       if (in_thread_list (inferior_ptid))
13556         b->thread = pid_to_thread_id (inferior_ptid);
13557
13558       /* We're being called after following a fork.  The new fork is
13559          selected as current, and unless this was a vfork will have a
13560          different program space from the original thread.  Reset that
13561          as well.  */
13562       b->loc->pspace = current_program_space;
13563     }
13564 }
13565
13566 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13567    If from_tty is nonzero, it prints a message to that effect,
13568    which ends with a period (no newline).  */
13569
13570 void
13571 set_ignore_count (int bptnum, int count, int from_tty)
13572 {
13573   struct breakpoint *b;
13574
13575   if (count < 0)
13576     count = 0;
13577
13578   ALL_BREAKPOINTS (b)
13579     if (b->number == bptnum)
13580     {
13581       if (is_tracepoint (b))
13582         {
13583           if (from_tty && count != 0)
13584             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13585                              bptnum);
13586           return;
13587         }
13588       
13589       b->ignore_count = count;
13590       if (from_tty)
13591         {
13592           if (count == 0)
13593             printf_filtered (_("Will stop next time "
13594                                "breakpoint %d is reached."),
13595                              bptnum);
13596           else if (count == 1)
13597             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13598                              bptnum);
13599           else
13600             printf_filtered (_("Will ignore next %d "
13601                                "crossings of breakpoint %d."),
13602                              count, bptnum);
13603         }
13604       breakpoints_changed ();
13605       observer_notify_breakpoint_modified (b);
13606       return;
13607     }
13608
13609   error (_("No breakpoint number %d."), bptnum);
13610 }
13611
13612 /* Command to set ignore-count of breakpoint N to COUNT.  */
13613
13614 static void
13615 ignore_command (char *args, int from_tty)
13616 {
13617   char *p = args;
13618   int num;
13619
13620   if (p == 0)
13621     error_no_arg (_("a breakpoint number"));
13622
13623   num = get_number (&p);
13624   if (num == 0)
13625     error (_("bad breakpoint number: '%s'"), args);
13626   if (*p == 0)
13627     error (_("Second argument (specified ignore-count) is missing."));
13628
13629   set_ignore_count (num,
13630                     longest_to_int (value_as_long (parse_and_eval (p))),
13631                     from_tty);
13632   if (from_tty)
13633     printf_filtered ("\n");
13634 }
13635 \f
13636 /* Call FUNCTION on each of the breakpoints
13637    whose numbers are given in ARGS.  */
13638
13639 static void
13640 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
13641                                                       void *),
13642                         void *data)
13643 {
13644   int num;
13645   struct breakpoint *b, *tmp;
13646   int match;
13647   struct get_number_or_range_state state;
13648
13649   if (args == 0)
13650     error_no_arg (_("one or more breakpoint numbers"));
13651
13652   init_number_or_range (&state, args);
13653
13654   while (!state.finished)
13655     {
13656       char *p = state.string;
13657
13658       match = 0;
13659
13660       num = get_number_or_range (&state);
13661       if (num == 0)
13662         {
13663           warning (_("bad breakpoint number at or near '%s'"), p);
13664         }
13665       else
13666         {
13667           ALL_BREAKPOINTS_SAFE (b, tmp)
13668             if (b->number == num)
13669               {
13670                 match = 1;
13671                 function (b, data);
13672                 break;
13673               }
13674           if (match == 0)
13675             printf_unfiltered (_("No breakpoint number %d.\n"), num);
13676         }
13677     }
13678 }
13679
13680 static struct bp_location *
13681 find_location_by_number (char *number)
13682 {
13683   char *dot = strchr (number, '.');
13684   char *p1;
13685   int bp_num;
13686   int loc_num;
13687   struct breakpoint *b;
13688   struct bp_location *loc;  
13689
13690   *dot = '\0';
13691
13692   p1 = number;
13693   bp_num = get_number (&p1);
13694   if (bp_num == 0)
13695     error (_("Bad breakpoint number '%s'"), number);
13696
13697   ALL_BREAKPOINTS (b)
13698     if (b->number == bp_num)
13699       {
13700         break;
13701       }
13702
13703   if (!b || b->number != bp_num)
13704     error (_("Bad breakpoint number '%s'"), number);
13705   
13706   p1 = dot+1;
13707   loc_num = get_number (&p1);
13708   if (loc_num == 0)
13709     error (_("Bad breakpoint location number '%s'"), number);
13710
13711   --loc_num;
13712   loc = b->loc;
13713   for (;loc_num && loc; --loc_num, loc = loc->next)
13714     ;
13715   if (!loc)
13716     error (_("Bad breakpoint location number '%s'"), dot+1);
13717     
13718   return loc;  
13719 }
13720
13721
13722 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13723    If from_tty is nonzero, it prints a message to that effect,
13724    which ends with a period (no newline).  */
13725
13726 void
13727 disable_breakpoint (struct breakpoint *bpt)
13728 {
13729   /* Never disable a watchpoint scope breakpoint; we want to
13730      hit them when we leave scope so we can delete both the
13731      watchpoint and its scope breakpoint at that time.  */
13732   if (bpt->type == bp_watchpoint_scope)
13733     return;
13734
13735   /* You can't disable permanent breakpoints.  */
13736   if (bpt->enable_state == bp_permanent)
13737     return;
13738
13739   bpt->enable_state = bp_disabled;
13740
13741   /* Mark breakpoint locations modified.  */
13742   mark_breakpoint_modified (bpt);
13743
13744   if (target_supports_enable_disable_tracepoint ()
13745       && current_trace_status ()->running && is_tracepoint (bpt))
13746     {
13747       struct bp_location *location;
13748      
13749       for (location = bpt->loc; location; location = location->next)
13750         target_disable_tracepoint (location);
13751     }
13752
13753   update_global_location_list (0);
13754
13755   observer_notify_breakpoint_modified (bpt);
13756 }
13757
13758 /* A callback for iterate_over_related_breakpoints.  */
13759
13760 static void
13761 do_disable_breakpoint (struct breakpoint *b, void *ignore)
13762 {
13763   disable_breakpoint (b);
13764 }
13765
13766 /* A callback for map_breakpoint_numbers that calls
13767    disable_breakpoint.  */
13768
13769 static void
13770 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
13771 {
13772   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
13773 }
13774
13775 static void
13776 disable_command (char *args, int from_tty)
13777 {
13778   if (args == 0)
13779     {
13780       struct breakpoint *bpt;
13781
13782       ALL_BREAKPOINTS (bpt)
13783         if (user_breakpoint_p (bpt))
13784           disable_breakpoint (bpt);
13785     }
13786   else if (strchr (args, '.'))
13787     {
13788       struct bp_location *loc = find_location_by_number (args);
13789       if (loc)
13790         {
13791           if (loc->enabled)
13792             {
13793               loc->enabled = 0;
13794               mark_breakpoint_location_modified (loc);
13795             }
13796           if (target_supports_enable_disable_tracepoint ()
13797               && current_trace_status ()->running && loc->owner
13798               && is_tracepoint (loc->owner))
13799             target_disable_tracepoint (loc);
13800         }
13801       update_global_location_list (0);
13802     }
13803   else
13804     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
13805 }
13806
13807 static void
13808 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13809                         int count)
13810 {
13811   int target_resources_ok;
13812
13813   if (bpt->type == bp_hardware_breakpoint)
13814     {
13815       int i;
13816       i = hw_breakpoint_used_count ();
13817       target_resources_ok = 
13818         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
13819                                             i + 1, 0);
13820       if (target_resources_ok == 0)
13821         error (_("No hardware breakpoint support in the target."));
13822       else if (target_resources_ok < 0)
13823         error (_("Hardware breakpoints used exceeds limit."));
13824     }
13825
13826   if (is_watchpoint (bpt))
13827     {
13828       /* Initialize it just to avoid a GCC false warning.  */
13829       enum enable_state orig_enable_state = 0;
13830       volatile struct gdb_exception e;
13831
13832       TRY_CATCH (e, RETURN_MASK_ALL)
13833         {
13834           struct watchpoint *w = (struct watchpoint *) bpt;
13835
13836           orig_enable_state = bpt->enable_state;
13837           bpt->enable_state = bp_enabled;
13838           update_watchpoint (w, 1 /* reparse */);
13839         }
13840       if (e.reason < 0)
13841         {
13842           bpt->enable_state = orig_enable_state;
13843           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13844                              bpt->number);
13845           return;
13846         }
13847     }
13848
13849   if (bpt->enable_state != bp_permanent)
13850     bpt->enable_state = bp_enabled;
13851
13852   bpt->enable_state = bp_enabled;
13853
13854   /* Mark breakpoint locations modified.  */
13855   mark_breakpoint_modified (bpt);
13856
13857   if (target_supports_enable_disable_tracepoint ()
13858       && current_trace_status ()->running && is_tracepoint (bpt))
13859     {
13860       struct bp_location *location;
13861
13862       for (location = bpt->loc; location; location = location->next)
13863         target_enable_tracepoint (location);
13864     }
13865
13866   bpt->disposition = disposition;
13867   bpt->enable_count = count;
13868   update_global_location_list (1);
13869   breakpoints_changed ();
13870   
13871   observer_notify_breakpoint_modified (bpt);
13872 }
13873
13874
13875 void
13876 enable_breakpoint (struct breakpoint *bpt)
13877 {
13878   enable_breakpoint_disp (bpt, bpt->disposition, 0);
13879 }
13880
13881 static void
13882 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
13883 {
13884   enable_breakpoint (bpt);
13885 }
13886
13887 /* A callback for map_breakpoint_numbers that calls
13888    enable_breakpoint.  */
13889
13890 static void
13891 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
13892 {
13893   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
13894 }
13895
13896 /* The enable command enables the specified breakpoints (or all defined
13897    breakpoints) so they once again become (or continue to be) effective
13898    in stopping the inferior.  */
13899
13900 static void
13901 enable_command (char *args, int from_tty)
13902 {
13903   if (args == 0)
13904     {
13905       struct breakpoint *bpt;
13906
13907       ALL_BREAKPOINTS (bpt)
13908         if (user_breakpoint_p (bpt))
13909           enable_breakpoint (bpt);
13910     }
13911   else if (strchr (args, '.'))
13912     {
13913       struct bp_location *loc = find_location_by_number (args);
13914       if (loc)
13915         {
13916           if (!loc->enabled)
13917             {
13918               loc->enabled = 1;
13919               mark_breakpoint_location_modified (loc);
13920             }
13921           if (target_supports_enable_disable_tracepoint ()
13922               && current_trace_status ()->running && loc->owner
13923               && is_tracepoint (loc->owner))
13924             target_enable_tracepoint (loc);
13925         }
13926       update_global_location_list (1);
13927     }
13928   else
13929     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
13930 }
13931
13932 /* This struct packages up disposition data for application to multiple
13933    breakpoints.  */
13934
13935 struct disp_data
13936 {
13937   enum bpdisp disp;
13938   int count;
13939 };
13940
13941 static void
13942 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
13943 {
13944   struct disp_data disp_data = *(struct disp_data *) arg;
13945
13946   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
13947 }
13948
13949 static void
13950 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
13951 {
13952   struct disp_data disp = { disp_disable, 1 };
13953
13954   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13955 }
13956
13957 static void
13958 enable_once_command (char *args, int from_tty)
13959 {
13960   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
13961 }
13962
13963 static void
13964 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
13965 {
13966   struct disp_data disp = { disp_disable, *(int *) countptr };
13967
13968   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13969 }
13970
13971 static void
13972 enable_count_command (char *args, int from_tty)
13973 {
13974   int count = get_number (&args);
13975
13976   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
13977 }
13978
13979 static void
13980 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
13981 {
13982   struct disp_data disp = { disp_del, 1 };
13983
13984   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13985 }
13986
13987 static void
13988 enable_delete_command (char *args, int from_tty)
13989 {
13990   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
13991 }
13992 \f
13993 static void
13994 set_breakpoint_cmd (char *args, int from_tty)
13995 {
13996 }
13997
13998 static void
13999 show_breakpoint_cmd (char *args, int from_tty)
14000 {
14001 }
14002
14003 /* Invalidate last known value of any hardware watchpoint if
14004    the memory which that value represents has been written to by
14005    GDB itself.  */
14006
14007 static void
14008 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
14009                                       const bfd_byte *data)
14010 {
14011   struct breakpoint *bp;
14012
14013   ALL_BREAKPOINTS (bp)
14014     if (bp->enable_state == bp_enabled
14015         && bp->type == bp_hardware_watchpoint)
14016       {
14017         struct watchpoint *wp = (struct watchpoint *) bp;
14018
14019         if (wp->val_valid && wp->val)
14020           {
14021             struct bp_location *loc;
14022
14023             for (loc = bp->loc; loc != NULL; loc = loc->next)
14024               if (loc->loc_type == bp_loc_hardware_watchpoint
14025                   && loc->address + loc->length > addr
14026                   && addr + len > loc->address)
14027                 {
14028                   value_free (wp->val);
14029                   wp->val = NULL;
14030                   wp->val_valid = 0;
14031                 }
14032           }
14033       }
14034 }
14035
14036 /* Use the last displayed codepoint's values, or nothing
14037    if they aren't valid.  */
14038
14039 struct symtabs_and_lines
14040 decode_line_spec_1 (char *string, int flags)
14041 {
14042   struct symtabs_and_lines sals;
14043
14044   if (string == 0)
14045     error (_("Empty line specification."));
14046   if (last_displayed_sal_is_valid ())
14047     sals = decode_line_1 (&string, flags,
14048                           get_last_displayed_symtab (),
14049                           get_last_displayed_line ());
14050   else
14051     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
14052   if (*string)
14053     error (_("Junk at end of line specification: %s"), string);
14054   return sals;
14055 }
14056
14057 /* Create and insert a raw software breakpoint at PC.  Return an
14058    identifier, which should be used to remove the breakpoint later.
14059    In general, places which call this should be using something on the
14060    breakpoint chain instead; this function should be eliminated
14061    someday.  */
14062
14063 void *
14064 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14065                                   struct address_space *aspace, CORE_ADDR pc)
14066 {
14067   struct bp_target_info *bp_tgt;
14068
14069   bp_tgt = XZALLOC (struct bp_target_info);
14070
14071   bp_tgt->placed_address_space = aspace;
14072   bp_tgt->placed_address = pc;
14073
14074   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14075     {
14076       /* Could not insert the breakpoint.  */
14077       xfree (bp_tgt);
14078       return NULL;
14079     }
14080
14081   return bp_tgt;
14082 }
14083
14084 /* Remove a breakpoint BP inserted by
14085    deprecated_insert_raw_breakpoint.  */
14086
14087 int
14088 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14089 {
14090   struct bp_target_info *bp_tgt = bp;
14091   int ret;
14092
14093   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14094   xfree (bp_tgt);
14095
14096   return ret;
14097 }
14098
14099 /* One (or perhaps two) breakpoints used for software single
14100    stepping.  */
14101
14102 static void *single_step_breakpoints[2];
14103 static struct gdbarch *single_step_gdbarch[2];
14104
14105 /* Create and insert a breakpoint for software single step.  */
14106
14107 void
14108 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14109                                struct address_space *aspace, 
14110                                CORE_ADDR next_pc)
14111 {
14112   void **bpt_p;
14113
14114   if (single_step_breakpoints[0] == NULL)
14115     {
14116       bpt_p = &single_step_breakpoints[0];
14117       single_step_gdbarch[0] = gdbarch;
14118     }
14119   else
14120     {
14121       gdb_assert (single_step_breakpoints[1] == NULL);
14122       bpt_p = &single_step_breakpoints[1];
14123       single_step_gdbarch[1] = gdbarch;
14124     }
14125
14126   /* NOTE drow/2006-04-11: A future improvement to this function would
14127      be to only create the breakpoints once, and actually put them on
14128      the breakpoint chain.  That would let us use set_raw_breakpoint.
14129      We could adjust the addresses each time they were needed.  Doing
14130      this requires corresponding changes elsewhere where single step
14131      breakpoints are handled, however.  So, for now, we use this.  */
14132
14133   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14134   if (*bpt_p == NULL)
14135     error (_("Could not insert single-step breakpoint at %s"),
14136              paddress (gdbarch, next_pc));
14137 }
14138
14139 /* Check if the breakpoints used for software single stepping
14140    were inserted or not.  */
14141
14142 int
14143 single_step_breakpoints_inserted (void)
14144 {
14145   return (single_step_breakpoints[0] != NULL
14146           || single_step_breakpoints[1] != NULL);
14147 }
14148
14149 /* Remove and delete any breakpoints used for software single step.  */
14150
14151 void
14152 remove_single_step_breakpoints (void)
14153 {
14154   gdb_assert (single_step_breakpoints[0] != NULL);
14155
14156   /* See insert_single_step_breakpoint for more about this deprecated
14157      call.  */
14158   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14159                                     single_step_breakpoints[0]);
14160   single_step_gdbarch[0] = NULL;
14161   single_step_breakpoints[0] = NULL;
14162
14163   if (single_step_breakpoints[1] != NULL)
14164     {
14165       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14166                                         single_step_breakpoints[1]);
14167       single_step_gdbarch[1] = NULL;
14168       single_step_breakpoints[1] = NULL;
14169     }
14170 }
14171
14172 /* Delete software single step breakpoints without removing them from
14173    the inferior.  This is intended to be used if the inferior's address
14174    space where they were inserted is already gone, e.g. after exit or
14175    exec.  */
14176
14177 void
14178 cancel_single_step_breakpoints (void)
14179 {
14180   int i;
14181
14182   for (i = 0; i < 2; i++)
14183     if (single_step_breakpoints[i])
14184       {
14185         xfree (single_step_breakpoints[i]);
14186         single_step_breakpoints[i] = NULL;
14187         single_step_gdbarch[i] = NULL;
14188       }
14189 }
14190
14191 /* Detach software single-step breakpoints from INFERIOR_PTID without
14192    removing them.  */
14193
14194 static void
14195 detach_single_step_breakpoints (void)
14196 {
14197   int i;
14198
14199   for (i = 0; i < 2; i++)
14200     if (single_step_breakpoints[i])
14201       target_remove_breakpoint (single_step_gdbarch[i],
14202                                 single_step_breakpoints[i]);
14203 }
14204
14205 /* Check whether a software single-step breakpoint is inserted at
14206    PC.  */
14207
14208 static int
14209 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
14210                                         CORE_ADDR pc)
14211 {
14212   int i;
14213
14214   for (i = 0; i < 2; i++)
14215     {
14216       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
14217       if (bp_tgt
14218           && breakpoint_address_match (bp_tgt->placed_address_space,
14219                                        bp_tgt->placed_address,
14220                                        aspace, pc))
14221         return 1;
14222     }
14223
14224   return 0;
14225 }
14226
14227 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
14228    non-zero otherwise.  */
14229 static int
14230 is_syscall_catchpoint_enabled (struct breakpoint *bp)
14231 {
14232   if (syscall_catchpoint_p (bp)
14233       && bp->enable_state != bp_disabled
14234       && bp->enable_state != bp_call_disabled)
14235     return 1;
14236   else
14237     return 0;
14238 }
14239
14240 int
14241 catch_syscall_enabled (void)
14242 {
14243   struct catch_syscall_inferior_data *inf_data
14244     = get_catch_syscall_inferior_data (current_inferior ());
14245
14246   return inf_data->total_syscalls_count != 0;
14247 }
14248
14249 int
14250 catching_syscall_number (int syscall_number)
14251 {
14252   struct breakpoint *bp;
14253
14254   ALL_BREAKPOINTS (bp)
14255     if (is_syscall_catchpoint_enabled (bp))
14256       {
14257         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
14258
14259         if (c->syscalls_to_be_caught)
14260           {
14261             int i, iter;
14262             for (i = 0;
14263                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
14264                  i++)
14265               if (syscall_number == iter)
14266                 return 1;
14267           }
14268         else
14269           return 1;
14270       }
14271
14272   return 0;
14273 }
14274
14275 /* Complete syscall names.  Used by "catch syscall".  */
14276 static char **
14277 catch_syscall_completer (struct cmd_list_element *cmd,
14278                          char *text, char *word)
14279 {
14280   const char **list = get_syscall_names ();
14281   char **retlist
14282     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
14283
14284   xfree (list);
14285   return retlist;
14286 }
14287
14288 /* Tracepoint-specific operations.  */
14289
14290 /* Set tracepoint count to NUM.  */
14291 static void
14292 set_tracepoint_count (int num)
14293 {
14294   tracepoint_count = num;
14295   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14296 }
14297
14298 static void
14299 trace_command (char *arg, int from_tty)
14300 {
14301   struct breakpoint_ops *ops;
14302   const char *arg_cp = arg;
14303
14304   if (arg && probe_linespec_to_ops (&arg_cp))
14305     ops = &tracepoint_probe_breakpoint_ops;
14306   else
14307     ops = &tracepoint_breakpoint_ops;
14308
14309   if (create_breakpoint (get_current_arch (),
14310                          arg,
14311                          NULL, 0, 1 /* parse arg */,
14312                          0 /* tempflag */,
14313                          bp_tracepoint /* type_wanted */,
14314                          0 /* Ignore count */,
14315                          pending_break_support,
14316                          ops,
14317                          from_tty,
14318                          1 /* enabled */,
14319                          0 /* internal */, 0))
14320     set_tracepoint_count (breakpoint_count);
14321 }
14322
14323 static void
14324 ftrace_command (char *arg, int from_tty)
14325 {
14326   if (create_breakpoint (get_current_arch (),
14327                          arg,
14328                          NULL, 0, 1 /* parse arg */,
14329                          0 /* tempflag */,
14330                          bp_fast_tracepoint /* type_wanted */,
14331                          0 /* Ignore count */,
14332                          pending_break_support,
14333                          &tracepoint_breakpoint_ops,
14334                          from_tty,
14335                          1 /* enabled */,
14336                          0 /* internal */, 0))
14337     set_tracepoint_count (breakpoint_count);
14338 }
14339
14340 /* strace command implementation.  Creates a static tracepoint.  */
14341
14342 static void
14343 strace_command (char *arg, int from_tty)
14344 {
14345   struct breakpoint_ops *ops;
14346
14347   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14348      or with a normal static tracepoint.  */
14349   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
14350     ops = &strace_marker_breakpoint_ops;
14351   else
14352     ops = &tracepoint_breakpoint_ops;
14353
14354   if (create_breakpoint (get_current_arch (),
14355                          arg,
14356                          NULL, 0, 1 /* parse arg */,
14357                          0 /* tempflag */,
14358                          bp_static_tracepoint /* type_wanted */,
14359                          0 /* Ignore count */,
14360                          pending_break_support,
14361                          ops,
14362                          from_tty,
14363                          1 /* enabled */,
14364                          0 /* internal */, 0))
14365     set_tracepoint_count (breakpoint_count);
14366 }
14367
14368 /* Set up a fake reader function that gets command lines from a linked
14369    list that was acquired during tracepoint uploading.  */
14370
14371 static struct uploaded_tp *this_utp;
14372 static int next_cmd;
14373
14374 static char *
14375 read_uploaded_action (void)
14376 {
14377   char *rslt;
14378
14379   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14380
14381   next_cmd++;
14382
14383   return rslt;
14384 }
14385
14386 /* Given information about a tracepoint as recorded on a target (which
14387    can be either a live system or a trace file), attempt to create an
14388    equivalent GDB tracepoint.  This is not a reliable process, since
14389    the target does not necessarily have all the information used when
14390    the tracepoint was originally defined.  */
14391   
14392 struct tracepoint *
14393 create_tracepoint_from_upload (struct uploaded_tp *utp)
14394 {
14395   char *addr_str, small_buf[100];
14396   struct tracepoint *tp;
14397
14398   if (utp->at_string)
14399     addr_str = utp->at_string;
14400   else
14401     {
14402       /* In the absence of a source location, fall back to raw
14403          address.  Since there is no way to confirm that the address
14404          means the same thing as when the trace was started, warn the
14405          user.  */
14406       warning (_("Uploaded tracepoint %d has no "
14407                  "source location, using raw address"),
14408                utp->number);
14409       sprintf (small_buf, "*%s", hex_string (utp->addr));
14410       addr_str = small_buf;
14411     }
14412
14413   /* There's not much we can do with a sequence of bytecodes.  */
14414   if (utp->cond && !utp->cond_string)
14415     warning (_("Uploaded tracepoint %d condition "
14416                "has no source form, ignoring it"),
14417              utp->number);
14418
14419   if (!create_breakpoint (get_current_arch (),
14420                           addr_str,
14421                           utp->cond_string, -1, 0 /* parse cond/thread */,
14422                           0 /* tempflag */,
14423                           utp->type /* type_wanted */,
14424                           0 /* Ignore count */,
14425                           pending_break_support,
14426                           &tracepoint_breakpoint_ops,
14427                           0 /* from_tty */,
14428                           utp->enabled /* enabled */,
14429                           0 /* internal */,
14430                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14431     return NULL;
14432
14433   set_tracepoint_count (breakpoint_count);
14434   
14435   /* Get the tracepoint we just created.  */
14436   tp = get_tracepoint (tracepoint_count);
14437   gdb_assert (tp != NULL);
14438
14439   if (utp->pass > 0)
14440     {
14441       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
14442
14443       trace_pass_command (small_buf, 0);
14444     }
14445
14446   /* If we have uploaded versions of the original commands, set up a
14447      special-purpose "reader" function and call the usual command line
14448      reader, then pass the result to the breakpoint command-setting
14449      function.  */
14450   if (!VEC_empty (char_ptr, utp->cmd_strings))
14451     {
14452       struct command_line *cmd_list;
14453
14454       this_utp = utp;
14455       next_cmd = 0;
14456
14457       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14458
14459       breakpoint_set_commands (&tp->base, cmd_list);
14460     }
14461   else if (!VEC_empty (char_ptr, utp->actions)
14462            || !VEC_empty (char_ptr, utp->step_actions))
14463     warning (_("Uploaded tracepoint %d actions "
14464                "have no source form, ignoring them"),
14465              utp->number);
14466
14467   /* Copy any status information that might be available.  */
14468   tp->base.hit_count = utp->hit_count;
14469   tp->traceframe_usage = utp->traceframe_usage;
14470
14471   return tp;
14472 }
14473   
14474 /* Print information on tracepoint number TPNUM_EXP, or all if
14475    omitted.  */
14476
14477 static void
14478 tracepoints_info (char *args, int from_tty)
14479 {
14480   struct ui_out *uiout = current_uiout;
14481   int num_printed;
14482
14483   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14484
14485   if (num_printed == 0)
14486     {
14487       if (args == NULL || *args == '\0')
14488         ui_out_message (uiout, 0, "No tracepoints.\n");
14489       else
14490         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
14491     }
14492
14493   default_collect_info ();
14494 }
14495
14496 /* The 'enable trace' command enables tracepoints.
14497    Not supported by all targets.  */
14498 static void
14499 enable_trace_command (char *args, int from_tty)
14500 {
14501   enable_command (args, from_tty);
14502 }
14503
14504 /* The 'disable trace' command disables tracepoints.
14505    Not supported by all targets.  */
14506 static void
14507 disable_trace_command (char *args, int from_tty)
14508 {
14509   disable_command (args, from_tty);
14510 }
14511
14512 /* Remove a tracepoint (or all if no argument).  */
14513 static void
14514 delete_trace_command (char *arg, int from_tty)
14515 {
14516   struct breakpoint *b, *b_tmp;
14517
14518   dont_repeat ();
14519
14520   if (arg == 0)
14521     {
14522       int breaks_to_delete = 0;
14523
14524       /* Delete all breakpoints if no argument.
14525          Do not delete internal or call-dummy breakpoints, these
14526          have to be deleted with an explicit breakpoint number 
14527          argument.  */
14528       ALL_TRACEPOINTS (b)
14529         if (is_tracepoint (b) && user_breakpoint_p (b))
14530           {
14531             breaks_to_delete = 1;
14532             break;
14533           }
14534
14535       /* Ask user only if there are some breakpoints to delete.  */
14536       if (!from_tty
14537           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14538         {
14539           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14540             if (is_tracepoint (b) && user_breakpoint_p (b))
14541               delete_breakpoint (b);
14542         }
14543     }
14544   else
14545     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14546 }
14547
14548 /* Helper function for trace_pass_command.  */
14549
14550 static void
14551 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14552 {
14553   tp->pass_count = count;
14554   observer_notify_tracepoint_modified (tp->base.number);
14555   if (from_tty)
14556     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14557                      tp->base.number, count);
14558 }
14559
14560 /* Set passcount for tracepoint.
14561
14562    First command argument is passcount, second is tracepoint number.
14563    If tracepoint number omitted, apply to most recently defined.
14564    Also accepts special argument "all".  */
14565
14566 static void
14567 trace_pass_command (char *args, int from_tty)
14568 {
14569   struct tracepoint *t1;
14570   unsigned int count;
14571
14572   if (args == 0 || *args == 0)
14573     error (_("passcount command requires an "
14574              "argument (count + optional TP num)"));
14575
14576   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
14577
14578   while (*args && isspace ((int) *args))
14579     args++;
14580
14581   if (*args && strncasecmp (args, "all", 3) == 0)
14582     {
14583       struct breakpoint *b;
14584
14585       args += 3;                        /* Skip special argument "all".  */
14586       if (*args)
14587         error (_("Junk at end of arguments."));
14588
14589       ALL_TRACEPOINTS (b)
14590       {
14591         t1 = (struct tracepoint *) b;
14592         trace_pass_set_count (t1, count, from_tty);
14593       }
14594     }
14595   else if (*args == '\0')
14596     {
14597       t1 = get_tracepoint_by_number (&args, NULL, 1);
14598       if (t1)
14599         trace_pass_set_count (t1, count, from_tty);
14600     }
14601   else
14602     {
14603       struct get_number_or_range_state state;
14604
14605       init_number_or_range (&state, args);
14606       while (!state.finished)
14607         {
14608           t1 = get_tracepoint_by_number (&args, &state, 1);
14609           if (t1)
14610             trace_pass_set_count (t1, count, from_tty);
14611         }
14612     }
14613 }
14614
14615 struct tracepoint *
14616 get_tracepoint (int num)
14617 {
14618   struct breakpoint *t;
14619
14620   ALL_TRACEPOINTS (t)
14621     if (t->number == num)
14622       return (struct tracepoint *) t;
14623
14624   return NULL;
14625 }
14626
14627 /* Find the tracepoint with the given target-side number (which may be
14628    different from the tracepoint number after disconnecting and
14629    reconnecting).  */
14630
14631 struct tracepoint *
14632 get_tracepoint_by_number_on_target (int num)
14633 {
14634   struct breakpoint *b;
14635
14636   ALL_TRACEPOINTS (b)
14637     {
14638       struct tracepoint *t = (struct tracepoint *) b;
14639
14640       if (t->number_on_target == num)
14641         return t;
14642     }
14643
14644   return NULL;
14645 }
14646
14647 /* Utility: parse a tracepoint number and look it up in the list.
14648    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14649    If OPTIONAL_P is true, then if the argument is missing, the most
14650    recent tracepoint (tracepoint_count) is returned.  */
14651 struct tracepoint *
14652 get_tracepoint_by_number (char **arg,
14653                           struct get_number_or_range_state *state,
14654                           int optional_p)
14655 {
14656   extern int tracepoint_count;
14657   struct breakpoint *t;
14658   int tpnum;
14659   char *instring = arg == NULL ? NULL : *arg;
14660
14661   if (state)
14662     {
14663       gdb_assert (!state->finished);
14664       tpnum = get_number_or_range (state);
14665     }
14666   else if (arg == NULL || *arg == NULL || ! **arg)
14667     {
14668       if (optional_p)
14669         tpnum = tracepoint_count;
14670       else
14671         error_no_arg (_("tracepoint number"));
14672     }
14673   else
14674     tpnum = get_number (arg);
14675
14676   if (tpnum <= 0)
14677     {
14678       if (instring && *instring)
14679         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14680                          instring);
14681       else
14682         printf_filtered (_("Tracepoint argument missing "
14683                            "and no previous tracepoint\n"));
14684       return NULL;
14685     }
14686
14687   ALL_TRACEPOINTS (t)
14688     if (t->number == tpnum)
14689     {
14690       return (struct tracepoint *) t;
14691     }
14692
14693   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14694   return NULL;
14695 }
14696
14697 void
14698 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14699 {
14700   if (b->thread != -1)
14701     fprintf_unfiltered (fp, " thread %d", b->thread);
14702
14703   if (b->task != 0)
14704     fprintf_unfiltered (fp, " task %d", b->task);
14705
14706   fprintf_unfiltered (fp, "\n");
14707 }
14708
14709 /* Save information on user settable breakpoints (watchpoints, etc) to
14710    a new script file named FILENAME.  If FILTER is non-NULL, call it
14711    on each breakpoint and only include the ones for which it returns
14712    non-zero.  */
14713
14714 static void
14715 save_breakpoints (char *filename, int from_tty,
14716                   int (*filter) (const struct breakpoint *))
14717 {
14718   struct breakpoint *tp;
14719   int any = 0;
14720   char *pathname;
14721   struct cleanup *cleanup;
14722   struct ui_file *fp;
14723   int extra_trace_bits = 0;
14724
14725   if (filename == 0 || *filename == 0)
14726     error (_("Argument required (file name in which to save)"));
14727
14728   /* See if we have anything to save.  */
14729   ALL_BREAKPOINTS (tp)
14730   {
14731     /* Skip internal and momentary breakpoints.  */
14732     if (!user_breakpoint_p (tp))
14733       continue;
14734
14735     /* If we have a filter, only save the breakpoints it accepts.  */
14736     if (filter && !filter (tp))
14737       continue;
14738
14739     any = 1;
14740
14741     if (is_tracepoint (tp))
14742       {
14743         extra_trace_bits = 1;
14744
14745         /* We can stop searching.  */
14746         break;
14747       }
14748   }
14749
14750   if (!any)
14751     {
14752       warning (_("Nothing to save."));
14753       return;
14754     }
14755
14756   pathname = tilde_expand (filename);
14757   cleanup = make_cleanup (xfree, pathname);
14758   fp = gdb_fopen (pathname, "w");
14759   if (!fp)
14760     error (_("Unable to open file '%s' for saving (%s)"),
14761            filename, safe_strerror (errno));
14762   make_cleanup_ui_file_delete (fp);
14763
14764   if (extra_trace_bits)
14765     save_trace_state_variables (fp);
14766
14767   ALL_BREAKPOINTS (tp)
14768   {
14769     /* Skip internal and momentary breakpoints.  */
14770     if (!user_breakpoint_p (tp))
14771       continue;
14772
14773     /* If we have a filter, only save the breakpoints it accepts.  */
14774     if (filter && !filter (tp))
14775       continue;
14776
14777     tp->ops->print_recreate (tp, fp);
14778
14779     /* Note, we can't rely on tp->number for anything, as we can't
14780        assume the recreated breakpoint numbers will match.  Use $bpnum
14781        instead.  */
14782
14783     if (tp->cond_string)
14784       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
14785
14786     if (tp->ignore_count)
14787       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
14788
14789     if (tp->commands)
14790       {
14791         volatile struct gdb_exception ex;       
14792
14793         fprintf_unfiltered (fp, "  commands\n");
14794         
14795         ui_out_redirect (current_uiout, fp);
14796         TRY_CATCH (ex, RETURN_MASK_ALL)
14797           {
14798             print_command_lines (current_uiout, tp->commands->commands, 2);
14799           }
14800         ui_out_redirect (current_uiout, NULL);
14801
14802         if (ex.reason < 0)
14803           throw_exception (ex);
14804
14805         fprintf_unfiltered (fp, "  end\n");
14806       }
14807
14808     if (tp->enable_state == bp_disabled)
14809       fprintf_unfiltered (fp, "disable\n");
14810
14811     /* If this is a multi-location breakpoint, check if the locations
14812        should be individually disabled.  Watchpoint locations are
14813        special, and not user visible.  */
14814     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
14815       {
14816         struct bp_location *loc;
14817         int n = 1;
14818
14819         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
14820           if (!loc->enabled)
14821             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
14822       }
14823   }
14824
14825   if (extra_trace_bits && *default_collect)
14826     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
14827
14828   do_cleanups (cleanup);
14829   if (from_tty)
14830     printf_filtered (_("Saved to file '%s'.\n"), filename);
14831 }
14832
14833 /* The `save breakpoints' command.  */
14834
14835 static void
14836 save_breakpoints_command (char *args, int from_tty)
14837 {
14838   save_breakpoints (args, from_tty, NULL);
14839 }
14840
14841 /* The `save tracepoints' command.  */
14842
14843 static void
14844 save_tracepoints_command (char *args, int from_tty)
14845 {
14846   save_breakpoints (args, from_tty, is_tracepoint);
14847 }
14848
14849 /* Create a vector of all tracepoints.  */
14850
14851 VEC(breakpoint_p) *
14852 all_tracepoints (void)
14853 {
14854   VEC(breakpoint_p) *tp_vec = 0;
14855   struct breakpoint *tp;
14856
14857   ALL_TRACEPOINTS (tp)
14858   {
14859     VEC_safe_push (breakpoint_p, tp_vec, tp);
14860   }
14861
14862   return tp_vec;
14863 }
14864
14865 \f
14866 /* This help string is used for the break, hbreak, tbreak and thbreak
14867    commands.  It is defined as a macro to prevent duplication.
14868    COMMAND should be a string constant containing the name of the
14869    command.  */
14870 #define BREAK_ARGS_HELP(command) \
14871 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
14872 LOCATION may be a line number, function name, or \"*\" and an address.\n\
14873 If a line number is specified, break at start of code for that line.\n\
14874 If a function is specified, break at start of code for that function.\n\
14875 If an address is specified, break at that exact address.\n\
14876 With no LOCATION, uses current execution address of the selected\n\
14877 stack frame.  This is useful for breaking on return to a stack frame.\n\
14878 \n\
14879 THREADNUM is the number from \"info threads\".\n\
14880 CONDITION is a boolean expression.\n\
14881 \n\
14882 Multiple breakpoints at one place are permitted, and useful if their\n\
14883 conditions are different.\n\
14884 \n\
14885 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14886
14887 /* List of subcommands for "catch".  */
14888 static struct cmd_list_element *catch_cmdlist;
14889
14890 /* List of subcommands for "tcatch".  */
14891 static struct cmd_list_element *tcatch_cmdlist;
14892
14893 void
14894 add_catch_command (char *name, char *docstring,
14895                    void (*sfunc) (char *args, int from_tty,
14896                                   struct cmd_list_element *command),
14897                    char **(*completer) (struct cmd_list_element *cmd,
14898                                          char *text, char *word),
14899                    void *user_data_catch,
14900                    void *user_data_tcatch)
14901 {
14902   struct cmd_list_element *command;
14903
14904   command = add_cmd (name, class_breakpoint, NULL, docstring,
14905                      &catch_cmdlist);
14906   set_cmd_sfunc (command, sfunc);
14907   set_cmd_context (command, user_data_catch);
14908   set_cmd_completer (command, completer);
14909
14910   command = add_cmd (name, class_breakpoint, NULL, docstring,
14911                      &tcatch_cmdlist);
14912   set_cmd_sfunc (command, sfunc);
14913   set_cmd_context (command, user_data_tcatch);
14914   set_cmd_completer (command, completer);
14915 }
14916
14917 static void
14918 clear_syscall_counts (struct inferior *inf)
14919 {
14920   struct catch_syscall_inferior_data *inf_data
14921     = get_catch_syscall_inferior_data (inf);
14922
14923   inf_data->total_syscalls_count = 0;
14924   inf_data->any_syscall_count = 0;
14925   VEC_free (int, inf_data->syscalls_counts);
14926 }
14927
14928 static void
14929 save_command (char *arg, int from_tty)
14930 {
14931   printf_unfiltered (_("\"save\" must be followed by "
14932                        "the name of a save subcommand.\n"));
14933   help_list (save_cmdlist, "save ", -1, gdb_stdout);
14934 }
14935
14936 struct breakpoint *
14937 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
14938                           void *data)
14939 {
14940   struct breakpoint *b, *b_tmp;
14941
14942   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14943     {
14944       if ((*callback) (b, data))
14945         return b;
14946     }
14947
14948   return NULL;
14949 }
14950
14951 /* Zero if any of the breakpoint's locations could be a location where
14952    functions have been inlined, nonzero otherwise.  */
14953
14954 static int
14955 is_non_inline_function (struct breakpoint *b)
14956 {
14957   /* The shared library event breakpoint is set on the address of a
14958      non-inline function.  */
14959   if (b->type == bp_shlib_event)
14960     return 1;
14961
14962   return 0;
14963 }
14964
14965 /* Nonzero if the specified PC cannot be a location where functions
14966    have been inlined.  */
14967
14968 int
14969 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
14970                            const struct target_waitstatus *ws)
14971 {
14972   struct breakpoint *b;
14973   struct bp_location *bl;
14974
14975   ALL_BREAKPOINTS (b)
14976     {
14977       if (!is_non_inline_function (b))
14978         continue;
14979
14980       for (bl = b->loc; bl != NULL; bl = bl->next)
14981         {
14982           if (!bl->shlib_disabled
14983               && bpstat_check_location (bl, aspace, pc, ws))
14984             return 1;
14985         }
14986     }
14987
14988   return 0;
14989 }
14990
14991 void
14992 initialize_breakpoint_ops (void)
14993 {
14994   static int initialized = 0;
14995
14996   struct breakpoint_ops *ops;
14997
14998   if (initialized)
14999     return;
15000   initialized = 1;
15001
15002   /* The breakpoint_ops structure to be inherit by all kinds of
15003      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15004      internal and momentary breakpoints, etc.).  */
15005   ops = &bkpt_base_breakpoint_ops;
15006   *ops = base_breakpoint_ops;
15007   ops->re_set = bkpt_re_set;
15008   ops->insert_location = bkpt_insert_location;
15009   ops->remove_location = bkpt_remove_location;
15010   ops->breakpoint_hit = bkpt_breakpoint_hit;
15011   ops->create_sals_from_address = bkpt_create_sals_from_address;
15012   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15013   ops->decode_linespec = bkpt_decode_linespec;
15014
15015   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15016   ops = &bkpt_breakpoint_ops;
15017   *ops = bkpt_base_breakpoint_ops;
15018   ops->re_set = bkpt_re_set;
15019   ops->resources_needed = bkpt_resources_needed;
15020   ops->print_it = bkpt_print_it;
15021   ops->print_mention = bkpt_print_mention;
15022   ops->print_recreate = bkpt_print_recreate;
15023
15024   /* Ranged breakpoints.  */
15025   ops = &ranged_breakpoint_ops;
15026   *ops = bkpt_breakpoint_ops;
15027   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15028   ops->resources_needed = resources_needed_ranged_breakpoint;
15029   ops->print_it = print_it_ranged_breakpoint;
15030   ops->print_one = print_one_ranged_breakpoint;
15031   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15032   ops->print_mention = print_mention_ranged_breakpoint;
15033   ops->print_recreate = print_recreate_ranged_breakpoint;
15034
15035   /* Internal breakpoints.  */
15036   ops = &internal_breakpoint_ops;
15037   *ops = bkpt_base_breakpoint_ops;
15038   ops->re_set = internal_bkpt_re_set;
15039   ops->check_status = internal_bkpt_check_status;
15040   ops->print_it = internal_bkpt_print_it;
15041   ops->print_mention = internal_bkpt_print_mention;
15042
15043   /* Momentary breakpoints.  */
15044   ops = &momentary_breakpoint_ops;
15045   *ops = bkpt_base_breakpoint_ops;
15046   ops->re_set = momentary_bkpt_re_set;
15047   ops->check_status = momentary_bkpt_check_status;
15048   ops->print_it = momentary_bkpt_print_it;
15049   ops->print_mention = momentary_bkpt_print_mention;
15050
15051   /* Probe breakpoints.  */
15052   ops = &bkpt_probe_breakpoint_ops;
15053   *ops = bkpt_breakpoint_ops;
15054   ops->insert_location = bkpt_probe_insert_location;
15055   ops->remove_location = bkpt_probe_remove_location;
15056   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15057   ops->decode_linespec = bkpt_probe_decode_linespec;
15058
15059   /* GNU v3 exception catchpoints.  */
15060   ops = &gnu_v3_exception_catchpoint_ops;
15061   *ops = bkpt_breakpoint_ops;
15062   ops->print_it = print_it_exception_catchpoint;
15063   ops->print_one = print_one_exception_catchpoint;
15064   ops->print_mention = print_mention_exception_catchpoint;
15065   ops->print_recreate = print_recreate_exception_catchpoint;
15066
15067   /* Watchpoints.  */
15068   ops = &watchpoint_breakpoint_ops;
15069   *ops = base_breakpoint_ops;
15070   ops->dtor = dtor_watchpoint;
15071   ops->re_set = re_set_watchpoint;
15072   ops->insert_location = insert_watchpoint;
15073   ops->remove_location = remove_watchpoint;
15074   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15075   ops->check_status = check_status_watchpoint;
15076   ops->resources_needed = resources_needed_watchpoint;
15077   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15078   ops->print_it = print_it_watchpoint;
15079   ops->print_mention = print_mention_watchpoint;
15080   ops->print_recreate = print_recreate_watchpoint;
15081
15082   /* Masked watchpoints.  */
15083   ops = &masked_watchpoint_breakpoint_ops;
15084   *ops = watchpoint_breakpoint_ops;
15085   ops->insert_location = insert_masked_watchpoint;
15086   ops->remove_location = remove_masked_watchpoint;
15087   ops->resources_needed = resources_needed_masked_watchpoint;
15088   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15089   ops->print_it = print_it_masked_watchpoint;
15090   ops->print_one_detail = print_one_detail_masked_watchpoint;
15091   ops->print_mention = print_mention_masked_watchpoint;
15092   ops->print_recreate = print_recreate_masked_watchpoint;
15093
15094   /* Tracepoints.  */
15095   ops = &tracepoint_breakpoint_ops;
15096   *ops = base_breakpoint_ops;
15097   ops->re_set = tracepoint_re_set;
15098   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15099   ops->print_one_detail = tracepoint_print_one_detail;
15100   ops->print_mention = tracepoint_print_mention;
15101   ops->print_recreate = tracepoint_print_recreate;
15102   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15103   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15104   ops->decode_linespec = tracepoint_decode_linespec;
15105
15106   /* Probe tracepoints.  */
15107   ops = &tracepoint_probe_breakpoint_ops;
15108   *ops = tracepoint_breakpoint_ops;
15109   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15110   ops->decode_linespec = tracepoint_probe_decode_linespec;
15111
15112   /* Static tracepoints with marker (`-m').  */
15113   ops = &strace_marker_breakpoint_ops;
15114   *ops = tracepoint_breakpoint_ops;
15115   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15116   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15117   ops->decode_linespec = strace_marker_decode_linespec;
15118
15119   /* Fork catchpoints.  */
15120   ops = &catch_fork_breakpoint_ops;
15121   *ops = base_breakpoint_ops;
15122   ops->insert_location = insert_catch_fork;
15123   ops->remove_location = remove_catch_fork;
15124   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15125   ops->print_it = print_it_catch_fork;
15126   ops->print_one = print_one_catch_fork;
15127   ops->print_mention = print_mention_catch_fork;
15128   ops->print_recreate = print_recreate_catch_fork;
15129
15130   /* Vfork catchpoints.  */
15131   ops = &catch_vfork_breakpoint_ops;
15132   *ops = base_breakpoint_ops;
15133   ops->insert_location = insert_catch_vfork;
15134   ops->remove_location = remove_catch_vfork;
15135   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15136   ops->print_it = print_it_catch_vfork;
15137   ops->print_one = print_one_catch_vfork;
15138   ops->print_mention = print_mention_catch_vfork;
15139   ops->print_recreate = print_recreate_catch_vfork;
15140
15141   /* Exec catchpoints.  */
15142   ops = &catch_exec_breakpoint_ops;
15143   *ops = base_breakpoint_ops;
15144   ops->dtor = dtor_catch_exec;
15145   ops->insert_location = insert_catch_exec;
15146   ops->remove_location = remove_catch_exec;
15147   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15148   ops->print_it = print_it_catch_exec;
15149   ops->print_one = print_one_catch_exec;
15150   ops->print_mention = print_mention_catch_exec;
15151   ops->print_recreate = print_recreate_catch_exec;
15152
15153   /* Syscall catchpoints.  */
15154   ops = &catch_syscall_breakpoint_ops;
15155   *ops = base_breakpoint_ops;
15156   ops->dtor = dtor_catch_syscall;
15157   ops->insert_location = insert_catch_syscall;
15158   ops->remove_location = remove_catch_syscall;
15159   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15160   ops->print_it = print_it_catch_syscall;
15161   ops->print_one = print_one_catch_syscall;
15162   ops->print_mention = print_mention_catch_syscall;
15163   ops->print_recreate = print_recreate_catch_syscall;
15164
15165   /* Solib-related catchpoints.  */
15166   ops = &catch_solib_breakpoint_ops;
15167   *ops = base_breakpoint_ops;
15168   ops->dtor = dtor_catch_solib;
15169   ops->insert_location = insert_catch_solib;
15170   ops->remove_location = remove_catch_solib;
15171   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15172   ops->check_status = check_status_catch_solib;
15173   ops->print_it = print_it_catch_solib;
15174   ops->print_one = print_one_catch_solib;
15175   ops->print_mention = print_mention_catch_solib;
15176   ops->print_recreate = print_recreate_catch_solib;
15177 }
15178
15179 void
15180 _initialize_breakpoint (void)
15181 {
15182   struct cmd_list_element *c;
15183
15184   initialize_breakpoint_ops ();
15185
15186   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15187   observer_attach_inferior_exit (clear_syscall_counts);
15188   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15189
15190   breakpoint_objfile_key
15191     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15192
15193   catch_syscall_inferior_data
15194     = register_inferior_data_with_cleanup (catch_syscall_inferior_data_cleanup);
15195
15196   breakpoint_chain = 0;
15197   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15198      before a breakpoint is set.  */
15199   breakpoint_count = 0;
15200
15201   tracepoint_count = 0;
15202
15203   add_com ("ignore", class_breakpoint, ignore_command, _("\
15204 Set ignore-count of breakpoint number N to COUNT.\n\
15205 Usage is `ignore N COUNT'."));
15206   if (xdb_commands)
15207     add_com_alias ("bc", "ignore", class_breakpoint, 1);
15208
15209   add_com ("commands", class_breakpoint, commands_command, _("\
15210 Set commands to be executed when a breakpoint is hit.\n\
15211 Give breakpoint number as argument after \"commands\".\n\
15212 With no argument, the targeted breakpoint is the last one set.\n\
15213 The commands themselves follow starting on the next line.\n\
15214 Type a line containing \"end\" to indicate the end of them.\n\
15215 Give \"silent\" as the first line to make the breakpoint silent;\n\
15216 then no output is printed when it is hit, except what the commands print."));
15217
15218   add_com ("condition", class_breakpoint, condition_command, _("\
15219 Specify breakpoint number N to break only if COND is true.\n\
15220 Usage is `condition N COND', where N is an integer and COND is an\n\
15221 expression to be evaluated whenever breakpoint N is reached."));
15222
15223   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15224 Set a temporary breakpoint.\n\
15225 Like \"break\" except the breakpoint is only temporary,\n\
15226 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15227 by using \"enable delete\" on the breakpoint number.\n\
15228 \n"
15229 BREAK_ARGS_HELP ("tbreak")));
15230   set_cmd_completer (c, location_completer);
15231
15232   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15233 Set a hardware assisted breakpoint.\n\
15234 Like \"break\" except the breakpoint requires hardware support,\n\
15235 some target hardware may not have this support.\n\
15236 \n"
15237 BREAK_ARGS_HELP ("hbreak")));
15238   set_cmd_completer (c, location_completer);
15239
15240   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15241 Set a temporary hardware assisted breakpoint.\n\
15242 Like \"hbreak\" except the breakpoint is only temporary,\n\
15243 so it will be deleted when hit.\n\
15244 \n"
15245 BREAK_ARGS_HELP ("thbreak")));
15246   set_cmd_completer (c, location_completer);
15247
15248   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15249 Enable some breakpoints.\n\
15250 Give breakpoint numbers (separated by spaces) as arguments.\n\
15251 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15252 This is used to cancel the effect of the \"disable\" command.\n\
15253 With a subcommand you can enable temporarily."),
15254                   &enablelist, "enable ", 1, &cmdlist);
15255   if (xdb_commands)
15256     add_com ("ab", class_breakpoint, enable_command, _("\
15257 Enable some breakpoints.\n\
15258 Give breakpoint numbers (separated by spaces) as arguments.\n\
15259 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15260 This is used to cancel the effect of the \"disable\" command.\n\
15261 With a subcommand you can enable temporarily."));
15262
15263   add_com_alias ("en", "enable", class_breakpoint, 1);
15264
15265   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15266 Enable some breakpoints.\n\
15267 Give breakpoint numbers (separated by spaces) as arguments.\n\
15268 This is used to cancel the effect of the \"disable\" command.\n\
15269 May be abbreviated to simply \"enable\".\n"),
15270                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15271
15272   add_cmd ("once", no_class, enable_once_command, _("\
15273 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15274 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15275            &enablebreaklist);
15276
15277   add_cmd ("delete", no_class, enable_delete_command, _("\
15278 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15279 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15280            &enablebreaklist);
15281
15282   add_cmd ("count", no_class, enable_count_command, _("\
15283 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15284 If a breakpoint is hit while enabled in this fashion,\n\
15285 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15286            &enablebreaklist);
15287
15288   add_cmd ("delete", no_class, enable_delete_command, _("\
15289 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15290 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15291            &enablelist);
15292
15293   add_cmd ("once", no_class, enable_once_command, _("\
15294 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15295 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15296            &enablelist);
15297
15298   add_cmd ("count", no_class, enable_count_command, _("\
15299 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15300 If a breakpoint is hit while enabled in this fashion,\n\
15301 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15302            &enablelist);
15303
15304   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15305 Disable some breakpoints.\n\
15306 Arguments are breakpoint numbers with spaces in between.\n\
15307 To disable all breakpoints, give no argument.\n\
15308 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15309                   &disablelist, "disable ", 1, &cmdlist);
15310   add_com_alias ("dis", "disable", class_breakpoint, 1);
15311   add_com_alias ("disa", "disable", class_breakpoint, 1);
15312   if (xdb_commands)
15313     add_com ("sb", class_breakpoint, disable_command, _("\
15314 Disable some breakpoints.\n\
15315 Arguments are breakpoint numbers with spaces in between.\n\
15316 To disable all breakpoints, give no argument.\n\
15317 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
15318
15319   add_cmd ("breakpoints", class_alias, disable_command, _("\
15320 Disable some breakpoints.\n\
15321 Arguments are breakpoint numbers with spaces in between.\n\
15322 To disable all breakpoints, give no argument.\n\
15323 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15324 This command may be abbreviated \"disable\"."),
15325            &disablelist);
15326
15327   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15328 Delete some breakpoints or auto-display expressions.\n\
15329 Arguments are breakpoint numbers with spaces in between.\n\
15330 To delete all breakpoints, give no argument.\n\
15331 \n\
15332 Also a prefix command for deletion of other GDB objects.\n\
15333 The \"unset\" command is also an alias for \"delete\"."),
15334                   &deletelist, "delete ", 1, &cmdlist);
15335   add_com_alias ("d", "delete", class_breakpoint, 1);
15336   add_com_alias ("del", "delete", class_breakpoint, 1);
15337   if (xdb_commands)
15338     add_com ("db", class_breakpoint, delete_command, _("\
15339 Delete some breakpoints.\n\
15340 Arguments are breakpoint numbers with spaces in between.\n\
15341 To delete all breakpoints, give no argument.\n"));
15342
15343   add_cmd ("breakpoints", class_alias, delete_command, _("\
15344 Delete some breakpoints or auto-display expressions.\n\
15345 Arguments are breakpoint numbers with spaces in between.\n\
15346 To delete all breakpoints, give no argument.\n\
15347 This command may be abbreviated \"delete\"."),
15348            &deletelist);
15349
15350   add_com ("clear", class_breakpoint, clear_command, _("\
15351 Clear breakpoint at specified line or function.\n\
15352 Argument may be line number, function name, or \"*\" and an address.\n\
15353 If line number is specified, all breakpoints in that line are cleared.\n\
15354 If function is specified, breakpoints at beginning of function are cleared.\n\
15355 If an address is specified, breakpoints at that address are cleared.\n\
15356 \n\
15357 With no argument, clears all breakpoints in the line that the selected frame\n\
15358 is executing in.\n\
15359 \n\
15360 See also the \"delete\" command which clears breakpoints by number."));
15361   add_com_alias ("cl", "clear", class_breakpoint, 1);
15362
15363   c = add_com ("break", class_breakpoint, break_command, _("\
15364 Set breakpoint at specified line or function.\n"
15365 BREAK_ARGS_HELP ("break")));
15366   set_cmd_completer (c, location_completer);
15367
15368   add_com_alias ("b", "break", class_run, 1);
15369   add_com_alias ("br", "break", class_run, 1);
15370   add_com_alias ("bre", "break", class_run, 1);
15371   add_com_alias ("brea", "break", class_run, 1);
15372
15373   if (xdb_commands)
15374    add_com_alias ("ba", "break", class_breakpoint, 1);
15375
15376   if (dbx_commands)
15377     {
15378       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15379 Break in function/address or break at a line in the current file."),
15380                              &stoplist, "stop ", 1, &cmdlist);
15381       add_cmd ("in", class_breakpoint, stopin_command,
15382                _("Break in function or address."), &stoplist);
15383       add_cmd ("at", class_breakpoint, stopat_command,
15384                _("Break at a line in the current file."), &stoplist);
15385       add_com ("status", class_info, breakpoints_info, _("\
15386 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15387 The \"Type\" column indicates one of:\n\
15388 \tbreakpoint     - normal breakpoint\n\
15389 \twatchpoint     - watchpoint\n\
15390 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15391 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15392 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15393 address and file/line number respectively.\n\
15394 \n\
15395 Convenience variable \"$_\" and default examine address for \"x\"\n\
15396 are set to the address of the last breakpoint listed unless the command\n\
15397 is prefixed with \"server \".\n\n\
15398 Convenience variable \"$bpnum\" contains the number of the last\n\
15399 breakpoint set."));
15400     }
15401
15402   add_info ("breakpoints", breakpoints_info, _("\
15403 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15404 The \"Type\" column indicates one of:\n\
15405 \tbreakpoint     - normal breakpoint\n\
15406 \twatchpoint     - watchpoint\n\
15407 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15408 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15409 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15410 address and file/line number respectively.\n\
15411 \n\
15412 Convenience variable \"$_\" and default examine address for \"x\"\n\
15413 are set to the address of the last breakpoint listed unless the command\n\
15414 is prefixed with \"server \".\n\n\
15415 Convenience variable \"$bpnum\" contains the number of the last\n\
15416 breakpoint set."));
15417
15418   add_info_alias ("b", "breakpoints", 1);
15419
15420   if (xdb_commands)
15421     add_com ("lb", class_breakpoint, breakpoints_info, _("\
15422 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15423 The \"Type\" column indicates one of:\n\
15424 \tbreakpoint     - normal breakpoint\n\
15425 \twatchpoint     - watchpoint\n\
15426 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15427 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15428 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15429 address and file/line number respectively.\n\
15430 \n\
15431 Convenience variable \"$_\" and default examine address for \"x\"\n\
15432 are set to the address of the last breakpoint listed unless the command\n\
15433 is prefixed with \"server \".\n\n\
15434 Convenience variable \"$bpnum\" contains the number of the last\n\
15435 breakpoint set."));
15436
15437   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15438 Status of all breakpoints, or breakpoint number NUMBER.\n\
15439 The \"Type\" column indicates one of:\n\
15440 \tbreakpoint     - normal breakpoint\n\
15441 \twatchpoint     - watchpoint\n\
15442 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15443 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15444 \tuntil          - internal breakpoint used by the \"until\" command\n\
15445 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15446 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15447 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15448 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15449 address and file/line number respectively.\n\
15450 \n\
15451 Convenience variable \"$_\" and default examine address for \"x\"\n\
15452 are set to the address of the last breakpoint listed unless the command\n\
15453 is prefixed with \"server \".\n\n\
15454 Convenience variable \"$bpnum\" contains the number of the last\n\
15455 breakpoint set."),
15456            &maintenanceinfolist);
15457
15458   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15459 Set catchpoints to catch events."),
15460                   &catch_cmdlist, "catch ",
15461                   0/*allow-unknown*/, &cmdlist);
15462
15463   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15464 Set temporary catchpoints to catch events."),
15465                   &tcatch_cmdlist, "tcatch ",
15466                   0/*allow-unknown*/, &cmdlist);
15467
15468   /* Add catch and tcatch sub-commands.  */
15469   add_catch_command ("catch", _("\
15470 Catch an exception, when caught."),
15471                      catch_catch_command,
15472                      NULL,
15473                      CATCH_PERMANENT,
15474                      CATCH_TEMPORARY);
15475   add_catch_command ("throw", _("\
15476 Catch an exception, when thrown."),
15477                      catch_throw_command,
15478                      NULL,
15479                      CATCH_PERMANENT,
15480                      CATCH_TEMPORARY);
15481   add_catch_command ("fork", _("Catch calls to fork."),
15482                      catch_fork_command_1,
15483                      NULL,
15484                      (void *) (uintptr_t) catch_fork_permanent,
15485                      (void *) (uintptr_t) catch_fork_temporary);
15486   add_catch_command ("vfork", _("Catch calls to vfork."),
15487                      catch_fork_command_1,
15488                      NULL,
15489                      (void *) (uintptr_t) catch_vfork_permanent,
15490                      (void *) (uintptr_t) catch_vfork_temporary);
15491   add_catch_command ("exec", _("Catch calls to exec."),
15492                      catch_exec_command_1,
15493                      NULL,
15494                      CATCH_PERMANENT,
15495                      CATCH_TEMPORARY);
15496   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15497 Usage: catch load [REGEX]\n\
15498 If REGEX is given, only stop for libraries matching the regular expression."),
15499                      catch_load_command_1,
15500                      NULL,
15501                      CATCH_PERMANENT,
15502                      CATCH_TEMPORARY);
15503   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15504 Usage: catch unload [REGEX]\n\
15505 If REGEX is given, only stop for libraries matching the regular expression."),
15506                      catch_unload_command_1,
15507                      NULL,
15508                      CATCH_PERMANENT,
15509                      CATCH_TEMPORARY);
15510   add_catch_command ("syscall", _("\
15511 Catch system calls by their names and/or numbers.\n\
15512 Arguments say which system calls to catch.  If no arguments\n\
15513 are given, every system call will be caught.\n\
15514 Arguments, if given, should be one or more system call names\n\
15515 (if your system supports that), or system call numbers."),
15516                      catch_syscall_command_1,
15517                      catch_syscall_completer,
15518                      CATCH_PERMANENT,
15519                      CATCH_TEMPORARY);
15520
15521   c = add_com ("watch", class_breakpoint, watch_command, _("\
15522 Set a watchpoint for an expression.\n\
15523 Usage: watch [-l|-location] EXPRESSION\n\
15524 A watchpoint stops execution of your program whenever the value of\n\
15525 an expression changes.\n\
15526 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15527 the memory to which it refers."));
15528   set_cmd_completer (c, expression_completer);
15529
15530   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15531 Set a read watchpoint for an expression.\n\
15532 Usage: rwatch [-l|-location] EXPRESSION\n\
15533 A watchpoint stops execution of your program whenever the value of\n\
15534 an expression is read.\n\
15535 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15536 the memory to which it refers."));
15537   set_cmd_completer (c, expression_completer);
15538
15539   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15540 Set a watchpoint for an expression.\n\
15541 Usage: awatch [-l|-location] EXPRESSION\n\
15542 A watchpoint stops execution of your program whenever the value of\n\
15543 an expression is either read or written.\n\
15544 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15545 the memory to which it refers."));
15546   set_cmd_completer (c, expression_completer);
15547
15548   add_info ("watchpoints", watchpoints_info, _("\
15549 Status of specified watchpoints (all watchpoints if no argument)."));
15550
15551   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15552      respond to changes - contrary to the description.  */
15553   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15554                             &can_use_hw_watchpoints, _("\
15555 Set debugger's willingness to use watchpoint hardware."), _("\
15556 Show debugger's willingness to use watchpoint hardware."), _("\
15557 If zero, gdb will not use hardware for new watchpoints, even if\n\
15558 such is available.  (However, any hardware watchpoints that were\n\
15559 created before setting this to nonzero, will continue to use watchpoint\n\
15560 hardware.)"),
15561                             NULL,
15562                             show_can_use_hw_watchpoints,
15563                             &setlist, &showlist);
15564
15565   can_use_hw_watchpoints = 1;
15566
15567   /* Tracepoint manipulation commands.  */
15568
15569   c = add_com ("trace", class_breakpoint, trace_command, _("\
15570 Set a tracepoint at specified line or function.\n\
15571 \n"
15572 BREAK_ARGS_HELP ("trace") "\n\
15573 Do \"help tracepoints\" for info on other tracepoint commands."));
15574   set_cmd_completer (c, location_completer);
15575
15576   add_com_alias ("tp", "trace", class_alias, 0);
15577   add_com_alias ("tr", "trace", class_alias, 1);
15578   add_com_alias ("tra", "trace", class_alias, 1);
15579   add_com_alias ("trac", "trace", class_alias, 1);
15580
15581   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15582 Set a fast tracepoint at specified line or function.\n\
15583 \n"
15584 BREAK_ARGS_HELP ("ftrace") "\n\
15585 Do \"help tracepoints\" for info on other tracepoint commands."));
15586   set_cmd_completer (c, location_completer);
15587
15588   c = add_com ("strace", class_breakpoint, strace_command, _("\
15589 Set a static tracepoint at specified line, function or marker.\n\
15590 \n\
15591 strace [LOCATION] [if CONDITION]\n\
15592 LOCATION may be a line number, function name, \"*\" and an address,\n\
15593 or -m MARKER_ID.\n\
15594 If a line number is specified, probe the marker at start of code\n\
15595 for that line.  If a function is specified, probe the marker at start\n\
15596 of code for that function.  If an address is specified, probe the marker\n\
15597 at that exact address.  If a marker id is specified, probe the marker\n\
15598 with that name.  With no LOCATION, uses current execution address of\n\
15599 the selected stack frame.\n\
15600 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15601 This collects arbitrary user data passed in the probe point call to the\n\
15602 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15603 by printing the $_sdata variable like any other convenience variable.\n\
15604 \n\
15605 CONDITION is a boolean expression.\n\
15606 \n\
15607 Multiple tracepoints at one place are permitted, and useful if their\n\
15608 conditions are different.\n\
15609 \n\
15610 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15611 Do \"help tracepoints\" for info on other tracepoint commands."));
15612   set_cmd_completer (c, location_completer);
15613
15614   add_info ("tracepoints", tracepoints_info, _("\
15615 Status of specified tracepoints (all tracepoints if no argument).\n\
15616 Convenience variable \"$tpnum\" contains the number of the\n\
15617 last tracepoint set."));
15618
15619   add_info_alias ("tp", "tracepoints", 1);
15620
15621   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15622 Delete specified tracepoints.\n\
15623 Arguments are tracepoint numbers, separated by spaces.\n\
15624 No argument means delete all tracepoints."),
15625            &deletelist);
15626
15627   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15628 Disable specified tracepoints.\n\
15629 Arguments are tracepoint numbers, separated by spaces.\n\
15630 No argument means disable all tracepoints."),
15631            &disablelist);
15632   deprecate_cmd (c, "disable");
15633
15634   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15635 Enable specified tracepoints.\n\
15636 Arguments are tracepoint numbers, separated by spaces.\n\
15637 No argument means enable all tracepoints."),
15638            &enablelist);
15639   deprecate_cmd (c, "enable");
15640
15641   add_com ("passcount", class_trace, trace_pass_command, _("\
15642 Set the passcount for a tracepoint.\n\
15643 The trace will end when the tracepoint has been passed 'count' times.\n\
15644 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15645 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15646
15647   add_prefix_cmd ("save", class_breakpoint, save_command,
15648                   _("Save breakpoint definitions as a script."),
15649                   &save_cmdlist, "save ",
15650                   0/*allow-unknown*/, &cmdlist);
15651
15652   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15653 Save current breakpoint definitions as a script.\n\
15654 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15655 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15656 session to restore them."),
15657                &save_cmdlist);
15658   set_cmd_completer (c, filename_completer);
15659
15660   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15661 Save current tracepoint definitions as a script.\n\
15662 Use the 'source' command in another debug session to restore them."),
15663                &save_cmdlist);
15664   set_cmd_completer (c, filename_completer);
15665
15666   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15667   deprecate_cmd (c, "save tracepoints");
15668
15669   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15670 Breakpoint specific settings\n\
15671 Configure various breakpoint-specific variables such as\n\
15672 pending breakpoint behavior"),
15673                   &breakpoint_set_cmdlist, "set breakpoint ",
15674                   0/*allow-unknown*/, &setlist);
15675   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15676 Breakpoint specific settings\n\
15677 Configure various breakpoint-specific variables such as\n\
15678 pending breakpoint behavior"),
15679                   &breakpoint_show_cmdlist, "show breakpoint ",
15680                   0/*allow-unknown*/, &showlist);
15681
15682   add_setshow_auto_boolean_cmd ("pending", no_class,
15683                                 &pending_break_support, _("\
15684 Set debugger's behavior regarding pending breakpoints."), _("\
15685 Show debugger's behavior regarding pending breakpoints."), _("\
15686 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15687 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15688 an error.  If auto, an unrecognized breakpoint location results in a\n\
15689 user-query to see if a pending breakpoint should be created."),
15690                                 NULL,
15691                                 show_pending_break_support,
15692                                 &breakpoint_set_cmdlist,
15693                                 &breakpoint_show_cmdlist);
15694
15695   pending_break_support = AUTO_BOOLEAN_AUTO;
15696
15697   add_setshow_boolean_cmd ("auto-hw", no_class,
15698                            &automatic_hardware_breakpoints, _("\
15699 Set automatic usage of hardware breakpoints."), _("\
15700 Show automatic usage of hardware breakpoints."), _("\
15701 If set, the debugger will automatically use hardware breakpoints for\n\
15702 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15703 a warning will be emitted for such breakpoints."),
15704                            NULL,
15705                            show_automatic_hardware_breakpoints,
15706                            &breakpoint_set_cmdlist,
15707                            &breakpoint_show_cmdlist);
15708
15709   add_setshow_enum_cmd ("always-inserted", class_support,
15710                         always_inserted_enums, &always_inserted_mode, _("\
15711 Set mode for inserting breakpoints."), _("\
15712 Show mode for inserting breakpoints."), _("\
15713 When this mode is off, breakpoints are inserted in inferior when it is\n\
15714 resumed, and removed when execution stops.  When this mode is on,\n\
15715 breakpoints are inserted immediately and removed only when the user\n\
15716 deletes the breakpoint.  When this mode is auto (which is the default),\n\
15717 the behaviour depends on the non-stop setting (see help set non-stop).\n\
15718 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
15719 behaves as if always-inserted mode is on; if gdb is controlling the\n\
15720 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
15721                            NULL,
15722                            &show_always_inserted_mode,
15723                            &breakpoint_set_cmdlist,
15724                            &breakpoint_show_cmdlist);
15725
15726   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15727                         condition_evaluation_enums,
15728                         &condition_evaluation_mode_1, _("\
15729 Set mode of breakpoint condition evaluation."), _("\
15730 Show mode of breakpoint condition evaluation."), _("\
15731 When this is set to \"host\", breakpoint conditions will be\n\
15732 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15733 breakpoint conditions will be downloaded to the target (if the target\n\
15734 supports such feature) and conditions will be evaluated on the target's side.\n\
15735 If this is set to \"auto\" (default), this will be automatically set to\n\
15736 \"target\" if it supports condition evaluation, otherwise it will\n\
15737 be set to \"gdb\""),
15738                            &set_condition_evaluation_mode,
15739                            &show_condition_evaluation_mode,
15740                            &breakpoint_set_cmdlist,
15741                            &breakpoint_show_cmdlist);
15742
15743   add_com ("break-range", class_breakpoint, break_range_command, _("\
15744 Set a breakpoint for an address range.\n\
15745 break-range START-LOCATION, END-LOCATION\n\
15746 where START-LOCATION and END-LOCATION can be one of the following:\n\
15747   LINENUM, for that line in the current file,\n\
15748   FILE:LINENUM, for that line in that file,\n\
15749   +OFFSET, for that number of lines after the current line\n\
15750            or the start of the range\n\
15751   FUNCTION, for the first line in that function,\n\
15752   FILE:FUNCTION, to distinguish among like-named static functions.\n\
15753   *ADDRESS, for the instruction at that address.\n\
15754 \n\
15755 The breakpoint will stop execution of the inferior whenever it executes\n\
15756 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15757 range (including START-LOCATION and END-LOCATION)."));
15758
15759   automatic_hardware_breakpoints = 1;
15760
15761   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
15762 }