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