gdb/
[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 "cli/cli-utils.h"
64 #include "continuations.h"
65 #include "stack.h"
66 #include "skip.h"
67 #include "record.h"
68 #include "gdb_regex.h"
69 #include "ax-gdb.h"
70
71 /* readline include files */
72 #include "readline/readline.h"
73 #include "readline/history.h"
74
75 /* readline defines this.  */
76 #undef savestring
77
78 #include "mi/mi-common.h"
79 #include "python/python.h"
80
81 /* Prototypes for local functions.  */
82
83 static void enable_delete_command (char *, int);
84
85 static void enable_once_command (char *, int);
86
87 static void enable_count_command (char *, int);
88
89 static void disable_command (char *, int);
90
91 static void enable_command (char *, int);
92
93 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
94                                                       void *),
95                                     void *);
96
97 static void ignore_command (char *, int);
98
99 static int breakpoint_re_set_one (void *);
100
101 static void breakpoint_re_set_default (struct breakpoint *);
102
103 static void create_sals_from_address_default (char **,
104                                               struct linespec_result *,
105                                               enum bptype, char *,
106                                               char **);
107
108 static void create_breakpoints_sal_default (struct gdbarch *,
109                                             struct linespec_result *,
110                                             struct linespec_sals *,
111                                             char *, enum bptype,
112                                             enum bpdisp, int, int,
113                                             int,
114                                             const struct breakpoint_ops *,
115                                             int, int, int, unsigned);
116
117 static void decode_linespec_default (struct breakpoint *, char **,
118                                      struct symtabs_and_lines *);
119
120 static void clear_command (char *, int);
121
122 static void catch_command (char *, int);
123
124 static int can_use_hardware_watchpoint (struct value *);
125
126 static void break_command_1 (char *, int, int);
127
128 static void mention (struct breakpoint *);
129
130 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
131                                                                enum bptype,
132                                                                const struct breakpoint_ops *);
133 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
134                                                        const struct symtab_and_line *);
135
136 /* This function is used in gdbtk sources and thus can not be made
137    static.  */
138 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
139                                        struct symtab_and_line,
140                                        enum bptype,
141                                        const struct breakpoint_ops *);
142
143 static struct breakpoint *
144   momentary_breakpoint_from_master (struct breakpoint *orig,
145                                     enum bptype type,
146                                     const struct breakpoint_ops *ops);
147
148 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
149
150 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
151                                             CORE_ADDR bpaddr,
152                                             enum bptype bptype);
153
154 static void describe_other_breakpoints (struct gdbarch *,
155                                         struct program_space *, CORE_ADDR,
156                                         struct obj_section *, int);
157
158 static int breakpoint_address_match (struct address_space *aspace1,
159                                      CORE_ADDR addr1,
160                                      struct address_space *aspace2,
161                                      CORE_ADDR addr2);
162
163 static int watchpoint_locations_match (struct bp_location *loc1,
164                                        struct bp_location *loc2);
165
166 static int breakpoint_location_address_match (struct bp_location *bl,
167                                               struct address_space *aspace,
168                                               CORE_ADDR addr);
169
170 static void breakpoints_info (char *, int);
171
172 static void watchpoints_info (char *, int);
173
174 static int breakpoint_1 (char *, int, 
175                          int (*) (const struct breakpoint *));
176
177 static int breakpoint_cond_eval (void *);
178
179 static void cleanup_executing_breakpoints (void *);
180
181 static void commands_command (char *, int);
182
183 static void condition_command (char *, int);
184
185 typedef enum
186   {
187     mark_inserted,
188     mark_uninserted
189   }
190 insertion_state_t;
191
192 static int remove_breakpoint (struct bp_location *, insertion_state_t);
193 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
194
195 static enum print_stop_action print_bp_stop_message (bpstat bs);
196
197 static int watchpoint_check (void *);
198
199 static void maintenance_info_breakpoints (char *, int);
200
201 static int hw_breakpoint_used_count (void);
202
203 static int hw_watchpoint_use_count (struct breakpoint *);
204
205 static int hw_watchpoint_used_count_others (struct breakpoint *except,
206                                             enum bptype type,
207                                             int *other_type_used);
208
209 static void hbreak_command (char *, int);
210
211 static void thbreak_command (char *, int);
212
213 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
214                                     int count);
215
216 static void stop_command (char *arg, int from_tty);
217
218 static void stopin_command (char *arg, int from_tty);
219
220 static void stopat_command (char *arg, int from_tty);
221
222 static char *ep_parse_optional_if_clause (char **arg);
223
224 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
225                                        char *arg, int tempflag, int from_tty);
226
227 static void tcatch_command (char *arg, int from_tty);
228
229 static void detach_single_step_breakpoints (void);
230
231 static int single_step_breakpoint_inserted_here_p (struct address_space *,
232                                                    CORE_ADDR pc);
233
234 static void free_bp_location (struct bp_location *loc);
235 static void incref_bp_location (struct bp_location *loc);
236 static void decref_bp_location (struct bp_location **loc);
237
238 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
239
240 static void update_global_location_list (int);
241
242 static void update_global_location_list_nothrow (int);
243
244 static int is_hardware_watchpoint (const struct breakpoint *bpt);
245
246 static void insert_breakpoint_locations (void);
247
248 static int syscall_catchpoint_p (struct breakpoint *b);
249
250 static void tracepoints_info (char *, int);
251
252 static void delete_trace_command (char *, int);
253
254 static void enable_trace_command (char *, int);
255
256 static void disable_trace_command (char *, int);
257
258 static void trace_pass_command (char *, int);
259
260 static int is_masked_watchpoint (const struct breakpoint *b);
261
262 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
263
264 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
265    otherwise.  */
266
267 static int strace_marker_p (struct breakpoint *b);
268
269 static void init_catchpoint (struct breakpoint *b,
270                              struct gdbarch *gdbarch, int tempflag,
271                              char *cond_string,
272                              const struct breakpoint_ops *ops);
273
274 /* The abstract base class all breakpoint_ops structures inherit
275    from.  */
276 static struct breakpoint_ops base_breakpoint_ops;
277
278 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
279    that are implemented on top of software or hardware breakpoints
280    (user breakpoints, internal and momentary breakpoints, etc.).  */
281 static struct breakpoint_ops bkpt_base_breakpoint_ops;
282
283 /* Internal breakpoints class type.  */
284 static struct breakpoint_ops internal_breakpoint_ops;
285
286 /* Momentary breakpoints class type.  */
287 static struct breakpoint_ops momentary_breakpoint_ops;
288
289 /* The breakpoint_ops structure to be used in regular user created
290    breakpoints.  */
291 struct breakpoint_ops bkpt_breakpoint_ops;
292
293 /* A reference-counted struct command_line.  This lets multiple
294    breakpoints share a single command list.  */
295 struct counted_command_line
296 {
297   /* The reference count.  */
298   int refc;
299
300   /* The command list.  */
301   struct command_line *commands;
302 };
303
304 struct command_line *
305 breakpoint_commands (struct breakpoint *b)
306 {
307   return b->commands ? b->commands->commands : NULL;
308 }
309
310 /* Flag indicating that a command has proceeded the inferior past the
311    current breakpoint.  */
312
313 static int breakpoint_proceeded;
314
315 const char *
316 bpdisp_text (enum bpdisp disp)
317 {
318   /* NOTE: the following values are a part of MI protocol and
319      represent values of 'disp' field returned when inferior stops at
320      a breakpoint.  */
321   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
322
323   return bpdisps[(int) disp];
324 }
325
326 /* Prototypes for exported functions.  */
327 /* If FALSE, gdb will not use hardware support for watchpoints, even
328    if such is available.  */
329 static int can_use_hw_watchpoints;
330
331 static void
332 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
333                              struct cmd_list_element *c,
334                              const char *value)
335 {
336   fprintf_filtered (file,
337                     _("Debugger's willingness to use "
338                       "watchpoint hardware is %s.\n"),
339                     value);
340 }
341
342 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
343    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
344    for unrecognized breakpoint locations.
345    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
346 static enum auto_boolean pending_break_support;
347 static void
348 show_pending_break_support (struct ui_file *file, int from_tty,
349                             struct cmd_list_element *c,
350                             const char *value)
351 {
352   fprintf_filtered (file,
353                     _("Debugger's behavior regarding "
354                       "pending breakpoints is %s.\n"),
355                     value);
356 }
357
358 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
359    set with "break" but falling in read-only memory.
360    If 0, gdb will warn about such breakpoints, but won't automatically
361    use hardware breakpoints.  */
362 static int automatic_hardware_breakpoints;
363 static void
364 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
365                                      struct cmd_list_element *c,
366                                      const char *value)
367 {
368   fprintf_filtered (file,
369                     _("Automatic usage of hardware breakpoints is %s.\n"),
370                     value);
371 }
372
373 /* If on, gdb will keep breakpoints inserted even as inferior is
374    stopped, and immediately insert any new breakpoints.  If off, gdb
375    will insert breakpoints into inferior only when resuming it, and
376    will remove breakpoints upon stop.  If auto, GDB will behave as ON
377    if in non-stop mode, and as OFF if all-stop mode.*/
378
379 static const char always_inserted_auto[] = "auto";
380 static const char always_inserted_on[] = "on";
381 static const char always_inserted_off[] = "off";
382 static const char *const always_inserted_enums[] = {
383   always_inserted_auto,
384   always_inserted_off,
385   always_inserted_on,
386   NULL
387 };
388 static const char *always_inserted_mode = always_inserted_auto;
389 static void
390 show_always_inserted_mode (struct ui_file *file, int from_tty,
391                      struct cmd_list_element *c, const char *value)
392 {
393   if (always_inserted_mode == always_inserted_auto)
394     fprintf_filtered (file,
395                       _("Always inserted breakpoint "
396                         "mode is %s (currently %s).\n"),
397                       value,
398                       breakpoints_always_inserted_mode () ? "on" : "off");
399   else
400     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
401                       value);
402 }
403
404 int
405 breakpoints_always_inserted_mode (void)
406 {
407   return ((always_inserted_mode == always_inserted_on
408            || (always_inserted_mode == always_inserted_auto && non_stop))
409           && !RECORD_IS_USED);
410 }
411
412 static const char condition_evaluation_both[] = "host or target";
413
414 /* Modes for breakpoint condition evaluation.  */
415 static const char condition_evaluation_auto[] = "auto";
416 static const char condition_evaluation_host[] = "host";
417 static const char condition_evaluation_target[] = "target";
418 static const char *const condition_evaluation_enums[] = {
419   condition_evaluation_auto,
420   condition_evaluation_host,
421   condition_evaluation_target,
422   NULL
423 };
424
425 /* Global that holds the current mode for breakpoint condition evaluation.  */
426 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
427
428 /* Global that we use to display information to the user (gets its value from
429    condition_evaluation_mode_1.  */
430 static const char *condition_evaluation_mode = condition_evaluation_auto;
431
432 /* Translate a condition evaluation mode MODE into either "host"
433    or "target".  This is used mostly to translate from "auto" to the
434    real setting that is being used.  It returns the translated
435    evaluation mode.  */
436
437 static const char *
438 translate_condition_evaluation_mode (const char *mode)
439 {
440   if (mode == condition_evaluation_auto)
441     {
442       if (target_supports_evaluation_of_breakpoint_conditions ())
443         return condition_evaluation_target;
444       else
445         return condition_evaluation_host;
446     }
447   else
448     return mode;
449 }
450
451 /* Discovers what condition_evaluation_auto translates to.  */
452
453 static const char *
454 breakpoint_condition_evaluation_mode (void)
455 {
456   return translate_condition_evaluation_mode (condition_evaluation_mode);
457 }
458
459 /* Return true if GDB should evaluate breakpoint conditions or false
460    otherwise.  */
461
462 static int
463 gdb_evaluates_breakpoint_condition_p (void)
464 {
465   const char *mode = breakpoint_condition_evaluation_mode ();
466
467   return (mode == condition_evaluation_host);
468 }
469
470 void _initialize_breakpoint (void);
471
472 /* Are we executing breakpoint commands?  */
473 static int executing_breakpoint_commands;
474
475 /* Are overlay event breakpoints enabled? */
476 static int overlay_events_enabled;
477
478 /* See description in breakpoint.h. */
479 int target_exact_watchpoints = 0;
480
481 /* Walk the following statement or block through all breakpoints.
482    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
483    current breakpoint.  */
484
485 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
486
487 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
488         for (B = breakpoint_chain;      \
489              B ? (TMP=B->next, 1): 0;   \
490              B = TMP)
491
492 /* Similar iterator for the low-level breakpoints.  SAFE variant is
493    not provided so update_global_location_list must not be called
494    while executing the block of ALL_BP_LOCATIONS.  */
495
496 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
497         for (BP_TMP = bp_location;                                      \
498              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
499              BP_TMP++)
500
501 /* Iterates through locations with address ADDRESS for the currently selected
502    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
503    to where the loop should start from.
504    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
505    appropriate location to start with.  */
506
507 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
508         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
509              BP_LOCP_TMP = BP_LOCP_START;                               \
510              BP_LOCP_START                                              \
511              && (BP_LOCP_TMP < bp_location + bp_location_count          \
512              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
513              BP_LOCP_TMP++)
514
515 /* Iterator for tracepoints only.  */
516
517 #define ALL_TRACEPOINTS(B)  \
518   for (B = breakpoint_chain; B; B = B->next)  \
519     if (is_tracepoint (B))
520
521 /* Chains of all breakpoints defined.  */
522
523 struct breakpoint *breakpoint_chain;
524
525 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
526
527 static struct bp_location **bp_location;
528
529 /* Number of elements of BP_LOCATION.  */
530
531 static unsigned bp_location_count;
532
533 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
534    ADDRESS for the current elements of BP_LOCATION which get a valid
535    result from bp_location_has_shadow.  You can use it for roughly
536    limiting the subrange of BP_LOCATION to scan for shadow bytes for
537    an address you need to read.  */
538
539 static CORE_ADDR bp_location_placed_address_before_address_max;
540
541 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
542    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
543    BP_LOCATION which get a valid result from bp_location_has_shadow.
544    You can use it for roughly limiting the subrange of BP_LOCATION to
545    scan for shadow bytes for an address you need to read.  */
546
547 static CORE_ADDR bp_location_shadow_len_after_address_max;
548
549 /* The locations that no longer correspond to any breakpoint, unlinked
550    from bp_location array, but for which a hit may still be reported
551    by a target.  */
552 VEC(bp_location_p) *moribund_locations = NULL;
553
554 /* Number of last breakpoint made.  */
555
556 static int breakpoint_count;
557
558 /* The value of `breakpoint_count' before the last command that
559    created breakpoints.  If the last (break-like) command created more
560    than one breakpoint, then the difference between BREAKPOINT_COUNT
561    and PREV_BREAKPOINT_COUNT is more than one.  */
562 static int prev_breakpoint_count;
563
564 /* Number of last tracepoint made.  */
565
566 static int tracepoint_count;
567
568 static struct cmd_list_element *breakpoint_set_cmdlist;
569 static struct cmd_list_element *breakpoint_show_cmdlist;
570 struct cmd_list_element *save_cmdlist;
571
572 /* Return whether a breakpoint is an active enabled breakpoint.  */
573 static int
574 breakpoint_enabled (struct breakpoint *b)
575 {
576   return (b->enable_state == bp_enabled);
577 }
578
579 /* Set breakpoint count to NUM.  */
580
581 static void
582 set_breakpoint_count (int num)
583 {
584   prev_breakpoint_count = breakpoint_count;
585   breakpoint_count = num;
586   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
587 }
588
589 /* Used by `start_rbreak_breakpoints' below, to record the current
590    breakpoint count before "rbreak" creates any breakpoint.  */
591 static int rbreak_start_breakpoint_count;
592
593 /* Called at the start an "rbreak" command to record the first
594    breakpoint made.  */
595
596 void
597 start_rbreak_breakpoints (void)
598 {
599   rbreak_start_breakpoint_count = breakpoint_count;
600 }
601
602 /* Called at the end of an "rbreak" command to record the last
603    breakpoint made.  */
604
605 void
606 end_rbreak_breakpoints (void)
607 {
608   prev_breakpoint_count = rbreak_start_breakpoint_count;
609 }
610
611 /* Used in run_command to zero the hit count when a new run starts.  */
612
613 void
614 clear_breakpoint_hit_counts (void)
615 {
616   struct breakpoint *b;
617
618   ALL_BREAKPOINTS (b)
619     b->hit_count = 0;
620 }
621
622 /* Allocate a new counted_command_line with reference count of 1.
623    The new structure owns COMMANDS.  */
624
625 static struct counted_command_line *
626 alloc_counted_command_line (struct command_line *commands)
627 {
628   struct counted_command_line *result
629     = xmalloc (sizeof (struct counted_command_line));
630
631   result->refc = 1;
632   result->commands = commands;
633   return result;
634 }
635
636 /* Increment reference count.  This does nothing if CMD is NULL.  */
637
638 static void
639 incref_counted_command_line (struct counted_command_line *cmd)
640 {
641   if (cmd)
642     ++cmd->refc;
643 }
644
645 /* Decrement reference count.  If the reference count reaches 0,
646    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
647    nothing if *CMDP is NULL.  */
648
649 static void
650 decref_counted_command_line (struct counted_command_line **cmdp)
651 {
652   if (*cmdp)
653     {
654       if (--(*cmdp)->refc == 0)
655         {
656           free_command_lines (&(*cmdp)->commands);
657           xfree (*cmdp);
658         }
659       *cmdp = NULL;
660     }
661 }
662
663 /* A cleanup function that calls decref_counted_command_line.  */
664
665 static void
666 do_cleanup_counted_command_line (void *arg)
667 {
668   decref_counted_command_line (arg);
669 }
670
671 /* Create a cleanup that calls decref_counted_command_line on the
672    argument.  */
673
674 static struct cleanup *
675 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
676 {
677   return make_cleanup (do_cleanup_counted_command_line, cmdp);
678 }
679
680 \f
681 /* Return the breakpoint with the specified number, or NULL
682    if the number does not refer to an existing breakpoint.  */
683
684 struct breakpoint *
685 get_breakpoint (int num)
686 {
687   struct breakpoint *b;
688
689   ALL_BREAKPOINTS (b)
690     if (b->number == num)
691       return b;
692   
693   return NULL;
694 }
695
696 \f
697
698 /* Mark locations as "conditions have changed" in case the target supports
699    evaluating conditions on its side.  */
700
701 static void
702 mark_breakpoint_modified (struct breakpoint *b)
703 {
704   struct bp_location *loc;
705
706   /* This is only meaningful if the target is
707      evaluating conditions and if the user has
708      opted for condition evaluation on the target's
709      side.  */
710   if (gdb_evaluates_breakpoint_condition_p ()
711       || !target_supports_evaluation_of_breakpoint_conditions ())
712     return;
713
714   if (!is_breakpoint (b))
715     return;
716
717   for (loc = b->loc; loc; loc = loc->next)
718     loc->condition_changed = condition_modified;
719 }
720
721 /* Mark location as "conditions have changed" in case the target supports
722    evaluating conditions on its side.  */
723
724 static void
725 mark_breakpoint_location_modified (struct bp_location *loc)
726 {
727   /* This is only meaningful if the target is
728      evaluating conditions and if the user has
729      opted for condition evaluation on the target's
730      side.  */
731   if (gdb_evaluates_breakpoint_condition_p ()
732       || !target_supports_evaluation_of_breakpoint_conditions ())
733
734     return;
735
736   if (!is_breakpoint (loc->owner))
737     return;
738
739   loc->condition_changed = condition_modified;
740 }
741
742 /* Sets the condition-evaluation mode using the static global
743    condition_evaluation_mode.  */
744
745 static void
746 set_condition_evaluation_mode (char *args, int from_tty,
747                                struct cmd_list_element *c)
748 {
749   struct breakpoint *b;
750   const char *old_mode, *new_mode;
751
752   if ((condition_evaluation_mode_1 == condition_evaluation_target)
753       && !target_supports_evaluation_of_breakpoint_conditions ())
754     {
755       condition_evaluation_mode_1 = condition_evaluation_mode;
756       warning (_("Target does not support breakpoint condition evaluation.\n"
757                  "Using host evaluation mode instead."));
758       return;
759     }
760
761   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
762   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
763
764   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
765      settings was "auto".  */
766   condition_evaluation_mode = condition_evaluation_mode_1;
767
768   /* Only update the mode if the user picked a different one.  */
769   if (new_mode != old_mode)
770     {
771       struct bp_location *loc, **loc_tmp;
772       /* If the user switched to a different evaluation mode, we
773          need to synch the changes with the target as follows:
774
775          "host" -> "target": Send all (valid) conditions to the target.
776          "target" -> "host": Remove all the conditions from the target.
777       */
778
779       if (new_mode == condition_evaluation_target)
780         {
781           /* Mark everything modified and synch conditions with the
782              target.  */
783           ALL_BP_LOCATIONS (loc, loc_tmp)
784             mark_breakpoint_location_modified (loc);
785         }
786       else
787         {
788           /* Manually mark non-duplicate locations to synch conditions
789              with the target.  We do this to remove all the conditions the
790              target knows about.  */
791           ALL_BP_LOCATIONS (loc, loc_tmp)
792             if (is_breakpoint (loc->owner) && loc->inserted)
793               loc->needs_update = 1;
794         }
795
796       /* Do the update.  */
797       update_global_location_list (1);
798     }
799
800   return;
801 }
802
803 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
804    what "auto" is translating to.  */
805
806 static void
807 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
808                                 struct cmd_list_element *c, const char *value)
809 {
810   if (condition_evaluation_mode == condition_evaluation_auto)
811     fprintf_filtered (file,
812                       _("Breakpoint condition evaluation "
813                         "mode is %s (currently %s).\n"),
814                       value,
815                       breakpoint_condition_evaluation_mode ());
816   else
817     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
818                       value);
819 }
820
821 /* A comparison function for bp_location AP and BP that is used by
822    bsearch.  This comparison function only cares about addresses, unlike
823    the more general bp_location_compare function.  */
824
825 static int
826 bp_location_compare_addrs (const void *ap, const void *bp)
827 {
828   struct bp_location *a = *(void **) ap;
829   struct bp_location *b = *(void **) bp;
830
831   if (a->address == b->address)
832     return 0;
833   else
834     return ((a->address > b->address) - (a->address < b->address));
835 }
836
837 /* Helper function to skip all bp_locations with addresses
838    less than ADDRESS.  It returns the first bp_location that
839    is greater than or equal to ADDRESS.  If none is found, just
840    return NULL.  */
841
842 static struct bp_location **
843 get_first_locp_gte_addr (CORE_ADDR address)
844 {
845   struct bp_location dummy_loc;
846   struct bp_location *dummy_locp = &dummy_loc;
847   struct bp_location **locp_found = NULL;
848
849   /* Initialize the dummy location's address field.  */
850   memset (&dummy_loc, 0, sizeof (struct bp_location));
851   dummy_loc.address = address;
852
853   /* Find a close match to the first location at ADDRESS.  */
854   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
855                         sizeof (struct bp_location **),
856                         bp_location_compare_addrs);
857
858   /* Nothing was found, nothing left to do.  */
859   if (locp_found == NULL)
860     return NULL;
861
862   /* We may have found a location that is at ADDRESS but is not the first in the
863      location's list.  Go backwards (if possible) and locate the first one.  */
864   while ((locp_found - 1) >= bp_location
865          && (*(locp_found - 1))->address == address)
866     locp_found--;
867
868   return locp_found;
869 }
870
871 void
872 set_breakpoint_condition (struct breakpoint *b, char *exp,
873                           int from_tty)
874 {
875   xfree (b->cond_string);
876   b->cond_string = NULL;
877
878   if (is_watchpoint (b))
879     {
880       struct watchpoint *w = (struct watchpoint *) b;
881
882       xfree (w->cond_exp);
883       w->cond_exp = NULL;
884     }
885   else
886     {
887       struct bp_location *loc;
888
889       for (loc = b->loc; loc; loc = loc->next)
890         {
891           xfree (loc->cond);
892           loc->cond = NULL;
893
894           /* No need to free the condition agent expression
895              bytecode (if we have one).  We will handle this
896              when we go through update_global_location_list.  */
897         }
898     }
899
900   if (*exp == 0)
901     {
902       if (from_tty)
903         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
904     }
905   else
906     {
907       char *arg = exp;
908
909       /* I don't know if it matters whether this is the string the user
910          typed in or the decompiled expression.  */
911       b->cond_string = xstrdup (arg);
912       b->condition_not_parsed = 0;
913
914       if (is_watchpoint (b))
915         {
916           struct watchpoint *w = (struct watchpoint *) b;
917
918           innermost_block = NULL;
919           arg = exp;
920           w->cond_exp = parse_exp_1 (&arg, 0, 0);
921           if (*arg)
922             error (_("Junk at end of expression"));
923           w->cond_exp_valid_block = innermost_block;
924         }
925       else
926         {
927           struct bp_location *loc;
928
929           for (loc = b->loc; loc; loc = loc->next)
930             {
931               arg = exp;
932               loc->cond =
933                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
934               if (*arg)
935                 error (_("Junk at end of expression"));
936             }
937         }
938     }
939   mark_breakpoint_modified (b);
940
941   breakpoints_changed ();
942   observer_notify_breakpoint_modified (b);
943 }
944
945 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
946
947 static void
948 condition_command (char *arg, int from_tty)
949 {
950   struct breakpoint *b;
951   char *p;
952   int bnum;
953
954   if (arg == 0)
955     error_no_arg (_("breakpoint number"));
956
957   p = arg;
958   bnum = get_number (&p);
959   if (bnum == 0)
960     error (_("Bad breakpoint argument: '%s'"), arg);
961
962   ALL_BREAKPOINTS (b)
963     if (b->number == bnum)
964       {
965         /* Check if this breakpoint has a Python object assigned to
966            it, and if it has a definition of the "stop"
967            method.  This method and conditions entered into GDB from
968            the CLI are mutually exclusive.  */
969         if (b->py_bp_object
970             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
971           error (_("Cannot set a condition where a Python 'stop' "
972                    "method has been defined in the breakpoint."));
973         set_breakpoint_condition (b, p, from_tty);
974
975         if (is_breakpoint (b))
976           update_global_location_list (1);
977
978         return;
979       }
980
981   error (_("No breakpoint number %d."), bnum);
982 }
983
984 /* Check that COMMAND do not contain commands that are suitable
985    only for tracepoints and not suitable for ordinary breakpoints.
986    Throw if any such commands is found.  */
987
988 static void
989 check_no_tracepoint_commands (struct command_line *commands)
990 {
991   struct command_line *c;
992
993   for (c = commands; c; c = c->next)
994     {
995       int i;
996
997       if (c->control_type == while_stepping_control)
998         error (_("The 'while-stepping' command can "
999                  "only be used for tracepoints"));
1000
1001       for (i = 0; i < c->body_count; ++i)
1002         check_no_tracepoint_commands ((c->body_list)[i]);
1003
1004       /* Not that command parsing removes leading whitespace and comment
1005          lines and also empty lines.  So, we only need to check for
1006          command directly.  */
1007       if (strstr (c->line, "collect ") == c->line)
1008         error (_("The 'collect' command can only be used for tracepoints"));
1009
1010       if (strstr (c->line, "teval ") == c->line)
1011         error (_("The 'teval' command can only be used for tracepoints"));
1012     }
1013 }
1014
1015 /* Encapsulate tests for different types of tracepoints.  */
1016
1017 static int
1018 is_tracepoint_type (enum bptype type)
1019 {
1020   return (type == bp_tracepoint
1021           || type == bp_fast_tracepoint
1022           || type == bp_static_tracepoint);
1023 }
1024
1025 int
1026 is_tracepoint (const struct breakpoint *b)
1027 {
1028   return is_tracepoint_type (b->type);
1029 }
1030
1031 /* A helper function that validates that COMMANDS are valid for a
1032    breakpoint.  This function will throw an exception if a problem is
1033    found.  */
1034
1035 static void
1036 validate_commands_for_breakpoint (struct breakpoint *b,
1037                                   struct command_line *commands)
1038 {
1039   if (is_tracepoint (b))
1040     {
1041       /* We need to verify that each top-level element of commands is
1042          valid for tracepoints, that there's at most one
1043          while-stepping element, and that while-stepping's body has
1044          valid tracing commands excluding nested while-stepping.  */
1045       struct command_line *c;
1046       struct command_line *while_stepping = 0;
1047       for (c = commands; c; c = c->next)
1048         {
1049           if (c->control_type == while_stepping_control)
1050             {
1051               if (b->type == bp_fast_tracepoint)
1052                 error (_("The 'while-stepping' command "
1053                          "cannot be used for fast tracepoint"));
1054               else if (b->type == bp_static_tracepoint)
1055                 error (_("The 'while-stepping' command "
1056                          "cannot be used for static tracepoint"));
1057
1058               if (while_stepping)
1059                 error (_("The 'while-stepping' command "
1060                          "can be used only once"));
1061               else
1062                 while_stepping = c;
1063             }
1064         }
1065       if (while_stepping)
1066         {
1067           struct command_line *c2;
1068
1069           gdb_assert (while_stepping->body_count == 1);
1070           c2 = while_stepping->body_list[0];
1071           for (; c2; c2 = c2->next)
1072             {
1073               if (c2->control_type == while_stepping_control)
1074                 error (_("The 'while-stepping' command cannot be nested"));
1075             }
1076         }
1077     }
1078   else
1079     {
1080       check_no_tracepoint_commands (commands);
1081     }
1082 }
1083
1084 /* Return a vector of all the static tracepoints set at ADDR.  The
1085    caller is responsible for releasing the vector.  */
1086
1087 VEC(breakpoint_p) *
1088 static_tracepoints_here (CORE_ADDR addr)
1089 {
1090   struct breakpoint *b;
1091   VEC(breakpoint_p) *found = 0;
1092   struct bp_location *loc;
1093
1094   ALL_BREAKPOINTS (b)
1095     if (b->type == bp_static_tracepoint)
1096       {
1097         for (loc = b->loc; loc; loc = loc->next)
1098           if (loc->address == addr)
1099             VEC_safe_push(breakpoint_p, found, b);
1100       }
1101
1102   return found;
1103 }
1104
1105 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1106    validate that only allowed commands are included.  */
1107
1108 void
1109 breakpoint_set_commands (struct breakpoint *b, 
1110                          struct command_line *commands)
1111 {
1112   validate_commands_for_breakpoint (b, commands);
1113
1114   decref_counted_command_line (&b->commands);
1115   b->commands = alloc_counted_command_line (commands);
1116   breakpoints_changed ();
1117   observer_notify_breakpoint_modified (b);
1118 }
1119
1120 /* Set the internal `silent' flag on the breakpoint.  Note that this
1121    is not the same as the "silent" that may appear in the breakpoint's
1122    commands.  */
1123
1124 void
1125 breakpoint_set_silent (struct breakpoint *b, int silent)
1126 {
1127   int old_silent = b->silent;
1128
1129   b->silent = silent;
1130   if (old_silent != silent)
1131     observer_notify_breakpoint_modified (b);
1132 }
1133
1134 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1135    breakpoint work for any thread.  */
1136
1137 void
1138 breakpoint_set_thread (struct breakpoint *b, int thread)
1139 {
1140   int old_thread = b->thread;
1141
1142   b->thread = thread;
1143   if (old_thread != thread)
1144     observer_notify_breakpoint_modified (b);
1145 }
1146
1147 /* Set the task for this breakpoint.  If TASK is 0, make the
1148    breakpoint work for any task.  */
1149
1150 void
1151 breakpoint_set_task (struct breakpoint *b, int task)
1152 {
1153   int old_task = b->task;
1154
1155   b->task = task;
1156   if (old_task != task)
1157     observer_notify_breakpoint_modified (b);
1158 }
1159
1160 void
1161 check_tracepoint_command (char *line, void *closure)
1162 {
1163   struct breakpoint *b = closure;
1164
1165   validate_actionline (&line, b);
1166 }
1167
1168 /* A structure used to pass information through
1169    map_breakpoint_numbers.  */
1170
1171 struct commands_info
1172 {
1173   /* True if the command was typed at a tty.  */
1174   int from_tty;
1175
1176   /* The breakpoint range spec.  */
1177   char *arg;
1178
1179   /* Non-NULL if the body of the commands are being read from this
1180      already-parsed command.  */
1181   struct command_line *control;
1182
1183   /* The command lines read from the user, or NULL if they have not
1184      yet been read.  */
1185   struct counted_command_line *cmd;
1186 };
1187
1188 /* A callback for map_breakpoint_numbers that sets the commands for
1189    commands_command.  */
1190
1191 static void
1192 do_map_commands_command (struct breakpoint *b, void *data)
1193 {
1194   struct commands_info *info = data;
1195
1196   if (info->cmd == NULL)
1197     {
1198       struct command_line *l;
1199
1200       if (info->control != NULL)
1201         l = copy_command_lines (info->control->body_list[0]);
1202       else
1203         {
1204           struct cleanup *old_chain;
1205           char *str;
1206
1207           str = xstrprintf (_("Type commands for breakpoint(s) "
1208                               "%s, one per line."),
1209                             info->arg);
1210
1211           old_chain = make_cleanup (xfree, str);
1212
1213           l = read_command_lines (str,
1214                                   info->from_tty, 1,
1215                                   (is_tracepoint (b)
1216                                    ? check_tracepoint_command : 0),
1217                                   b);
1218
1219           do_cleanups (old_chain);
1220         }
1221
1222       info->cmd = alloc_counted_command_line (l);
1223     }
1224
1225   /* If a breakpoint was on the list more than once, we don't need to
1226      do anything.  */
1227   if (b->commands != info->cmd)
1228     {
1229       validate_commands_for_breakpoint (b, info->cmd->commands);
1230       incref_counted_command_line (info->cmd);
1231       decref_counted_command_line (&b->commands);
1232       b->commands = info->cmd;
1233       breakpoints_changed ();
1234       observer_notify_breakpoint_modified (b);
1235     }
1236 }
1237
1238 static void
1239 commands_command_1 (char *arg, int from_tty, 
1240                     struct command_line *control)
1241 {
1242   struct cleanup *cleanups;
1243   struct commands_info info;
1244
1245   info.from_tty = from_tty;
1246   info.control = control;
1247   info.cmd = NULL;
1248   /* If we read command lines from the user, then `info' will hold an
1249      extra reference to the commands that we must clean up.  */
1250   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1251
1252   if (arg == NULL || !*arg)
1253     {
1254       if (breakpoint_count - prev_breakpoint_count > 1)
1255         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1256                           breakpoint_count);
1257       else if (breakpoint_count > 0)
1258         arg = xstrprintf ("%d", breakpoint_count);
1259       else
1260         {
1261           /* So that we don't try to free the incoming non-NULL
1262              argument in the cleanup below.  Mapping breakpoint
1263              numbers will fail in this case.  */
1264           arg = NULL;
1265         }
1266     }
1267   else
1268     /* The command loop has some static state, so we need to preserve
1269        our argument.  */
1270     arg = xstrdup (arg);
1271
1272   if (arg != NULL)
1273     make_cleanup (xfree, arg);
1274
1275   info.arg = arg;
1276
1277   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1278
1279   if (info.cmd == NULL)
1280     error (_("No breakpoints specified."));
1281
1282   do_cleanups (cleanups);
1283 }
1284
1285 static void
1286 commands_command (char *arg, int from_tty)
1287 {
1288   commands_command_1 (arg, from_tty, NULL);
1289 }
1290
1291 /* Like commands_command, but instead of reading the commands from
1292    input stream, takes them from an already parsed command structure.
1293
1294    This is used by cli-script.c to DTRT with breakpoint commands
1295    that are part of if and while bodies.  */
1296 enum command_control_type
1297 commands_from_control_command (char *arg, struct command_line *cmd)
1298 {
1299   commands_command_1 (arg, 0, cmd);
1300   return simple_control;
1301 }
1302
1303 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1304
1305 static int
1306 bp_location_has_shadow (struct bp_location *bl)
1307 {
1308   if (bl->loc_type != bp_loc_software_breakpoint)
1309     return 0;
1310   if (!bl->inserted)
1311     return 0;
1312   if (bl->target_info.shadow_len == 0)
1313     /* BL isn't valid, or doesn't shadow memory.  */
1314     return 0;
1315   return 1;
1316 }
1317
1318 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1319    by replacing any memory breakpoints with their shadowed contents.
1320
1321    If READBUF is not NULL, this buffer must not overlap with any of
1322    the breakpoint location's shadow_contents buffers.  Otherwise,
1323    a failed assertion internal error will be raised.
1324
1325    The range of shadowed area by each bp_location is:
1326      bl->address - bp_location_placed_address_before_address_max
1327      up to bl->address + bp_location_shadow_len_after_address_max
1328    The range we were requested to resolve shadows for is:
1329      memaddr ... memaddr + len
1330    Thus the safe cutoff boundaries for performance optimization are
1331      memaddr + len <= (bl->address
1332                        - bp_location_placed_address_before_address_max)
1333    and:
1334      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1335
1336 void
1337 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1338                         const gdb_byte *writebuf_org,
1339                         ULONGEST memaddr, LONGEST len)
1340 {
1341   /* Left boundary, right boundary and median element of our binary
1342      search.  */
1343   unsigned bc_l, bc_r, bc;
1344
1345   /* Find BC_L which is a leftmost element which may affect BUF
1346      content.  It is safe to report lower value but a failure to
1347      report higher one.  */
1348
1349   bc_l = 0;
1350   bc_r = bp_location_count;
1351   while (bc_l + 1 < bc_r)
1352     {
1353       struct bp_location *bl;
1354
1355       bc = (bc_l + bc_r) / 2;
1356       bl = bp_location[bc];
1357
1358       /* Check first BL->ADDRESS will not overflow due to the added
1359          constant.  Then advance the left boundary only if we are sure
1360          the BC element can in no way affect the BUF content (MEMADDR
1361          to MEMADDR + LEN range).
1362
1363          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1364          offset so that we cannot miss a breakpoint with its shadow
1365          range tail still reaching MEMADDR.  */
1366
1367       if ((bl->address + bp_location_shadow_len_after_address_max
1368            >= bl->address)
1369           && (bl->address + bp_location_shadow_len_after_address_max
1370               <= memaddr))
1371         bc_l = bc;
1372       else
1373         bc_r = bc;
1374     }
1375
1376   /* Due to the binary search above, we need to make sure we pick the
1377      first location that's at BC_L's address.  E.g., if there are
1378      multiple locations at the same address, BC_L may end up pointing
1379      at a duplicate location, and miss the "master"/"inserted"
1380      location.  Say, given locations L1, L2 and L3 at addresses A and
1381      B:
1382
1383       L1@A, L2@A, L3@B, ...
1384
1385      BC_L could end up pointing at location L2, while the "master"
1386      location could be L1.  Since the `loc->inserted' flag is only set
1387      on "master" locations, we'd forget to restore the shadow of L1
1388      and L2.  */
1389   while (bc_l > 0
1390          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1391     bc_l--;
1392
1393   /* Now do full processing of the found relevant range of elements.  */
1394
1395   for (bc = bc_l; bc < bp_location_count; bc++)
1396   {
1397     struct bp_location *bl = bp_location[bc];
1398     CORE_ADDR bp_addr = 0;
1399     int bp_size = 0;
1400     int bptoffset = 0;
1401
1402     /* bp_location array has BL->OWNER always non-NULL.  */
1403     if (bl->owner->type == bp_none)
1404       warning (_("reading through apparently deleted breakpoint #%d?"),
1405                bl->owner->number);
1406
1407     /* Performance optimization: any further element can no longer affect BUF
1408        content.  */
1409
1410     if (bl->address >= bp_location_placed_address_before_address_max
1411         && memaddr + len <= (bl->address
1412                              - bp_location_placed_address_before_address_max))
1413       break;
1414
1415     if (!bp_location_has_shadow (bl))
1416       continue;
1417     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1418                                    current_program_space->aspace, 0))
1419       continue;
1420
1421     /* Addresses and length of the part of the breakpoint that
1422        we need to copy.  */
1423     bp_addr = bl->target_info.placed_address;
1424     bp_size = bl->target_info.shadow_len;
1425
1426     if (bp_addr + bp_size <= memaddr)
1427       /* The breakpoint is entirely before the chunk of memory we
1428          are reading.  */
1429       continue;
1430
1431     if (bp_addr >= memaddr + len)
1432       /* The breakpoint is entirely after the chunk of memory we are
1433          reading.  */
1434       continue;
1435
1436     /* Offset within shadow_contents.  */
1437     if (bp_addr < memaddr)
1438       {
1439         /* Only copy the second part of the breakpoint.  */
1440         bp_size -= memaddr - bp_addr;
1441         bptoffset = memaddr - bp_addr;
1442         bp_addr = memaddr;
1443       }
1444
1445     if (bp_addr + bp_size > memaddr + len)
1446       {
1447         /* Only copy the first part of the breakpoint.  */
1448         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1449       }
1450
1451     if (readbuf != NULL)
1452       {
1453         /* Verify that the readbuf buffer does not overlap with
1454            the shadow_contents buffer.  */
1455         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1456                     || readbuf >= (bl->target_info.shadow_contents
1457                                    + bl->target_info.shadow_len));
1458
1459         /* Update the read buffer with this inserted breakpoint's
1460            shadow.  */
1461         memcpy (readbuf + bp_addr - memaddr,
1462                 bl->target_info.shadow_contents + bptoffset, bp_size);
1463       }
1464     else
1465       {
1466         struct gdbarch *gdbarch = bl->gdbarch;
1467         const unsigned char *bp;
1468         CORE_ADDR placed_address = bl->target_info.placed_address;
1469         unsigned placed_size = bl->target_info.placed_size;
1470
1471         /* Update the shadow with what we want to write to memory.  */
1472         memcpy (bl->target_info.shadow_contents + bptoffset,
1473                 writebuf_org + bp_addr - memaddr, bp_size);
1474
1475         /* Determine appropriate breakpoint contents and size for this
1476            address.  */
1477         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1478
1479         /* Update the final write buffer with this inserted
1480            breakpoint's INSN.  */
1481         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1482       }
1483   }
1484 }
1485 \f
1486
1487 /* Return true if BPT is either a software breakpoint or a hardware
1488    breakpoint.  */
1489
1490 int
1491 is_breakpoint (const struct breakpoint *bpt)
1492 {
1493   return (bpt->type == bp_breakpoint
1494           || bpt->type == bp_hardware_breakpoint);
1495 }
1496
1497 /* Return true if BPT is of any hardware watchpoint kind.  */
1498
1499 static int
1500 is_hardware_watchpoint (const struct breakpoint *bpt)
1501 {
1502   return (bpt->type == bp_hardware_watchpoint
1503           || bpt->type == bp_read_watchpoint
1504           || bpt->type == bp_access_watchpoint);
1505 }
1506
1507 /* Return true if BPT is of any watchpoint kind, hardware or
1508    software.  */
1509
1510 int
1511 is_watchpoint (const struct breakpoint *bpt)
1512 {
1513   return (is_hardware_watchpoint (bpt)
1514           || bpt->type == bp_watchpoint);
1515 }
1516
1517 /* Returns true if the current thread and its running state are safe
1518    to evaluate or update watchpoint B.  Watchpoints on local
1519    expressions need to be evaluated in the context of the thread that
1520    was current when the watchpoint was created, and, that thread needs
1521    to be stopped to be able to select the correct frame context.
1522    Watchpoints on global expressions can be evaluated on any thread,
1523    and in any state.  It is presently left to the target allowing
1524    memory accesses when threads are running.  */
1525
1526 static int
1527 watchpoint_in_thread_scope (struct watchpoint *b)
1528 {
1529   return (b->base.pspace == current_program_space
1530           && (ptid_equal (b->watchpoint_thread, null_ptid)
1531               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1532                   && !is_executing (inferior_ptid))));
1533 }
1534
1535 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1536    associated bp_watchpoint_scope breakpoint.  */
1537
1538 static void
1539 watchpoint_del_at_next_stop (struct watchpoint *w)
1540 {
1541   struct breakpoint *b = &w->base;
1542
1543   if (b->related_breakpoint != b)
1544     {
1545       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1546       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1547       b->related_breakpoint->disposition = disp_del_at_next_stop;
1548       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1549       b->related_breakpoint = b;
1550     }
1551   b->disposition = disp_del_at_next_stop;
1552 }
1553
1554 /* Assuming that B is a watchpoint:
1555    - Reparse watchpoint expression, if REPARSE is non-zero
1556    - Evaluate expression and store the result in B->val
1557    - Evaluate the condition if there is one, and store the result
1558      in b->loc->cond.
1559    - Update the list of values that must be watched in B->loc.
1560
1561    If the watchpoint disposition is disp_del_at_next_stop, then do
1562    nothing.  If this is local watchpoint that is out of scope, delete
1563    it.
1564
1565    Even with `set breakpoint always-inserted on' the watchpoints are
1566    removed + inserted on each stop here.  Normal breakpoints must
1567    never be removed because they might be missed by a running thread
1568    when debugging in non-stop mode.  On the other hand, hardware
1569    watchpoints (is_hardware_watchpoint; processed here) are specific
1570    to each LWP since they are stored in each LWP's hardware debug
1571    registers.  Therefore, such LWP must be stopped first in order to
1572    be able to modify its hardware watchpoints.
1573
1574    Hardware watchpoints must be reset exactly once after being
1575    presented to the user.  It cannot be done sooner, because it would
1576    reset the data used to present the watchpoint hit to the user.  And
1577    it must not be done later because it could display the same single
1578    watchpoint hit during multiple GDB stops.  Note that the latter is
1579    relevant only to the hardware watchpoint types bp_read_watchpoint
1580    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1581    not user-visible - its hit is suppressed if the memory content has
1582    not changed.
1583
1584    The following constraints influence the location where we can reset
1585    hardware watchpoints:
1586
1587    * target_stopped_by_watchpoint and target_stopped_data_address are
1588      called several times when GDB stops.
1589
1590    [linux] 
1591    * Multiple hardware watchpoints can be hit at the same time,
1592      causing GDB to stop.  GDB only presents one hardware watchpoint
1593      hit at a time as the reason for stopping, and all the other hits
1594      are presented later, one after the other, each time the user
1595      requests the execution to be resumed.  Execution is not resumed
1596      for the threads still having pending hit event stored in
1597      LWP_INFO->STATUS.  While the watchpoint is already removed from
1598      the inferior on the first stop the thread hit event is kept being
1599      reported from its cached value by linux_nat_stopped_data_address
1600      until the real thread resume happens after the watchpoint gets
1601      presented and thus its LWP_INFO->STATUS gets reset.
1602
1603    Therefore the hardware watchpoint hit can get safely reset on the
1604    watchpoint removal from inferior.  */
1605
1606 static void
1607 update_watchpoint (struct watchpoint *b, int reparse)
1608 {
1609   int within_current_scope;
1610   struct frame_id saved_frame_id;
1611   int frame_saved;
1612
1613   /* If this is a local watchpoint, we only want to check if the
1614      watchpoint frame is in scope if the current thread is the thread
1615      that was used to create the watchpoint.  */
1616   if (!watchpoint_in_thread_scope (b))
1617     return;
1618
1619   if (b->base.disposition == disp_del_at_next_stop)
1620     return;
1621  
1622   frame_saved = 0;
1623
1624   /* Determine if the watchpoint is within scope.  */
1625   if (b->exp_valid_block == NULL)
1626     within_current_scope = 1;
1627   else
1628     {
1629       struct frame_info *fi = get_current_frame ();
1630       struct gdbarch *frame_arch = get_frame_arch (fi);
1631       CORE_ADDR frame_pc = get_frame_pc (fi);
1632
1633       /* If we're in a function epilogue, unwinding may not work
1634          properly, so do not attempt to recreate locations at this
1635          point.  See similar comments in watchpoint_check.  */
1636       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1637         return;
1638
1639       /* Save the current frame's ID so we can restore it after
1640          evaluating the watchpoint expression on its own frame.  */
1641       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1642          took a frame parameter, so that we didn't have to change the
1643          selected frame.  */
1644       frame_saved = 1;
1645       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1646
1647       fi = frame_find_by_id (b->watchpoint_frame);
1648       within_current_scope = (fi != NULL);
1649       if (within_current_scope)
1650         select_frame (fi);
1651     }
1652
1653   /* We don't free locations.  They are stored in the bp_location array
1654      and update_global_location_list will eventually delete them and
1655      remove breakpoints if needed.  */
1656   b->base.loc = NULL;
1657
1658   if (within_current_scope && reparse)
1659     {
1660       char *s;
1661
1662       if (b->exp)
1663         {
1664           xfree (b->exp);
1665           b->exp = NULL;
1666         }
1667       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1668       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1669       /* If the meaning of expression itself changed, the old value is
1670          no longer relevant.  We don't want to report a watchpoint hit
1671          to the user when the old value and the new value may actually
1672          be completely different objects.  */
1673       value_free (b->val);
1674       b->val = NULL;
1675       b->val_valid = 0;
1676
1677       /* Note that unlike with breakpoints, the watchpoint's condition
1678          expression is stored in the breakpoint object, not in the
1679          locations (re)created below.  */
1680       if (b->base.cond_string != NULL)
1681         {
1682           if (b->cond_exp != NULL)
1683             {
1684               xfree (b->cond_exp);
1685               b->cond_exp = NULL;
1686             }
1687
1688           s = b->base.cond_string;
1689           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1690         }
1691     }
1692
1693   /* If we failed to parse the expression, for example because
1694      it refers to a global variable in a not-yet-loaded shared library,
1695      don't try to insert watchpoint.  We don't automatically delete
1696      such watchpoint, though, since failure to parse expression
1697      is different from out-of-scope watchpoint.  */
1698   if ( !target_has_execution)
1699     {
1700       /* Without execution, memory can't change.  No use to try and
1701          set watchpoint locations.  The watchpoint will be reset when
1702          the target gains execution, through breakpoint_re_set.  */
1703     }
1704   else if (within_current_scope && b->exp)
1705     {
1706       int pc = 0;
1707       struct value *val_chain, *v, *result, *next;
1708       struct program_space *frame_pspace;
1709
1710       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1711
1712       /* Avoid setting b->val if it's already set.  The meaning of
1713          b->val is 'the last value' user saw, and we should update
1714          it only if we reported that last value to user.  As it
1715          happens, the code that reports it updates b->val directly.
1716          We don't keep track of the memory value for masked
1717          watchpoints.  */
1718       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1719         {
1720           b->val = v;
1721           b->val_valid = 1;
1722         }
1723
1724       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1725
1726       /* Look at each value on the value chain.  */
1727       for (v = val_chain; v; v = value_next (v))
1728         {
1729           /* If it's a memory location, and GDB actually needed
1730              its contents to evaluate the expression, then we
1731              must watch it.  If the first value returned is
1732              still lazy, that means an error occurred reading it;
1733              watch it anyway in case it becomes readable.  */
1734           if (VALUE_LVAL (v) == lval_memory
1735               && (v == val_chain || ! value_lazy (v)))
1736             {
1737               struct type *vtype = check_typedef (value_type (v));
1738
1739               /* We only watch structs and arrays if user asked
1740                  for it explicitly, never if they just happen to
1741                  appear in the middle of some value chain.  */
1742               if (v == result
1743                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1744                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1745                 {
1746                   CORE_ADDR addr;
1747                   int len, type;
1748                   struct bp_location *loc, **tmp;
1749
1750                   addr = value_address (v);
1751                   len = TYPE_LENGTH (value_type (v));
1752                   type = hw_write;
1753                   if (b->base.type == bp_read_watchpoint)
1754                     type = hw_read;
1755                   else if (b->base.type == bp_access_watchpoint)
1756                     type = hw_access;
1757
1758                   loc = allocate_bp_location (&b->base);
1759                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1760                     ;
1761                   *tmp = loc;
1762                   loc->gdbarch = get_type_arch (value_type (v));
1763
1764                   loc->pspace = frame_pspace;
1765                   loc->address = addr;
1766                   loc->length = len;
1767                   loc->watchpoint_type = type;
1768                 }
1769             }
1770         }
1771
1772       /* Change the type of breakpoint between hardware assisted or
1773          an ordinary watchpoint depending on the hardware support
1774          and free hardware slots.  REPARSE is set when the inferior
1775          is started.  */
1776       if (reparse)
1777         {
1778           int reg_cnt;
1779           enum bp_loc_type loc_type;
1780           struct bp_location *bl;
1781
1782           reg_cnt = can_use_hardware_watchpoint (val_chain);
1783
1784           if (reg_cnt)
1785             {
1786               int i, target_resources_ok, other_type_used;
1787               enum bptype type;
1788
1789               /* Use an exact watchpoint when there's only one memory region to be
1790                  watched, and only one debug register is needed to watch it.  */
1791               b->exact = target_exact_watchpoints && reg_cnt == 1;
1792
1793               /* We need to determine how many resources are already
1794                  used for all other hardware watchpoints plus this one
1795                  to see if we still have enough resources to also fit
1796                  this watchpoint in as well.  */
1797
1798               /* If this is a software watchpoint, we try to turn it
1799                  to a hardware one -- count resources as if B was of
1800                  hardware watchpoint type.  */
1801               type = b->base.type;
1802               if (type == bp_watchpoint)
1803                 type = bp_hardware_watchpoint;
1804
1805               /* This watchpoint may or may not have been placed on
1806                  the list yet at this point (it won't be in the list
1807                  if we're trying to create it for the first time,
1808                  through watch_command), so always account for it
1809                  manually.  */
1810
1811               /* Count resources used by all watchpoints except B.  */
1812               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1813
1814               /* Add in the resources needed for B.  */
1815               i += hw_watchpoint_use_count (&b->base);
1816
1817               target_resources_ok
1818                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1819               if (target_resources_ok <= 0)
1820                 {
1821                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1822
1823                   if (target_resources_ok == 0 && !sw_mode)
1824                     error (_("Target does not support this type of "
1825                              "hardware watchpoint."));
1826                   else if (target_resources_ok < 0 && !sw_mode)
1827                     error (_("There are not enough available hardware "
1828                              "resources for this watchpoint."));
1829
1830                   /* Downgrade to software watchpoint.  */
1831                   b->base.type = bp_watchpoint;
1832                 }
1833               else
1834                 {
1835                   /* If this was a software watchpoint, we've just
1836                      found we have enough resources to turn it to a
1837                      hardware watchpoint.  Otherwise, this is a
1838                      nop.  */
1839                   b->base.type = type;
1840                 }
1841             }
1842           else if (!b->base.ops->works_in_software_mode (&b->base))
1843             error (_("Expression cannot be implemented with "
1844                      "read/access watchpoint."));
1845           else
1846             b->base.type = bp_watchpoint;
1847
1848           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1849                       : bp_loc_hardware_watchpoint);
1850           for (bl = b->base.loc; bl; bl = bl->next)
1851             bl->loc_type = loc_type;
1852         }
1853
1854       for (v = val_chain; v; v = next)
1855         {
1856           next = value_next (v);
1857           if (v != b->val)
1858             value_free (v);
1859         }
1860
1861       /* If a software watchpoint is not watching any memory, then the
1862          above left it without any location set up.  But,
1863          bpstat_stop_status requires a location to be able to report
1864          stops, so make sure there's at least a dummy one.  */
1865       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1866         {
1867           struct breakpoint *base = &b->base;
1868           base->loc = allocate_bp_location (base);
1869           base->loc->pspace = frame_pspace;
1870           base->loc->address = -1;
1871           base->loc->length = -1;
1872           base->loc->watchpoint_type = -1;
1873         }
1874     }
1875   else if (!within_current_scope)
1876     {
1877       printf_filtered (_("\
1878 Watchpoint %d deleted because the program has left the block\n\
1879 in which its expression is valid.\n"),
1880                        b->base.number);
1881       watchpoint_del_at_next_stop (b);
1882     }
1883
1884   /* Restore the selected frame.  */
1885   if (frame_saved)
1886     select_frame (frame_find_by_id (saved_frame_id));
1887 }
1888
1889
1890 /* Returns 1 iff breakpoint location should be
1891    inserted in the inferior.  We don't differentiate the type of BL's owner
1892    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1893    breakpoint_ops is not defined, because in insert_bp_location,
1894    tracepoint's insert_location will not be called.  */
1895 static int
1896 should_be_inserted (struct bp_location *bl)
1897 {
1898   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1899     return 0;
1900
1901   if (bl->owner->disposition == disp_del_at_next_stop)
1902     return 0;
1903
1904   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1905     return 0;
1906
1907   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1908     return 0;
1909
1910   /* This is set for example, when we're attached to the parent of a
1911      vfork, and have detached from the child.  The child is running
1912      free, and we expect it to do an exec or exit, at which point the
1913      OS makes the parent schedulable again (and the target reports
1914      that the vfork is done).  Until the child is done with the shared
1915      memory region, do not insert breakpoints in the parent, otherwise
1916      the child could still trip on the parent's breakpoints.  Since
1917      the parent is blocked anyway, it won't miss any breakpoint.  */
1918   if (bl->pspace->breakpoints_not_allowed)
1919     return 0;
1920
1921   return 1;
1922 }
1923
1924 /* Same as should_be_inserted but does the check assuming
1925    that the location is not duplicated.  */
1926
1927 static int
1928 unduplicated_should_be_inserted (struct bp_location *bl)
1929 {
1930   int result;
1931   const int save_duplicate = bl->duplicate;
1932
1933   bl->duplicate = 0;
1934   result = should_be_inserted (bl);
1935   bl->duplicate = save_duplicate;
1936   return result;
1937 }
1938
1939 /* Parses a conditional described by an expression COND into an
1940    agent expression bytecode suitable for evaluation
1941    by the bytecode interpreter.  Return NULL if there was
1942    any error during parsing.  */
1943
1944 static struct agent_expr *
1945 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
1946 {
1947   struct agent_expr *aexpr = NULL;
1948   struct cleanup *old_chain = NULL;
1949   volatile struct gdb_exception ex;
1950
1951   if (!cond)
1952     return NULL;
1953
1954   /* We don't want to stop processing, so catch any errors
1955      that may show up.  */
1956   TRY_CATCH (ex, RETURN_MASK_ERROR)
1957     {
1958       aexpr = gen_eval_for_expr (scope, cond);
1959     }
1960
1961   if (ex.reason < 0)
1962     {
1963       /* If we got here, it means the condition could not be parsed to a valid
1964          bytecode expression and thus can't be evaluated on the target's side.
1965          It's no use iterating through the conditions.  */
1966       return NULL;
1967     }
1968
1969   /* We have a valid agent expression.  */
1970   return aexpr;
1971 }
1972
1973 /* Based on location BL, create a list of breakpoint conditions to be
1974    passed on to the target.  If we have duplicated locations with different
1975    conditions, we will add such conditions to the list.  The idea is that the
1976    target will evaluate the list of conditions and will only notify GDB when
1977    one of them is true.  */
1978
1979 static void
1980 build_target_condition_list (struct bp_location *bl)
1981 {
1982   struct bp_location **locp = NULL, **loc2p;
1983   int null_condition_or_parse_error = 0;
1984   int modified = bl->needs_update;
1985   struct bp_location *loc;
1986
1987   /* This is only meaningful if the target is
1988      evaluating conditions and if the user has
1989      opted for condition evaluation on the target's
1990      side.  */
1991   if (gdb_evaluates_breakpoint_condition_p ()
1992       || !target_supports_evaluation_of_breakpoint_conditions ())
1993     return;
1994
1995   /* Do a first pass to check for locations with no assigned
1996      conditions or conditions that fail to parse to a valid agent expression
1997      bytecode.  If any of these happen, then it's no use to send conditions
1998      to the target since this location will always trigger and generate a
1999      response back to GDB.  */
2000   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2001     {
2002       loc = (*loc2p);
2003       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2004         {
2005           if (modified)
2006             {
2007               struct agent_expr *aexpr;
2008
2009               /* Re-parse the conditions since something changed.  In that
2010                  case we already freed the condition bytecodes (see
2011                  force_breakpoint_reinsertion).  We just
2012                  need to parse the condition to bytecodes again.  */
2013               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2014               loc->cond_bytecode = aexpr;
2015
2016               /* Check if we managed to parse the conditional expression
2017                  correctly.  If not, we will not send this condition
2018                  to the target.  */
2019               if (aexpr)
2020                 continue;
2021             }
2022
2023           /* If we have a NULL bytecode expression, it means something
2024              went wrong or we have a null condition expression.  */
2025           if (!loc->cond_bytecode)
2026             {
2027               null_condition_or_parse_error = 1;
2028               break;
2029             }
2030         }
2031     }
2032
2033   /* If any of these happened, it means we will have to evaluate the conditions
2034      for the location's address on gdb's side.  It is no use keeping bytecodes
2035      for all the other duplicate locations, thus we free all of them here.
2036
2037      This is so we have a finer control over which locations' conditions are
2038      being evaluated by GDB or the remote stub.  */
2039   if (null_condition_or_parse_error)
2040     {
2041       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2042         {
2043           loc = (*loc2p);
2044           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2045             {
2046               /* Only go as far as the first NULL bytecode is
2047                  located.  */
2048               if (!loc->cond_bytecode)
2049                 return;
2050
2051               free_agent_expr (loc->cond_bytecode);
2052               loc->cond_bytecode = NULL;
2053             }
2054         }
2055     }
2056
2057   /* No NULL conditions or failed bytecode generation.  Build a condition list
2058      for this location's address.  */
2059   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2060     {
2061       loc = (*loc2p);
2062       if (loc->cond
2063           && is_breakpoint (loc->owner)
2064           && loc->pspace->num == bl->pspace->num
2065           && loc->owner->enable_state == bp_enabled
2066           && loc->enabled)
2067         /* Add the condition to the vector.  This will be used later to send the
2068            conditions to the target.  */
2069         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2070                        loc->cond_bytecode);
2071     }
2072
2073   return;
2074 }
2075
2076 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2077    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2078    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2079    Returns 0 for success, 1 if the bp_location type is not supported or
2080    -1 for failure.
2081
2082    NOTE drow/2003-09-09: This routine could be broken down to an
2083    object-style method for each breakpoint or catchpoint type.  */
2084 static int
2085 insert_bp_location (struct bp_location *bl,
2086                     struct ui_file *tmp_error_stream,
2087                     int *disabled_breaks,
2088                     int *hw_breakpoint_error)
2089 {
2090   int val = 0;
2091
2092   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2093     return 0;
2094
2095   /* Note we don't initialize bl->target_info, as that wipes out
2096      the breakpoint location's shadow_contents if the breakpoint
2097      is still inserted at that location.  This in turn breaks
2098      target_read_memory which depends on these buffers when
2099      a memory read is requested at the breakpoint location:
2100      Once the target_info has been wiped, we fail to see that
2101      we have a breakpoint inserted at that address and thus
2102      read the breakpoint instead of returning the data saved in
2103      the breakpoint location's shadow contents.  */
2104   bl->target_info.placed_address = bl->address;
2105   bl->target_info.placed_address_space = bl->pspace->aspace;
2106   bl->target_info.length = bl->length;
2107
2108   /* When working with target-side conditions, we must pass all the conditions
2109      for the same breakpoint address down to the target since GDB will not
2110      insert those locations.  With a list of breakpoint conditions, the target
2111      can decide when to stop and notify GDB.  */
2112
2113   if (is_breakpoint (bl->owner))
2114     {
2115       build_target_condition_list (bl);
2116       /* Reset the condition modification marker.  */
2117       bl->needs_update = 0;
2118     }
2119
2120   if (bl->loc_type == bp_loc_software_breakpoint
2121       || bl->loc_type == bp_loc_hardware_breakpoint)
2122     {
2123       if (bl->owner->type != bp_hardware_breakpoint)
2124         {
2125           /* If the explicitly specified breakpoint type
2126              is not hardware breakpoint, check the memory map to see
2127              if the breakpoint address is in read only memory or not.
2128
2129              Two important cases are:
2130              - location type is not hardware breakpoint, memory
2131              is readonly.  We change the type of the location to
2132              hardware breakpoint.
2133              - location type is hardware breakpoint, memory is
2134              read-write.  This means we've previously made the
2135              location hardware one, but then the memory map changed,
2136              so we undo.
2137              
2138              When breakpoints are removed, remove_breakpoints will use
2139              location types we've just set here, the only possible
2140              problem is that memory map has changed during running
2141              program, but it's not going to work anyway with current
2142              gdb.  */
2143           struct mem_region *mr 
2144             = lookup_mem_region (bl->target_info.placed_address);
2145           
2146           if (mr)
2147             {
2148               if (automatic_hardware_breakpoints)
2149                 {
2150                   enum bp_loc_type new_type;
2151                   
2152                   if (mr->attrib.mode != MEM_RW)
2153                     new_type = bp_loc_hardware_breakpoint;
2154                   else 
2155                     new_type = bp_loc_software_breakpoint;
2156                   
2157                   if (new_type != bl->loc_type)
2158                     {
2159                       static int said = 0;
2160
2161                       bl->loc_type = new_type;
2162                       if (!said)
2163                         {
2164                           fprintf_filtered (gdb_stdout,
2165                                             _("Note: automatically using "
2166                                               "hardware breakpoints for "
2167                                               "read-only addresses.\n"));
2168                           said = 1;
2169                         }
2170                     }
2171                 }
2172               else if (bl->loc_type == bp_loc_software_breakpoint
2173                        && mr->attrib.mode != MEM_RW)        
2174                 warning (_("cannot set software breakpoint "
2175                            "at readonly address %s"),
2176                          paddress (bl->gdbarch, bl->address));
2177             }
2178         }
2179         
2180       /* First check to see if we have to handle an overlay.  */
2181       if (overlay_debugging == ovly_off
2182           || bl->section == NULL
2183           || !(section_is_overlay (bl->section)))
2184         {
2185           /* No overlay handling: just set the breakpoint.  */
2186
2187           val = bl->owner->ops->insert_location (bl);
2188         }
2189       else
2190         {
2191           /* This breakpoint is in an overlay section.
2192              Shall we set a breakpoint at the LMA?  */
2193           if (!overlay_events_enabled)
2194             {
2195               /* Yes -- overlay event support is not active, 
2196                  so we must try to set a breakpoint at the LMA.
2197                  This will not work for a hardware breakpoint.  */
2198               if (bl->loc_type == bp_loc_hardware_breakpoint)
2199                 warning (_("hardware breakpoint %d not supported in overlay!"),
2200                          bl->owner->number);
2201               else
2202                 {
2203                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2204                                                              bl->section);
2205                   /* Set a software (trap) breakpoint at the LMA.  */
2206                   bl->overlay_target_info = bl->target_info;
2207                   bl->overlay_target_info.placed_address = addr;
2208                   val = target_insert_breakpoint (bl->gdbarch,
2209                                                   &bl->overlay_target_info);
2210                   if (val != 0)
2211                     fprintf_unfiltered (tmp_error_stream,
2212                                         "Overlay breakpoint %d "
2213                                         "failed: in ROM?\n",
2214                                         bl->owner->number);
2215                 }
2216             }
2217           /* Shall we set a breakpoint at the VMA? */
2218           if (section_is_mapped (bl->section))
2219             {
2220               /* Yes.  This overlay section is mapped into memory.  */
2221               val = bl->owner->ops->insert_location (bl);
2222             }
2223           else
2224             {
2225               /* No.  This breakpoint will not be inserted.  
2226                  No error, but do not mark the bp as 'inserted'.  */
2227               return 0;
2228             }
2229         }
2230
2231       if (val)
2232         {
2233           /* Can't set the breakpoint.  */
2234           if (solib_name_from_address (bl->pspace, bl->address))
2235             {
2236               /* See also: disable_breakpoints_in_shlibs.  */
2237               val = 0;
2238               bl->shlib_disabled = 1;
2239               observer_notify_breakpoint_modified (bl->owner);
2240               if (!*disabled_breaks)
2241                 {
2242                   fprintf_unfiltered (tmp_error_stream, 
2243                                       "Cannot insert breakpoint %d.\n", 
2244                                       bl->owner->number);
2245                   fprintf_unfiltered (tmp_error_stream, 
2246                                       "Temporarily disabling shared "
2247                                       "library breakpoints:\n");
2248                 }
2249               *disabled_breaks = 1;
2250               fprintf_unfiltered (tmp_error_stream,
2251                                   "breakpoint #%d\n", bl->owner->number);
2252             }
2253           else
2254             {
2255               if (bl->loc_type == bp_loc_hardware_breakpoint)
2256                 {
2257                   *hw_breakpoint_error = 1;
2258                   fprintf_unfiltered (tmp_error_stream,
2259                                       "Cannot insert hardware "
2260                                       "breakpoint %d.\n",
2261                                       bl->owner->number);
2262                 }
2263               else
2264                 {
2265                   fprintf_unfiltered (tmp_error_stream, 
2266                                       "Cannot insert breakpoint %d.\n", 
2267                                       bl->owner->number);
2268                   fprintf_filtered (tmp_error_stream, 
2269                                     "Error accessing memory address ");
2270                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2271                                   tmp_error_stream);
2272                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2273                                     safe_strerror (val));
2274                 }
2275
2276             }
2277         }
2278       else
2279         bl->inserted = 1;
2280
2281       return val;
2282     }
2283
2284   else if (bl->loc_type == bp_loc_hardware_watchpoint
2285            /* NOTE drow/2003-09-08: This state only exists for removing
2286               watchpoints.  It's not clear that it's necessary...  */
2287            && bl->owner->disposition != disp_del_at_next_stop)
2288     {
2289       gdb_assert (bl->owner->ops != NULL
2290                   && bl->owner->ops->insert_location != NULL);
2291
2292       val = bl->owner->ops->insert_location (bl);
2293
2294       /* If trying to set a read-watchpoint, and it turns out it's not
2295          supported, try emulating one with an access watchpoint.  */
2296       if (val == 1 && bl->watchpoint_type == hw_read)
2297         {
2298           struct bp_location *loc, **loc_temp;
2299
2300           /* But don't try to insert it, if there's already another
2301              hw_access location that would be considered a duplicate
2302              of this one.  */
2303           ALL_BP_LOCATIONS (loc, loc_temp)
2304             if (loc != bl
2305                 && loc->watchpoint_type == hw_access
2306                 && watchpoint_locations_match (bl, loc))
2307               {
2308                 bl->duplicate = 1;
2309                 bl->inserted = 1;
2310                 bl->target_info = loc->target_info;
2311                 bl->watchpoint_type = hw_access;
2312                 val = 0;
2313                 break;
2314               }
2315
2316           if (val == 1)
2317             {
2318               bl->watchpoint_type = hw_access;
2319               val = bl->owner->ops->insert_location (bl);
2320
2321               if (val)
2322                 /* Back to the original value.  */
2323                 bl->watchpoint_type = hw_read;
2324             }
2325         }
2326
2327       bl->inserted = (val == 0);
2328     }
2329
2330   else if (bl->owner->type == bp_catchpoint)
2331     {
2332       gdb_assert (bl->owner->ops != NULL
2333                   && bl->owner->ops->insert_location != NULL);
2334
2335       val = bl->owner->ops->insert_location (bl);
2336       if (val)
2337         {
2338           bl->owner->enable_state = bp_disabled;
2339
2340           if (val == 1)
2341             warning (_("\
2342 Error inserting catchpoint %d: Your system does not support this type\n\
2343 of catchpoint."), bl->owner->number);
2344           else
2345             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2346         }
2347
2348       bl->inserted = (val == 0);
2349
2350       /* We've already printed an error message if there was a problem
2351          inserting this catchpoint, and we've disabled the catchpoint,
2352          so just return success.  */
2353       return 0;
2354     }
2355
2356   return 0;
2357 }
2358
2359 /* This function is called when program space PSPACE is about to be
2360    deleted.  It takes care of updating breakpoints to not reference
2361    PSPACE anymore.  */
2362
2363 void
2364 breakpoint_program_space_exit (struct program_space *pspace)
2365 {
2366   struct breakpoint *b, *b_temp;
2367   struct bp_location *loc, **loc_temp;
2368
2369   /* Remove any breakpoint that was set through this program space.  */
2370   ALL_BREAKPOINTS_SAFE (b, b_temp)
2371     {
2372       if (b->pspace == pspace)
2373         delete_breakpoint (b);
2374     }
2375
2376   /* Breakpoints set through other program spaces could have locations
2377      bound to PSPACE as well.  Remove those.  */
2378   ALL_BP_LOCATIONS (loc, loc_temp)
2379     {
2380       struct bp_location *tmp;
2381
2382       if (loc->pspace == pspace)
2383         {
2384           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2385           if (loc->owner->loc == loc)
2386             loc->owner->loc = loc->next;
2387           else
2388             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2389               if (tmp->next == loc)
2390                 {
2391                   tmp->next = loc->next;
2392                   break;
2393                 }
2394         }
2395     }
2396
2397   /* Now update the global location list to permanently delete the
2398      removed locations above.  */
2399   update_global_location_list (0);
2400 }
2401
2402 /* Make sure all breakpoints are inserted in inferior.
2403    Throws exception on any error.
2404    A breakpoint that is already inserted won't be inserted
2405    again, so calling this function twice is safe.  */
2406 void
2407 insert_breakpoints (void)
2408 {
2409   struct breakpoint *bpt;
2410
2411   ALL_BREAKPOINTS (bpt)
2412     if (is_hardware_watchpoint (bpt))
2413       {
2414         struct watchpoint *w = (struct watchpoint *) bpt;
2415
2416         update_watchpoint (w, 0 /* don't reparse.  */);
2417       }
2418
2419   update_global_location_list (1);
2420
2421   /* update_global_location_list does not insert breakpoints when
2422      always_inserted_mode is not enabled.  Explicitly insert them
2423      now.  */
2424   if (!breakpoints_always_inserted_mode ())
2425     insert_breakpoint_locations ();
2426 }
2427
2428 /* This is used when we need to synch breakpoint conditions between GDB and the
2429    target.  It is the case with deleting and disabling of breakpoints when using
2430    always-inserted mode.  */
2431
2432 static void
2433 update_inserted_breakpoint_locations (void)
2434 {
2435   struct bp_location *bl, **blp_tmp;
2436   int error_flag = 0;
2437   int val = 0;
2438   int disabled_breaks = 0;
2439   int hw_breakpoint_error = 0;
2440
2441   struct ui_file *tmp_error_stream = mem_fileopen ();
2442   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2443
2444   /* Explicitly mark the warning -- this will only be printed if
2445      there was an error.  */
2446   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2447
2448   save_current_space_and_thread ();
2449
2450   ALL_BP_LOCATIONS (bl, blp_tmp)
2451     {
2452       /* We only want to update software breakpoints and hardware
2453          breakpoints.  */
2454       if (!is_breakpoint (bl->owner))
2455         continue;
2456
2457       /* We only want to update locations that are already inserted
2458          and need updating.  This is to avoid unwanted insertion during
2459          deletion of breakpoints.  */
2460       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2461         continue;
2462
2463       switch_to_program_space_and_thread (bl->pspace);
2464
2465       /* For targets that support global breakpoints, there's no need
2466          to select an inferior to insert breakpoint to.  In fact, even
2467          if we aren't attached to any process yet, we should still
2468          insert breakpoints.  */
2469       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2470           && ptid_equal (inferior_ptid, null_ptid))
2471         continue;
2472
2473       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2474                                     &hw_breakpoint_error);
2475       if (val)
2476         error_flag = val;
2477     }
2478
2479   if (error_flag)
2480     {
2481       target_terminal_ours_for_output ();
2482       error_stream (tmp_error_stream);
2483     }
2484
2485   do_cleanups (cleanups);
2486 }
2487
2488 /* Used when starting or continuing the program.  */
2489
2490 static void
2491 insert_breakpoint_locations (void)
2492 {
2493   struct breakpoint *bpt;
2494   struct bp_location *bl, **blp_tmp;
2495   int error_flag = 0;
2496   int val = 0;
2497   int disabled_breaks = 0;
2498   int hw_breakpoint_error = 0;
2499
2500   struct ui_file *tmp_error_stream = mem_fileopen ();
2501   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2502   
2503   /* Explicitly mark the warning -- this will only be printed if
2504      there was an error.  */
2505   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2506
2507   save_current_space_and_thread ();
2508
2509   ALL_BP_LOCATIONS (bl, blp_tmp)
2510     {
2511       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2512         continue;
2513
2514       /* There is no point inserting thread-specific breakpoints if
2515          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2516          has BL->OWNER always non-NULL.  */
2517       if (bl->owner->thread != -1
2518           && !valid_thread_id (bl->owner->thread))
2519         continue;
2520
2521       switch_to_program_space_and_thread (bl->pspace);
2522
2523       /* For targets that support global breakpoints, there's no need
2524          to select an inferior to insert breakpoint to.  In fact, even
2525          if we aren't attached to any process yet, we should still
2526          insert breakpoints.  */
2527       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2528           && ptid_equal (inferior_ptid, null_ptid))
2529         continue;
2530
2531       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2532                                     &hw_breakpoint_error);
2533       if (val)
2534         error_flag = val;
2535     }
2536
2537   /* If we failed to insert all locations of a watchpoint, remove
2538      them, as half-inserted watchpoint is of limited use.  */
2539   ALL_BREAKPOINTS (bpt)  
2540     {
2541       int some_failed = 0;
2542       struct bp_location *loc;
2543
2544       if (!is_hardware_watchpoint (bpt))
2545         continue;
2546
2547       if (!breakpoint_enabled (bpt))
2548         continue;
2549
2550       if (bpt->disposition == disp_del_at_next_stop)
2551         continue;
2552       
2553       for (loc = bpt->loc; loc; loc = loc->next)
2554         if (!loc->inserted && should_be_inserted (loc))
2555           {
2556             some_failed = 1;
2557             break;
2558           }
2559       if (some_failed)
2560         {
2561           for (loc = bpt->loc; loc; loc = loc->next)
2562             if (loc->inserted)
2563               remove_breakpoint (loc, mark_uninserted);
2564
2565           hw_breakpoint_error = 1;
2566           fprintf_unfiltered (tmp_error_stream,
2567                               "Could not insert hardware watchpoint %d.\n", 
2568                               bpt->number);
2569           error_flag = -1;
2570         }
2571     }
2572
2573   if (error_flag)
2574     {
2575       /* If a hardware breakpoint or watchpoint was inserted, add a
2576          message about possibly exhausted resources.  */
2577       if (hw_breakpoint_error)
2578         {
2579           fprintf_unfiltered (tmp_error_stream, 
2580                               "Could not insert hardware breakpoints:\n\
2581 You may have requested too many hardware breakpoints/watchpoints.\n");
2582         }
2583       target_terminal_ours_for_output ();
2584       error_stream (tmp_error_stream);
2585     }
2586
2587   do_cleanups (cleanups);
2588 }
2589
2590 /* Used when the program stops.
2591    Returns zero if successful, or non-zero if there was a problem
2592    removing a breakpoint location.  */
2593
2594 int
2595 remove_breakpoints (void)
2596 {
2597   struct bp_location *bl, **blp_tmp;
2598   int val = 0;
2599
2600   ALL_BP_LOCATIONS (bl, blp_tmp)
2601   {
2602     if (bl->inserted && !is_tracepoint (bl->owner))
2603       val |= remove_breakpoint (bl, mark_uninserted);
2604   }
2605   return val;
2606 }
2607
2608 /* Remove breakpoints of process PID.  */
2609
2610 int
2611 remove_breakpoints_pid (int pid)
2612 {
2613   struct bp_location *bl, **blp_tmp;
2614   int val;
2615   struct inferior *inf = find_inferior_pid (pid);
2616
2617   ALL_BP_LOCATIONS (bl, blp_tmp)
2618   {
2619     if (bl->pspace != inf->pspace)
2620       continue;
2621
2622     if (bl->inserted)
2623       {
2624         val = remove_breakpoint (bl, mark_uninserted);
2625         if (val != 0)
2626           return val;
2627       }
2628   }
2629   return 0;
2630 }
2631
2632 int
2633 reattach_breakpoints (int pid)
2634 {
2635   struct cleanup *old_chain;
2636   struct bp_location *bl, **blp_tmp;
2637   int val;
2638   struct ui_file *tmp_error_stream;
2639   int dummy1 = 0, dummy2 = 0;
2640   struct inferior *inf;
2641   struct thread_info *tp;
2642
2643   tp = any_live_thread_of_process (pid);
2644   if (tp == NULL)
2645     return 1;
2646
2647   inf = find_inferior_pid (pid);
2648   old_chain = save_inferior_ptid ();
2649
2650   inferior_ptid = tp->ptid;
2651
2652   tmp_error_stream = mem_fileopen ();
2653   make_cleanup_ui_file_delete (tmp_error_stream);
2654
2655   ALL_BP_LOCATIONS (bl, blp_tmp)
2656   {
2657     if (bl->pspace != inf->pspace)
2658       continue;
2659
2660     if (bl->inserted)
2661       {
2662         bl->inserted = 0;
2663         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2664         if (val != 0)
2665           {
2666             do_cleanups (old_chain);
2667             return val;
2668           }
2669       }
2670   }
2671   do_cleanups (old_chain);
2672   return 0;
2673 }
2674
2675 static int internal_breakpoint_number = -1;
2676
2677 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2678    If INTERNAL is non-zero, the breakpoint number will be populated
2679    from internal_breakpoint_number and that variable decremented.
2680    Otherwise the breakpoint number will be populated from
2681    breakpoint_count and that value incremented.  Internal breakpoints
2682    do not set the internal var bpnum.  */
2683 static void
2684 set_breakpoint_number (int internal, struct breakpoint *b)
2685 {
2686   if (internal)
2687     b->number = internal_breakpoint_number--;
2688   else
2689     {
2690       set_breakpoint_count (breakpoint_count + 1);
2691       b->number = breakpoint_count;
2692     }
2693 }
2694
2695 static struct breakpoint *
2696 create_internal_breakpoint (struct gdbarch *gdbarch,
2697                             CORE_ADDR address, enum bptype type,
2698                             const struct breakpoint_ops *ops)
2699 {
2700   struct symtab_and_line sal;
2701   struct breakpoint *b;
2702
2703   init_sal (&sal);              /* Initialize to zeroes.  */
2704
2705   sal.pc = address;
2706   sal.section = find_pc_overlay (sal.pc);
2707   sal.pspace = current_program_space;
2708
2709   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2710   b->number = internal_breakpoint_number--;
2711   b->disposition = disp_donttouch;
2712
2713   return b;
2714 }
2715
2716 static const char *const longjmp_names[] =
2717   {
2718     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2719   };
2720 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2721
2722 /* Per-objfile data private to breakpoint.c.  */
2723 struct breakpoint_objfile_data
2724 {
2725   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2726   struct minimal_symbol *overlay_msym;
2727
2728   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2729   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2730
2731   /* Minimal symbol for "std::terminate()" (if any).  */
2732   struct minimal_symbol *terminate_msym;
2733
2734   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2735   struct minimal_symbol *exception_msym;
2736 };
2737
2738 static const struct objfile_data *breakpoint_objfile_key;
2739
2740 /* Minimal symbol not found sentinel.  */
2741 static struct minimal_symbol msym_not_found;
2742
2743 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2744
2745 static int
2746 msym_not_found_p (const struct minimal_symbol *msym)
2747 {
2748   return msym == &msym_not_found;
2749 }
2750
2751 /* Return per-objfile data needed by breakpoint.c.
2752    Allocate the data if necessary.  */
2753
2754 static struct breakpoint_objfile_data *
2755 get_breakpoint_objfile_data (struct objfile *objfile)
2756 {
2757   struct breakpoint_objfile_data *bp_objfile_data;
2758
2759   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2760   if (bp_objfile_data == NULL)
2761     {
2762       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2763                                        sizeof (*bp_objfile_data));
2764
2765       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2766       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2767     }
2768   return bp_objfile_data;
2769 }
2770
2771 static void
2772 create_overlay_event_breakpoint (void)
2773 {
2774   struct objfile *objfile;
2775   const char *const func_name = "_ovly_debug_event";
2776
2777   ALL_OBJFILES (objfile)
2778     {
2779       struct breakpoint *b;
2780       struct breakpoint_objfile_data *bp_objfile_data;
2781       CORE_ADDR addr;
2782
2783       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2784
2785       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2786         continue;
2787
2788       if (bp_objfile_data->overlay_msym == NULL)
2789         {
2790           struct minimal_symbol *m;
2791
2792           m = lookup_minimal_symbol_text (func_name, objfile);
2793           if (m == NULL)
2794             {
2795               /* Avoid future lookups in this objfile.  */
2796               bp_objfile_data->overlay_msym = &msym_not_found;
2797               continue;
2798             }
2799           bp_objfile_data->overlay_msym = m;
2800         }
2801
2802       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2803       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2804                                       bp_overlay_event,
2805                                       &internal_breakpoint_ops);
2806       b->addr_string = xstrdup (func_name);
2807
2808       if (overlay_debugging == ovly_auto)
2809         {
2810           b->enable_state = bp_enabled;
2811           overlay_events_enabled = 1;
2812         }
2813       else
2814        {
2815          b->enable_state = bp_disabled;
2816          overlay_events_enabled = 0;
2817        }
2818     }
2819   update_global_location_list (1);
2820 }
2821
2822 static void
2823 create_longjmp_master_breakpoint (void)
2824 {
2825   struct program_space *pspace;
2826   struct cleanup *old_chain;
2827
2828   old_chain = save_current_program_space ();
2829
2830   ALL_PSPACES (pspace)
2831   {
2832     struct objfile *objfile;
2833
2834     set_current_program_space (pspace);
2835
2836     ALL_OBJFILES (objfile)
2837     {
2838       int i;
2839       struct gdbarch *gdbarch;
2840       struct breakpoint_objfile_data *bp_objfile_data;
2841
2842       gdbarch = get_objfile_arch (objfile);
2843       if (!gdbarch_get_longjmp_target_p (gdbarch))
2844         continue;
2845
2846       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2847
2848       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2849         {
2850           struct breakpoint *b;
2851           const char *func_name;
2852           CORE_ADDR addr;
2853
2854           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2855             continue;
2856
2857           func_name = longjmp_names[i];
2858           if (bp_objfile_data->longjmp_msym[i] == NULL)
2859             {
2860               struct minimal_symbol *m;
2861
2862               m = lookup_minimal_symbol_text (func_name, objfile);
2863               if (m == NULL)
2864                 {
2865                   /* Prevent future lookups in this objfile.  */
2866                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2867                   continue;
2868                 }
2869               bp_objfile_data->longjmp_msym[i] = m;
2870             }
2871
2872           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2873           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2874                                           &internal_breakpoint_ops);
2875           b->addr_string = xstrdup (func_name);
2876           b->enable_state = bp_disabled;
2877         }
2878     }
2879   }
2880   update_global_location_list (1);
2881
2882   do_cleanups (old_chain);
2883 }
2884
2885 /* Create a master std::terminate breakpoint.  */
2886 static void
2887 create_std_terminate_master_breakpoint (void)
2888 {
2889   struct program_space *pspace;
2890   struct cleanup *old_chain;
2891   const char *const func_name = "std::terminate()";
2892
2893   old_chain = save_current_program_space ();
2894
2895   ALL_PSPACES (pspace)
2896   {
2897     struct objfile *objfile;
2898     CORE_ADDR addr;
2899
2900     set_current_program_space (pspace);
2901
2902     ALL_OBJFILES (objfile)
2903     {
2904       struct breakpoint *b;
2905       struct breakpoint_objfile_data *bp_objfile_data;
2906
2907       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2908
2909       if (msym_not_found_p (bp_objfile_data->terminate_msym))
2910         continue;
2911
2912       if (bp_objfile_data->terminate_msym == NULL)
2913         {
2914           struct minimal_symbol *m;
2915
2916           m = lookup_minimal_symbol (func_name, NULL, objfile);
2917           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
2918                             && MSYMBOL_TYPE (m) != mst_file_text))
2919             {
2920               /* Prevent future lookups in this objfile.  */
2921               bp_objfile_data->terminate_msym = &msym_not_found;
2922               continue;
2923             }
2924           bp_objfile_data->terminate_msym = m;
2925         }
2926
2927       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
2928       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2929                                       bp_std_terminate_master,
2930                                       &internal_breakpoint_ops);
2931       b->addr_string = xstrdup (func_name);
2932       b->enable_state = bp_disabled;
2933     }
2934   }
2935
2936   update_global_location_list (1);
2937
2938   do_cleanups (old_chain);
2939 }
2940
2941 /* Install a master breakpoint on the unwinder's debug hook.  */
2942
2943 static void
2944 create_exception_master_breakpoint (void)
2945 {
2946   struct objfile *objfile;
2947   const char *const func_name = "_Unwind_DebugHook";
2948
2949   ALL_OBJFILES (objfile)
2950     {
2951       struct breakpoint *b;
2952       struct gdbarch *gdbarch;
2953       struct breakpoint_objfile_data *bp_objfile_data;
2954       CORE_ADDR addr;
2955
2956       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2957
2958       if (msym_not_found_p (bp_objfile_data->exception_msym))
2959         continue;
2960
2961       gdbarch = get_objfile_arch (objfile);
2962
2963       if (bp_objfile_data->exception_msym == NULL)
2964         {
2965           struct minimal_symbol *debug_hook;
2966
2967           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
2968           if (debug_hook == NULL)
2969             {
2970               bp_objfile_data->exception_msym = &msym_not_found;
2971               continue;
2972             }
2973
2974           bp_objfile_data->exception_msym = debug_hook;
2975         }
2976
2977       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
2978       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
2979                                                  &current_target);
2980       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
2981                                       &internal_breakpoint_ops);
2982       b->addr_string = xstrdup (func_name);
2983       b->enable_state = bp_disabled;
2984     }
2985
2986   update_global_location_list (1);
2987 }
2988
2989 void
2990 update_breakpoints_after_exec (void)
2991 {
2992   struct breakpoint *b, *b_tmp;
2993   struct bp_location *bploc, **bplocp_tmp;
2994
2995   /* We're about to delete breakpoints from GDB's lists.  If the
2996      INSERTED flag is true, GDB will try to lift the breakpoints by
2997      writing the breakpoints' "shadow contents" back into memory.  The
2998      "shadow contents" are NOT valid after an exec, so GDB should not
2999      do that.  Instead, the target is responsible from marking
3000      breakpoints out as soon as it detects an exec.  We don't do that
3001      here instead, because there may be other attempts to delete
3002      breakpoints after detecting an exec and before reaching here.  */
3003   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3004     if (bploc->pspace == current_program_space)
3005       gdb_assert (!bploc->inserted);
3006
3007   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3008   {
3009     if (b->pspace != current_program_space)
3010       continue;
3011
3012     /* Solib breakpoints must be explicitly reset after an exec().  */
3013     if (b->type == bp_shlib_event)
3014       {
3015         delete_breakpoint (b);
3016         continue;
3017       }
3018
3019     /* JIT breakpoints must be explicitly reset after an exec().  */
3020     if (b->type == bp_jit_event)
3021       {
3022         delete_breakpoint (b);
3023         continue;
3024       }
3025
3026     /* Thread event breakpoints must be set anew after an exec(),
3027        as must overlay event and longjmp master breakpoints.  */
3028     if (b->type == bp_thread_event || b->type == bp_overlay_event
3029         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3030         || b->type == bp_exception_master)
3031       {
3032         delete_breakpoint (b);
3033         continue;
3034       }
3035
3036     /* Step-resume breakpoints are meaningless after an exec().  */
3037     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3038       {
3039         delete_breakpoint (b);
3040         continue;
3041       }
3042
3043     /* Longjmp and longjmp-resume breakpoints are also meaningless
3044        after an exec.  */
3045     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3046         || b->type == bp_exception || b->type == bp_exception_resume)
3047       {
3048         delete_breakpoint (b);
3049         continue;
3050       }
3051
3052     if (b->type == bp_catchpoint)
3053       {
3054         /* For now, none of the bp_catchpoint breakpoints need to
3055            do anything at this point.  In the future, if some of
3056            the catchpoints need to something, we will need to add
3057            a new method, and call this method from here.  */
3058         continue;
3059       }
3060
3061     /* bp_finish is a special case.  The only way we ought to be able
3062        to see one of these when an exec() has happened, is if the user
3063        caught a vfork, and then said "finish".  Ordinarily a finish just
3064        carries them to the call-site of the current callee, by setting
3065        a temporary bp there and resuming.  But in this case, the finish
3066        will carry them entirely through the vfork & exec.
3067
3068        We don't want to allow a bp_finish to remain inserted now.  But
3069        we can't safely delete it, 'cause finish_command has a handle to
3070        the bp on a bpstat, and will later want to delete it.  There's a
3071        chance (and I've seen it happen) that if we delete the bp_finish
3072        here, that its storage will get reused by the time finish_command
3073        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3074        We really must allow finish_command to delete a bp_finish.
3075
3076        In the absence of a general solution for the "how do we know
3077        it's safe to delete something others may have handles to?"
3078        problem, what we'll do here is just uninsert the bp_finish, and
3079        let finish_command delete it.
3080
3081        (We know the bp_finish is "doomed" in the sense that it's
3082        momentary, and will be deleted as soon as finish_command sees
3083        the inferior stopped.  So it doesn't matter that the bp's
3084        address is probably bogus in the new a.out, unlike e.g., the
3085        solib breakpoints.)  */
3086
3087     if (b->type == bp_finish)
3088       {
3089         continue;
3090       }
3091
3092     /* Without a symbolic address, we have little hope of the
3093        pre-exec() address meaning the same thing in the post-exec()
3094        a.out.  */
3095     if (b->addr_string == NULL)
3096       {
3097         delete_breakpoint (b);
3098         continue;
3099       }
3100   }
3101   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3102   create_overlay_event_breakpoint ();
3103   create_longjmp_master_breakpoint ();
3104   create_std_terminate_master_breakpoint ();
3105   create_exception_master_breakpoint ();
3106 }
3107
3108 int
3109 detach_breakpoints (int pid)
3110 {
3111   struct bp_location *bl, **blp_tmp;
3112   int val = 0;
3113   struct cleanup *old_chain = save_inferior_ptid ();
3114   struct inferior *inf = current_inferior ();
3115
3116   if (pid == PIDGET (inferior_ptid))
3117     error (_("Cannot detach breakpoints of inferior_ptid"));
3118
3119   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3120   inferior_ptid = pid_to_ptid (pid);
3121   ALL_BP_LOCATIONS (bl, blp_tmp)
3122   {
3123     if (bl->pspace != inf->pspace)
3124       continue;
3125
3126     if (bl->inserted)
3127       val |= remove_breakpoint_1 (bl, mark_inserted);
3128   }
3129
3130   /* Detach single-step breakpoints as well.  */
3131   detach_single_step_breakpoints ();
3132
3133   do_cleanups (old_chain);
3134   return val;
3135 }
3136
3137 /* Remove the breakpoint location BL from the current address space.
3138    Note that this is used to detach breakpoints from a child fork.
3139    When we get here, the child isn't in the inferior list, and neither
3140    do we have objects to represent its address space --- we should
3141    *not* look at bl->pspace->aspace here.  */
3142
3143 static int
3144 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3145 {
3146   int val;
3147
3148   /* BL is never in moribund_locations by our callers.  */
3149   gdb_assert (bl->owner != NULL);
3150
3151   if (bl->owner->enable_state == bp_permanent)
3152     /* Permanent breakpoints cannot be inserted or removed.  */
3153     return 0;
3154
3155   /* The type of none suggests that owner is actually deleted.
3156      This should not ever happen.  */
3157   gdb_assert (bl->owner->type != bp_none);
3158
3159   if (bl->loc_type == bp_loc_software_breakpoint
3160       || bl->loc_type == bp_loc_hardware_breakpoint)
3161     {
3162       /* "Normal" instruction breakpoint: either the standard
3163          trap-instruction bp (bp_breakpoint), or a
3164          bp_hardware_breakpoint.  */
3165
3166       /* First check to see if we have to handle an overlay.  */
3167       if (overlay_debugging == ovly_off
3168           || bl->section == NULL
3169           || !(section_is_overlay (bl->section)))
3170         {
3171           /* No overlay handling: just remove the breakpoint.  */
3172           val = bl->owner->ops->remove_location (bl);
3173         }
3174       else
3175         {
3176           /* This breakpoint is in an overlay section.
3177              Did we set a breakpoint at the LMA?  */
3178           if (!overlay_events_enabled)
3179               {
3180                 /* Yes -- overlay event support is not active, so we
3181                    should have set a breakpoint at the LMA.  Remove it.  
3182                 */
3183                 /* Ignore any failures: if the LMA is in ROM, we will
3184                    have already warned when we failed to insert it.  */
3185                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3186                   target_remove_hw_breakpoint (bl->gdbarch,
3187                                                &bl->overlay_target_info);
3188                 else
3189                   target_remove_breakpoint (bl->gdbarch,
3190                                             &bl->overlay_target_info);
3191               }
3192           /* Did we set a breakpoint at the VMA? 
3193              If so, we will have marked the breakpoint 'inserted'.  */
3194           if (bl->inserted)
3195             {
3196               /* Yes -- remove it.  Previously we did not bother to
3197                  remove the breakpoint if the section had been
3198                  unmapped, but let's not rely on that being safe.  We
3199                  don't know what the overlay manager might do.  */
3200
3201               /* However, we should remove *software* breakpoints only
3202                  if the section is still mapped, or else we overwrite
3203                  wrong code with the saved shadow contents.  */
3204               if (bl->loc_type == bp_loc_hardware_breakpoint
3205                   || section_is_mapped (bl->section))
3206                 val = bl->owner->ops->remove_location (bl);
3207               else
3208                 val = 0;
3209             }
3210           else
3211             {
3212               /* No -- not inserted, so no need to remove.  No error.  */
3213               val = 0;
3214             }
3215         }
3216
3217       /* In some cases, we might not be able to remove a breakpoint
3218          in a shared library that has already been removed, but we
3219          have not yet processed the shlib unload event.  */
3220       if (val && solib_name_from_address (bl->pspace, bl->address))
3221         val = 0;
3222
3223       if (val)
3224         return val;
3225       bl->inserted = (is == mark_inserted);
3226     }
3227   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3228     {
3229       gdb_assert (bl->owner->ops != NULL
3230                   && bl->owner->ops->remove_location != NULL);
3231
3232       bl->inserted = (is == mark_inserted);
3233       bl->owner->ops->remove_location (bl);
3234
3235       /* Failure to remove any of the hardware watchpoints comes here.  */
3236       if ((is == mark_uninserted) && (bl->inserted))
3237         warning (_("Could not remove hardware watchpoint %d."),
3238                  bl->owner->number);
3239     }
3240   else if (bl->owner->type == bp_catchpoint
3241            && breakpoint_enabled (bl->owner)
3242            && !bl->duplicate)
3243     {
3244       gdb_assert (bl->owner->ops != NULL
3245                   && bl->owner->ops->remove_location != NULL);
3246
3247       val = bl->owner->ops->remove_location (bl);
3248       if (val)
3249         return val;
3250
3251       bl->inserted = (is == mark_inserted);
3252     }
3253
3254   return 0;
3255 }
3256
3257 static int
3258 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3259 {
3260   int ret;
3261   struct cleanup *old_chain;
3262
3263   /* BL is never in moribund_locations by our callers.  */
3264   gdb_assert (bl->owner != NULL);
3265
3266   if (bl->owner->enable_state == bp_permanent)
3267     /* Permanent breakpoints cannot be inserted or removed.  */
3268     return 0;
3269
3270   /* The type of none suggests that owner is actually deleted.
3271      This should not ever happen.  */
3272   gdb_assert (bl->owner->type != bp_none);
3273
3274   old_chain = save_current_space_and_thread ();
3275
3276   switch_to_program_space_and_thread (bl->pspace);
3277
3278   ret = remove_breakpoint_1 (bl, is);
3279
3280   do_cleanups (old_chain);
3281   return ret;
3282 }
3283
3284 /* Clear the "inserted" flag in all breakpoints.  */
3285
3286 void
3287 mark_breakpoints_out (void)
3288 {
3289   struct bp_location *bl, **blp_tmp;
3290
3291   ALL_BP_LOCATIONS (bl, blp_tmp)
3292     if (bl->pspace == current_program_space)
3293       bl->inserted = 0;
3294 }
3295
3296 /* Clear the "inserted" flag in all breakpoints and delete any
3297    breakpoints which should go away between runs of the program.
3298
3299    Plus other such housekeeping that has to be done for breakpoints
3300    between runs.
3301
3302    Note: this function gets called at the end of a run (by
3303    generic_mourn_inferior) and when a run begins (by
3304    init_wait_for_inferior).  */
3305
3306
3307
3308 void
3309 breakpoint_init_inferior (enum inf_context context)
3310 {
3311   struct breakpoint *b, *b_tmp;
3312   struct bp_location *bl, **blp_tmp;
3313   int ix;
3314   struct program_space *pspace = current_program_space;
3315
3316   /* If breakpoint locations are shared across processes, then there's
3317      nothing to do.  */
3318   if (gdbarch_has_global_breakpoints (target_gdbarch))
3319     return;
3320
3321   ALL_BP_LOCATIONS (bl, blp_tmp)
3322   {
3323     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3324     if (bl->pspace == pspace
3325         && bl->owner->enable_state != bp_permanent)
3326       bl->inserted = 0;
3327   }
3328
3329   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3330   {
3331     if (b->loc && b->loc->pspace != pspace)
3332       continue;
3333
3334     switch (b->type)
3335       {
3336       case bp_call_dummy:
3337
3338         /* If the call dummy breakpoint is at the entry point it will
3339            cause problems when the inferior is rerun, so we better get
3340            rid of it.  */
3341
3342       case bp_watchpoint_scope:
3343
3344         /* Also get rid of scope breakpoints.  */
3345
3346       case bp_shlib_event:
3347
3348         /* Also remove solib event breakpoints.  Their addresses may
3349            have changed since the last time we ran the program.
3350            Actually we may now be debugging against different target;
3351            and so the solib backend that installed this breakpoint may
3352            not be used in by the target.  E.g.,
3353
3354            (gdb) file prog-linux
3355            (gdb) run               # native linux target
3356            ...
3357            (gdb) kill
3358            (gdb) file prog-win.exe
3359            (gdb) tar rem :9999     # remote Windows gdbserver.
3360         */
3361
3362       case bp_step_resume:
3363
3364         /* Also remove step-resume breakpoints.  */
3365
3366         delete_breakpoint (b);
3367         break;
3368
3369       case bp_watchpoint:
3370       case bp_hardware_watchpoint:
3371       case bp_read_watchpoint:
3372       case bp_access_watchpoint:
3373         {
3374           struct watchpoint *w = (struct watchpoint *) b;
3375
3376           /* Likewise for watchpoints on local expressions.  */
3377           if (w->exp_valid_block != NULL)
3378             delete_breakpoint (b);
3379           else if (context == inf_starting)
3380             {
3381               /* Reset val field to force reread of starting value in
3382                  insert_breakpoints.  */
3383               if (w->val)
3384                 value_free (w->val);
3385               w->val = NULL;
3386               w->val_valid = 0;
3387           }
3388         }
3389         break;
3390       default:
3391         break;
3392       }
3393   }
3394
3395   /* Get rid of the moribund locations.  */
3396   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3397     decref_bp_location (&bl);
3398   VEC_free (bp_location_p, moribund_locations);
3399 }
3400
3401 /* These functions concern about actual breakpoints inserted in the
3402    target --- to e.g. check if we need to do decr_pc adjustment or if
3403    we need to hop over the bkpt --- so we check for address space
3404    match, not program space.  */
3405
3406 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3407    exists at PC.  It returns ordinary_breakpoint_here if it's an
3408    ordinary breakpoint, or permanent_breakpoint_here if it's a
3409    permanent breakpoint.
3410    - When continuing from a location with an ordinary breakpoint, we
3411      actually single step once before calling insert_breakpoints.
3412    - When continuing from a location with a permanent breakpoint, we
3413      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3414      the target, to advance the PC past the breakpoint.  */
3415
3416 enum breakpoint_here
3417 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3418 {
3419   struct bp_location *bl, **blp_tmp;
3420   int any_breakpoint_here = 0;
3421
3422   ALL_BP_LOCATIONS (bl, blp_tmp)
3423     {
3424       if (bl->loc_type != bp_loc_software_breakpoint
3425           && bl->loc_type != bp_loc_hardware_breakpoint)
3426         continue;
3427
3428       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3429       if ((breakpoint_enabled (bl->owner)
3430            || bl->owner->enable_state == bp_permanent)
3431           && breakpoint_location_address_match (bl, aspace, pc))
3432         {
3433           if (overlay_debugging 
3434               && section_is_overlay (bl->section)
3435               && !section_is_mapped (bl->section))
3436             continue;           /* unmapped overlay -- can't be a match */
3437           else if (bl->owner->enable_state == bp_permanent)
3438             return permanent_breakpoint_here;
3439           else
3440             any_breakpoint_here = 1;
3441         }
3442     }
3443
3444   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3445 }
3446
3447 /* Return true if there's a moribund breakpoint at PC.  */
3448
3449 int
3450 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3451 {
3452   struct bp_location *loc;
3453   int ix;
3454
3455   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3456     if (breakpoint_location_address_match (loc, aspace, pc))
3457       return 1;
3458
3459   return 0;
3460 }
3461
3462 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3463    inserted using regular breakpoint_chain / bp_location array
3464    mechanism.  This does not check for single-step breakpoints, which
3465    are inserted and removed using direct target manipulation.  */
3466
3467 int
3468 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3469                                     CORE_ADDR pc)
3470 {
3471   struct bp_location *bl, **blp_tmp;
3472
3473   ALL_BP_LOCATIONS (bl, blp_tmp)
3474     {
3475       if (bl->loc_type != bp_loc_software_breakpoint
3476           && bl->loc_type != bp_loc_hardware_breakpoint)
3477         continue;
3478
3479       if (bl->inserted
3480           && breakpoint_location_address_match (bl, aspace, pc))
3481         {
3482           if (overlay_debugging 
3483               && section_is_overlay (bl->section)
3484               && !section_is_mapped (bl->section))
3485             continue;           /* unmapped overlay -- can't be a match */
3486           else
3487             return 1;
3488         }
3489     }
3490   return 0;
3491 }
3492
3493 /* Returns non-zero iff there's either regular breakpoint
3494    or a single step breakpoint inserted at PC.  */
3495
3496 int
3497 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3498 {
3499   if (regular_breakpoint_inserted_here_p (aspace, pc))
3500     return 1;
3501
3502   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3503     return 1;
3504
3505   return 0;
3506 }
3507
3508 /* This function returns non-zero iff there is a software breakpoint
3509    inserted at PC.  */
3510
3511 int
3512 software_breakpoint_inserted_here_p (struct address_space *aspace,
3513                                      CORE_ADDR pc)
3514 {
3515   struct bp_location *bl, **blp_tmp;
3516
3517   ALL_BP_LOCATIONS (bl, blp_tmp)
3518     {
3519       if (bl->loc_type != bp_loc_software_breakpoint)
3520         continue;
3521
3522       if (bl->inserted
3523           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3524                                        aspace, pc))
3525         {
3526           if (overlay_debugging 
3527               && section_is_overlay (bl->section)
3528               && !section_is_mapped (bl->section))
3529             continue;           /* unmapped overlay -- can't be a match */
3530           else
3531             return 1;
3532         }
3533     }
3534
3535   /* Also check for software single-step breakpoints.  */
3536   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3537     return 1;
3538
3539   return 0;
3540 }
3541
3542 int
3543 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3544                                        CORE_ADDR addr, ULONGEST len)
3545 {
3546   struct breakpoint *bpt;
3547
3548   ALL_BREAKPOINTS (bpt)
3549     {
3550       struct bp_location *loc;
3551
3552       if (bpt->type != bp_hardware_watchpoint
3553           && bpt->type != bp_access_watchpoint)
3554         continue;
3555
3556       if (!breakpoint_enabled (bpt))
3557         continue;
3558
3559       for (loc = bpt->loc; loc; loc = loc->next)
3560         if (loc->pspace->aspace == aspace && loc->inserted)
3561           {
3562             CORE_ADDR l, h;
3563
3564             /* Check for intersection.  */
3565             l = max (loc->address, addr);
3566             h = min (loc->address + loc->length, addr + len);
3567             if (l < h)
3568               return 1;
3569           }
3570     }
3571   return 0;
3572 }
3573
3574 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3575    PC is valid for process/thread PTID.  */
3576
3577 int
3578 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3579                          ptid_t ptid)
3580 {
3581   struct bp_location *bl, **blp_tmp;
3582   /* The thread and task IDs associated to PTID, computed lazily.  */
3583   int thread = -1;
3584   int task = 0;
3585   
3586   ALL_BP_LOCATIONS (bl, blp_tmp)
3587     {
3588       if (bl->loc_type != bp_loc_software_breakpoint
3589           && bl->loc_type != bp_loc_hardware_breakpoint)
3590         continue;
3591
3592       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3593       if (!breakpoint_enabled (bl->owner)
3594           && bl->owner->enable_state != bp_permanent)
3595         continue;
3596
3597       if (!breakpoint_location_address_match (bl, aspace, pc))
3598         continue;
3599
3600       if (bl->owner->thread != -1)
3601         {
3602           /* This is a thread-specific breakpoint.  Check that ptid
3603              matches that thread.  If thread hasn't been computed yet,
3604              it is now time to do so.  */
3605           if (thread == -1)
3606             thread = pid_to_thread_id (ptid);
3607           if (bl->owner->thread != thread)
3608             continue;
3609         }
3610
3611       if (bl->owner->task != 0)
3612         {
3613           /* This is a task-specific breakpoint.  Check that ptid
3614              matches that task.  If task hasn't been computed yet,
3615              it is now time to do so.  */
3616           if (task == 0)
3617             task = ada_get_task_number (ptid);
3618           if (bl->owner->task != task)
3619             continue;
3620         }
3621
3622       if (overlay_debugging 
3623           && section_is_overlay (bl->section)
3624           && !section_is_mapped (bl->section))
3625         continue;           /* unmapped overlay -- can't be a match */
3626
3627       return 1;
3628     }
3629
3630   return 0;
3631 }
3632 \f
3633
3634 /* bpstat stuff.  External routines' interfaces are documented
3635    in breakpoint.h.  */
3636
3637 int
3638 is_catchpoint (struct breakpoint *ep)
3639 {
3640   return (ep->type == bp_catchpoint);
3641 }
3642
3643 /* Frees any storage that is part of a bpstat.  Does not walk the
3644    'next' chain.  */
3645
3646 static void
3647 bpstat_free (bpstat bs)
3648 {
3649   if (bs->old_val != NULL)
3650     value_free (bs->old_val);
3651   decref_counted_command_line (&bs->commands);
3652   decref_bp_location (&bs->bp_location_at);
3653   xfree (bs);
3654 }
3655
3656 /* Clear a bpstat so that it says we are not at any breakpoint.
3657    Also free any storage that is part of a bpstat.  */
3658
3659 void
3660 bpstat_clear (bpstat *bsp)
3661 {
3662   bpstat p;
3663   bpstat q;
3664
3665   if (bsp == 0)
3666     return;
3667   p = *bsp;
3668   while (p != NULL)
3669     {
3670       q = p->next;
3671       bpstat_free (p);
3672       p = q;
3673     }
3674   *bsp = NULL;
3675 }
3676
3677 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3678    is part of the bpstat is copied as well.  */
3679
3680 bpstat
3681 bpstat_copy (bpstat bs)
3682 {
3683   bpstat p = NULL;
3684   bpstat tmp;
3685   bpstat retval = NULL;
3686
3687   if (bs == NULL)
3688     return bs;
3689
3690   for (; bs != NULL; bs = bs->next)
3691     {
3692       tmp = (bpstat) xmalloc (sizeof (*tmp));
3693       memcpy (tmp, bs, sizeof (*tmp));
3694       incref_counted_command_line (tmp->commands);
3695       incref_bp_location (tmp->bp_location_at);
3696       if (bs->old_val != NULL)
3697         {
3698           tmp->old_val = value_copy (bs->old_val);
3699           release_value (tmp->old_val);
3700         }
3701
3702       if (p == NULL)
3703         /* This is the first thing in the chain.  */
3704         retval = tmp;
3705       else
3706         p->next = tmp;
3707       p = tmp;
3708     }
3709   p->next = NULL;
3710   return retval;
3711 }
3712
3713 /* Find the bpstat associated with this breakpoint.  */
3714
3715 bpstat
3716 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3717 {
3718   if (bsp == NULL)
3719     return NULL;
3720
3721   for (; bsp != NULL; bsp = bsp->next)
3722     {
3723       if (bsp->breakpoint_at == breakpoint)
3724         return bsp;
3725     }
3726   return NULL;
3727 }
3728
3729 /* Put in *NUM the breakpoint number of the first breakpoint we are
3730    stopped at.  *BSP upon return is a bpstat which points to the
3731    remaining breakpoints stopped at (but which is not guaranteed to be
3732    good for anything but further calls to bpstat_num).
3733
3734    Return 0 if passed a bpstat which does not indicate any breakpoints.
3735    Return -1 if stopped at a breakpoint that has been deleted since
3736    we set it.
3737    Return 1 otherwise.  */
3738
3739 int
3740 bpstat_num (bpstat *bsp, int *num)
3741 {
3742   struct breakpoint *b;
3743
3744   if ((*bsp) == NULL)
3745     return 0;                   /* No more breakpoint values */
3746
3747   /* We assume we'll never have several bpstats that correspond to a
3748      single breakpoint -- otherwise, this function might return the
3749      same number more than once and this will look ugly.  */
3750   b = (*bsp)->breakpoint_at;
3751   *bsp = (*bsp)->next;
3752   if (b == NULL)
3753     return -1;                  /* breakpoint that's been deleted since */
3754
3755   *num = b->number;             /* We have its number */
3756   return 1;
3757 }
3758
3759 /* See breakpoint.h.  */
3760
3761 void
3762 bpstat_clear_actions (void)
3763 {
3764   struct thread_info *tp;
3765   bpstat bs;
3766
3767   if (ptid_equal (inferior_ptid, null_ptid))
3768     return;
3769
3770   tp = find_thread_ptid (inferior_ptid);
3771   if (tp == NULL)
3772     return;
3773
3774   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3775     {
3776       decref_counted_command_line (&bs->commands);
3777
3778       if (bs->old_val != NULL)
3779         {
3780           value_free (bs->old_val);
3781           bs->old_val = NULL;
3782         }
3783     }
3784 }
3785
3786 /* Called when a command is about to proceed the inferior.  */
3787
3788 static void
3789 breakpoint_about_to_proceed (void)
3790 {
3791   if (!ptid_equal (inferior_ptid, null_ptid))
3792     {
3793       struct thread_info *tp = inferior_thread ();
3794
3795       /* Allow inferior function calls in breakpoint commands to not
3796          interrupt the command list.  When the call finishes
3797          successfully, the inferior will be standing at the same
3798          breakpoint as if nothing happened.  */
3799       if (tp->control.in_infcall)
3800         return;
3801     }
3802
3803   breakpoint_proceeded = 1;
3804 }
3805
3806 /* Stub for cleaning up our state if we error-out of a breakpoint
3807    command.  */
3808 static void
3809 cleanup_executing_breakpoints (void *ignore)
3810 {
3811   executing_breakpoint_commands = 0;
3812 }
3813
3814 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3815    or its equivalent.  */
3816
3817 static int
3818 command_line_is_silent (struct command_line *cmd)
3819 {
3820   return cmd && (strcmp ("silent", cmd->line) == 0
3821                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3822 }
3823
3824 /* Execute all the commands associated with all the breakpoints at
3825    this location.  Any of these commands could cause the process to
3826    proceed beyond this point, etc.  We look out for such changes by
3827    checking the global "breakpoint_proceeded" after each command.
3828
3829    Returns true if a breakpoint command resumed the inferior.  In that
3830    case, it is the caller's responsibility to recall it again with the
3831    bpstat of the current thread.  */
3832
3833 static int
3834 bpstat_do_actions_1 (bpstat *bsp)
3835 {
3836   bpstat bs;
3837   struct cleanup *old_chain;
3838   int again = 0;
3839
3840   /* Avoid endless recursion if a `source' command is contained
3841      in bs->commands.  */
3842   if (executing_breakpoint_commands)
3843     return 0;
3844
3845   executing_breakpoint_commands = 1;
3846   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
3847
3848   prevent_dont_repeat ();
3849
3850   /* This pointer will iterate over the list of bpstat's.  */
3851   bs = *bsp;
3852
3853   breakpoint_proceeded = 0;
3854   for (; bs != NULL; bs = bs->next)
3855     {
3856       struct counted_command_line *ccmd;
3857       struct command_line *cmd;
3858       struct cleanup *this_cmd_tree_chain;
3859
3860       /* Take ownership of the BSP's command tree, if it has one.
3861
3862          The command tree could legitimately contain commands like
3863          'step' and 'next', which call clear_proceed_status, which
3864          frees stop_bpstat's command tree.  To make sure this doesn't
3865          free the tree we're executing out from under us, we need to
3866          take ownership of the tree ourselves.  Since a given bpstat's
3867          commands are only executed once, we don't need to copy it; we
3868          can clear the pointer in the bpstat, and make sure we free
3869          the tree when we're done.  */
3870       ccmd = bs->commands;
3871       bs->commands = NULL;
3872       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
3873       cmd = ccmd ? ccmd->commands : NULL;
3874       if (command_line_is_silent (cmd))
3875         {
3876           /* The action has been already done by bpstat_stop_status.  */
3877           cmd = cmd->next;
3878         }
3879
3880       while (cmd != NULL)
3881         {
3882           execute_control_command (cmd);
3883
3884           if (breakpoint_proceeded)
3885             break;
3886           else
3887             cmd = cmd->next;
3888         }
3889
3890       /* We can free this command tree now.  */
3891       do_cleanups (this_cmd_tree_chain);
3892
3893       if (breakpoint_proceeded)
3894         {
3895           if (target_can_async_p ())
3896             /* If we are in async mode, then the target might be still
3897                running, not stopped at any breakpoint, so nothing for
3898                us to do here -- just return to the event loop.  */
3899             ;
3900           else
3901             /* In sync mode, when execute_control_command returns
3902                we're already standing on the next breakpoint.
3903                Breakpoint commands for that stop were not run, since
3904                execute_command does not run breakpoint commands --
3905                only command_line_handler does, but that one is not
3906                involved in execution of breakpoint commands.  So, we
3907                can now execute breakpoint commands.  It should be
3908                noted that making execute_command do bpstat actions is
3909                not an option -- in this case we'll have recursive
3910                invocation of bpstat for each breakpoint with a
3911                command, and can easily blow up GDB stack.  Instead, we
3912                return true, which will trigger the caller to recall us
3913                with the new stop_bpstat.  */
3914             again = 1;
3915           break;
3916         }
3917     }
3918   do_cleanups (old_chain);
3919   return again;
3920 }
3921
3922 void
3923 bpstat_do_actions (void)
3924 {
3925   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
3926
3927   /* Do any commands attached to breakpoint we are stopped at.  */
3928   while (!ptid_equal (inferior_ptid, null_ptid)
3929          && target_has_execution
3930          && !is_exited (inferior_ptid)
3931          && !is_executing (inferior_ptid))
3932     /* Since in sync mode, bpstat_do_actions may resume the inferior,
3933        and only return when it is stopped at the next breakpoint, we
3934        keep doing breakpoint actions until it returns false to
3935        indicate the inferior was not resumed.  */
3936     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
3937       break;
3938
3939   discard_cleanups (cleanup_if_error);
3940 }
3941
3942 /* Print out the (old or new) value associated with a watchpoint.  */
3943
3944 static void
3945 watchpoint_value_print (struct value *val, struct ui_file *stream)
3946 {
3947   if (val == NULL)
3948     fprintf_unfiltered (stream, _("<unreadable>"));
3949   else
3950     {
3951       struct value_print_options opts;
3952       get_user_print_options (&opts);
3953       value_print (val, stream, &opts);
3954     }
3955 }
3956
3957 /* Generic routine for printing messages indicating why we
3958    stopped.  The behavior of this function depends on the value
3959    'print_it' in the bpstat structure.  Under some circumstances we
3960    may decide not to print anything here and delegate the task to
3961    normal_stop().  */
3962
3963 static enum print_stop_action
3964 print_bp_stop_message (bpstat bs)
3965 {
3966   switch (bs->print_it)
3967     {
3968     case print_it_noop:
3969       /* Nothing should be printed for this bpstat entry.  */
3970       return PRINT_UNKNOWN;
3971       break;
3972
3973     case print_it_done:
3974       /* We still want to print the frame, but we already printed the
3975          relevant messages.  */
3976       return PRINT_SRC_AND_LOC;
3977       break;
3978
3979     case print_it_normal:
3980       {
3981         struct breakpoint *b = bs->breakpoint_at;
3982
3983         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
3984            which has since been deleted.  */
3985         if (b == NULL)
3986           return PRINT_UNKNOWN;
3987
3988         /* Normal case.  Call the breakpoint's print_it method.  */
3989         return b->ops->print_it (bs);
3990       }
3991       break;
3992
3993     default:
3994       internal_error (__FILE__, __LINE__,
3995                       _("print_bp_stop_message: unrecognized enum value"));
3996       break;
3997     }
3998 }
3999
4000 /* A helper function that prints a shared library stopped event.  */
4001
4002 static void
4003 print_solib_event (int is_catchpoint)
4004 {
4005   int any_deleted
4006     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4007   int any_added
4008     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4009
4010   if (!is_catchpoint)
4011     {
4012       if (any_added || any_deleted)
4013         ui_out_text (current_uiout,
4014                      _("Stopped due to shared library event:\n"));
4015       else
4016         ui_out_text (current_uiout,
4017                      _("Stopped due to shared library event (no "
4018                        "libraries added or removed)\n"));
4019     }
4020
4021   if (ui_out_is_mi_like_p (current_uiout))
4022     ui_out_field_string (current_uiout, "reason",
4023                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4024
4025   if (any_deleted)
4026     {
4027       struct cleanup *cleanup;
4028       char *name;
4029       int ix;
4030
4031       ui_out_text (current_uiout, _("  Inferior unloaded "));
4032       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4033                                                     "removed");
4034       for (ix = 0;
4035            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4036                         ix, name);
4037            ++ix)
4038         {
4039           if (ix > 0)
4040             ui_out_text (current_uiout, "    ");
4041           ui_out_field_string (current_uiout, "library", name);
4042           ui_out_text (current_uiout, "\n");
4043         }
4044
4045       do_cleanups (cleanup);
4046     }
4047
4048   if (any_added)
4049     {
4050       struct so_list *iter;
4051       int ix;
4052       struct cleanup *cleanup;
4053
4054       ui_out_text (current_uiout, _("  Inferior loaded "));
4055       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4056                                                     "added");
4057       for (ix = 0;
4058            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4059                         ix, iter);
4060            ++ix)
4061         {
4062           if (ix > 0)
4063             ui_out_text (current_uiout, "    ");
4064           ui_out_field_string (current_uiout, "library", iter->so_name);
4065           ui_out_text (current_uiout, "\n");
4066         }
4067
4068       do_cleanups (cleanup);
4069     }
4070 }
4071
4072 /* Print a message indicating what happened.  This is called from
4073    normal_stop().  The input to this routine is the head of the bpstat
4074    list - a list of the eventpoints that caused this stop.  KIND is
4075    the target_waitkind for the stopping event.  This
4076    routine calls the generic print routine for printing a message
4077    about reasons for stopping.  This will print (for example) the
4078    "Breakpoint n," part of the output.  The return value of this
4079    routine is one of:
4080
4081    PRINT_UNKNOWN: Means we printed nothing.
4082    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4083    code to print the location.  An example is 
4084    "Breakpoint 1, " which should be followed by
4085    the location.
4086    PRINT_SRC_ONLY: Means we printed something, but there is no need
4087    to also print the location part of the message.
4088    An example is the catch/throw messages, which
4089    don't require a location appended to the end.
4090    PRINT_NOTHING: We have done some printing and we don't need any 
4091    further info to be printed.  */
4092
4093 enum print_stop_action
4094 bpstat_print (bpstat bs, int kind)
4095 {
4096   int val;
4097
4098   /* Maybe another breakpoint in the chain caused us to stop.
4099      (Currently all watchpoints go on the bpstat whether hit or not.
4100      That probably could (should) be changed, provided care is taken
4101      with respect to bpstat_explains_signal).  */
4102   for (; bs; bs = bs->next)
4103     {
4104       val = print_bp_stop_message (bs);
4105       if (val == PRINT_SRC_ONLY 
4106           || val == PRINT_SRC_AND_LOC 
4107           || val == PRINT_NOTHING)
4108         return val;
4109     }
4110
4111   /* If we had hit a shared library event breakpoint,
4112      print_bp_stop_message would print out this message.  If we hit an
4113      OS-level shared library event, do the same thing.  */
4114   if (kind == TARGET_WAITKIND_LOADED)
4115     {
4116       print_solib_event (0);
4117       return PRINT_NOTHING;
4118     }
4119
4120   /* We reached the end of the chain, or we got a null BS to start
4121      with and nothing was printed.  */
4122   return PRINT_UNKNOWN;
4123 }
4124
4125 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4126    used inside a catch_errors to evaluate the breakpoint condition.
4127    The argument is a "struct expression *" that has been cast to a
4128    "char *" to make it pass through catch_errors.  */
4129
4130 static int
4131 breakpoint_cond_eval (void *exp)
4132 {
4133   struct value *mark = value_mark ();
4134   int i = !value_true (evaluate_expression ((struct expression *) exp));
4135
4136   value_free_to_mark (mark);
4137   return i;
4138 }
4139
4140 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4141
4142 static bpstat
4143 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4144 {
4145   bpstat bs;
4146
4147   bs = (bpstat) xmalloc (sizeof (*bs));
4148   bs->next = NULL;
4149   **bs_link_pointer = bs;
4150   *bs_link_pointer = &bs->next;
4151   bs->breakpoint_at = bl->owner;
4152   bs->bp_location_at = bl;
4153   incref_bp_location (bl);
4154   /* If the condition is false, etc., don't do the commands.  */
4155   bs->commands = NULL;
4156   bs->old_val = NULL;
4157   bs->print_it = print_it_normal;
4158   return bs;
4159 }
4160 \f
4161 /* The target has stopped with waitstatus WS.  Check if any hardware
4162    watchpoints have triggered, according to the target.  */
4163
4164 int
4165 watchpoints_triggered (struct target_waitstatus *ws)
4166 {
4167   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4168   CORE_ADDR addr;
4169   struct breakpoint *b;
4170
4171   if (!stopped_by_watchpoint)
4172     {
4173       /* We were not stopped by a watchpoint.  Mark all watchpoints
4174          as not triggered.  */
4175       ALL_BREAKPOINTS (b)
4176         if (is_hardware_watchpoint (b))
4177           {
4178             struct watchpoint *w = (struct watchpoint *) b;
4179
4180             w->watchpoint_triggered = watch_triggered_no;
4181           }
4182
4183       return 0;
4184     }
4185
4186   if (!target_stopped_data_address (&current_target, &addr))
4187     {
4188       /* We were stopped by a watchpoint, but we don't know where.
4189          Mark all watchpoints as unknown.  */
4190       ALL_BREAKPOINTS (b)
4191         if (is_hardware_watchpoint (b))
4192           {
4193             struct watchpoint *w = (struct watchpoint *) b;
4194
4195             w->watchpoint_triggered = watch_triggered_unknown;
4196           }
4197
4198       return stopped_by_watchpoint;
4199     }
4200
4201   /* The target could report the data address.  Mark watchpoints
4202      affected by this data address as triggered, and all others as not
4203      triggered.  */
4204
4205   ALL_BREAKPOINTS (b)
4206     if (is_hardware_watchpoint (b))
4207       {
4208         struct watchpoint *w = (struct watchpoint *) b;
4209         struct bp_location *loc;
4210
4211         w->watchpoint_triggered = watch_triggered_no;
4212         for (loc = b->loc; loc; loc = loc->next)
4213           {
4214             if (is_masked_watchpoint (b))
4215               {
4216                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4217                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4218
4219                 if (newaddr == start)
4220                   {
4221                     w->watchpoint_triggered = watch_triggered_yes;
4222                     break;
4223                   }
4224               }
4225             /* Exact match not required.  Within range is sufficient.  */
4226             else if (target_watchpoint_addr_within_range (&current_target,
4227                                                          addr, loc->address,
4228                                                          loc->length))
4229               {
4230                 w->watchpoint_triggered = watch_triggered_yes;
4231                 break;
4232               }
4233           }
4234       }
4235
4236   return 1;
4237 }
4238
4239 /* Possible return values for watchpoint_check (this can't be an enum
4240    because of check_errors).  */
4241 /* The watchpoint has been deleted.  */
4242 #define WP_DELETED 1
4243 /* The value has changed.  */
4244 #define WP_VALUE_CHANGED 2
4245 /* The value has not changed.  */
4246 #define WP_VALUE_NOT_CHANGED 3
4247 /* Ignore this watchpoint, no matter if the value changed or not.  */
4248 #define WP_IGNORE 4
4249
4250 #define BP_TEMPFLAG 1
4251 #define BP_HARDWAREFLAG 2
4252
4253 /* Evaluate watchpoint condition expression and check if its value
4254    changed.
4255
4256    P should be a pointer to struct bpstat, but is defined as a void *
4257    in order for this function to be usable with catch_errors.  */
4258
4259 static int
4260 watchpoint_check (void *p)
4261 {
4262   bpstat bs = (bpstat) p;
4263   struct watchpoint *b;
4264   struct frame_info *fr;
4265   int within_current_scope;
4266
4267   /* BS is built from an existing struct breakpoint.  */
4268   gdb_assert (bs->breakpoint_at != NULL);
4269   b = (struct watchpoint *) bs->breakpoint_at;
4270
4271   /* If this is a local watchpoint, we only want to check if the
4272      watchpoint frame is in scope if the current thread is the thread
4273      that was used to create the watchpoint.  */
4274   if (!watchpoint_in_thread_scope (b))
4275     return WP_IGNORE;
4276
4277   if (b->exp_valid_block == NULL)
4278     within_current_scope = 1;
4279   else
4280     {
4281       struct frame_info *frame = get_current_frame ();
4282       struct gdbarch *frame_arch = get_frame_arch (frame);
4283       CORE_ADDR frame_pc = get_frame_pc (frame);
4284
4285       /* in_function_epilogue_p() returns a non-zero value if we're
4286          still in the function but the stack frame has already been
4287          invalidated.  Since we can't rely on the values of local
4288          variables after the stack has been destroyed, we are treating
4289          the watchpoint in that state as `not changed' without further
4290          checking.  Don't mark watchpoints as changed if the current
4291          frame is in an epilogue - even if they are in some other
4292          frame, our view of the stack is likely to be wrong and
4293          frame_find_by_id could error out.  */
4294       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4295         return WP_IGNORE;
4296
4297       fr = frame_find_by_id (b->watchpoint_frame);
4298       within_current_scope = (fr != NULL);
4299
4300       /* If we've gotten confused in the unwinder, we might have
4301          returned a frame that can't describe this variable.  */
4302       if (within_current_scope)
4303         {
4304           struct symbol *function;
4305
4306           function = get_frame_function (fr);
4307           if (function == NULL
4308               || !contained_in (b->exp_valid_block,
4309                                 SYMBOL_BLOCK_VALUE (function)))
4310             within_current_scope = 0;
4311         }
4312
4313       if (within_current_scope)
4314         /* If we end up stopping, the current frame will get selected
4315            in normal_stop.  So this call to select_frame won't affect
4316            the user.  */
4317         select_frame (fr);
4318     }
4319
4320   if (within_current_scope)
4321     {
4322       /* We use value_{,free_to_}mark because it could be a *long*
4323          time before we return to the command level and call
4324          free_all_values.  We can't call free_all_values because we
4325          might be in the middle of evaluating a function call.  */
4326
4327       int pc = 0;
4328       struct value *mark;
4329       struct value *new_val;
4330
4331       if (is_masked_watchpoint (&b->base))
4332         /* Since we don't know the exact trigger address (from
4333            stopped_data_address), just tell the user we've triggered
4334            a mask watchpoint.  */
4335         return WP_VALUE_CHANGED;
4336
4337       mark = value_mark ();
4338       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4339
4340       /* We use value_equal_contents instead of value_equal because
4341          the latter coerces an array to a pointer, thus comparing just
4342          the address of the array instead of its contents.  This is
4343          not what we want.  */
4344       if ((b->val != NULL) != (new_val != NULL)
4345           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4346         {
4347           if (new_val != NULL)
4348             {
4349               release_value (new_val);
4350               value_free_to_mark (mark);
4351             }
4352           bs->old_val = b->val;
4353           b->val = new_val;
4354           b->val_valid = 1;
4355           return WP_VALUE_CHANGED;
4356         }
4357       else
4358         {
4359           /* Nothing changed.  */
4360           value_free_to_mark (mark);
4361           return WP_VALUE_NOT_CHANGED;
4362         }
4363     }
4364   else
4365     {
4366       struct ui_out *uiout = current_uiout;
4367
4368       /* This seems like the only logical thing to do because
4369          if we temporarily ignored the watchpoint, then when
4370          we reenter the block in which it is valid it contains
4371          garbage (in the case of a function, it may have two
4372          garbage values, one before and one after the prologue).
4373          So we can't even detect the first assignment to it and
4374          watch after that (since the garbage may or may not equal
4375          the first value assigned).  */
4376       /* We print all the stop information in
4377          breakpoint_ops->print_it, but in this case, by the time we
4378          call breakpoint_ops->print_it this bp will be deleted
4379          already.  So we have no choice but print the information
4380          here.  */
4381       if (ui_out_is_mi_like_p (uiout))
4382         ui_out_field_string
4383           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4384       ui_out_text (uiout, "\nWatchpoint ");
4385       ui_out_field_int (uiout, "wpnum", b->base.number);
4386       ui_out_text (uiout,
4387                    " deleted because the program has left the block in\n\
4388 which its expression is valid.\n");     
4389
4390       /* Make sure the watchpoint's commands aren't executed.  */
4391       decref_counted_command_line (&b->base.commands);
4392       watchpoint_del_at_next_stop (b);
4393
4394       return WP_DELETED;
4395     }
4396 }
4397
4398 /* Return true if it looks like target has stopped due to hitting
4399    breakpoint location BL.  This function does not check if we should
4400    stop, only if BL explains the stop.  */
4401
4402 static int
4403 bpstat_check_location (const struct bp_location *bl,
4404                        struct address_space *aspace, CORE_ADDR bp_addr,
4405                        const struct target_waitstatus *ws)
4406 {
4407   struct breakpoint *b = bl->owner;
4408
4409   /* BL is from an existing breakpoint.  */
4410   gdb_assert (b != NULL);
4411
4412   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4413 }
4414
4415 /* Determine if the watched values have actually changed, and we
4416    should stop.  If not, set BS->stop to 0.  */
4417
4418 static void
4419 bpstat_check_watchpoint (bpstat bs)
4420 {
4421   const struct bp_location *bl;
4422   struct watchpoint *b;
4423
4424   /* BS is built for existing struct breakpoint.  */
4425   bl = bs->bp_location_at;
4426   gdb_assert (bl != NULL);
4427   b = (struct watchpoint *) bs->breakpoint_at;
4428   gdb_assert (b != NULL);
4429
4430     {
4431       int must_check_value = 0;
4432       
4433       if (b->base.type == bp_watchpoint)
4434         /* For a software watchpoint, we must always check the
4435            watched value.  */
4436         must_check_value = 1;
4437       else if (b->watchpoint_triggered == watch_triggered_yes)
4438         /* We have a hardware watchpoint (read, write, or access)
4439            and the target earlier reported an address watched by
4440            this watchpoint.  */
4441         must_check_value = 1;
4442       else if (b->watchpoint_triggered == watch_triggered_unknown
4443                && b->base.type == bp_hardware_watchpoint)
4444         /* We were stopped by a hardware watchpoint, but the target could
4445            not report the data address.  We must check the watchpoint's
4446            value.  Access and read watchpoints are out of luck; without
4447            a data address, we can't figure it out.  */
4448         must_check_value = 1;
4449
4450       if (must_check_value)
4451         {
4452           char *message
4453             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4454                           b->base.number);
4455           struct cleanup *cleanups = make_cleanup (xfree, message);
4456           int e = catch_errors (watchpoint_check, bs, message,
4457                                 RETURN_MASK_ALL);
4458           do_cleanups (cleanups);
4459           switch (e)
4460             {
4461             case WP_DELETED:
4462               /* We've already printed what needs to be printed.  */
4463               bs->print_it = print_it_done;
4464               /* Stop.  */
4465               break;
4466             case WP_IGNORE:
4467               bs->print_it = print_it_noop;
4468               bs->stop = 0;
4469               break;
4470             case WP_VALUE_CHANGED:
4471               if (b->base.type == bp_read_watchpoint)
4472                 {
4473                   /* There are two cases to consider here:
4474
4475                      1. We're watching the triggered memory for reads.
4476                      In that case, trust the target, and always report
4477                      the watchpoint hit to the user.  Even though
4478                      reads don't cause value changes, the value may
4479                      have changed since the last time it was read, and
4480                      since we're not trapping writes, we will not see
4481                      those, and as such we should ignore our notion of
4482                      old value.
4483
4484                      2. We're watching the triggered memory for both
4485                      reads and writes.  There are two ways this may
4486                      happen:
4487
4488                      2.1. This is a target that can't break on data
4489                      reads only, but can break on accesses (reads or
4490                      writes), such as e.g., x86.  We detect this case
4491                      at the time we try to insert read watchpoints.
4492
4493                      2.2. Otherwise, the target supports read
4494                      watchpoints, but, the user set an access or write
4495                      watchpoint watching the same memory as this read
4496                      watchpoint.
4497
4498                      If we're watching memory writes as well as reads,
4499                      ignore watchpoint hits when we find that the
4500                      value hasn't changed, as reads don't cause
4501                      changes.  This still gives false positives when
4502                      the program writes the same value to memory as
4503                      what there was already in memory (we will confuse
4504                      it for a read), but it's much better than
4505                      nothing.  */
4506
4507                   int other_write_watchpoint = 0;
4508
4509                   if (bl->watchpoint_type == hw_read)
4510                     {
4511                       struct breakpoint *other_b;
4512
4513                       ALL_BREAKPOINTS (other_b)
4514                         if (other_b->type == bp_hardware_watchpoint
4515                             || other_b->type == bp_access_watchpoint)
4516                           {
4517                             struct watchpoint *other_w =
4518                               (struct watchpoint *) other_b;
4519
4520                             if (other_w->watchpoint_triggered
4521                                 == watch_triggered_yes)
4522                               {
4523                                 other_write_watchpoint = 1;
4524                                 break;
4525                               }
4526                           }
4527                     }
4528
4529                   if (other_write_watchpoint
4530                       || bl->watchpoint_type == hw_access)
4531                     {
4532                       /* We're watching the same memory for writes,
4533                          and the value changed since the last time we
4534                          updated it, so this trap must be for a write.
4535                          Ignore it.  */
4536                       bs->print_it = print_it_noop;
4537                       bs->stop = 0;
4538                     }
4539                 }
4540               break;
4541             case WP_VALUE_NOT_CHANGED:
4542               if (b->base.type == bp_hardware_watchpoint
4543                   || b->base.type == bp_watchpoint)
4544                 {
4545                   /* Don't stop: write watchpoints shouldn't fire if
4546                      the value hasn't changed.  */
4547                   bs->print_it = print_it_noop;
4548                   bs->stop = 0;
4549                 }
4550               /* Stop.  */
4551               break;
4552             default:
4553               /* Can't happen.  */
4554             case 0:
4555               /* Error from catch_errors.  */
4556               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
4557               watchpoint_del_at_next_stop (b);
4558               /* We've already printed what needs to be printed.  */
4559               bs->print_it = print_it_done;
4560               break;
4561             }
4562         }
4563       else      /* must_check_value == 0 */
4564         {
4565           /* This is a case where some watchpoint(s) triggered, but
4566              not at the address of this watchpoint, or else no
4567              watchpoint triggered after all.  So don't print
4568              anything for this watchpoint.  */
4569           bs->print_it = print_it_noop;
4570           bs->stop = 0;
4571         }
4572     }
4573 }
4574
4575
4576 /* Check conditions (condition proper, frame, thread and ignore count)
4577    of breakpoint referred to by BS.  If we should not stop for this
4578    breakpoint, set BS->stop to 0.  */
4579
4580 static void
4581 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4582 {
4583   int thread_id = pid_to_thread_id (ptid);
4584   const struct bp_location *bl;
4585   struct breakpoint *b;
4586
4587   /* BS is built for existing struct breakpoint.  */
4588   bl = bs->bp_location_at;
4589   gdb_assert (bl != NULL);
4590   b = bs->breakpoint_at;
4591   gdb_assert (b != NULL);
4592
4593   /* Even if the target evaluated the condition on its end and notified GDB, we
4594      need to do so again since GDB does not know if we stopped due to a
4595      breakpoint or a single step breakpoint.  */
4596
4597   if (frame_id_p (b->frame_id)
4598       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4599     bs->stop = 0;
4600   else if (bs->stop)
4601     {
4602       int value_is_zero = 0;
4603       struct expression *cond;
4604
4605       /* Evaluate Python breakpoints that have a "stop"
4606          method implemented.  */
4607       if (b->py_bp_object)
4608         bs->stop = gdbpy_should_stop (b->py_bp_object);
4609
4610       if (is_watchpoint (b))
4611         {
4612           struct watchpoint *w = (struct watchpoint *) b;
4613
4614           cond = w->cond_exp;
4615         }
4616       else
4617         cond = bl->cond;
4618
4619       if (cond && b->disposition != disp_del_at_next_stop)
4620         {
4621           int within_current_scope = 1;
4622           struct watchpoint * w;
4623
4624           /* We use value_mark and value_free_to_mark because it could
4625              be a long time before we return to the command level and
4626              call free_all_values.  We can't call free_all_values
4627              because we might be in the middle of evaluating a
4628              function call.  */
4629           struct value *mark = value_mark ();
4630
4631           if (is_watchpoint (b))
4632             w = (struct watchpoint *) b;
4633           else
4634             w = NULL;
4635
4636           /* Need to select the frame, with all that implies so that
4637              the conditions will have the right context.  Because we
4638              use the frame, we will not see an inlined function's
4639              variables when we arrive at a breakpoint at the start
4640              of the inlined function; the current frame will be the
4641              call site.  */
4642           if (w == NULL || w->cond_exp_valid_block == NULL)
4643             select_frame (get_current_frame ());
4644           else
4645             {
4646               struct frame_info *frame;
4647
4648               /* For local watchpoint expressions, which particular
4649                  instance of a local is being watched matters, so we
4650                  keep track of the frame to evaluate the expression
4651                  in.  To evaluate the condition however, it doesn't
4652                  really matter which instantiation of the function
4653                  where the condition makes sense triggers the
4654                  watchpoint.  This allows an expression like "watch
4655                  global if q > 10" set in `func', catch writes to
4656                  global on all threads that call `func', or catch
4657                  writes on all recursive calls of `func' by a single
4658                  thread.  We simply always evaluate the condition in
4659                  the innermost frame that's executing where it makes
4660                  sense to evaluate the condition.  It seems
4661                  intuitive.  */
4662               frame = block_innermost_frame (w->cond_exp_valid_block);
4663               if (frame != NULL)
4664                 select_frame (frame);
4665               else
4666                 within_current_scope = 0;
4667             }
4668           if (within_current_scope)
4669             value_is_zero
4670               = catch_errors (breakpoint_cond_eval, cond,
4671                               "Error in testing breakpoint condition:\n",
4672                               RETURN_MASK_ALL);
4673           else
4674             {
4675               warning (_("Watchpoint condition cannot be tested "
4676                          "in the current scope"));
4677               /* If we failed to set the right context for this
4678                  watchpoint, unconditionally report it.  */
4679               value_is_zero = 0;
4680             }
4681           /* FIXME-someday, should give breakpoint #.  */
4682           value_free_to_mark (mark);
4683         }
4684
4685       if (cond && value_is_zero)
4686         {
4687           bs->stop = 0;
4688         }
4689       else if (b->thread != -1 && b->thread != thread_id)
4690         {
4691           bs->stop = 0;
4692         }
4693       else if (b->ignore_count > 0)
4694         {
4695           b->ignore_count--;
4696           annotate_ignore_count_change ();
4697           bs->stop = 0;
4698           /* Increase the hit count even though we don't stop.  */
4699           ++(b->hit_count);
4700           observer_notify_breakpoint_modified (b);
4701         }       
4702     }
4703 }
4704
4705
4706 /* Get a bpstat associated with having just stopped at address
4707    BP_ADDR in thread PTID.
4708
4709    Determine whether we stopped at a breakpoint, etc, or whether we
4710    don't understand this stop.  Result is a chain of bpstat's such
4711    that:
4712
4713    if we don't understand the stop, the result is a null pointer.
4714
4715    if we understand why we stopped, the result is not null.
4716
4717    Each element of the chain refers to a particular breakpoint or
4718    watchpoint at which we have stopped.  (We may have stopped for
4719    several reasons concurrently.)
4720
4721    Each element of the chain has valid next, breakpoint_at,
4722    commands, FIXME??? fields.  */
4723
4724 bpstat
4725 bpstat_stop_status (struct address_space *aspace,
4726                     CORE_ADDR bp_addr, ptid_t ptid,
4727                     const struct target_waitstatus *ws)
4728 {
4729   struct breakpoint *b = NULL;
4730   struct bp_location *bl;
4731   struct bp_location *loc;
4732   /* First item of allocated bpstat's.  */
4733   bpstat bs_head = NULL, *bs_link = &bs_head;
4734   /* Pointer to the last thing in the chain currently.  */
4735   bpstat bs;
4736   int ix;
4737   int need_remove_insert;
4738   int removed_any;
4739
4740   /* First, build the bpstat chain with locations that explain a
4741      target stop, while being careful to not set the target running,
4742      as that may invalidate locations (in particular watchpoint
4743      locations are recreated).  Resuming will happen here with
4744      breakpoint conditions or watchpoint expressions that include
4745      inferior function calls.  */
4746
4747   ALL_BREAKPOINTS (b)
4748     {
4749       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4750         continue;
4751
4752       for (bl = b->loc; bl != NULL; bl = bl->next)
4753         {
4754           /* For hardware watchpoints, we look only at the first
4755              location.  The watchpoint_check function will work on the
4756              entire expression, not the individual locations.  For
4757              read watchpoints, the watchpoints_triggered function has
4758              checked all locations already.  */
4759           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4760             break;
4761
4762           if (bl->shlib_disabled)
4763             continue;
4764
4765           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
4766             continue;
4767
4768           /* Come here if it's a watchpoint, or if the break address
4769              matches.  */
4770
4771           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4772                                                    explain stop.  */
4773
4774           /* Assume we stop.  Should we find a watchpoint that is not
4775              actually triggered, or if the condition of the breakpoint
4776              evaluates as false, we'll reset 'stop' to 0.  */
4777           bs->stop = 1;
4778           bs->print = 1;
4779
4780           /* If this is a scope breakpoint, mark the associated
4781              watchpoint as triggered so that we will handle the
4782              out-of-scope event.  We'll get to the watchpoint next
4783              iteration.  */
4784           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4785             {
4786               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4787
4788               w->watchpoint_triggered = watch_triggered_yes;
4789             }
4790         }
4791     }
4792
4793   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4794     {
4795       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4796         {
4797           bs = bpstat_alloc (loc, &bs_link);
4798           /* For hits of moribund locations, we should just proceed.  */
4799           bs->stop = 0;
4800           bs->print = 0;
4801           bs->print_it = print_it_noop;
4802         }
4803     }
4804
4805   /* A bit of special processing for shlib breakpoints.  We need to
4806      process solib loading here, so that the lists of loaded and
4807      unloaded libraries are correct before we handle "catch load" and
4808      "catch unload".  */
4809   for (bs = bs_head; bs != NULL; bs = bs->next)
4810     {
4811       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
4812         {
4813           handle_solib_event ();
4814           break;
4815         }
4816     }
4817
4818   /* Now go through the locations that caused the target to stop, and
4819      check whether we're interested in reporting this stop to higher
4820      layers, or whether we should resume the target transparently.  */
4821
4822   removed_any = 0;
4823
4824   for (bs = bs_head; bs != NULL; bs = bs->next)
4825     {
4826       if (!bs->stop)
4827         continue;
4828
4829       b = bs->breakpoint_at;
4830       b->ops->check_status (bs);
4831       if (bs->stop)
4832         {
4833           bpstat_check_breakpoint_conditions (bs, ptid);
4834
4835           if (bs->stop)
4836             {
4837               ++(b->hit_count);
4838               observer_notify_breakpoint_modified (b);
4839
4840               /* We will stop here.  */
4841               if (b->disposition == disp_disable)
4842                 {
4843                   --(b->enable_count);
4844                   if (b->enable_count <= 0
4845                       && b->enable_state != bp_permanent)
4846                     b->enable_state = bp_disabled;
4847                   removed_any = 1;
4848                 }
4849               if (b->silent)
4850                 bs->print = 0;
4851               bs->commands = b->commands;
4852               incref_counted_command_line (bs->commands);
4853               if (command_line_is_silent (bs->commands
4854                                           ? bs->commands->commands : NULL))
4855                 bs->print = 0;
4856             }
4857
4858         }
4859
4860       /* Print nothing for this entry if we don't stop or don't
4861          print.  */
4862       if (!bs->stop || !bs->print)
4863         bs->print_it = print_it_noop;
4864     }
4865
4866   /* If we aren't stopping, the value of some hardware watchpoint may
4867      not have changed, but the intermediate memory locations we are
4868      watching may have.  Don't bother if we're stopping; this will get
4869      done later.  */
4870   need_remove_insert = 0;
4871   if (! bpstat_causes_stop (bs_head))
4872     for (bs = bs_head; bs != NULL; bs = bs->next)
4873       if (!bs->stop
4874           && bs->breakpoint_at
4875           && is_hardware_watchpoint (bs->breakpoint_at))
4876         {
4877           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
4878
4879           update_watchpoint (w, 0 /* don't reparse.  */);
4880           need_remove_insert = 1;
4881         }
4882
4883   if (need_remove_insert)
4884     update_global_location_list (1);
4885   else if (removed_any)
4886     update_global_location_list (0);
4887
4888   return bs_head;
4889 }
4890
4891 static void
4892 handle_jit_event (void)
4893 {
4894   struct frame_info *frame;
4895   struct gdbarch *gdbarch;
4896
4897   /* Switch terminal for any messages produced by
4898      breakpoint_re_set.  */
4899   target_terminal_ours_for_output ();
4900
4901   frame = get_current_frame ();
4902   gdbarch = get_frame_arch (frame);
4903
4904   jit_event_handler (gdbarch);
4905
4906   target_terminal_inferior ();
4907 }
4908
4909 /* Handle an solib event by calling solib_add.  */
4910
4911 void
4912 handle_solib_event (void)
4913 {
4914   clear_program_space_solib_cache (current_inferior ()->pspace);
4915
4916   /* Check for any newly added shared libraries if we're supposed to
4917      be adding them automatically.  Switch terminal for any messages
4918      produced by breakpoint_re_set.  */
4919   target_terminal_ours_for_output ();
4920 #ifdef SOLIB_ADD
4921   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
4922 #else
4923   solib_add (NULL, 0, &current_target, auto_solib_add);
4924 #endif
4925   target_terminal_inferior ();
4926 }
4927
4928 /* Prepare WHAT final decision for infrun.  */
4929
4930 /* Decide what infrun needs to do with this bpstat.  */
4931
4932 struct bpstat_what
4933 bpstat_what (bpstat bs_head)
4934 {
4935   struct bpstat_what retval;
4936   int jit_event = 0;
4937   bpstat bs;
4938
4939   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
4940   retval.call_dummy = STOP_NONE;
4941   retval.is_longjmp = 0;
4942
4943   for (bs = bs_head; bs != NULL; bs = bs->next)
4944     {
4945       /* Extract this BS's action.  After processing each BS, we check
4946          if its action overrides all we've seem so far.  */
4947       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
4948       enum bptype bptype;
4949
4950       if (bs->breakpoint_at == NULL)
4951         {
4952           /* I suspect this can happen if it was a momentary
4953              breakpoint which has since been deleted.  */
4954           bptype = bp_none;
4955         }
4956       else
4957         bptype = bs->breakpoint_at->type;
4958
4959       switch (bptype)
4960         {
4961         case bp_none:
4962           break;
4963         case bp_breakpoint:
4964         case bp_hardware_breakpoint:
4965         case bp_until:
4966         case bp_finish:
4967         case bp_shlib_event:
4968           if (bs->stop)
4969             {
4970               if (bs->print)
4971                 this_action = BPSTAT_WHAT_STOP_NOISY;
4972               else
4973                 this_action = BPSTAT_WHAT_STOP_SILENT;
4974             }
4975           else
4976             this_action = BPSTAT_WHAT_SINGLE;
4977           break;
4978         case bp_watchpoint:
4979         case bp_hardware_watchpoint:
4980         case bp_read_watchpoint:
4981         case bp_access_watchpoint:
4982           if (bs->stop)
4983             {
4984               if (bs->print)
4985                 this_action = BPSTAT_WHAT_STOP_NOISY;
4986               else
4987                 this_action = BPSTAT_WHAT_STOP_SILENT;
4988             }
4989           else
4990             {
4991               /* There was a watchpoint, but we're not stopping.
4992                  This requires no further action.  */
4993             }
4994           break;
4995         case bp_longjmp:
4996         case bp_exception:
4997           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
4998           retval.is_longjmp = bptype == bp_longjmp;
4999           break;
5000         case bp_longjmp_resume:
5001         case bp_exception_resume:
5002           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5003           retval.is_longjmp = bptype == bp_longjmp_resume;
5004           break;
5005         case bp_step_resume:
5006           if (bs->stop)
5007             this_action = BPSTAT_WHAT_STEP_RESUME;
5008           else
5009             {
5010               /* It is for the wrong frame.  */
5011               this_action = BPSTAT_WHAT_SINGLE;
5012             }
5013           break;
5014         case bp_hp_step_resume:
5015           if (bs->stop)
5016             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5017           else
5018             {
5019               /* It is for the wrong frame.  */
5020               this_action = BPSTAT_WHAT_SINGLE;
5021             }
5022           break;
5023         case bp_watchpoint_scope:
5024         case bp_thread_event:
5025         case bp_overlay_event:
5026         case bp_longjmp_master:
5027         case bp_std_terminate_master:
5028         case bp_exception_master:
5029           this_action = BPSTAT_WHAT_SINGLE;
5030           break;
5031         case bp_catchpoint:
5032           if (bs->stop)
5033             {
5034               if (bs->print)
5035                 this_action = BPSTAT_WHAT_STOP_NOISY;
5036               else
5037                 this_action = BPSTAT_WHAT_STOP_SILENT;
5038             }
5039           else
5040             {
5041               /* There was a catchpoint, but we're not stopping.
5042                  This requires no further action.  */
5043             }
5044           break;
5045         case bp_jit_event:
5046           jit_event = 1;
5047           this_action = BPSTAT_WHAT_SINGLE;
5048           break;
5049         case bp_call_dummy:
5050           /* Make sure the action is stop (silent or noisy),
5051              so infrun.c pops the dummy frame.  */
5052           retval.call_dummy = STOP_STACK_DUMMY;
5053           this_action = BPSTAT_WHAT_STOP_SILENT;
5054           break;
5055         case bp_std_terminate:
5056           /* Make sure the action is stop (silent or noisy),
5057              so infrun.c pops the dummy frame.  */
5058           retval.call_dummy = STOP_STD_TERMINATE;
5059           this_action = BPSTAT_WHAT_STOP_SILENT;
5060           break;
5061         case bp_tracepoint:
5062         case bp_fast_tracepoint:
5063         case bp_static_tracepoint:
5064           /* Tracepoint hits should not be reported back to GDB, and
5065              if one got through somehow, it should have been filtered
5066              out already.  */
5067           internal_error (__FILE__, __LINE__,
5068                           _("bpstat_what: tracepoint encountered"));
5069           break;
5070         case bp_gnu_ifunc_resolver:
5071           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5072           this_action = BPSTAT_WHAT_SINGLE;
5073           break;
5074         case bp_gnu_ifunc_resolver_return:
5075           /* The breakpoint will be removed, execution will restart from the
5076              PC of the former breakpoint.  */
5077           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5078           break;
5079         default:
5080           internal_error (__FILE__, __LINE__,
5081                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5082         }
5083
5084       retval.main_action = max (retval.main_action, this_action);
5085     }
5086
5087   /* These operations may affect the bs->breakpoint_at state so they are
5088      delayed after MAIN_ACTION is decided above.  */
5089
5090   if (jit_event)
5091     {
5092       if (debug_infrun)
5093         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5094
5095       handle_jit_event ();
5096     }
5097
5098   for (bs = bs_head; bs != NULL; bs = bs->next)
5099     {
5100       struct breakpoint *b = bs->breakpoint_at;
5101
5102       if (b == NULL)
5103         continue;
5104       switch (b->type)
5105         {
5106         case bp_gnu_ifunc_resolver:
5107           gnu_ifunc_resolver_stop (b);
5108           break;
5109         case bp_gnu_ifunc_resolver_return:
5110           gnu_ifunc_resolver_return_stop (b);
5111           break;
5112         }
5113     }
5114
5115   return retval;
5116 }
5117
5118 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5119    without hardware support).  This isn't related to a specific bpstat,
5120    just to things like whether watchpoints are set.  */
5121
5122 int
5123 bpstat_should_step (void)
5124 {
5125   struct breakpoint *b;
5126
5127   ALL_BREAKPOINTS (b)
5128     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5129       return 1;
5130   return 0;
5131 }
5132
5133 int
5134 bpstat_causes_stop (bpstat bs)
5135 {
5136   for (; bs != NULL; bs = bs->next)
5137     if (bs->stop)
5138       return 1;
5139
5140   return 0;
5141 }
5142
5143 \f
5144
5145 /* Compute a string of spaces suitable to indent the next line
5146    so it starts at the position corresponding to the table column
5147    named COL_NAME in the currently active table of UIOUT.  */
5148
5149 static char *
5150 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5151 {
5152   static char wrap_indent[80];
5153   int i, total_width, width, align;
5154   char *text;
5155
5156   total_width = 0;
5157   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5158     {
5159       if (strcmp (text, col_name) == 0)
5160         {
5161           gdb_assert (total_width < sizeof wrap_indent);
5162           memset (wrap_indent, ' ', total_width);
5163           wrap_indent[total_width] = 0;
5164
5165           return wrap_indent;
5166         }
5167
5168       total_width += width + 1;
5169     }
5170
5171   return NULL;
5172 }
5173
5174 /* Determine if the locations of this breakpoint will have their conditions
5175    evaluated by the target, host or a mix of both.  Returns the following:
5176
5177     "host": Host evals condition.
5178     "host or target": Host or Target evals condition.
5179     "target": Target evals condition.
5180 */
5181
5182 static const char *
5183 bp_condition_evaluator (struct breakpoint *b)
5184 {
5185   struct bp_location *bl;
5186   char host_evals = 0;
5187   char target_evals = 0;
5188
5189   if (!b)
5190     return NULL;
5191
5192   if (!is_breakpoint (b))
5193     return NULL;
5194
5195   if (gdb_evaluates_breakpoint_condition_p ()
5196       || !target_supports_evaluation_of_breakpoint_conditions ())
5197     return condition_evaluation_host;
5198
5199   for (bl = b->loc; bl; bl = bl->next)
5200     {
5201       if (bl->cond_bytecode)
5202         target_evals++;
5203       else
5204         host_evals++;
5205     }
5206
5207   if (host_evals && target_evals)
5208     return condition_evaluation_both;
5209   else if (target_evals)
5210     return condition_evaluation_target;
5211   else
5212     return condition_evaluation_host;
5213 }
5214
5215 /* Determine the breakpoint location's condition evaluator.  This is
5216    similar to bp_condition_evaluator, but for locations.  */
5217
5218 static const char *
5219 bp_location_condition_evaluator (struct bp_location *bl)
5220 {
5221   if (bl && !is_breakpoint (bl->owner))
5222     return NULL;
5223
5224   if (gdb_evaluates_breakpoint_condition_p ()
5225       || !target_supports_evaluation_of_breakpoint_conditions ())
5226     return condition_evaluation_host;
5227
5228   if (bl && bl->cond_bytecode)
5229     return condition_evaluation_target;
5230   else
5231     return condition_evaluation_host;
5232 }
5233
5234 /* Print the LOC location out of the list of B->LOC locations.  */
5235
5236 static void
5237 print_breakpoint_location (struct breakpoint *b,
5238                            struct bp_location *loc)
5239 {
5240   struct ui_out *uiout = current_uiout;
5241   struct cleanup *old_chain = save_current_program_space ();
5242
5243   if (loc != NULL && loc->shlib_disabled)
5244     loc = NULL;
5245
5246   if (loc != NULL)
5247     set_current_program_space (loc->pspace);
5248
5249   if (b->display_canonical)
5250     ui_out_field_string (uiout, "what", b->addr_string);
5251   else if (loc && loc->source_file)
5252     {
5253       struct symbol *sym 
5254         = find_pc_sect_function (loc->address, loc->section);
5255       if (sym)
5256         {
5257           ui_out_text (uiout, "in ");
5258           ui_out_field_string (uiout, "func",
5259                                SYMBOL_PRINT_NAME (sym));
5260           ui_out_text (uiout, " ");
5261           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5262           ui_out_text (uiout, "at ");
5263         }
5264       ui_out_field_string (uiout, "file", loc->source_file);
5265       ui_out_text (uiout, ":");
5266       
5267       if (ui_out_is_mi_like_p (uiout))
5268         {
5269           struct symtab_and_line sal = find_pc_line (loc->address, 0);
5270           char *fullname = symtab_to_fullname (sal.symtab);
5271           
5272           if (fullname)
5273             ui_out_field_string (uiout, "fullname", fullname);
5274         }
5275       
5276       ui_out_field_int (uiout, "line", loc->line_number);
5277     }
5278   else if (loc)
5279     {
5280       struct ui_file *stb = mem_fileopen ();
5281       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5282
5283       print_address_symbolic (loc->gdbarch, loc->address, stb,
5284                               demangle, "");
5285       ui_out_field_stream (uiout, "at", stb);
5286
5287       do_cleanups (stb_chain);
5288     }
5289   else
5290     ui_out_field_string (uiout, "pending", b->addr_string);
5291
5292   if (loc && is_breakpoint (b)
5293       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5294       && bp_condition_evaluator (b) == condition_evaluation_both)
5295     {
5296       ui_out_text (uiout, " (");
5297       ui_out_field_string (uiout, "evaluated-by",
5298                            bp_location_condition_evaluator (loc));
5299       ui_out_text (uiout, ")");
5300     }
5301
5302   do_cleanups (old_chain);
5303 }
5304
5305 static const char *
5306 bptype_string (enum bptype type)
5307 {
5308   struct ep_type_description
5309     {
5310       enum bptype type;
5311       char *description;
5312     };
5313   static struct ep_type_description bptypes[] =
5314   {
5315     {bp_none, "?deleted?"},
5316     {bp_breakpoint, "breakpoint"},
5317     {bp_hardware_breakpoint, "hw breakpoint"},
5318     {bp_until, "until"},
5319     {bp_finish, "finish"},
5320     {bp_watchpoint, "watchpoint"},
5321     {bp_hardware_watchpoint, "hw watchpoint"},
5322     {bp_read_watchpoint, "read watchpoint"},
5323     {bp_access_watchpoint, "acc watchpoint"},
5324     {bp_longjmp, "longjmp"},
5325     {bp_longjmp_resume, "longjmp resume"},
5326     {bp_exception, "exception"},
5327     {bp_exception_resume, "exception resume"},
5328     {bp_step_resume, "step resume"},
5329     {bp_hp_step_resume, "high-priority step resume"},
5330     {bp_watchpoint_scope, "watchpoint scope"},
5331     {bp_call_dummy, "call dummy"},
5332     {bp_std_terminate, "std::terminate"},
5333     {bp_shlib_event, "shlib events"},
5334     {bp_thread_event, "thread events"},
5335     {bp_overlay_event, "overlay events"},
5336     {bp_longjmp_master, "longjmp master"},
5337     {bp_std_terminate_master, "std::terminate master"},
5338     {bp_exception_master, "exception master"},
5339     {bp_catchpoint, "catchpoint"},
5340     {bp_tracepoint, "tracepoint"},
5341     {bp_fast_tracepoint, "fast tracepoint"},
5342     {bp_static_tracepoint, "static tracepoint"},
5343     {bp_jit_event, "jit events"},
5344     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5345     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5346   };
5347
5348   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5349       || ((int) type != bptypes[(int) type].type))
5350     internal_error (__FILE__, __LINE__,
5351                     _("bptypes table does not describe type #%d."),
5352                     (int) type);
5353
5354   return bptypes[(int) type].description;
5355 }
5356
5357 /* Print B to gdb_stdout.  */
5358
5359 static void
5360 print_one_breakpoint_location (struct breakpoint *b,
5361                                struct bp_location *loc,
5362                                int loc_number,
5363                                struct bp_location **last_loc,
5364                                int allflag)
5365 {
5366   struct command_line *l;
5367   static char bpenables[] = "nynny";
5368
5369   struct ui_out *uiout = current_uiout;
5370   int header_of_multiple = 0;
5371   int part_of_multiple = (loc != NULL);
5372   struct value_print_options opts;
5373
5374   get_user_print_options (&opts);
5375
5376   gdb_assert (!loc || loc_number != 0);
5377   /* See comment in print_one_breakpoint concerning treatment of
5378      breakpoints with single disabled location.  */
5379   if (loc == NULL 
5380       && (b->loc != NULL 
5381           && (b->loc->next != NULL || !b->loc->enabled)))
5382     header_of_multiple = 1;
5383   if (loc == NULL)
5384     loc = b->loc;
5385
5386   annotate_record ();
5387
5388   /* 1 */
5389   annotate_field (0);
5390   if (part_of_multiple)
5391     {
5392       char *formatted;
5393       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5394       ui_out_field_string (uiout, "number", formatted);
5395       xfree (formatted);
5396     }
5397   else
5398     {
5399       ui_out_field_int (uiout, "number", b->number);
5400     }
5401
5402   /* 2 */
5403   annotate_field (1);
5404   if (part_of_multiple)
5405     ui_out_field_skip (uiout, "type");
5406   else
5407     ui_out_field_string (uiout, "type", bptype_string (b->type));
5408
5409   /* 3 */
5410   annotate_field (2);
5411   if (part_of_multiple)
5412     ui_out_field_skip (uiout, "disp");
5413   else
5414     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5415
5416
5417   /* 4 */
5418   annotate_field (3);
5419   if (part_of_multiple)
5420     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5421   else
5422     ui_out_field_fmt (uiout, "enabled", "%c", 
5423                       bpenables[(int) b->enable_state]);
5424   ui_out_spaces (uiout, 2);
5425
5426   
5427   /* 5 and 6 */
5428   if (b->ops != NULL && b->ops->print_one != NULL)
5429     {
5430       /* Although the print_one can possibly print all locations,
5431          calling it here is not likely to get any nice result.  So,
5432          make sure there's just one location.  */
5433       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5434       b->ops->print_one (b, last_loc);
5435     }
5436   else
5437     switch (b->type)
5438       {
5439       case bp_none:
5440         internal_error (__FILE__, __LINE__,
5441                         _("print_one_breakpoint: bp_none encountered\n"));
5442         break;
5443
5444       case bp_watchpoint:
5445       case bp_hardware_watchpoint:
5446       case bp_read_watchpoint:
5447       case bp_access_watchpoint:
5448         {
5449           struct watchpoint *w = (struct watchpoint *) b;
5450
5451           /* Field 4, the address, is omitted (which makes the columns
5452              not line up too nicely with the headers, but the effect
5453              is relatively readable).  */
5454           if (opts.addressprint)
5455             ui_out_field_skip (uiout, "addr");
5456           annotate_field (5);
5457           ui_out_field_string (uiout, "what", w->exp_string);
5458         }
5459         break;
5460
5461       case bp_breakpoint:
5462       case bp_hardware_breakpoint:
5463       case bp_until:
5464       case bp_finish:
5465       case bp_longjmp:
5466       case bp_longjmp_resume:
5467       case bp_exception:
5468       case bp_exception_resume:
5469       case bp_step_resume:
5470       case bp_hp_step_resume:
5471       case bp_watchpoint_scope:
5472       case bp_call_dummy:
5473       case bp_std_terminate:
5474       case bp_shlib_event:
5475       case bp_thread_event:
5476       case bp_overlay_event:
5477       case bp_longjmp_master:
5478       case bp_std_terminate_master:
5479       case bp_exception_master:
5480       case bp_tracepoint:
5481       case bp_fast_tracepoint:
5482       case bp_static_tracepoint:
5483       case bp_jit_event:
5484       case bp_gnu_ifunc_resolver:
5485       case bp_gnu_ifunc_resolver_return:
5486         if (opts.addressprint)
5487           {
5488             annotate_field (4);
5489             if (header_of_multiple)
5490               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5491             else if (b->loc == NULL || loc->shlib_disabled)
5492               ui_out_field_string (uiout, "addr", "<PENDING>");
5493             else
5494               ui_out_field_core_addr (uiout, "addr",
5495                                       loc->gdbarch, loc->address);
5496           }
5497         annotate_field (5);
5498         if (!header_of_multiple)
5499           print_breakpoint_location (b, loc);
5500         if (b->loc)
5501           *last_loc = b->loc;
5502         break;
5503       }
5504
5505
5506   /* For backward compatibility, don't display inferiors unless there
5507      are several.  */
5508   if (loc != NULL
5509       && !header_of_multiple
5510       && (allflag
5511           || (!gdbarch_has_global_breakpoints (target_gdbarch)
5512               && (number_of_program_spaces () > 1
5513                   || number_of_inferiors () > 1)
5514               /* LOC is for existing B, it cannot be in
5515                  moribund_locations and thus having NULL OWNER.  */
5516               && loc->owner->type != bp_catchpoint)))
5517     {
5518       struct inferior *inf;
5519       int first = 1;
5520
5521       for (inf = inferior_list; inf != NULL; inf = inf->next)
5522         {
5523           if (inf->pspace == loc->pspace)
5524             {
5525               if (first)
5526                 {
5527                   first = 0;
5528                   ui_out_text (uiout, " inf ");
5529                 }
5530               else
5531                 ui_out_text (uiout, ", ");
5532               ui_out_text (uiout, plongest (inf->num));
5533             }
5534         }
5535     }
5536
5537   if (!part_of_multiple)
5538     {
5539       if (b->thread != -1)
5540         {
5541           /* FIXME: This seems to be redundant and lost here; see the
5542              "stop only in" line a little further down.  */
5543           ui_out_text (uiout, " thread ");
5544           ui_out_field_int (uiout, "thread", b->thread);
5545         }
5546       else if (b->task != 0)
5547         {
5548           ui_out_text (uiout, " task ");
5549           ui_out_field_int (uiout, "task", b->task);
5550         }
5551     }
5552
5553   ui_out_text (uiout, "\n");
5554
5555   if (!part_of_multiple)
5556     b->ops->print_one_detail (b, uiout);
5557
5558   if (part_of_multiple && frame_id_p (b->frame_id))
5559     {
5560       annotate_field (6);
5561       ui_out_text (uiout, "\tstop only in stack frame at ");
5562       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
5563          the frame ID.  */
5564       ui_out_field_core_addr (uiout, "frame",
5565                               b->gdbarch, b->frame_id.stack_addr);
5566       ui_out_text (uiout, "\n");
5567     }
5568   
5569   if (!part_of_multiple && b->cond_string)
5570     {
5571       annotate_field (7);
5572       if (is_tracepoint (b))
5573         ui_out_text (uiout, "\ttrace only if ");
5574       else
5575         ui_out_text (uiout, "\tstop only if ");
5576       ui_out_field_string (uiout, "cond", b->cond_string);
5577
5578       /* Print whether the target is doing the breakpoint's condition
5579          evaluation.  If GDB is doing the evaluation, don't print anything.  */
5580       if (is_breakpoint (b)
5581           && breakpoint_condition_evaluation_mode ()
5582           == condition_evaluation_target)
5583         {
5584           ui_out_text (uiout, " (");
5585           ui_out_field_string (uiout, "evaluated-by",
5586                                bp_condition_evaluator (b));
5587           ui_out_text (uiout, " evals)");
5588         }
5589       ui_out_text (uiout, "\n");
5590     }
5591
5592   if (!part_of_multiple && b->thread != -1)
5593     {
5594       /* FIXME should make an annotation for this.  */
5595       ui_out_text (uiout, "\tstop only in thread ");
5596       ui_out_field_int (uiout, "thread", b->thread);
5597       ui_out_text (uiout, "\n");
5598     }
5599   
5600   if (!part_of_multiple && b->hit_count)
5601     {
5602       /* FIXME should make an annotation for this.  */
5603       if (is_catchpoint (b))
5604         ui_out_text (uiout, "\tcatchpoint");
5605       else if (is_tracepoint (b))
5606         ui_out_text (uiout, "\ttracepoint");
5607       else
5608         ui_out_text (uiout, "\tbreakpoint");
5609       ui_out_text (uiout, " already hit ");
5610       ui_out_field_int (uiout, "times", b->hit_count);
5611       if (b->hit_count == 1)
5612         ui_out_text (uiout, " time\n");
5613       else
5614         ui_out_text (uiout, " times\n");
5615     }
5616   
5617   /* Output the count also if it is zero, but only if this is mi.
5618      FIXME: Should have a better test for this.  */
5619   if (ui_out_is_mi_like_p (uiout))
5620     if (!part_of_multiple && b->hit_count == 0)
5621       ui_out_field_int (uiout, "times", b->hit_count);
5622
5623   if (!part_of_multiple && b->ignore_count)
5624     {
5625       annotate_field (8);
5626       ui_out_text (uiout, "\tignore next ");
5627       ui_out_field_int (uiout, "ignore", b->ignore_count);
5628       ui_out_text (uiout, " hits\n");
5629     }
5630
5631   /* Note that an enable count of 1 corresponds to "enable once"
5632      behavior, which is reported by the combination of enablement and
5633      disposition, so we don't need to mention it here.  */
5634   if (!part_of_multiple && b->enable_count > 1)
5635     {
5636       annotate_field (8);
5637       ui_out_text (uiout, "\tdisable after ");
5638       /* Tweak the wording to clarify that ignore and enable counts
5639          are distinct, and have additive effect.  */
5640       if (b->ignore_count)
5641         ui_out_text (uiout, "additional ");
5642       else
5643         ui_out_text (uiout, "next ");
5644       ui_out_field_int (uiout, "enable", b->enable_count);
5645       ui_out_text (uiout, " hits\n");
5646     }
5647
5648   if (!part_of_multiple && is_tracepoint (b))
5649     {
5650       struct tracepoint *tp = (struct tracepoint *) b;
5651
5652       if (tp->traceframe_usage)
5653         {
5654           ui_out_text (uiout, "\ttrace buffer usage ");
5655           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
5656           ui_out_text (uiout, " bytes\n");
5657         }
5658     }
5659   
5660   l = b->commands ? b->commands->commands : NULL;
5661   if (!part_of_multiple && l)
5662     {
5663       struct cleanup *script_chain;
5664
5665       annotate_field (9);
5666       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
5667       print_command_lines (uiout, l, 4);
5668       do_cleanups (script_chain);
5669     }
5670
5671   if (is_tracepoint (b))
5672     {
5673       struct tracepoint *t = (struct tracepoint *) b;
5674
5675       if (!part_of_multiple && t->pass_count)
5676         {
5677           annotate_field (10);
5678           ui_out_text (uiout, "\tpass count ");
5679           ui_out_field_int (uiout, "pass", t->pass_count);
5680           ui_out_text (uiout, " \n");
5681         }
5682     }
5683
5684   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5685     {
5686       if (is_watchpoint (b))
5687         {
5688           struct watchpoint *w = (struct watchpoint *) b;
5689
5690           ui_out_field_string (uiout, "original-location", w->exp_string);
5691         }
5692       else if (b->addr_string)
5693         ui_out_field_string (uiout, "original-location", b->addr_string);
5694     }
5695 }
5696
5697 static void
5698 print_one_breakpoint (struct breakpoint *b,
5699                       struct bp_location **last_loc, 
5700                       int allflag)
5701 {
5702   struct cleanup *bkpt_chain;
5703   struct ui_out *uiout = current_uiout;
5704
5705   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5706
5707   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5708   do_cleanups (bkpt_chain);
5709
5710   /* If this breakpoint has custom print function,
5711      it's already printed.  Otherwise, print individual
5712      locations, if any.  */
5713   if (b->ops == NULL || b->ops->print_one == NULL)
5714     {
5715       /* If breakpoint has a single location that is disabled, we
5716          print it as if it had several locations, since otherwise it's
5717          hard to represent "breakpoint enabled, location disabled"
5718          situation.
5719
5720          Note that while hardware watchpoints have several locations
5721          internally, that's not a property exposed to user.  */
5722       if (b->loc 
5723           && !is_hardware_watchpoint (b)
5724           && (b->loc->next || !b->loc->enabled))
5725         {
5726           struct bp_location *loc;
5727           int n = 1;
5728
5729           for (loc = b->loc; loc; loc = loc->next, ++n)
5730             {
5731               struct cleanup *inner2 =
5732                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5733               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5734               do_cleanups (inner2);
5735             }
5736         }
5737     }
5738 }
5739
5740 static int
5741 breakpoint_address_bits (struct breakpoint *b)
5742 {
5743   int print_address_bits = 0;
5744   struct bp_location *loc;
5745
5746   for (loc = b->loc; loc; loc = loc->next)
5747     {
5748       int addr_bit;
5749
5750       /* Software watchpoints that aren't watching memory don't have
5751          an address to print.  */
5752       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5753         continue;
5754
5755       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5756       if (addr_bit > print_address_bits)
5757         print_address_bits = addr_bit;
5758     }
5759
5760   return print_address_bits;
5761 }
5762
5763 struct captured_breakpoint_query_args
5764   {
5765     int bnum;
5766   };
5767
5768 static int
5769 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5770 {
5771   struct captured_breakpoint_query_args *args = data;
5772   struct breakpoint *b;
5773   struct bp_location *dummy_loc = NULL;
5774
5775   ALL_BREAKPOINTS (b)
5776     {
5777       if (args->bnum == b->number)
5778         {
5779           print_one_breakpoint (b, &dummy_loc, 0);
5780           return GDB_RC_OK;
5781         }
5782     }
5783   return GDB_RC_NONE;
5784 }
5785
5786 enum gdb_rc
5787 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5788                       char **error_message)
5789 {
5790   struct captured_breakpoint_query_args args;
5791
5792   args.bnum = bnum;
5793   /* For the moment we don't trust print_one_breakpoint() to not throw
5794      an error.  */
5795   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5796                                  error_message, RETURN_MASK_ALL) < 0)
5797     return GDB_RC_FAIL;
5798   else
5799     return GDB_RC_OK;
5800 }
5801
5802 /* Return true if this breakpoint was set by the user, false if it is
5803    internal or momentary.  */
5804
5805 int
5806 user_breakpoint_p (struct breakpoint *b)
5807 {
5808   return b->number > 0;
5809 }
5810
5811 /* Print information on user settable breakpoint (watchpoint, etc)
5812    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5813    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5814    FILTER is non-NULL, call it on each breakpoint and only include the
5815    ones for which it returns non-zero.  Return the total number of
5816    breakpoints listed.  */
5817
5818 static int
5819 breakpoint_1 (char *args, int allflag, 
5820               int (*filter) (const struct breakpoint *))
5821 {
5822   struct breakpoint *b;
5823   struct bp_location *last_loc = NULL;
5824   int nr_printable_breakpoints;
5825   struct cleanup *bkpttbl_chain;
5826   struct value_print_options opts;
5827   int print_address_bits = 0;
5828   int print_type_col_width = 14;
5829   struct ui_out *uiout = current_uiout;
5830
5831   get_user_print_options (&opts);
5832
5833   /* Compute the number of rows in the table, as well as the size
5834      required for address fields.  */
5835   nr_printable_breakpoints = 0;
5836   ALL_BREAKPOINTS (b)
5837     {
5838       /* If we have a filter, only list the breakpoints it accepts.  */
5839       if (filter && !filter (b))
5840         continue;
5841
5842       /* If we have an "args" string, it is a list of breakpoints to 
5843          accept.  Skip the others.  */
5844       if (args != NULL && *args != '\0')
5845         {
5846           if (allflag && parse_and_eval_long (args) != b->number)
5847             continue;
5848           if (!allflag && !number_is_in_list (args, b->number))
5849             continue;
5850         }
5851
5852       if (allflag || user_breakpoint_p (b))
5853         {
5854           int addr_bit, type_len;
5855
5856           addr_bit = breakpoint_address_bits (b);
5857           if (addr_bit > print_address_bits)
5858             print_address_bits = addr_bit;
5859
5860           type_len = strlen (bptype_string (b->type));
5861           if (type_len > print_type_col_width)
5862             print_type_col_width = type_len;
5863
5864           nr_printable_breakpoints++;
5865         }
5866     }
5867
5868   if (opts.addressprint)
5869     bkpttbl_chain 
5870       = make_cleanup_ui_out_table_begin_end (uiout, 6,
5871                                              nr_printable_breakpoints,
5872                                              "BreakpointTable");
5873   else
5874     bkpttbl_chain 
5875       = make_cleanup_ui_out_table_begin_end (uiout, 5,
5876                                              nr_printable_breakpoints,
5877                                              "BreakpointTable");
5878
5879   if (nr_printable_breakpoints > 0)
5880     annotate_breakpoints_headers ();
5881   if (nr_printable_breakpoints > 0)
5882     annotate_field (0);
5883   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
5884   if (nr_printable_breakpoints > 0)
5885     annotate_field (1);
5886   ui_out_table_header (uiout, print_type_col_width, ui_left,
5887                        "type", "Type");                         /* 2 */
5888   if (nr_printable_breakpoints > 0)
5889     annotate_field (2);
5890   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
5891   if (nr_printable_breakpoints > 0)
5892     annotate_field (3);
5893   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
5894   if (opts.addressprint)
5895     {
5896       if (nr_printable_breakpoints > 0)
5897         annotate_field (4);
5898       if (print_address_bits <= 32)
5899         ui_out_table_header (uiout, 10, ui_left, 
5900                              "addr", "Address");                /* 5 */
5901       else
5902         ui_out_table_header (uiout, 18, ui_left, 
5903                              "addr", "Address");                /* 5 */
5904     }
5905   if (nr_printable_breakpoints > 0)
5906     annotate_field (5);
5907   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
5908   ui_out_table_body (uiout);
5909   if (nr_printable_breakpoints > 0)
5910     annotate_breakpoints_table ();
5911
5912   ALL_BREAKPOINTS (b)
5913     {
5914       QUIT;
5915       /* If we have a filter, only list the breakpoints it accepts.  */
5916       if (filter && !filter (b))
5917         continue;
5918
5919       /* If we have an "args" string, it is a list of breakpoints to 
5920          accept.  Skip the others.  */
5921
5922       if (args != NULL && *args != '\0')
5923         {
5924           if (allflag)  /* maintenance info breakpoint */
5925             {
5926               if (parse_and_eval_long (args) != b->number)
5927                 continue;
5928             }
5929           else          /* all others */
5930             {
5931               if (!number_is_in_list (args, b->number))
5932                 continue;
5933             }
5934         }
5935       /* We only print out user settable breakpoints unless the
5936          allflag is set.  */
5937       if (allflag || user_breakpoint_p (b))
5938         print_one_breakpoint (b, &last_loc, allflag);
5939     }
5940
5941   do_cleanups (bkpttbl_chain);
5942
5943   if (nr_printable_breakpoints == 0)
5944     {
5945       /* If there's a filter, let the caller decide how to report
5946          empty list.  */
5947       if (!filter)
5948         {
5949           if (args == NULL || *args == '\0')
5950             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
5951           else
5952             ui_out_message (uiout, 0, 
5953                             "No breakpoint or watchpoint matching '%s'.\n",
5954                             args);
5955         }
5956     }
5957   else
5958     {
5959       if (last_loc && !server_command)
5960         set_next_address (last_loc->gdbarch, last_loc->address);
5961     }
5962
5963   /* FIXME?  Should this be moved up so that it is only called when
5964      there have been breakpoints? */
5965   annotate_breakpoints_table_end ();
5966
5967   return nr_printable_breakpoints;
5968 }
5969
5970 /* Display the value of default-collect in a way that is generally
5971    compatible with the breakpoint list.  */
5972
5973 static void
5974 default_collect_info (void)
5975 {
5976   struct ui_out *uiout = current_uiout;
5977
5978   /* If it has no value (which is frequently the case), say nothing; a
5979      message like "No default-collect." gets in user's face when it's
5980      not wanted.  */
5981   if (!*default_collect)
5982     return;
5983
5984   /* The following phrase lines up nicely with per-tracepoint collect
5985      actions.  */
5986   ui_out_text (uiout, "default collect ");
5987   ui_out_field_string (uiout, "default-collect", default_collect);
5988   ui_out_text (uiout, " \n");
5989 }
5990   
5991 static void
5992 breakpoints_info (char *args, int from_tty)
5993 {
5994   breakpoint_1 (args, 0, NULL);
5995
5996   default_collect_info ();
5997 }
5998
5999 static void
6000 watchpoints_info (char *args, int from_tty)
6001 {
6002   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6003   struct ui_out *uiout = current_uiout;
6004
6005   if (num_printed == 0)
6006     {
6007       if (args == NULL || *args == '\0')
6008         ui_out_message (uiout, 0, "No watchpoints.\n");
6009       else
6010         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6011     }
6012 }
6013
6014 static void
6015 maintenance_info_breakpoints (char *args, int from_tty)
6016 {
6017   breakpoint_1 (args, 1, NULL);
6018
6019   default_collect_info ();
6020 }
6021
6022 static int
6023 breakpoint_has_pc (struct breakpoint *b,
6024                    struct program_space *pspace,
6025                    CORE_ADDR pc, struct obj_section *section)
6026 {
6027   struct bp_location *bl = b->loc;
6028
6029   for (; bl; bl = bl->next)
6030     {
6031       if (bl->pspace == pspace
6032           && bl->address == pc
6033           && (!overlay_debugging || bl->section == section))
6034         return 1;         
6035     }
6036   return 0;
6037 }
6038
6039 /* Print a message describing any user-breakpoints set at PC.  This
6040    concerns with logical breakpoints, so we match program spaces, not
6041    address spaces.  */
6042
6043 static void
6044 describe_other_breakpoints (struct gdbarch *gdbarch,
6045                             struct program_space *pspace, CORE_ADDR pc,
6046                             struct obj_section *section, int thread)
6047 {
6048   int others = 0;
6049   struct breakpoint *b;
6050
6051   ALL_BREAKPOINTS (b)
6052     others += (user_breakpoint_p (b)
6053                && breakpoint_has_pc (b, pspace, pc, section));
6054   if (others > 0)
6055     {
6056       if (others == 1)
6057         printf_filtered (_("Note: breakpoint "));
6058       else /* if (others == ???) */
6059         printf_filtered (_("Note: breakpoints "));
6060       ALL_BREAKPOINTS (b)
6061         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6062           {
6063             others--;
6064             printf_filtered ("%d", b->number);
6065             if (b->thread == -1 && thread != -1)
6066               printf_filtered (" (all threads)");
6067             else if (b->thread != -1)
6068               printf_filtered (" (thread %d)", b->thread);
6069             printf_filtered ("%s%s ",
6070                              ((b->enable_state == bp_disabled
6071                                || b->enable_state == bp_call_disabled)
6072                               ? " (disabled)"
6073                               : b->enable_state == bp_permanent 
6074                               ? " (permanent)"
6075                               : ""),
6076                              (others > 1) ? "," 
6077                              : ((others == 1) ? " and" : ""));
6078           }
6079       printf_filtered (_("also set at pc "));
6080       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6081       printf_filtered (".\n");
6082     }
6083 }
6084 \f
6085
6086 /* Return true iff it is meaningful to use the address member of
6087    BPT.  For some breakpoint types, the address member is irrelevant
6088    and it makes no sense to attempt to compare it to other addresses
6089    (or use it for any other purpose either).
6090
6091    More specifically, each of the following breakpoint types will
6092    always have a zero valued address and we don't want to mark
6093    breakpoints of any of these types to be a duplicate of an actual
6094    breakpoint at address zero:
6095
6096       bp_watchpoint
6097       bp_catchpoint
6098
6099 */
6100
6101 static int
6102 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6103 {
6104   enum bptype type = bpt->type;
6105
6106   return (type != bp_watchpoint && type != bp_catchpoint);
6107 }
6108
6109 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6110    true if LOC1 and LOC2 represent the same watchpoint location.  */
6111
6112 static int
6113 watchpoint_locations_match (struct bp_location *loc1, 
6114                             struct bp_location *loc2)
6115 {
6116   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6117   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6118
6119   /* Both of them must exist.  */
6120   gdb_assert (w1 != NULL);
6121   gdb_assert (w2 != NULL);
6122
6123   /* If the target can evaluate the condition expression in hardware,
6124      then we we need to insert both watchpoints even if they are at
6125      the same place.  Otherwise the watchpoint will only trigger when
6126      the condition of whichever watchpoint was inserted evaluates to
6127      true, not giving a chance for GDB to check the condition of the
6128      other watchpoint.  */
6129   if ((w1->cond_exp
6130        && target_can_accel_watchpoint_condition (loc1->address, 
6131                                                  loc1->length,
6132                                                  loc1->watchpoint_type,
6133                                                  w1->cond_exp))
6134       || (w2->cond_exp
6135           && target_can_accel_watchpoint_condition (loc2->address, 
6136                                                     loc2->length,
6137                                                     loc2->watchpoint_type,
6138                                                     w2->cond_exp)))
6139     return 0;
6140
6141   /* Note that this checks the owner's type, not the location's.  In
6142      case the target does not support read watchpoints, but does
6143      support access watchpoints, we'll have bp_read_watchpoint
6144      watchpoints with hw_access locations.  Those should be considered
6145      duplicates of hw_read locations.  The hw_read locations will
6146      become hw_access locations later.  */
6147   return (loc1->owner->type == loc2->owner->type
6148           && loc1->pspace->aspace == loc2->pspace->aspace
6149           && loc1->address == loc2->address
6150           && loc1->length == loc2->length);
6151 }
6152
6153 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6154    same breakpoint location.  In most targets, this can only be true
6155    if ASPACE1 matches ASPACE2.  On targets that have global
6156    breakpoints, the address space doesn't really matter.  */
6157
6158 static int
6159 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6160                           struct address_space *aspace2, CORE_ADDR addr2)
6161 {
6162   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6163            || aspace1 == aspace2)
6164           && addr1 == addr2);
6165 }
6166
6167 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6168    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6169    matches ASPACE2.  On targets that have global breakpoints, the address
6170    space doesn't really matter.  */
6171
6172 static int
6173 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6174                                 int len1, struct address_space *aspace2,
6175                                 CORE_ADDR addr2)
6176 {
6177   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6178            || aspace1 == aspace2)
6179           && addr2 >= addr1 && addr2 < addr1 + len1);
6180 }
6181
6182 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6183    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6184    matches the breakpoint's address space.  On targets that have global
6185    breakpoints, the address space doesn't really matter.  */
6186
6187 static int
6188 breakpoint_location_address_match (struct bp_location *bl,
6189                                    struct address_space *aspace,
6190                                    CORE_ADDR addr)
6191 {
6192   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6193                                     aspace, addr)
6194           || (bl->length
6195               && breakpoint_address_match_range (bl->pspace->aspace,
6196                                                  bl->address, bl->length,
6197                                                  aspace, addr)));
6198 }
6199
6200 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6201    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6202    true, otherwise returns false.  */
6203
6204 static int
6205 tracepoint_locations_match (struct bp_location *loc1,
6206                             struct bp_location *loc2)
6207 {
6208   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6209     /* Since tracepoint locations are never duplicated with others', tracepoint
6210        locations at the same address of different tracepoints are regarded as
6211        different locations.  */
6212     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6213   else
6214     return 0;
6215 }
6216
6217 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6218    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6219    represent the same location.  */
6220
6221 static int
6222 breakpoint_locations_match (struct bp_location *loc1, 
6223                             struct bp_location *loc2)
6224 {
6225   int hw_point1, hw_point2;
6226
6227   /* Both of them must not be in moribund_locations.  */
6228   gdb_assert (loc1->owner != NULL);
6229   gdb_assert (loc2->owner != NULL);
6230
6231   hw_point1 = is_hardware_watchpoint (loc1->owner);
6232   hw_point2 = is_hardware_watchpoint (loc2->owner);
6233
6234   if (hw_point1 != hw_point2)
6235     return 0;
6236   else if (hw_point1)
6237     return watchpoint_locations_match (loc1, loc2);
6238   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6239     return tracepoint_locations_match (loc1, loc2);
6240   else
6241     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6242     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6243                                      loc2->pspace->aspace, loc2->address)
6244             && loc1->length == loc2->length);
6245 }
6246
6247 static void
6248 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6249                                int bnum, int have_bnum)
6250 {
6251   /* The longest string possibly returned by hex_string_custom
6252      is 50 chars.  These must be at least that big for safety.  */
6253   char astr1[64];
6254   char astr2[64];
6255
6256   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6257   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6258   if (have_bnum)
6259     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6260              bnum, astr1, astr2);
6261   else
6262     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6263 }
6264
6265 /* Adjust a breakpoint's address to account for architectural
6266    constraints on breakpoint placement.  Return the adjusted address.
6267    Note: Very few targets require this kind of adjustment.  For most
6268    targets, this function is simply the identity function.  */
6269
6270 static CORE_ADDR
6271 adjust_breakpoint_address (struct gdbarch *gdbarch,
6272                            CORE_ADDR bpaddr, enum bptype bptype)
6273 {
6274   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6275     {
6276       /* Very few targets need any kind of breakpoint adjustment.  */
6277       return bpaddr;
6278     }
6279   else if (bptype == bp_watchpoint
6280            || bptype == bp_hardware_watchpoint
6281            || bptype == bp_read_watchpoint
6282            || bptype == bp_access_watchpoint
6283            || bptype == bp_catchpoint)
6284     {
6285       /* Watchpoints and the various bp_catch_* eventpoints should not
6286          have their addresses modified.  */
6287       return bpaddr;
6288     }
6289   else
6290     {
6291       CORE_ADDR adjusted_bpaddr;
6292
6293       /* Some targets have architectural constraints on the placement
6294          of breakpoint instructions.  Obtain the adjusted address.  */
6295       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6296
6297       /* An adjusted breakpoint address can significantly alter
6298          a user's expectations.  Print a warning if an adjustment
6299          is required.  */
6300       if (adjusted_bpaddr != bpaddr)
6301         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6302
6303       return adjusted_bpaddr;
6304     }
6305 }
6306
6307 void
6308 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6309                   struct breakpoint *owner)
6310 {
6311   memset (loc, 0, sizeof (*loc));
6312
6313   gdb_assert (ops != NULL);
6314
6315   loc->ops = ops;
6316   loc->owner = owner;
6317   loc->cond = NULL;
6318   loc->cond_bytecode = NULL;
6319   loc->shlib_disabled = 0;
6320   loc->enabled = 1;
6321
6322   switch (owner->type)
6323     {
6324     case bp_breakpoint:
6325     case bp_until:
6326     case bp_finish:
6327     case bp_longjmp:
6328     case bp_longjmp_resume:
6329     case bp_exception:
6330     case bp_exception_resume:
6331     case bp_step_resume:
6332     case bp_hp_step_resume:
6333     case bp_watchpoint_scope:
6334     case bp_call_dummy:
6335     case bp_std_terminate:
6336     case bp_shlib_event:
6337     case bp_thread_event:
6338     case bp_overlay_event:
6339     case bp_jit_event:
6340     case bp_longjmp_master:
6341     case bp_std_terminate_master:
6342     case bp_exception_master:
6343     case bp_gnu_ifunc_resolver:
6344     case bp_gnu_ifunc_resolver_return:
6345       loc->loc_type = bp_loc_software_breakpoint;
6346       mark_breakpoint_location_modified (loc);
6347       break;
6348     case bp_hardware_breakpoint:
6349       loc->loc_type = bp_loc_hardware_breakpoint;
6350       mark_breakpoint_location_modified (loc);
6351       break;
6352     case bp_hardware_watchpoint:
6353     case bp_read_watchpoint:
6354     case bp_access_watchpoint:
6355       loc->loc_type = bp_loc_hardware_watchpoint;
6356       break;
6357     case bp_watchpoint:
6358     case bp_catchpoint:
6359     case bp_tracepoint:
6360     case bp_fast_tracepoint:
6361     case bp_static_tracepoint:
6362       loc->loc_type = bp_loc_other;
6363       break;
6364     default:
6365       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6366     }
6367
6368   loc->refc = 1;
6369 }
6370
6371 /* Allocate a struct bp_location.  */
6372
6373 static struct bp_location *
6374 allocate_bp_location (struct breakpoint *bpt)
6375 {
6376   return bpt->ops->allocate_location (bpt);
6377 }
6378
6379 static void
6380 free_bp_location (struct bp_location *loc)
6381 {
6382   loc->ops->dtor (loc);
6383   xfree (loc);
6384 }
6385
6386 /* Increment reference count.  */
6387
6388 static void
6389 incref_bp_location (struct bp_location *bl)
6390 {
6391   ++bl->refc;
6392 }
6393
6394 /* Decrement reference count.  If the reference count reaches 0,
6395    destroy the bp_location.  Sets *BLP to NULL.  */
6396
6397 static void
6398 decref_bp_location (struct bp_location **blp)
6399 {
6400   gdb_assert ((*blp)->refc > 0);
6401
6402   if (--(*blp)->refc == 0)
6403     free_bp_location (*blp);
6404   *blp = NULL;
6405 }
6406
6407 /* Add breakpoint B at the end of the global breakpoint chain.  */
6408
6409 static void
6410 add_to_breakpoint_chain (struct breakpoint *b)
6411 {
6412   struct breakpoint *b1;
6413
6414   /* Add this breakpoint to the end of the chain so that a list of
6415      breakpoints will come out in order of increasing numbers.  */
6416
6417   b1 = breakpoint_chain;
6418   if (b1 == 0)
6419     breakpoint_chain = b;
6420   else
6421     {
6422       while (b1->next)
6423         b1 = b1->next;
6424       b1->next = b;
6425     }
6426 }
6427
6428 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6429
6430 static void
6431 init_raw_breakpoint_without_location (struct breakpoint *b,
6432                                       struct gdbarch *gdbarch,
6433                                       enum bptype bptype,
6434                                       const struct breakpoint_ops *ops)
6435 {
6436   memset (b, 0, sizeof (*b));
6437
6438   gdb_assert (ops != NULL);
6439
6440   b->ops = ops;
6441   b->type = bptype;
6442   b->gdbarch = gdbarch;
6443   b->language = current_language->la_language;
6444   b->input_radix = input_radix;
6445   b->thread = -1;
6446   b->enable_state = bp_enabled;
6447   b->next = 0;
6448   b->silent = 0;
6449   b->ignore_count = 0;
6450   b->commands = NULL;
6451   b->frame_id = null_frame_id;
6452   b->condition_not_parsed = 0;
6453   b->py_bp_object = NULL;
6454   b->related_breakpoint = b;
6455 }
6456
6457 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6458    that has type BPTYPE and has no locations as yet.  */
6459
6460 static struct breakpoint *
6461 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6462                                      enum bptype bptype,
6463                                      const struct breakpoint_ops *ops)
6464 {
6465   struct breakpoint *b = XNEW (struct breakpoint);
6466
6467   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6468   add_to_breakpoint_chain (b);
6469   return b;
6470 }
6471
6472 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6473    resolutions should be made as the user specified the location explicitly
6474    enough.  */
6475
6476 static void
6477 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
6478 {
6479   gdb_assert (loc->owner != NULL);
6480
6481   if (loc->owner->type == bp_breakpoint
6482       || loc->owner->type == bp_hardware_breakpoint
6483       || is_tracepoint (loc->owner))
6484     {
6485       int is_gnu_ifunc;
6486       const char *function_name;
6487
6488       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
6489                                           NULL, NULL, &is_gnu_ifunc);
6490
6491       if (is_gnu_ifunc && !explicit_loc)
6492         {
6493           struct breakpoint *b = loc->owner;
6494
6495           gdb_assert (loc->pspace == current_program_space);
6496           if (gnu_ifunc_resolve_name (function_name,
6497                                       &loc->requested_address))
6498             {
6499               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
6500               loc->address = adjust_breakpoint_address (loc->gdbarch,
6501                                                         loc->requested_address,
6502                                                         b->type);
6503             }
6504           else if (b->type == bp_breakpoint && b->loc == loc
6505                    && loc->next == NULL && b->related_breakpoint == b)
6506             {
6507               /* Create only the whole new breakpoint of this type but do not
6508                  mess more complicated breakpoints with multiple locations.  */
6509               b->type = bp_gnu_ifunc_resolver;
6510             }
6511         }
6512
6513       if (function_name)
6514         loc->function_name = xstrdup (function_name);
6515     }
6516 }
6517
6518 /* Attempt to determine architecture of location identified by SAL.  */
6519 struct gdbarch *
6520 get_sal_arch (struct symtab_and_line sal)
6521 {
6522   if (sal.section)
6523     return get_objfile_arch (sal.section->objfile);
6524   if (sal.symtab)
6525     return get_objfile_arch (sal.symtab->objfile);
6526
6527   return NULL;
6528 }
6529
6530 /* Low level routine for partially initializing a breakpoint of type
6531    BPTYPE.  The newly created breakpoint's address, section, source
6532    file name, and line number are provided by SAL.
6533
6534    It is expected that the caller will complete the initialization of
6535    the newly created breakpoint struct as well as output any status
6536    information regarding the creation of a new breakpoint.  */
6537
6538 static void
6539 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
6540                      struct symtab_and_line sal, enum bptype bptype,
6541                      const struct breakpoint_ops *ops)
6542 {
6543   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6544
6545   add_location_to_breakpoint (b, &sal);
6546
6547   if (bptype != bp_catchpoint)
6548     gdb_assert (sal.pspace != NULL);
6549
6550   /* Store the program space that was used to set the breakpoint,
6551      except for ordinary breakpoints, which are independent of the
6552      program space.  */
6553   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
6554     b->pspace = sal.pspace;
6555
6556   breakpoints_changed ();
6557 }
6558
6559 /* set_raw_breakpoint is a low level routine for allocating and
6560    partially initializing a breakpoint of type BPTYPE.  The newly
6561    created breakpoint's address, section, source file name, and line
6562    number are provided by SAL.  The newly created and partially
6563    initialized breakpoint is added to the breakpoint chain and
6564    is also returned as the value of this function.
6565
6566    It is expected that the caller will complete the initialization of
6567    the newly created breakpoint struct as well as output any status
6568    information regarding the creation of a new breakpoint.  In
6569    particular, set_raw_breakpoint does NOT set the breakpoint
6570    number!  Care should be taken to not allow an error to occur
6571    prior to completing the initialization of the breakpoint.  If this
6572    should happen, a bogus breakpoint will be left on the chain.  */
6573
6574 struct breakpoint *
6575 set_raw_breakpoint (struct gdbarch *gdbarch,
6576                     struct symtab_and_line sal, enum bptype bptype,
6577                     const struct breakpoint_ops *ops)
6578 {
6579   struct breakpoint *b = XNEW (struct breakpoint);
6580
6581   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
6582   add_to_breakpoint_chain (b);
6583   return b;
6584 }
6585
6586
6587 /* Note that the breakpoint object B describes a permanent breakpoint
6588    instruction, hard-wired into the inferior's code.  */
6589 void
6590 make_breakpoint_permanent (struct breakpoint *b)
6591 {
6592   struct bp_location *bl;
6593
6594   b->enable_state = bp_permanent;
6595
6596   /* By definition, permanent breakpoints are already present in the
6597      code.  Mark all locations as inserted.  For now,
6598      make_breakpoint_permanent is called in just one place, so it's
6599      hard to say if it's reasonable to have permanent breakpoint with
6600      multiple locations or not, but it's easy to implement.  */
6601   for (bl = b->loc; bl; bl = bl->next)
6602     bl->inserted = 1;
6603 }
6604
6605 /* Call this routine when stepping and nexting to enable a breakpoint
6606    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
6607    initiated the operation.  */
6608
6609 void
6610 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
6611 {
6612   struct breakpoint *b, *b_tmp;
6613   int thread = tp->num;
6614
6615   /* To avoid having to rescan all objfile symbols at every step,
6616      we maintain a list of continually-inserted but always disabled
6617      longjmp "master" breakpoints.  Here, we simply create momentary
6618      clones of those and enable them for the requested thread.  */
6619   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6620     if (b->pspace == current_program_space
6621         && (b->type == bp_longjmp_master
6622             || b->type == bp_exception_master))
6623       {
6624         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
6625         struct breakpoint *clone;
6626
6627         clone = momentary_breakpoint_from_master (b, type,
6628                                                   &momentary_breakpoint_ops);
6629         clone->thread = thread;
6630       }
6631
6632   tp->initiating_frame = frame;
6633 }
6634
6635 /* Delete all longjmp breakpoints from THREAD.  */
6636 void
6637 delete_longjmp_breakpoint (int thread)
6638 {
6639   struct breakpoint *b, *b_tmp;
6640
6641   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6642     if (b->type == bp_longjmp || b->type == bp_exception)
6643       {
6644         if (b->thread == thread)
6645           delete_breakpoint (b);
6646       }
6647 }
6648
6649 void
6650 delete_longjmp_breakpoint_at_next_stop (int thread)
6651 {
6652   struct breakpoint *b, *b_tmp;
6653
6654   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6655     if (b->type == bp_longjmp || b->type == bp_exception)
6656       {
6657         if (b->thread == thread)
6658           b->disposition = disp_del_at_next_stop;
6659       }
6660 }
6661
6662 void
6663 enable_overlay_breakpoints (void)
6664 {
6665   struct breakpoint *b;
6666
6667   ALL_BREAKPOINTS (b)
6668     if (b->type == bp_overlay_event)
6669     {
6670       b->enable_state = bp_enabled;
6671       update_global_location_list (1);
6672       overlay_events_enabled = 1;
6673     }
6674 }
6675
6676 void
6677 disable_overlay_breakpoints (void)
6678 {
6679   struct breakpoint *b;
6680
6681   ALL_BREAKPOINTS (b)
6682     if (b->type == bp_overlay_event)
6683     {
6684       b->enable_state = bp_disabled;
6685       update_global_location_list (0);
6686       overlay_events_enabled = 0;
6687     }
6688 }
6689
6690 /* Set an active std::terminate breakpoint for each std::terminate
6691    master breakpoint.  */
6692 void
6693 set_std_terminate_breakpoint (void)
6694 {
6695   struct breakpoint *b, *b_tmp;
6696
6697   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6698     if (b->pspace == current_program_space
6699         && b->type == bp_std_terminate_master)
6700       {
6701         momentary_breakpoint_from_master (b, bp_std_terminate,
6702                                           &momentary_breakpoint_ops);
6703       }
6704 }
6705
6706 /* Delete all the std::terminate breakpoints.  */
6707 void
6708 delete_std_terminate_breakpoint (void)
6709 {
6710   struct breakpoint *b, *b_tmp;
6711
6712   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6713     if (b->type == bp_std_terminate)
6714       delete_breakpoint (b);
6715 }
6716
6717 struct breakpoint *
6718 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6719 {
6720   struct breakpoint *b;
6721
6722   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6723                                   &internal_breakpoint_ops);
6724
6725   b->enable_state = bp_enabled;
6726   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6727   b->addr_string
6728     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6729
6730   update_global_location_list_nothrow (1);
6731
6732   return b;
6733 }
6734
6735 void
6736 remove_thread_event_breakpoints (void)
6737 {
6738   struct breakpoint *b, *b_tmp;
6739
6740   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6741     if (b->type == bp_thread_event
6742         && b->loc->pspace == current_program_space)
6743       delete_breakpoint (b);
6744 }
6745
6746 struct lang_and_radix
6747   {
6748     enum language lang;
6749     int radix;
6750   };
6751
6752 /* Create a breakpoint for JIT code registration and unregistration.  */
6753
6754 struct breakpoint *
6755 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6756 {
6757   struct breakpoint *b;
6758
6759   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
6760                                   &internal_breakpoint_ops);
6761   update_global_location_list_nothrow (1);
6762   return b;
6763 }
6764
6765 /* Remove JIT code registration and unregistration breakpoint(s).  */
6766
6767 void
6768 remove_jit_event_breakpoints (void)
6769 {
6770   struct breakpoint *b, *b_tmp;
6771
6772   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6773     if (b->type == bp_jit_event
6774         && b->loc->pspace == current_program_space)
6775       delete_breakpoint (b);
6776 }
6777
6778 void
6779 remove_solib_event_breakpoints (void)
6780 {
6781   struct breakpoint *b, *b_tmp;
6782
6783   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6784     if (b->type == bp_shlib_event
6785         && b->loc->pspace == current_program_space)
6786       delete_breakpoint (b);
6787 }
6788
6789 struct breakpoint *
6790 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6791 {
6792   struct breakpoint *b;
6793
6794   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
6795                                   &internal_breakpoint_ops);
6796   update_global_location_list_nothrow (1);
6797   return b;
6798 }
6799
6800 /* Disable any breakpoints that are on code in shared libraries.  Only
6801    apply to enabled breakpoints, disabled ones can just stay disabled.  */
6802
6803 void
6804 disable_breakpoints_in_shlibs (void)
6805 {
6806   struct bp_location *loc, **locp_tmp;
6807
6808   ALL_BP_LOCATIONS (loc, locp_tmp)
6809   {
6810     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6811     struct breakpoint *b = loc->owner;
6812
6813     /* We apply the check to all breakpoints, including disabled for
6814        those with loc->duplicate set.  This is so that when breakpoint
6815        becomes enabled, or the duplicate is removed, gdb will try to
6816        insert all breakpoints.  If we don't set shlib_disabled here,
6817        we'll try to insert those breakpoints and fail.  */
6818     if (((b->type == bp_breakpoint)
6819          || (b->type == bp_jit_event)
6820          || (b->type == bp_hardware_breakpoint)
6821          || (is_tracepoint (b)))
6822         && loc->pspace == current_program_space
6823         && !loc->shlib_disabled
6824 #ifdef PC_SOLIB
6825         && PC_SOLIB (loc->address)
6826 #else
6827         && solib_name_from_address (loc->pspace, loc->address)
6828 #endif
6829         )
6830       {
6831         loc->shlib_disabled = 1;
6832       }
6833   }
6834 }
6835
6836 /* Disable any breakpoints and tracepoints that are in an unloaded shared
6837    library.  Only apply to enabled breakpoints, disabled ones can just stay
6838    disabled.  */
6839
6840 static void
6841 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
6842 {
6843   struct bp_location *loc, **locp_tmp;
6844   int disabled_shlib_breaks = 0;
6845
6846   /* SunOS a.out shared libraries are always mapped, so do not
6847      disable breakpoints; they will only be reported as unloaded
6848      through clear_solib when GDB discards its shared library
6849      list.  See clear_solib for more information.  */
6850   if (exec_bfd != NULL
6851       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
6852     return;
6853
6854   ALL_BP_LOCATIONS (loc, locp_tmp)
6855   {
6856     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6857     struct breakpoint *b = loc->owner;
6858
6859     if (solib->pspace == loc->pspace
6860         && !loc->shlib_disabled
6861         && (((b->type == bp_breakpoint
6862               || b->type == bp_jit_event
6863               || b->type == bp_hardware_breakpoint)
6864              && (loc->loc_type == bp_loc_hardware_breakpoint
6865                  || loc->loc_type == bp_loc_software_breakpoint))
6866             || is_tracepoint (b))
6867         && solib_contains_address_p (solib, loc->address))
6868       {
6869         loc->shlib_disabled = 1;
6870         /* At this point, we cannot rely on remove_breakpoint
6871            succeeding so we must mark the breakpoint as not inserted
6872            to prevent future errors occurring in remove_breakpoints.  */
6873         loc->inserted = 0;
6874
6875         /* This may cause duplicate notifications for the same breakpoint.  */
6876         observer_notify_breakpoint_modified (b);
6877
6878         if (!disabled_shlib_breaks)
6879           {
6880             target_terminal_ours_for_output ();
6881             warning (_("Temporarily disabling breakpoints "
6882                        "for unloaded shared library \"%s\""),
6883                      solib->so_name);
6884           }
6885         disabled_shlib_breaks = 1;
6886       }
6887   }
6888 }
6889
6890 /* FORK & VFORK catchpoints.  */
6891
6892 /* An instance of this type is used to represent a fork or vfork
6893    catchpoint.  It includes a "struct breakpoint" as a kind of base
6894    class; users downcast to "struct breakpoint *" when needed.  A
6895    breakpoint is really of this type iff its ops pointer points to
6896    CATCH_FORK_BREAKPOINT_OPS.  */
6897
6898 struct fork_catchpoint
6899 {
6900   /* The base class.  */
6901   struct breakpoint base;
6902
6903   /* Process id of a child process whose forking triggered this
6904      catchpoint.  This field is only valid immediately after this
6905      catchpoint has triggered.  */
6906   ptid_t forked_inferior_pid;
6907 };
6908
6909 /* Implement the "insert" breakpoint_ops method for fork
6910    catchpoints.  */
6911
6912 static int
6913 insert_catch_fork (struct bp_location *bl)
6914 {
6915   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
6916 }
6917
6918 /* Implement the "remove" breakpoint_ops method for fork
6919    catchpoints.  */
6920
6921 static int
6922 remove_catch_fork (struct bp_location *bl)
6923 {
6924   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
6925 }
6926
6927 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
6928    catchpoints.  */
6929
6930 static int
6931 breakpoint_hit_catch_fork (const struct bp_location *bl,
6932                            struct address_space *aspace, CORE_ADDR bp_addr,
6933                            const struct target_waitstatus *ws)
6934 {
6935   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6936
6937   if (ws->kind != TARGET_WAITKIND_FORKED)
6938     return 0;
6939
6940   c->forked_inferior_pid = ws->value.related_pid;
6941   return 1;
6942 }
6943
6944 /* Implement the "print_it" breakpoint_ops method for fork
6945    catchpoints.  */
6946
6947 static enum print_stop_action
6948 print_it_catch_fork (bpstat bs)
6949 {
6950   struct ui_out *uiout = current_uiout;
6951   struct breakpoint *b = bs->breakpoint_at;
6952   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
6953
6954   annotate_catchpoint (b->number);
6955   if (b->disposition == disp_del)
6956     ui_out_text (uiout, "\nTemporary catchpoint ");
6957   else
6958     ui_out_text (uiout, "\nCatchpoint ");
6959   if (ui_out_is_mi_like_p (uiout))
6960     {
6961       ui_out_field_string (uiout, "reason",
6962                            async_reason_lookup (EXEC_ASYNC_FORK));
6963       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6964     }
6965   ui_out_field_int (uiout, "bkptno", b->number);
6966   ui_out_text (uiout, " (forked process ");
6967   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6968   ui_out_text (uiout, "), ");
6969   return PRINT_SRC_AND_LOC;
6970 }
6971
6972 /* Implement the "print_one" breakpoint_ops method for fork
6973    catchpoints.  */
6974
6975 static void
6976 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
6977 {
6978   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6979   struct value_print_options opts;
6980   struct ui_out *uiout = current_uiout;
6981
6982   get_user_print_options (&opts);
6983
6984   /* Field 4, the address, is omitted (which makes the columns not
6985      line up too nicely with the headers, but the effect is relatively
6986      readable).  */
6987   if (opts.addressprint)
6988     ui_out_field_skip (uiout, "addr");
6989   annotate_field (5);
6990   ui_out_text (uiout, "fork");
6991   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6992     {
6993       ui_out_text (uiout, ", process ");
6994       ui_out_field_int (uiout, "what",
6995                         ptid_get_pid (c->forked_inferior_pid));
6996       ui_out_spaces (uiout, 1);
6997     }
6998 }
6999
7000 /* Implement the "print_mention" breakpoint_ops method for fork
7001    catchpoints.  */
7002
7003 static void
7004 print_mention_catch_fork (struct breakpoint *b)
7005 {
7006   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7007 }
7008
7009 /* Implement the "print_recreate" breakpoint_ops method for fork
7010    catchpoints.  */
7011
7012 static void
7013 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7014 {
7015   fprintf_unfiltered (fp, "catch fork");
7016   print_recreate_thread (b, fp);
7017 }
7018
7019 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7020
7021 static struct breakpoint_ops catch_fork_breakpoint_ops;
7022
7023 /* Implement the "insert" breakpoint_ops method for vfork
7024    catchpoints.  */
7025
7026 static int
7027 insert_catch_vfork (struct bp_location *bl)
7028 {
7029   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7030 }
7031
7032 /* Implement the "remove" breakpoint_ops method for vfork
7033    catchpoints.  */
7034
7035 static int
7036 remove_catch_vfork (struct bp_location *bl)
7037 {
7038   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7039 }
7040
7041 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7042    catchpoints.  */
7043
7044 static int
7045 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7046                             struct address_space *aspace, CORE_ADDR bp_addr,
7047                             const struct target_waitstatus *ws)
7048 {
7049   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7050
7051   if (ws->kind != TARGET_WAITKIND_VFORKED)
7052     return 0;
7053
7054   c->forked_inferior_pid = ws->value.related_pid;
7055   return 1;
7056 }
7057
7058 /* Implement the "print_it" breakpoint_ops method for vfork
7059    catchpoints.  */
7060
7061 static enum print_stop_action
7062 print_it_catch_vfork (bpstat bs)
7063 {
7064   struct ui_out *uiout = current_uiout;
7065   struct breakpoint *b = bs->breakpoint_at;
7066   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7067
7068   annotate_catchpoint (b->number);
7069   if (b->disposition == disp_del)
7070     ui_out_text (uiout, "\nTemporary catchpoint ");
7071   else
7072     ui_out_text (uiout, "\nCatchpoint ");
7073   if (ui_out_is_mi_like_p (uiout))
7074     {
7075       ui_out_field_string (uiout, "reason",
7076                            async_reason_lookup (EXEC_ASYNC_VFORK));
7077       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7078     }
7079   ui_out_field_int (uiout, "bkptno", b->number);
7080   ui_out_text (uiout, " (vforked process ");
7081   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7082   ui_out_text (uiout, "), ");
7083   return PRINT_SRC_AND_LOC;
7084 }
7085
7086 /* Implement the "print_one" breakpoint_ops method for vfork
7087    catchpoints.  */
7088
7089 static void
7090 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7091 {
7092   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7093   struct value_print_options opts;
7094   struct ui_out *uiout = current_uiout;
7095
7096   get_user_print_options (&opts);
7097   /* Field 4, the address, is omitted (which makes the columns not
7098      line up too nicely with the headers, but the effect is relatively
7099      readable).  */
7100   if (opts.addressprint)
7101     ui_out_field_skip (uiout, "addr");
7102   annotate_field (5);
7103   ui_out_text (uiout, "vfork");
7104   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7105     {
7106       ui_out_text (uiout, ", process ");
7107       ui_out_field_int (uiout, "what",
7108                         ptid_get_pid (c->forked_inferior_pid));
7109       ui_out_spaces (uiout, 1);
7110     }
7111 }
7112
7113 /* Implement the "print_mention" breakpoint_ops method for vfork
7114    catchpoints.  */
7115
7116 static void
7117 print_mention_catch_vfork (struct breakpoint *b)
7118 {
7119   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7120 }
7121
7122 /* Implement the "print_recreate" breakpoint_ops method for vfork
7123    catchpoints.  */
7124
7125 static void
7126 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7127 {
7128   fprintf_unfiltered (fp, "catch vfork");
7129   print_recreate_thread (b, fp);
7130 }
7131
7132 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7133
7134 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7135
7136 /* An instance of this type is used to represent an solib catchpoint.
7137    It includes a "struct breakpoint" as a kind of base class; users
7138    downcast to "struct breakpoint *" when needed.  A breakpoint is
7139    really of this type iff its ops pointer points to
7140    CATCH_SOLIB_BREAKPOINT_OPS.  */
7141
7142 struct solib_catchpoint
7143 {
7144   /* The base class.  */
7145   struct breakpoint base;
7146
7147   /* True for "catch load", false for "catch unload".  */
7148   unsigned char is_load;
7149
7150   /* Regular expression to match, if any.  COMPILED is only valid when
7151      REGEX is non-NULL.  */
7152   char *regex;
7153   regex_t compiled;
7154 };
7155
7156 static void
7157 dtor_catch_solib (struct breakpoint *b)
7158 {
7159   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7160
7161   if (self->regex)
7162     regfree (&self->compiled);
7163   xfree (self->regex);
7164
7165   base_breakpoint_ops.dtor (b);
7166 }
7167
7168 static int
7169 insert_catch_solib (struct bp_location *ignore)
7170 {
7171   return 0;
7172 }
7173
7174 static int
7175 remove_catch_solib (struct bp_location *ignore)
7176 {
7177   return 0;
7178 }
7179
7180 static int
7181 breakpoint_hit_catch_solib (const struct bp_location *bl,
7182                             struct address_space *aspace,
7183                             CORE_ADDR bp_addr,
7184                             const struct target_waitstatus *ws)
7185 {
7186   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7187   struct breakpoint *other;
7188
7189   if (ws->kind == TARGET_WAITKIND_LOADED)
7190     return 1;
7191
7192   ALL_BREAKPOINTS (other)
7193   {
7194     struct bp_location *other_bl;
7195
7196     if (other == bl->owner)
7197       continue;
7198
7199     if (other->type != bp_shlib_event)
7200       continue;
7201
7202     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7203       continue;
7204
7205     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7206       {
7207         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7208           return 1;
7209       }
7210   }
7211
7212   return 0;
7213 }
7214
7215 static void
7216 check_status_catch_solib (struct bpstats *bs)
7217 {
7218   struct solib_catchpoint *self
7219     = (struct solib_catchpoint *) bs->breakpoint_at;
7220   int ix;
7221
7222   if (self->is_load)
7223     {
7224       struct so_list *iter;
7225
7226       for (ix = 0;
7227            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7228                         ix, iter);
7229            ++ix)
7230         {
7231           if (!self->regex
7232               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7233             return;
7234         }
7235     }
7236   else
7237     {
7238       char *iter;
7239
7240       for (ix = 0;
7241            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7242                         ix, iter);
7243            ++ix)
7244         {
7245           if (!self->regex
7246               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7247             return;
7248         }
7249     }
7250
7251   bs->stop = 0;
7252   bs->print_it = print_it_noop;
7253 }
7254
7255 static enum print_stop_action
7256 print_it_catch_solib (bpstat bs)
7257 {
7258   struct breakpoint *b = bs->breakpoint_at;
7259   struct ui_out *uiout = current_uiout;
7260
7261   annotate_catchpoint (b->number);
7262   if (b->disposition == disp_del)
7263     ui_out_text (uiout, "\nTemporary catchpoint ");
7264   else
7265     ui_out_text (uiout, "\nCatchpoint ");
7266   ui_out_field_int (uiout, "bkptno", b->number);
7267   ui_out_text (uiout, "\n");
7268   if (ui_out_is_mi_like_p (uiout))
7269     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7270   print_solib_event (1);
7271   return PRINT_SRC_AND_LOC;
7272 }
7273
7274 static void
7275 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7276 {
7277   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7278   struct value_print_options opts;
7279   struct ui_out *uiout = current_uiout;
7280   char *msg;
7281
7282   get_user_print_options (&opts);
7283   /* Field 4, the address, is omitted (which makes the columns not
7284      line up too nicely with the headers, but the effect is relatively
7285      readable).  */
7286   if (opts.addressprint)
7287     {
7288       annotate_field (4);
7289       ui_out_field_skip (uiout, "addr");
7290     }
7291
7292   annotate_field (5);
7293   if (self->is_load)
7294     {
7295       if (self->regex)
7296         msg = xstrprintf (_("load of library matching %s"), self->regex);
7297       else
7298         msg = xstrdup (_("load of library"));
7299     }
7300   else
7301     {
7302       if (self->regex)
7303         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7304       else
7305         msg = xstrdup (_("unload of library"));
7306     }
7307   ui_out_field_string (uiout, "what", msg);
7308   xfree (msg);
7309 }
7310
7311 static void
7312 print_mention_catch_solib (struct breakpoint *b)
7313 {
7314   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7315
7316   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7317                    self->is_load ? "load" : "unload");
7318 }
7319
7320 static void
7321 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7322 {
7323   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7324
7325   fprintf_unfiltered (fp, "%s %s",
7326                       b->disposition == disp_del ? "tcatch" : "catch",
7327                       self->is_load ? "load" : "unload");
7328   if (self->regex)
7329     fprintf_unfiltered (fp, " %s", self->regex);
7330   fprintf_unfiltered (fp, "\n");
7331 }
7332
7333 static struct breakpoint_ops catch_solib_breakpoint_ops;
7334
7335 /* A helper function that does all the work for "catch load" and
7336    "catch unload".  */
7337
7338 static void
7339 catch_load_or_unload (char *arg, int from_tty, int is_load,
7340                       struct cmd_list_element *command)
7341 {
7342   struct solib_catchpoint *c;
7343   struct gdbarch *gdbarch = get_current_arch ();
7344   int tempflag;
7345   regex_t compiled;
7346   struct cleanup *cleanup;
7347
7348   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7349
7350   if (!arg)
7351     arg = "";
7352   arg = skip_spaces (arg);
7353
7354   c = XCNEW (struct solib_catchpoint);
7355   cleanup = make_cleanup (xfree, c);
7356
7357   if (*arg != '\0')
7358     {
7359       int errcode;
7360
7361       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7362       if (errcode != 0)
7363         {
7364           char *err = get_regcomp_error (errcode, &c->compiled);
7365
7366           make_cleanup (xfree, err);
7367           error (_("Invalid regexp (%s): %s"), err, arg);
7368         }
7369       c->regex = xstrdup (arg);
7370     }
7371
7372   c->is_load = is_load;
7373   init_catchpoint (&c->base, gdbarch, tempflag, NULL,
7374                    &catch_solib_breakpoint_ops);
7375
7376   discard_cleanups (cleanup);
7377   install_breakpoint (0, &c->base, 1);
7378 }
7379
7380 static void
7381 catch_load_command_1 (char *arg, int from_tty,
7382                       struct cmd_list_element *command)
7383 {
7384   catch_load_or_unload (arg, from_tty, 1, command);
7385 }
7386
7387 static void
7388 catch_unload_command_1 (char *arg, int from_tty,
7389                         struct cmd_list_element *command)
7390 {
7391   catch_load_or_unload (arg, from_tty, 0, command);
7392 }
7393
7394 DEF_VEC_I(int);
7395
7396 /* An instance of this type is used to represent a syscall catchpoint.
7397    It includes a "struct breakpoint" as a kind of base class; users
7398    downcast to "struct breakpoint *" when needed.  A breakpoint is
7399    really of this type iff its ops pointer points to
7400    CATCH_SYSCALL_BREAKPOINT_OPS.  */
7401
7402 struct syscall_catchpoint
7403 {
7404   /* The base class.  */
7405   struct breakpoint base;
7406
7407   /* Syscall numbers used for the 'catch syscall' feature.  If no
7408      syscall has been specified for filtering, its value is NULL.
7409      Otherwise, it holds a list of all syscalls to be caught.  The
7410      list elements are allocated with xmalloc.  */
7411   VEC(int) *syscalls_to_be_caught;
7412 };
7413
7414 /* Implement the "dtor" breakpoint_ops method for syscall
7415    catchpoints.  */
7416
7417 static void
7418 dtor_catch_syscall (struct breakpoint *b)
7419 {
7420   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7421
7422   VEC_free (int, c->syscalls_to_be_caught);
7423
7424   base_breakpoint_ops.dtor (b);
7425 }
7426
7427 static const struct inferior_data *catch_syscall_inferior_data = NULL;
7428
7429 struct catch_syscall_inferior_data
7430 {
7431   /* We keep a count of the number of times the user has requested a
7432      particular syscall to be tracked, and pass this information to the
7433      target.  This lets capable targets implement filtering directly.  */
7434
7435   /* Number of times that "any" syscall is requested.  */
7436   int any_syscall_count;
7437
7438   /* Count of each system call.  */
7439   VEC(int) *syscalls_counts;
7440
7441   /* This counts all syscall catch requests, so we can readily determine
7442      if any catching is necessary.  */
7443   int total_syscalls_count;
7444 };
7445
7446 static struct catch_syscall_inferior_data*
7447 get_catch_syscall_inferior_data (struct inferior *inf)
7448 {
7449   struct catch_syscall_inferior_data *inf_data;
7450
7451   inf_data = inferior_data (inf, catch_syscall_inferior_data);
7452   if (inf_data == NULL)
7453     {
7454       inf_data = XZALLOC (struct catch_syscall_inferior_data);
7455       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
7456     }
7457
7458   return inf_data;
7459 }
7460
7461 static void
7462 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
7463 {
7464   xfree (arg);
7465 }
7466
7467
7468 /* Implement the "insert" breakpoint_ops method for syscall
7469    catchpoints.  */
7470
7471 static int
7472 insert_catch_syscall (struct bp_location *bl)
7473 {
7474   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7475   struct inferior *inf = current_inferior ();
7476   struct catch_syscall_inferior_data *inf_data
7477     = get_catch_syscall_inferior_data (inf);
7478
7479   ++inf_data->total_syscalls_count;
7480   if (!c->syscalls_to_be_caught)
7481     ++inf_data->any_syscall_count;
7482   else
7483     {
7484       int i, iter;
7485
7486       for (i = 0;
7487            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7488            i++)
7489         {
7490           int elem;
7491
7492           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7493             {
7494               int old_size = VEC_length (int, inf_data->syscalls_counts);
7495               uintptr_t vec_addr_offset
7496                 = old_size * ((uintptr_t) sizeof (int));
7497               uintptr_t vec_addr;
7498               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
7499               vec_addr = ((uintptr_t) VEC_address (int,
7500                                                   inf_data->syscalls_counts)
7501                           + vec_addr_offset);
7502               memset ((void *) vec_addr, 0,
7503                       (iter + 1 - old_size) * sizeof (int));
7504             }
7505           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7506           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
7507         }
7508     }
7509
7510   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7511                                         inf_data->total_syscalls_count != 0,
7512                                         inf_data->any_syscall_count,
7513                                         VEC_length (int,
7514                                                     inf_data->syscalls_counts),
7515                                         VEC_address (int,
7516                                                      inf_data->syscalls_counts));
7517 }
7518
7519 /* Implement the "remove" breakpoint_ops method for syscall
7520    catchpoints.  */
7521
7522 static int
7523 remove_catch_syscall (struct bp_location *bl)
7524 {
7525   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7526   struct inferior *inf = current_inferior ();
7527   struct catch_syscall_inferior_data *inf_data
7528     = get_catch_syscall_inferior_data (inf);
7529
7530   --inf_data->total_syscalls_count;
7531   if (!c->syscalls_to_be_caught)
7532     --inf_data->any_syscall_count;
7533   else
7534     {
7535       int i, iter;
7536
7537       for (i = 0;
7538            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7539            i++)
7540         {
7541           int elem;
7542           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7543             /* Shouldn't happen.  */
7544             continue;
7545           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7546           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
7547         }
7548     }
7549
7550   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7551                                         inf_data->total_syscalls_count != 0,
7552                                         inf_data->any_syscall_count,
7553                                         VEC_length (int,
7554                                                     inf_data->syscalls_counts),
7555                                         VEC_address (int,
7556                                                      inf_data->syscalls_counts));
7557 }
7558
7559 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
7560    catchpoints.  */
7561
7562 static int
7563 breakpoint_hit_catch_syscall (const struct bp_location *bl,
7564                               struct address_space *aspace, CORE_ADDR bp_addr,
7565                               const struct target_waitstatus *ws)
7566 {
7567   /* We must check if we are catching specific syscalls in this
7568      breakpoint.  If we are, then we must guarantee that the called
7569      syscall is the same syscall we are catching.  */
7570   int syscall_number = 0;
7571   const struct syscall_catchpoint *c
7572     = (const struct syscall_catchpoint *) bl->owner;
7573
7574   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
7575       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
7576     return 0;
7577
7578   syscall_number = ws->value.syscall_number;
7579
7580   /* Now, checking if the syscall is the same.  */
7581   if (c->syscalls_to_be_caught)
7582     {
7583       int i, iter;
7584
7585       for (i = 0;
7586            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7587            i++)
7588         if (syscall_number == iter)
7589           break;
7590       /* Not the same.  */
7591       if (!iter)
7592         return 0;
7593     }
7594
7595   return 1;
7596 }
7597
7598 /* Implement the "print_it" breakpoint_ops method for syscall
7599    catchpoints.  */
7600
7601 static enum print_stop_action
7602 print_it_catch_syscall (bpstat bs)
7603 {
7604   struct ui_out *uiout = current_uiout;
7605   struct breakpoint *b = bs->breakpoint_at;
7606   /* These are needed because we want to know in which state a
7607      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
7608      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
7609      must print "called syscall" or "returned from syscall".  */
7610   ptid_t ptid;
7611   struct target_waitstatus last;
7612   struct syscall s;
7613   char *syscall_id;
7614
7615   get_last_target_status (&ptid, &last);
7616
7617   get_syscall_by_number (last.value.syscall_number, &s);
7618
7619   annotate_catchpoint (b->number);
7620
7621   if (b->disposition == disp_del)
7622     ui_out_text (uiout, "\nTemporary catchpoint ");
7623   else
7624     ui_out_text (uiout, "\nCatchpoint ");
7625   if (ui_out_is_mi_like_p (uiout))
7626     {
7627       ui_out_field_string (uiout, "reason",
7628                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
7629                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
7630                                                 : EXEC_ASYNC_SYSCALL_RETURN));
7631       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7632     }
7633   ui_out_field_int (uiout, "bkptno", b->number);
7634
7635   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
7636     ui_out_text (uiout, " (call to syscall ");
7637   else
7638     ui_out_text (uiout, " (returned from syscall ");
7639
7640   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
7641     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
7642   if (s.name != NULL)
7643     ui_out_field_string (uiout, "syscall-name", s.name);
7644
7645   ui_out_text (uiout, "), ");
7646
7647   return PRINT_SRC_AND_LOC;
7648 }
7649
7650 /* Implement the "print_one" breakpoint_ops method for syscall
7651    catchpoints.  */
7652
7653 static void
7654 print_one_catch_syscall (struct breakpoint *b,
7655                          struct bp_location **last_loc)
7656 {
7657   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7658   struct value_print_options opts;
7659   struct ui_out *uiout = current_uiout;
7660
7661   get_user_print_options (&opts);
7662   /* Field 4, the address, is omitted (which makes the columns not
7663      line up too nicely with the headers, but the effect is relatively
7664      readable).  */
7665   if (opts.addressprint)
7666     ui_out_field_skip (uiout, "addr");
7667   annotate_field (5);
7668
7669   if (c->syscalls_to_be_caught
7670       && VEC_length (int, c->syscalls_to_be_caught) > 1)
7671     ui_out_text (uiout, "syscalls \"");
7672   else
7673     ui_out_text (uiout, "syscall \"");
7674
7675   if (c->syscalls_to_be_caught)
7676     {
7677       int i, iter;
7678       char *text = xstrprintf ("%s", "");
7679
7680       for (i = 0;
7681            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7682            i++)
7683         {
7684           char *x = text;
7685           struct syscall s;
7686           get_syscall_by_number (iter, &s);
7687
7688           if (s.name != NULL)
7689             text = xstrprintf ("%s%s, ", text, s.name);
7690           else
7691             text = xstrprintf ("%s%d, ", text, iter);
7692
7693           /* We have to xfree the last 'text' (now stored at 'x')
7694              because xstrprintf dynamically allocates new space for it
7695              on every call.  */
7696           xfree (x);
7697         }
7698       /* Remove the last comma.  */
7699       text[strlen (text) - 2] = '\0';
7700       ui_out_field_string (uiout, "what", text);
7701     }
7702   else
7703     ui_out_field_string (uiout, "what", "<any syscall>");
7704   ui_out_text (uiout, "\" ");
7705 }
7706
7707 /* Implement the "print_mention" breakpoint_ops method for syscall
7708    catchpoints.  */
7709
7710 static void
7711 print_mention_catch_syscall (struct breakpoint *b)
7712 {
7713   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7714
7715   if (c->syscalls_to_be_caught)
7716     {
7717       int i, iter;
7718
7719       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
7720         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
7721       else
7722         printf_filtered (_("Catchpoint %d (syscall"), b->number);
7723
7724       for (i = 0;
7725            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7726            i++)
7727         {
7728           struct syscall s;
7729           get_syscall_by_number (iter, &s);
7730
7731           if (s.name)
7732             printf_filtered (" '%s' [%d]", s.name, s.number);
7733           else
7734             printf_filtered (" %d", s.number);
7735         }
7736       printf_filtered (")");
7737     }
7738   else
7739     printf_filtered (_("Catchpoint %d (any syscall)"),
7740                      b->number);
7741 }
7742
7743 /* Implement the "print_recreate" breakpoint_ops method for syscall
7744    catchpoints.  */
7745
7746 static void
7747 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
7748 {
7749   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7750
7751   fprintf_unfiltered (fp, "catch syscall");
7752
7753   if (c->syscalls_to_be_caught)
7754     {
7755       int i, iter;
7756
7757       for (i = 0;
7758            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7759            i++)
7760         {
7761           struct syscall s;
7762
7763           get_syscall_by_number (iter, &s);
7764           if (s.name)
7765             fprintf_unfiltered (fp, " %s", s.name);
7766           else
7767             fprintf_unfiltered (fp, " %d", s.number);
7768         }
7769     }
7770   print_recreate_thread (b, fp);
7771 }
7772
7773 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
7774
7775 static struct breakpoint_ops catch_syscall_breakpoint_ops;
7776
7777 /* Returns non-zero if 'b' is a syscall catchpoint.  */
7778
7779 static int
7780 syscall_catchpoint_p (struct breakpoint *b)
7781 {
7782   return (b->ops == &catch_syscall_breakpoint_ops);
7783 }
7784
7785 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
7786    is non-zero, then make the breakpoint temporary.  If COND_STRING is
7787    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
7788    the breakpoint_ops structure associated to the catchpoint.  */
7789
7790 static void
7791 init_catchpoint (struct breakpoint *b,
7792                  struct gdbarch *gdbarch, int tempflag,
7793                  char *cond_string,
7794                  const struct breakpoint_ops *ops)
7795 {
7796   struct symtab_and_line sal;
7797
7798   init_sal (&sal);
7799   sal.pspace = current_program_space;
7800
7801   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
7802
7803   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
7804   b->disposition = tempflag ? disp_del : disp_donttouch;
7805 }
7806
7807 void
7808 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
7809 {
7810   add_to_breakpoint_chain (b);
7811   set_breakpoint_number (internal, b);
7812   if (!internal)
7813     mention (b);
7814   observer_notify_breakpoint_created (b);
7815
7816   if (update_gll)
7817     update_global_location_list (1);
7818 }
7819
7820 static void
7821 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
7822                                     int tempflag, char *cond_string,
7823                                     const struct breakpoint_ops *ops)
7824 {
7825   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
7826
7827   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
7828
7829   c->forked_inferior_pid = null_ptid;
7830
7831   install_breakpoint (0, &c->base, 1);
7832 }
7833
7834 /* Exec catchpoints.  */
7835
7836 /* An instance of this type is used to represent an exec catchpoint.
7837    It includes a "struct breakpoint" as a kind of base class; users
7838    downcast to "struct breakpoint *" when needed.  A breakpoint is
7839    really of this type iff its ops pointer points to
7840    CATCH_EXEC_BREAKPOINT_OPS.  */
7841
7842 struct exec_catchpoint
7843 {
7844   /* The base class.  */
7845   struct breakpoint base;
7846
7847   /* Filename of a program whose exec triggered this catchpoint.
7848      This field is only valid immediately after this catchpoint has
7849      triggered.  */
7850   char *exec_pathname;
7851 };
7852
7853 /* Implement the "dtor" breakpoint_ops method for exec
7854    catchpoints.  */
7855
7856 static void
7857 dtor_catch_exec (struct breakpoint *b)
7858 {
7859   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7860
7861   xfree (c->exec_pathname);
7862
7863   base_breakpoint_ops.dtor (b);
7864 }
7865
7866 static int
7867 insert_catch_exec (struct bp_location *bl)
7868 {
7869   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
7870 }
7871
7872 static int
7873 remove_catch_exec (struct bp_location *bl)
7874 {
7875   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
7876 }
7877
7878 static int
7879 breakpoint_hit_catch_exec (const struct bp_location *bl,
7880                            struct address_space *aspace, CORE_ADDR bp_addr,
7881                            const struct target_waitstatus *ws)
7882 {
7883   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
7884
7885   if (ws->kind != TARGET_WAITKIND_EXECD)
7886     return 0;
7887
7888   c->exec_pathname = xstrdup (ws->value.execd_pathname);
7889   return 1;
7890 }
7891
7892 static enum print_stop_action
7893 print_it_catch_exec (bpstat bs)
7894 {
7895   struct ui_out *uiout = current_uiout;
7896   struct breakpoint *b = bs->breakpoint_at;
7897   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7898
7899   annotate_catchpoint (b->number);
7900   if (b->disposition == disp_del)
7901     ui_out_text (uiout, "\nTemporary catchpoint ");
7902   else
7903     ui_out_text (uiout, "\nCatchpoint ");
7904   if (ui_out_is_mi_like_p (uiout))
7905     {
7906       ui_out_field_string (uiout, "reason",
7907                            async_reason_lookup (EXEC_ASYNC_EXEC));
7908       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7909     }
7910   ui_out_field_int (uiout, "bkptno", b->number);
7911   ui_out_text (uiout, " (exec'd ");
7912   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
7913   ui_out_text (uiout, "), ");
7914
7915   return PRINT_SRC_AND_LOC;
7916 }
7917
7918 static void
7919 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
7920 {
7921   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7922   struct value_print_options opts;
7923   struct ui_out *uiout = current_uiout;
7924
7925   get_user_print_options (&opts);
7926
7927   /* Field 4, the address, is omitted (which makes the columns
7928      not line up too nicely with the headers, but the effect
7929      is relatively readable).  */
7930   if (opts.addressprint)
7931     ui_out_field_skip (uiout, "addr");
7932   annotate_field (5);
7933   ui_out_text (uiout, "exec");
7934   if (c->exec_pathname != NULL)
7935     {
7936       ui_out_text (uiout, ", program \"");
7937       ui_out_field_string (uiout, "what", c->exec_pathname);
7938       ui_out_text (uiout, "\" ");
7939     }
7940 }
7941
7942 static void
7943 print_mention_catch_exec (struct breakpoint *b)
7944 {
7945   printf_filtered (_("Catchpoint %d (exec)"), b->number);
7946 }
7947
7948 /* Implement the "print_recreate" breakpoint_ops method for exec
7949    catchpoints.  */
7950
7951 static void
7952 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
7953 {
7954   fprintf_unfiltered (fp, "catch exec");
7955   print_recreate_thread (b, fp);
7956 }
7957
7958 static struct breakpoint_ops catch_exec_breakpoint_ops;
7959
7960 static void
7961 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
7962                                  const struct breakpoint_ops *ops)
7963 {
7964   struct syscall_catchpoint *c;
7965   struct gdbarch *gdbarch = get_current_arch ();
7966
7967   c = XNEW (struct syscall_catchpoint);
7968   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
7969   c->syscalls_to_be_caught = filter;
7970
7971   install_breakpoint (0, &c->base, 1);
7972 }
7973
7974 static int
7975 hw_breakpoint_used_count (void)
7976 {
7977   int i = 0;
7978   struct breakpoint *b;
7979   struct bp_location *bl;
7980
7981   ALL_BREAKPOINTS (b)
7982   {
7983     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
7984       for (bl = b->loc; bl; bl = bl->next)
7985         {
7986           /* Special types of hardware breakpoints may use more than
7987              one register.  */
7988           i += b->ops->resources_needed (bl);
7989         }
7990   }
7991
7992   return i;
7993 }
7994
7995 /* Returns the resources B would use if it were a hardware
7996    watchpoint.  */
7997
7998 static int
7999 hw_watchpoint_use_count (struct breakpoint *b)
8000 {
8001   int i = 0;
8002   struct bp_location *bl;
8003
8004   if (!breakpoint_enabled (b))
8005     return 0;
8006
8007   for (bl = b->loc; bl; bl = bl->next)
8008     {
8009       /* Special types of hardware watchpoints may use more than
8010          one register.  */
8011       i += b->ops->resources_needed (bl);
8012     }
8013
8014   return i;
8015 }
8016
8017 /* Returns the sum the used resources of all hardware watchpoints of
8018    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8019    the sum of the used resources of all hardware watchpoints of other
8020    types _not_ TYPE.  */
8021
8022 static int
8023 hw_watchpoint_used_count_others (struct breakpoint *except,
8024                                  enum bptype type, int *other_type_used)
8025 {
8026   int i = 0;
8027   struct breakpoint *b;
8028
8029   *other_type_used = 0;
8030   ALL_BREAKPOINTS (b)
8031     {
8032       if (b == except)
8033         continue;
8034       if (!breakpoint_enabled (b))
8035         continue;
8036
8037       if (b->type == type)
8038         i += hw_watchpoint_use_count (b);
8039       else if (is_hardware_watchpoint (b))
8040         *other_type_used = 1;
8041     }
8042
8043   return i;
8044 }
8045
8046 void
8047 disable_watchpoints_before_interactive_call_start (void)
8048 {
8049   struct breakpoint *b;
8050
8051   ALL_BREAKPOINTS (b)
8052   {
8053     if (is_watchpoint (b) && breakpoint_enabled (b))
8054       {
8055         b->enable_state = bp_call_disabled;
8056         update_global_location_list (0);
8057       }
8058   }
8059 }
8060
8061 void
8062 enable_watchpoints_after_interactive_call_stop (void)
8063 {
8064   struct breakpoint *b;
8065
8066   ALL_BREAKPOINTS (b)
8067   {
8068     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8069       {
8070         b->enable_state = bp_enabled;
8071         update_global_location_list (1);
8072       }
8073   }
8074 }
8075
8076 void
8077 disable_breakpoints_before_startup (void)
8078 {
8079   current_program_space->executing_startup = 1;
8080   update_global_location_list (0);
8081 }
8082
8083 void
8084 enable_breakpoints_after_startup (void)
8085 {
8086   current_program_space->executing_startup = 0;
8087   breakpoint_re_set ();
8088 }
8089
8090
8091 /* Set a breakpoint that will evaporate an end of command
8092    at address specified by SAL.
8093    Restrict it to frame FRAME if FRAME is nonzero.  */
8094
8095 struct breakpoint *
8096 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8097                           struct frame_id frame_id, enum bptype type)
8098 {
8099   struct breakpoint *b;
8100
8101   /* If FRAME_ID is valid, it should be a real frame, not an inlined
8102      one.  */
8103   gdb_assert (!frame_id_inlined_p (frame_id));
8104
8105   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8106   b->enable_state = bp_enabled;
8107   b->disposition = disp_donttouch;
8108   b->frame_id = frame_id;
8109
8110   /* If we're debugging a multi-threaded program, then we want
8111      momentary breakpoints to be active in only a single thread of
8112      control.  */
8113   if (in_thread_list (inferior_ptid))
8114     b->thread = pid_to_thread_id (inferior_ptid);
8115
8116   update_global_location_list_nothrow (1);
8117
8118   return b;
8119 }
8120
8121 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8122    The new breakpoint will have type TYPE, and use OPS as it
8123    breakpoint_ops.  */
8124
8125 static struct breakpoint *
8126 momentary_breakpoint_from_master (struct breakpoint *orig,
8127                                   enum bptype type,
8128                                   const struct breakpoint_ops *ops)
8129 {
8130   struct breakpoint *copy;
8131
8132   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8133   copy->loc = allocate_bp_location (copy);
8134   set_breakpoint_location_function (copy->loc, 1);
8135
8136   copy->loc->gdbarch = orig->loc->gdbarch;
8137   copy->loc->requested_address = orig->loc->requested_address;
8138   copy->loc->address = orig->loc->address;
8139   copy->loc->section = orig->loc->section;
8140   copy->loc->pspace = orig->loc->pspace;
8141
8142   if (orig->loc->source_file != NULL)
8143     copy->loc->source_file = xstrdup (orig->loc->source_file);
8144
8145   copy->loc->line_number = orig->loc->line_number;
8146   copy->frame_id = orig->frame_id;
8147   copy->thread = orig->thread;
8148   copy->pspace = orig->pspace;
8149
8150   copy->enable_state = bp_enabled;
8151   copy->disposition = disp_donttouch;
8152   copy->number = internal_breakpoint_number--;
8153
8154   update_global_location_list_nothrow (0);
8155   return copy;
8156 }
8157
8158 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8159    ORIG is NULL.  */
8160
8161 struct breakpoint *
8162 clone_momentary_breakpoint (struct breakpoint *orig)
8163 {
8164   /* If there's nothing to clone, then return nothing.  */
8165   if (orig == NULL)
8166     return NULL;
8167
8168   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8169 }
8170
8171 struct breakpoint *
8172 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8173                                 enum bptype type)
8174 {
8175   struct symtab_and_line sal;
8176
8177   sal = find_pc_line (pc, 0);
8178   sal.pc = pc;
8179   sal.section = find_pc_overlay (pc);
8180   sal.explicit_pc = 1;
8181
8182   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8183 }
8184 \f
8185
8186 /* Tell the user we have just set a breakpoint B.  */
8187
8188 static void
8189 mention (struct breakpoint *b)
8190 {
8191   b->ops->print_mention (b);
8192   if (ui_out_is_mi_like_p (current_uiout))
8193     return;
8194   printf_filtered ("\n");
8195 }
8196 \f
8197
8198 static struct bp_location *
8199 add_location_to_breakpoint (struct breakpoint *b,
8200                             const struct symtab_and_line *sal)
8201 {
8202   struct bp_location *loc, **tmp;
8203   CORE_ADDR adjusted_address;
8204   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8205
8206   if (loc_gdbarch == NULL)
8207     loc_gdbarch = b->gdbarch;
8208
8209   /* Adjust the breakpoint's address prior to allocating a location.
8210      Once we call allocate_bp_location(), that mostly uninitialized
8211      location will be placed on the location chain.  Adjustment of the
8212      breakpoint may cause target_read_memory() to be called and we do
8213      not want its scan of the location chain to find a breakpoint and
8214      location that's only been partially initialized.  */
8215   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8216                                                 sal->pc, b->type);
8217
8218   loc = allocate_bp_location (b);
8219   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
8220     ;
8221   *tmp = loc;
8222
8223   loc->requested_address = sal->pc;
8224   loc->address = adjusted_address;
8225   loc->pspace = sal->pspace;
8226   gdb_assert (loc->pspace != NULL);
8227   loc->section = sal->section;
8228   loc->gdbarch = loc_gdbarch;
8229
8230   if (sal->symtab != NULL)
8231     loc->source_file = xstrdup (sal->symtab->filename);
8232   loc->line_number = sal->line;
8233
8234   set_breakpoint_location_function (loc,
8235                                     sal->explicit_pc || sal->explicit_line);
8236   return loc;
8237 }
8238 \f
8239
8240 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8241    return 0 otherwise.  */
8242
8243 static int
8244 bp_loc_is_permanent (struct bp_location *loc)
8245 {
8246   int len;
8247   CORE_ADDR addr;
8248   const gdb_byte *bpoint;
8249   gdb_byte *target_mem;
8250   struct cleanup *cleanup;
8251   int retval = 0;
8252
8253   gdb_assert (loc != NULL);
8254
8255   addr = loc->address;
8256   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8257
8258   /* Software breakpoints unsupported?  */
8259   if (bpoint == NULL)
8260     return 0;
8261
8262   target_mem = alloca (len);
8263
8264   /* Enable the automatic memory restoration from breakpoints while
8265      we read the memory.  Otherwise we could say about our temporary
8266      breakpoints they are permanent.  */
8267   cleanup = save_current_space_and_thread ();
8268
8269   switch_to_program_space_and_thread (loc->pspace);
8270   make_show_memory_breakpoints_cleanup (0);
8271
8272   if (target_read_memory (loc->address, target_mem, len) == 0
8273       && memcmp (target_mem, bpoint, len) == 0)
8274     retval = 1;
8275
8276   do_cleanups (cleanup);
8277
8278   return retval;
8279 }
8280
8281
8282
8283 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
8284    as textual description of the location, and COND_STRING
8285    as condition expression.  */
8286
8287 static void
8288 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8289                      struct symtabs_and_lines sals, char *addr_string,
8290                      char *filter, char *cond_string,
8291                      enum bptype type, enum bpdisp disposition,
8292                      int thread, int task, int ignore_count,
8293                      const struct breakpoint_ops *ops, int from_tty,
8294                      int enabled, int internal, unsigned flags,
8295                      int display_canonical)
8296 {
8297   int i;
8298
8299   if (type == bp_hardware_breakpoint)
8300     {
8301       int target_resources_ok;
8302
8303       i = hw_breakpoint_used_count ();
8304       target_resources_ok =
8305         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8306                                             i + 1, 0);
8307       if (target_resources_ok == 0)
8308         error (_("No hardware breakpoint support in the target."));
8309       else if (target_resources_ok < 0)
8310         error (_("Hardware breakpoints used exceeds limit."));
8311     }
8312
8313   gdb_assert (sals.nelts > 0);
8314
8315   for (i = 0; i < sals.nelts; ++i)
8316     {
8317       struct symtab_and_line sal = sals.sals[i];
8318       struct bp_location *loc;
8319
8320       if (from_tty)
8321         {
8322           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8323           if (!loc_gdbarch)
8324             loc_gdbarch = gdbarch;
8325
8326           describe_other_breakpoints (loc_gdbarch,
8327                                       sal.pspace, sal.pc, sal.section, thread);
8328         }
8329
8330       if (i == 0)
8331         {
8332           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8333           b->thread = thread;
8334           b->task = task;
8335   
8336           b->cond_string = cond_string;
8337           b->ignore_count = ignore_count;
8338           b->enable_state = enabled ? bp_enabled : bp_disabled;
8339           b->disposition = disposition;
8340
8341           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8342             b->loc->inserted = 1;
8343
8344           if (type == bp_static_tracepoint)
8345             {
8346               struct tracepoint *t = (struct tracepoint *) b;
8347               struct static_tracepoint_marker marker;
8348
8349               if (strace_marker_p (b))
8350                 {
8351                   /* We already know the marker exists, otherwise, we
8352                      wouldn't see a sal for it.  */
8353                   char *p = &addr_string[3];
8354                   char *endp;
8355                   char *marker_str;
8356
8357                   p = skip_spaces (p);
8358
8359                   endp = skip_to_space (p);
8360
8361                   marker_str = savestring (p, endp - p);
8362                   t->static_trace_marker_id = marker_str;
8363
8364                   printf_filtered (_("Probed static tracepoint "
8365                                      "marker \"%s\"\n"),
8366                                    t->static_trace_marker_id);
8367                 }
8368               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8369                 {
8370                   t->static_trace_marker_id = xstrdup (marker.str_id);
8371                   release_static_tracepoint_marker (&marker);
8372
8373                   printf_filtered (_("Probed static tracepoint "
8374                                      "marker \"%s\"\n"),
8375                                    t->static_trace_marker_id);
8376                 }
8377               else
8378                 warning (_("Couldn't determine the static "
8379                            "tracepoint marker to probe"));
8380             }
8381
8382           loc = b->loc;
8383         }
8384       else
8385         {
8386           loc = add_location_to_breakpoint (b, &sal);
8387           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8388             loc->inserted = 1;
8389         }
8390
8391       if (bp_loc_is_permanent (loc))
8392         make_breakpoint_permanent (b);
8393
8394       if (b->cond_string)
8395         {
8396           char *arg = b->cond_string;
8397           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
8398           if (*arg)
8399               error (_("Garbage %s follows condition"), arg);
8400         }
8401     }   
8402
8403   b->display_canonical = display_canonical;
8404   if (addr_string)
8405     b->addr_string = addr_string;
8406   else
8407     /* addr_string has to be used or breakpoint_re_set will delete
8408        me.  */
8409     b->addr_string
8410       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
8411   b->filter = filter;
8412 }
8413
8414 static void
8415 create_breakpoint_sal (struct gdbarch *gdbarch,
8416                        struct symtabs_and_lines sals, char *addr_string,
8417                        char *filter, char *cond_string,
8418                        enum bptype type, enum bpdisp disposition,
8419                        int thread, int task, int ignore_count,
8420                        const struct breakpoint_ops *ops, int from_tty,
8421                        int enabled, int internal, unsigned flags,
8422                        int display_canonical)
8423 {
8424   struct breakpoint *b;
8425   struct cleanup *old_chain;
8426
8427   if (is_tracepoint_type (type))
8428     {
8429       struct tracepoint *t;
8430
8431       t = XCNEW (struct tracepoint);
8432       b = &t->base;
8433     }
8434   else
8435     b = XNEW (struct breakpoint);
8436
8437   old_chain = make_cleanup (xfree, b);
8438
8439   init_breakpoint_sal (b, gdbarch,
8440                        sals, addr_string,
8441                        filter, cond_string,
8442                        type, disposition,
8443                        thread, task, ignore_count,
8444                        ops, from_tty,
8445                        enabled, internal, flags,
8446                        display_canonical);
8447   discard_cleanups (old_chain);
8448
8449   install_breakpoint (internal, b, 0);
8450 }
8451
8452 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8453    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8454    value.  COND_STRING, if not NULL, specified the condition to be
8455    used for all breakpoints.  Essentially the only case where
8456    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8457    function.  In that case, it's still not possible to specify
8458    separate conditions for different overloaded functions, so
8459    we take just a single condition string.
8460    
8461    NOTE: If the function succeeds, the caller is expected to cleanup
8462    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8463    array contents).  If the function fails (error() is called), the
8464    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8465    COND and SALS arrays and each of those arrays contents.  */
8466
8467 static void
8468 create_breakpoints_sal (struct gdbarch *gdbarch,
8469                         struct linespec_result *canonical,
8470                         char *cond_string,
8471                         enum bptype type, enum bpdisp disposition,
8472                         int thread, int task, int ignore_count,
8473                         const struct breakpoint_ops *ops, int from_tty,
8474                         int enabled, int internal, unsigned flags)
8475 {
8476   int i;
8477   struct linespec_sals *lsal;
8478
8479   if (canonical->pre_expanded)
8480     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
8481
8482   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
8483     {
8484       /* Note that 'addr_string' can be NULL in the case of a plain
8485          'break', without arguments.  */
8486       char *addr_string = (canonical->addr_string
8487                            ? xstrdup (canonical->addr_string)
8488                            : NULL);
8489       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
8490       struct cleanup *inner = make_cleanup (xfree, addr_string);
8491
8492       make_cleanup (xfree, filter_string);
8493       create_breakpoint_sal (gdbarch, lsal->sals,
8494                              addr_string,
8495                              filter_string,
8496                              cond_string, type, disposition,
8497                              thread, task, ignore_count, ops,
8498                              from_tty, enabled, internal, flags,
8499                              canonical->special_display);
8500       discard_cleanups (inner);
8501     }
8502 }
8503
8504 /* Parse ADDRESS which is assumed to be a SAL specification possibly
8505    followed by conditionals.  On return, SALS contains an array of SAL
8506    addresses found.  ADDR_STRING contains a vector of (canonical)
8507    address strings.  ADDRESS points to the end of the SAL.
8508
8509    The array and the line spec strings are allocated on the heap, it is
8510    the caller's responsibility to free them.  */
8511
8512 static void
8513 parse_breakpoint_sals (char **address,
8514                        struct linespec_result *canonical)
8515 {
8516   char *addr_start = *address;
8517
8518   /* If no arg given, or if first arg is 'if ', use the default
8519      breakpoint.  */
8520   if ((*address) == NULL
8521       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
8522     {
8523       /* The last displayed codepoint, if it's valid, is our default breakpoint
8524          address.  */
8525       if (last_displayed_sal_is_valid ())
8526         {
8527           struct linespec_sals lsal;
8528           struct symtab_and_line sal;
8529
8530           init_sal (&sal);              /* Initialize to zeroes.  */
8531           lsal.sals.sals = (struct symtab_and_line *)
8532             xmalloc (sizeof (struct symtab_and_line));
8533
8534           /* Set sal's pspace, pc, symtab, and line to the values
8535              corresponding to the last call to print_frame_info.  */
8536           get_last_displayed_sal (&sal);
8537           sal.section = find_pc_overlay (sal.pc);
8538
8539           /* "break" without arguments is equivalent to "break *PC"
8540              where PC is the last displayed codepoint's address.  So
8541              make sure to set sal.explicit_pc to prevent GDB from
8542              trying to expand the list of sals to include all other
8543              instances with the same symtab and line.  */
8544           sal.explicit_pc = 1;
8545
8546           lsal.sals.sals[0] = sal;
8547           lsal.sals.nelts = 1;
8548           lsal.canonical = NULL;
8549
8550           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
8551         }
8552       else
8553         error (_("No default breakpoint address now."));
8554     }
8555   else
8556     {
8557       /* Force almost all breakpoints to be in terms of the
8558          current_source_symtab (which is decode_line_1's default).
8559          This should produce the results we want almost all of the
8560          time while leaving default_breakpoint_* alone.  */
8561       if (last_displayed_sal_is_valid ())
8562         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8563                           get_last_displayed_symtab (),
8564                           get_last_displayed_line (),
8565                           canonical, NULL, NULL);
8566       else
8567         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8568                           (struct symtab *) NULL, 0,
8569                           canonical, NULL, NULL);
8570     }
8571 }
8572
8573
8574 /* Convert each SAL into a real PC.  Verify that the PC can be
8575    inserted as a breakpoint.  If it can't throw an error.  */
8576
8577 static void
8578 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
8579 {    
8580   int i;
8581
8582   for (i = 0; i < sals->nelts; i++)
8583     resolve_sal_pc (&sals->sals[i]);
8584 }
8585
8586 /* Fast tracepoints may have restrictions on valid locations.  For
8587    instance, a fast tracepoint using a jump instead of a trap will
8588    likely have to overwrite more bytes than a trap would, and so can
8589    only be placed where the instruction is longer than the jump, or a
8590    multi-instruction sequence does not have a jump into the middle of
8591    it, etc.  */
8592
8593 static void
8594 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8595                             struct symtabs_and_lines *sals)
8596 {
8597   int i, rslt;
8598   struct symtab_and_line *sal;
8599   char *msg;
8600   struct cleanup *old_chain;
8601
8602   for (i = 0; i < sals->nelts; i++)
8603     {
8604       struct gdbarch *sarch;
8605
8606       sal = &sals->sals[i];
8607
8608       sarch = get_sal_arch (*sal);
8609       /* We fall back to GDBARCH if there is no architecture
8610          associated with SAL.  */
8611       if (sarch == NULL)
8612         sarch = gdbarch;
8613       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
8614                                                NULL, &msg);
8615       old_chain = make_cleanup (xfree, msg);
8616
8617       if (!rslt)
8618         error (_("May not have a fast tracepoint at 0x%s%s"),
8619                paddress (sarch, sal->pc), (msg ? msg : ""));
8620
8621       do_cleanups (old_chain);
8622     }
8623 }
8624
8625 /* Given TOK, a string specification of condition and thread, as
8626    accepted by the 'break' command, extract the condition
8627    string and thread number and set *COND_STRING and *THREAD.
8628    PC identifies the context at which the condition should be parsed.
8629    If no condition is found, *COND_STRING is set to NULL.
8630    If no thread is found, *THREAD is set to -1.  */
8631 static void 
8632 find_condition_and_thread (char *tok, CORE_ADDR pc, 
8633                            char **cond_string, int *thread, int *task)
8634 {
8635   *cond_string = NULL;
8636   *thread = -1;
8637   while (tok && *tok)
8638     {
8639       char *end_tok;
8640       int toklen;
8641       char *cond_start = NULL;
8642       char *cond_end = NULL;
8643
8644       tok = skip_spaces (tok);
8645       
8646       end_tok = skip_to_space (tok);
8647       
8648       toklen = end_tok - tok;
8649       
8650       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8651         {
8652           struct expression *expr;
8653
8654           tok = cond_start = end_tok + 1;
8655           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
8656           xfree (expr);
8657           cond_end = tok;
8658           *cond_string = savestring (cond_start, 
8659                                      cond_end - cond_start);
8660         }
8661       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8662         {
8663           char *tmptok;
8664           
8665           tok = end_tok + 1;
8666           tmptok = tok;
8667           *thread = strtol (tok, &tok, 0);
8668           if (tok == tmptok)
8669             error (_("Junk after thread keyword."));
8670           if (!valid_thread_id (*thread))
8671             error (_("Unknown thread %d."), *thread);
8672         }
8673       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
8674         {
8675           char *tmptok;
8676
8677           tok = end_tok + 1;
8678           tmptok = tok;
8679           *task = strtol (tok, &tok, 0);
8680           if (tok == tmptok)
8681             error (_("Junk after task keyword."));
8682           if (!valid_task_id (*task))
8683             error (_("Unknown task %d."), *task);
8684         }
8685       else
8686         error (_("Junk at end of arguments."));
8687     }
8688 }
8689
8690 /* Decode a static tracepoint marker spec.  */
8691
8692 static struct symtabs_and_lines
8693 decode_static_tracepoint_spec (char **arg_p)
8694 {
8695   VEC(static_tracepoint_marker_p) *markers = NULL;
8696   struct symtabs_and_lines sals;
8697   struct symtab_and_line sal;
8698   struct symbol *sym;
8699   struct cleanup *old_chain;
8700   char *p = &(*arg_p)[3];
8701   char *endp;
8702   char *marker_str;
8703   int i;
8704
8705   p = skip_spaces (p);
8706
8707   endp = skip_to_space (p);
8708
8709   marker_str = savestring (p, endp - p);
8710   old_chain = make_cleanup (xfree, marker_str);
8711
8712   markers = target_static_tracepoint_markers_by_strid (marker_str);
8713   if (VEC_empty(static_tracepoint_marker_p, markers))
8714     error (_("No known static tracepoint marker named %s"), marker_str);
8715
8716   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
8717   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
8718
8719   for (i = 0; i < sals.nelts; i++)
8720     {
8721       struct static_tracepoint_marker *marker;
8722
8723       marker = VEC_index (static_tracepoint_marker_p, markers, i);
8724
8725       init_sal (&sals.sals[i]);
8726
8727       sals.sals[i] = find_pc_line (marker->address, 0);
8728       sals.sals[i].pc = marker->address;
8729
8730       release_static_tracepoint_marker (marker);
8731     }
8732
8733   do_cleanups (old_chain);
8734
8735   *arg_p = endp;
8736   return sals;
8737 }
8738
8739 /* Set a breakpoint.  This function is shared between CLI and MI
8740    functions for setting a breakpoint.  This function has two major
8741    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
8742    parameter.  If non-zero, the function will parse arg, extracting
8743    breakpoint location, address and thread.  Otherwise, ARG is just
8744    the location of breakpoint, with condition and thread specified by
8745    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
8746    the breakpoint number will be allocated from the internal
8747    breakpoint count.  Returns true if any breakpoint was created;
8748    false otherwise.  */
8749
8750 int
8751 create_breakpoint (struct gdbarch *gdbarch,
8752                    char *arg, char *cond_string, int thread,
8753                    int parse_condition_and_thread,
8754                    int tempflag, enum bptype type_wanted,
8755                    int ignore_count,
8756                    enum auto_boolean pending_break_support,
8757                    const struct breakpoint_ops *ops,
8758                    int from_tty, int enabled, int internal,
8759                    unsigned flags)
8760 {
8761   volatile struct gdb_exception e;
8762   char *copy_arg = NULL;
8763   char *addr_start = arg;
8764   struct linespec_result canonical;
8765   struct cleanup *old_chain;
8766   struct cleanup *bkpt_chain = NULL;
8767   int i;
8768   int pending = 0;
8769   int task = 0;
8770   int prev_bkpt_count = breakpoint_count;
8771
8772   gdb_assert (ops != NULL);
8773
8774   init_linespec_result (&canonical);
8775
8776   TRY_CATCH (e, RETURN_MASK_ALL)
8777     {
8778       ops->create_sals_from_address (&arg, &canonical, type_wanted,
8779                                      addr_start, &copy_arg);
8780     }
8781
8782   /* If caller is interested in rc value from parse, set value.  */
8783   switch (e.reason)
8784     {
8785     case GDB_NO_ERROR:
8786       if (VEC_empty (linespec_sals, canonical.sals))
8787         return 0;
8788       break;
8789     case RETURN_ERROR:
8790       switch (e.error)
8791         {
8792         case NOT_FOUND_ERROR:
8793
8794           /* If pending breakpoint support is turned off, throw
8795              error.  */
8796
8797           if (pending_break_support == AUTO_BOOLEAN_FALSE)
8798             throw_exception (e);
8799
8800           exception_print (gdb_stderr, e);
8801
8802           /* If pending breakpoint support is auto query and the user
8803              selects no, then simply return the error code.  */
8804           if (pending_break_support == AUTO_BOOLEAN_AUTO
8805               && !nquery (_("Make %s pending on future shared library load? "),
8806                           bptype_string (type_wanted)))
8807             return 0;
8808
8809           /* At this point, either the user was queried about setting
8810              a pending breakpoint and selected yes, or pending
8811              breakpoint behavior is on and thus a pending breakpoint
8812              is defaulted on behalf of the user.  */
8813           {
8814             struct linespec_sals lsal;
8815
8816             copy_arg = xstrdup (addr_start);
8817             lsal.canonical = xstrdup (copy_arg);
8818             lsal.sals.nelts = 1;
8819             lsal.sals.sals = XNEW (struct symtab_and_line);
8820             init_sal (&lsal.sals.sals[0]);
8821             pending = 1;
8822             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
8823           }
8824           break;
8825         default:
8826           throw_exception (e);
8827         }
8828       break;
8829     default:
8830       throw_exception (e);
8831     }
8832
8833   /* Create a chain of things that always need to be cleaned up.  */
8834   old_chain = make_cleanup_destroy_linespec_result (&canonical);
8835
8836   /* ----------------------------- SNIP -----------------------------
8837      Anything added to the cleanup chain beyond this point is assumed
8838      to be part of a breakpoint.  If the breakpoint create succeeds
8839      then the memory is not reclaimed.  */
8840   bkpt_chain = make_cleanup (null_cleanup, 0);
8841
8842   /* Resolve all line numbers to PC's and verify that the addresses
8843      are ok for the target.  */
8844   if (!pending)
8845     {
8846       int ix;
8847       struct linespec_sals *iter;
8848
8849       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8850         breakpoint_sals_to_pc (&iter->sals);
8851     }
8852
8853   /* Fast tracepoints may have additional restrictions on location.  */
8854   if (!pending && type_wanted == bp_fast_tracepoint)
8855     {
8856       int ix;
8857       struct linespec_sals *iter;
8858
8859       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
8860         check_fast_tracepoint_sals (gdbarch, &iter->sals);
8861     }
8862
8863   /* Verify that condition can be parsed, before setting any
8864      breakpoints.  Allocate a separate condition expression for each
8865      breakpoint.  */
8866   if (!pending)
8867     {
8868       struct linespec_sals *lsal;
8869
8870       lsal = VEC_index (linespec_sals, canonical.sals, 0);
8871
8872       if (parse_condition_and_thread)
8873         {
8874             /* Here we only parse 'arg' to separate condition
8875                from thread number, so parsing in context of first
8876                sal is OK.  When setting the breakpoint we'll 
8877                re-parse it in context of each sal.  */
8878             cond_string = NULL;
8879             thread = -1;
8880             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
8881                                        &thread, &task);
8882             if (cond_string)
8883                 make_cleanup (xfree, cond_string);
8884         }
8885       else
8886         {
8887             /* Create a private copy of condition string.  */
8888             if (cond_string)
8889             {
8890                 cond_string = xstrdup (cond_string);
8891                 make_cleanup (xfree, cond_string);
8892             }
8893         }
8894
8895       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
8896                                    cond_string, type_wanted,
8897                                    tempflag ? disp_del : disp_donttouch,
8898                                    thread, task, ignore_count, ops,
8899                                    from_tty, enabled, internal, flags);
8900     }
8901   else
8902     {
8903       struct breakpoint *b;
8904
8905       make_cleanup (xfree, copy_arg);
8906
8907       if (is_tracepoint_type (type_wanted))
8908         {
8909           struct tracepoint *t;
8910
8911           t = XCNEW (struct tracepoint);
8912           b = &t->base;
8913         }
8914       else
8915         b = XNEW (struct breakpoint);
8916
8917       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
8918
8919       b->addr_string = copy_arg;
8920       b->cond_string = NULL;
8921       b->ignore_count = ignore_count;
8922       b->disposition = tempflag ? disp_del : disp_donttouch;
8923       b->condition_not_parsed = 1;
8924       b->enable_state = enabled ? bp_enabled : bp_disabled;
8925       if ((type_wanted != bp_breakpoint
8926            && type_wanted != bp_hardware_breakpoint) || thread != -1)
8927         b->pspace = current_program_space;
8928
8929       install_breakpoint (internal, b, 0);
8930     }
8931   
8932   if (VEC_length (linespec_sals, canonical.sals) > 1)
8933     {
8934       warning (_("Multiple breakpoints were set.\nUse the "
8935                  "\"delete\" command to delete unwanted breakpoints."));
8936       prev_breakpoint_count = prev_bkpt_count;
8937     }
8938
8939   /* That's it.  Discard the cleanups for data inserted into the
8940      breakpoint.  */
8941   discard_cleanups (bkpt_chain);
8942   /* But cleanup everything else.  */
8943   do_cleanups (old_chain);
8944
8945   /* error call may happen here - have BKPT_CHAIN already discarded.  */
8946   update_global_location_list (1);
8947
8948   return 1;
8949 }
8950
8951 /* Set a breakpoint.
8952    ARG is a string describing breakpoint address,
8953    condition, and thread.
8954    FLAG specifies if a breakpoint is hardware on,
8955    and if breakpoint is temporary, using BP_HARDWARE_FLAG
8956    and BP_TEMPFLAG.  */
8957
8958 static void
8959 break_command_1 (char *arg, int flag, int from_tty)
8960 {
8961   int tempflag = flag & BP_TEMPFLAG;
8962   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
8963                              ? bp_hardware_breakpoint
8964                              : bp_breakpoint);
8965
8966   create_breakpoint (get_current_arch (),
8967                      arg,
8968                      NULL, 0, 1 /* parse arg */,
8969                      tempflag, type_wanted,
8970                      0 /* Ignore count */,
8971                      pending_break_support,
8972                      &bkpt_breakpoint_ops,
8973                      from_tty,
8974                      1 /* enabled */,
8975                      0 /* internal */,
8976                      0);
8977 }
8978
8979 /* Helper function for break_command_1 and disassemble_command.  */
8980
8981 void
8982 resolve_sal_pc (struct symtab_and_line *sal)
8983 {
8984   CORE_ADDR pc;
8985
8986   if (sal->pc == 0 && sal->symtab != NULL)
8987     {
8988       if (!find_line_pc (sal->symtab, sal->line, &pc))
8989         error (_("No line %d in file \"%s\"."),
8990                sal->line, sal->symtab->filename);
8991       sal->pc = pc;
8992
8993       /* If this SAL corresponds to a breakpoint inserted using a line
8994          number, then skip the function prologue if necessary.  */
8995       if (sal->explicit_line)
8996         skip_prologue_sal (sal);
8997     }
8998
8999   if (sal->section == 0 && sal->symtab != NULL)
9000     {
9001       struct blockvector *bv;
9002       struct block *b;
9003       struct symbol *sym;
9004
9005       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9006       if (bv != NULL)
9007         {
9008           sym = block_linkage_function (b);
9009           if (sym != NULL)
9010             {
9011               fixup_symbol_section (sym, sal->symtab->objfile);
9012               sal->section = SYMBOL_OBJ_SECTION (sym);
9013             }
9014           else
9015             {
9016               /* It really is worthwhile to have the section, so we'll
9017                  just have to look harder. This case can be executed
9018                  if we have line numbers but no functions (as can
9019                  happen in assembly source).  */
9020
9021               struct minimal_symbol *msym;
9022               struct cleanup *old_chain = save_current_space_and_thread ();
9023
9024               switch_to_program_space_and_thread (sal->pspace);
9025
9026               msym = lookup_minimal_symbol_by_pc (sal->pc);
9027               if (msym)
9028                 sal->section = SYMBOL_OBJ_SECTION (msym);
9029
9030               do_cleanups (old_chain);
9031             }
9032         }
9033     }
9034 }
9035
9036 void
9037 break_command (char *arg, int from_tty)
9038 {
9039   break_command_1 (arg, 0, from_tty);
9040 }
9041
9042 void
9043 tbreak_command (char *arg, int from_tty)
9044 {
9045   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9046 }
9047
9048 static void
9049 hbreak_command (char *arg, int from_tty)
9050 {
9051   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9052 }
9053
9054 static void
9055 thbreak_command (char *arg, int from_tty)
9056 {
9057   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9058 }
9059
9060 static void
9061 stop_command (char *arg, int from_tty)
9062 {
9063   printf_filtered (_("Specify the type of breakpoint to set.\n\
9064 Usage: stop in <function | address>\n\
9065        stop at <line>\n"));
9066 }
9067
9068 static void
9069 stopin_command (char *arg, int from_tty)
9070 {
9071   int badInput = 0;
9072
9073   if (arg == (char *) NULL)
9074     badInput = 1;
9075   else if (*arg != '*')
9076     {
9077       char *argptr = arg;
9078       int hasColon = 0;
9079
9080       /* Look for a ':'.  If this is a line number specification, then
9081          say it is bad, otherwise, it should be an address or
9082          function/method name.  */
9083       while (*argptr && !hasColon)
9084         {
9085           hasColon = (*argptr == ':');
9086           argptr++;
9087         }
9088
9089       if (hasColon)
9090         badInput = (*argptr != ':');    /* Not a class::method */
9091       else
9092         badInput = isdigit (*arg);      /* a simple line number */
9093     }
9094
9095   if (badInput)
9096     printf_filtered (_("Usage: stop in <function | address>\n"));
9097   else
9098     break_command_1 (arg, 0, from_tty);
9099 }
9100
9101 static void
9102 stopat_command (char *arg, int from_tty)
9103 {
9104   int badInput = 0;
9105
9106   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9107     badInput = 1;
9108   else
9109     {
9110       char *argptr = arg;
9111       int hasColon = 0;
9112
9113       /* Look for a ':'.  If there is a '::' then get out, otherwise
9114          it is probably a line number.  */
9115       while (*argptr && !hasColon)
9116         {
9117           hasColon = (*argptr == ':');
9118           argptr++;
9119         }
9120
9121       if (hasColon)
9122         badInput = (*argptr == ':');    /* we have class::method */
9123       else
9124         badInput = !isdigit (*arg);     /* not a line number */
9125     }
9126
9127   if (badInput)
9128     printf_filtered (_("Usage: stop at <line>\n"));
9129   else
9130     break_command_1 (arg, 0, from_tty);
9131 }
9132
9133 /* Implement the "breakpoint_hit" breakpoint_ops method for
9134    ranged breakpoints.  */
9135
9136 static int
9137 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9138                                   struct address_space *aspace,
9139                                   CORE_ADDR bp_addr,
9140                                   const struct target_waitstatus *ws)
9141 {
9142   if (ws->kind != TARGET_WAITKIND_STOPPED
9143       || ws->value.sig != TARGET_SIGNAL_TRAP)
9144     return 0;
9145
9146   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9147                                          bl->length, aspace, bp_addr);
9148 }
9149
9150 /* Implement the "resources_needed" breakpoint_ops method for
9151    ranged breakpoints.  */
9152
9153 static int
9154 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9155 {
9156   return target_ranged_break_num_registers ();
9157 }
9158
9159 /* Implement the "print_it" breakpoint_ops method for
9160    ranged breakpoints.  */
9161
9162 static enum print_stop_action
9163 print_it_ranged_breakpoint (bpstat bs)
9164 {
9165   struct breakpoint *b = bs->breakpoint_at;
9166   struct bp_location *bl = b->loc;
9167   struct ui_out *uiout = current_uiout;
9168
9169   gdb_assert (b->type == bp_hardware_breakpoint);
9170
9171   /* Ranged breakpoints have only one location.  */
9172   gdb_assert (bl && bl->next == NULL);
9173
9174   annotate_breakpoint (b->number);
9175   if (b->disposition == disp_del)
9176     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
9177   else
9178     ui_out_text (uiout, "\nRanged breakpoint ");
9179   if (ui_out_is_mi_like_p (uiout))
9180     {
9181       ui_out_field_string (uiout, "reason",
9182                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9183       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9184     }
9185   ui_out_field_int (uiout, "bkptno", b->number);
9186   ui_out_text (uiout, ", ");
9187
9188   return PRINT_SRC_AND_LOC;
9189 }
9190
9191 /* Implement the "print_one" breakpoint_ops method for
9192    ranged breakpoints.  */
9193
9194 static void
9195 print_one_ranged_breakpoint (struct breakpoint *b,
9196                              struct bp_location **last_loc)
9197 {
9198   struct bp_location *bl = b->loc;
9199   struct value_print_options opts;
9200   struct ui_out *uiout = current_uiout;
9201
9202   /* Ranged breakpoints have only one location.  */
9203   gdb_assert (bl && bl->next == NULL);
9204
9205   get_user_print_options (&opts);
9206
9207   if (opts.addressprint)
9208     /* We don't print the address range here, it will be printed later
9209        by print_one_detail_ranged_breakpoint.  */
9210     ui_out_field_skip (uiout, "addr");
9211   annotate_field (5);
9212   print_breakpoint_location (b, bl);
9213   *last_loc = bl;
9214 }
9215
9216 /* Implement the "print_one_detail" breakpoint_ops method for
9217    ranged breakpoints.  */
9218
9219 static void
9220 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9221                                     struct ui_out *uiout)
9222 {
9223   CORE_ADDR address_start, address_end;
9224   struct bp_location *bl = b->loc;
9225   struct ui_file *stb = mem_fileopen ();
9226   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
9227
9228   gdb_assert (bl);
9229
9230   address_start = bl->address;
9231   address_end = address_start + bl->length - 1;
9232
9233   ui_out_text (uiout, "\taddress range: ");
9234   fprintf_unfiltered (stb, "[%s, %s]",
9235                       print_core_address (bl->gdbarch, address_start),
9236                       print_core_address (bl->gdbarch, address_end));
9237   ui_out_field_stream (uiout, "addr", stb);
9238   ui_out_text (uiout, "\n");
9239
9240   do_cleanups (cleanup);
9241 }
9242
9243 /* Implement the "print_mention" breakpoint_ops method for
9244    ranged breakpoints.  */
9245
9246 static void
9247 print_mention_ranged_breakpoint (struct breakpoint *b)
9248 {
9249   struct bp_location *bl = b->loc;
9250   struct ui_out *uiout = current_uiout;
9251
9252   gdb_assert (bl);
9253   gdb_assert (b->type == bp_hardware_breakpoint);
9254
9255   if (ui_out_is_mi_like_p (uiout))
9256     return;
9257
9258   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9259                    b->number, paddress (bl->gdbarch, bl->address),
9260                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9261 }
9262
9263 /* Implement the "print_recreate" breakpoint_ops method for
9264    ranged breakpoints.  */
9265
9266 static void
9267 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9268 {
9269   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
9270                       b->addr_string_range_end);
9271   print_recreate_thread (b, fp);
9272 }
9273
9274 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9275
9276 static struct breakpoint_ops ranged_breakpoint_ops;
9277
9278 /* Find the address where the end of the breakpoint range should be
9279    placed, given the SAL of the end of the range.  This is so that if
9280    the user provides a line number, the end of the range is set to the
9281    last instruction of the given line.  */
9282
9283 static CORE_ADDR
9284 find_breakpoint_range_end (struct symtab_and_line sal)
9285 {
9286   CORE_ADDR end;
9287
9288   /* If the user provided a PC value, use it.  Otherwise,
9289      find the address of the end of the given location.  */
9290   if (sal.explicit_pc)
9291     end = sal.pc;
9292   else
9293     {
9294       int ret;
9295       CORE_ADDR start;
9296
9297       ret = find_line_pc_range (sal, &start, &end);
9298       if (!ret)
9299         error (_("Could not find location of the end of the range."));
9300
9301       /* find_line_pc_range returns the start of the next line.  */
9302       end--;
9303     }
9304
9305   return end;
9306 }
9307
9308 /* Implement the "break-range" CLI command.  */
9309
9310 static void
9311 break_range_command (char *arg, int from_tty)
9312 {
9313   char *arg_start, *addr_string_start, *addr_string_end;
9314   struct linespec_result canonical_start, canonical_end;
9315   int bp_count, can_use_bp, length;
9316   CORE_ADDR end;
9317   struct breakpoint *b;
9318   struct symtab_and_line sal_start, sal_end;
9319   struct cleanup *cleanup_bkpt;
9320   struct linespec_sals *lsal_start, *lsal_end;
9321
9322   /* We don't support software ranged breakpoints.  */
9323   if (target_ranged_break_num_registers () < 0)
9324     error (_("This target does not support hardware ranged breakpoints."));
9325
9326   bp_count = hw_breakpoint_used_count ();
9327   bp_count += target_ranged_break_num_registers ();
9328   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9329                                                    bp_count, 0);
9330   if (can_use_bp < 0)
9331     error (_("Hardware breakpoints used exceeds limit."));
9332
9333   arg = skip_spaces (arg);
9334   if (arg == NULL || arg[0] == '\0')
9335     error(_("No address range specified."));
9336
9337   init_linespec_result (&canonical_start);
9338
9339   arg_start = arg;
9340   parse_breakpoint_sals (&arg, &canonical_start);
9341
9342   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
9343
9344   if (arg[0] != ',')
9345     error (_("Too few arguments."));
9346   else if (VEC_empty (linespec_sals, canonical_start.sals))
9347     error (_("Could not find location of the beginning of the range."));
9348
9349   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
9350
9351   if (VEC_length (linespec_sals, canonical_start.sals) > 1
9352       || lsal_start->sals.nelts != 1)
9353     error (_("Cannot create a ranged breakpoint with multiple locations."));
9354
9355   sal_start = lsal_start->sals.sals[0];
9356   addr_string_start = savestring (arg_start, arg - arg_start);
9357   make_cleanup (xfree, addr_string_start);
9358
9359   arg++;        /* Skip the comma.  */
9360   arg = skip_spaces (arg);
9361
9362   /* Parse the end location.  */
9363
9364   init_linespec_result (&canonical_end);
9365   arg_start = arg;
9366
9367   /* We call decode_line_full directly here instead of using
9368      parse_breakpoint_sals because we need to specify the start location's
9369      symtab and line as the default symtab and line for the end of the
9370      range.  This makes it possible to have ranges like "foo.c:27, +14",
9371      where +14 means 14 lines from the start location.  */
9372   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
9373                     sal_start.symtab, sal_start.line,
9374                     &canonical_end, NULL, NULL);
9375
9376   make_cleanup_destroy_linespec_result (&canonical_end);
9377
9378   if (VEC_empty (linespec_sals, canonical_end.sals))
9379     error (_("Could not find location of the end of the range."));
9380
9381   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
9382   if (VEC_length (linespec_sals, canonical_end.sals) > 1
9383       || lsal_end->sals.nelts != 1)
9384     error (_("Cannot create a ranged breakpoint with multiple locations."));
9385
9386   sal_end = lsal_end->sals.sals[0];
9387   addr_string_end = savestring (arg_start, arg - arg_start);
9388   make_cleanup (xfree, addr_string_end);
9389
9390   end = find_breakpoint_range_end (sal_end);
9391   if (sal_start.pc > end)
9392     error (_("Invalid address range, end precedes start."));
9393
9394   length = end - sal_start.pc + 1;
9395   if (length < 0)
9396     /* Length overflowed.  */
9397     error (_("Address range too large."));
9398   else if (length == 1)
9399     {
9400       /* This range is simple enough to be handled by
9401          the `hbreak' command.  */
9402       hbreak_command (addr_string_start, 1);
9403
9404       do_cleanups (cleanup_bkpt);
9405
9406       return;
9407     }
9408
9409   /* Now set up the breakpoint.  */
9410   b = set_raw_breakpoint (get_current_arch (), sal_start,
9411                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9412   set_breakpoint_count (breakpoint_count + 1);
9413   b->number = breakpoint_count;
9414   b->disposition = disp_donttouch;
9415   b->addr_string = xstrdup (addr_string_start);
9416   b->addr_string_range_end = xstrdup (addr_string_end);
9417   b->loc->length = length;
9418
9419   do_cleanups (cleanup_bkpt);
9420
9421   mention (b);
9422   observer_notify_breakpoint_created (b);
9423   update_global_location_list (1);
9424 }
9425
9426 /*  Return non-zero if EXP is verified as constant.  Returned zero
9427     means EXP is variable.  Also the constant detection may fail for
9428     some constant expressions and in such case still falsely return
9429     zero.  */
9430
9431 static int
9432 watchpoint_exp_is_const (const struct expression *exp)
9433 {
9434   int i = exp->nelts;
9435
9436   while (i > 0)
9437     {
9438       int oplenp, argsp;
9439
9440       /* We are only interested in the descriptor of each element.  */
9441       operator_length (exp, i, &oplenp, &argsp);
9442       i -= oplenp;
9443
9444       switch (exp->elts[i].opcode)
9445         {
9446         case BINOP_ADD:
9447         case BINOP_SUB:
9448         case BINOP_MUL:
9449         case BINOP_DIV:
9450         case BINOP_REM:
9451         case BINOP_MOD:
9452         case BINOP_LSH:
9453         case BINOP_RSH:
9454         case BINOP_LOGICAL_AND:
9455         case BINOP_LOGICAL_OR:
9456         case BINOP_BITWISE_AND:
9457         case BINOP_BITWISE_IOR:
9458         case BINOP_BITWISE_XOR:
9459         case BINOP_EQUAL:
9460         case BINOP_NOTEQUAL:
9461         case BINOP_LESS:
9462         case BINOP_GTR:
9463         case BINOP_LEQ:
9464         case BINOP_GEQ:
9465         case BINOP_REPEAT:
9466         case BINOP_COMMA:
9467         case BINOP_EXP:
9468         case BINOP_MIN:
9469         case BINOP_MAX:
9470         case BINOP_INTDIV:
9471         case BINOP_CONCAT:
9472         case BINOP_IN:
9473         case BINOP_RANGE:
9474         case TERNOP_COND:
9475         case TERNOP_SLICE:
9476         case TERNOP_SLICE_COUNT:
9477
9478         case OP_LONG:
9479         case OP_DOUBLE:
9480         case OP_DECFLOAT:
9481         case OP_LAST:
9482         case OP_COMPLEX:
9483         case OP_STRING:
9484         case OP_BITSTRING:
9485         case OP_ARRAY:
9486         case OP_TYPE:
9487         case OP_NAME:
9488         case OP_OBJC_NSSTRING:
9489
9490         case UNOP_NEG:
9491         case UNOP_LOGICAL_NOT:
9492         case UNOP_COMPLEMENT:
9493         case UNOP_ADDR:
9494         case UNOP_HIGH:
9495         case UNOP_CAST:
9496           /* Unary, binary and ternary operators: We have to check
9497              their operands.  If they are constant, then so is the
9498              result of that operation.  For instance, if A and B are
9499              determined to be constants, then so is "A + B".
9500
9501              UNOP_IND is one exception to the rule above, because the
9502              value of *ADDR is not necessarily a constant, even when
9503              ADDR is.  */
9504           break;
9505
9506         case OP_VAR_VALUE:
9507           /* Check whether the associated symbol is a constant.
9508
9509              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9510              possible that a buggy compiler could mark a variable as
9511              constant even when it is not, and TYPE_CONST would return
9512              true in this case, while SYMBOL_CLASS wouldn't.
9513
9514              We also have to check for function symbols because they
9515              are always constant.  */
9516           {
9517             struct symbol *s = exp->elts[i + 2].symbol;
9518
9519             if (SYMBOL_CLASS (s) != LOC_BLOCK
9520                 && SYMBOL_CLASS (s) != LOC_CONST
9521                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
9522               return 0;
9523             break;
9524           }
9525
9526         /* The default action is to return 0 because we are using
9527            the optimistic approach here: If we don't know something,
9528            then it is not a constant.  */
9529         default:
9530           return 0;
9531         }
9532     }
9533
9534   return 1;
9535 }
9536
9537 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
9538
9539 static void
9540 dtor_watchpoint (struct breakpoint *self)
9541 {
9542   struct watchpoint *w = (struct watchpoint *) self;
9543
9544   xfree (w->cond_exp);
9545   xfree (w->exp);
9546   xfree (w->exp_string);
9547   xfree (w->exp_string_reparse);
9548   value_free (w->val);
9549
9550   base_breakpoint_ops.dtor (self);
9551 }
9552
9553 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
9554
9555 static void
9556 re_set_watchpoint (struct breakpoint *b)
9557 {
9558   struct watchpoint *w = (struct watchpoint *) b;
9559
9560   /* Watchpoint can be either on expression using entirely global
9561      variables, or it can be on local variables.
9562
9563      Watchpoints of the first kind are never auto-deleted, and even
9564      persist across program restarts.  Since they can use variables
9565      from shared libraries, we need to reparse expression as libraries
9566      are loaded and unloaded.
9567
9568      Watchpoints on local variables can also change meaning as result
9569      of solib event.  For example, if a watchpoint uses both a local
9570      and a global variables in expression, it's a local watchpoint,
9571      but unloading of a shared library will make the expression
9572      invalid.  This is not a very common use case, but we still
9573      re-evaluate expression, to avoid surprises to the user.
9574
9575      Note that for local watchpoints, we re-evaluate it only if
9576      watchpoints frame id is still valid.  If it's not, it means the
9577      watchpoint is out of scope and will be deleted soon.  In fact,
9578      I'm not sure we'll ever be called in this case.
9579
9580      If a local watchpoint's frame id is still valid, then
9581      w->exp_valid_block is likewise valid, and we can safely use it.
9582
9583      Don't do anything about disabled watchpoints, since they will be
9584      reevaluated again when enabled.  */
9585   update_watchpoint (w, 1 /* reparse */);
9586 }
9587
9588 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
9589
9590 static int
9591 insert_watchpoint (struct bp_location *bl)
9592 {
9593   struct watchpoint *w = (struct watchpoint *) bl->owner;
9594   int length = w->exact ? 1 : bl->length;
9595
9596   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9597                                    w->cond_exp);
9598 }
9599
9600 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
9601
9602 static int
9603 remove_watchpoint (struct bp_location *bl)
9604 {
9605   struct watchpoint *w = (struct watchpoint *) bl->owner;
9606   int length = w->exact ? 1 : bl->length;
9607
9608   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9609                                    w->cond_exp);
9610 }
9611
9612 static int
9613 breakpoint_hit_watchpoint (const struct bp_location *bl,
9614                            struct address_space *aspace, CORE_ADDR bp_addr,
9615                            const struct target_waitstatus *ws)
9616 {
9617   struct breakpoint *b = bl->owner;
9618   struct watchpoint *w = (struct watchpoint *) b;
9619
9620   /* Continuable hardware watchpoints are treated as non-existent if the
9621      reason we stopped wasn't a hardware watchpoint (we didn't stop on
9622      some data address).  Otherwise gdb won't stop on a break instruction
9623      in the code (not from a breakpoint) when a hardware watchpoint has
9624      been defined.  Also skip watchpoints which we know did not trigger
9625      (did not match the data address).  */
9626   if (is_hardware_watchpoint (b)
9627       && w->watchpoint_triggered == watch_triggered_no)
9628     return 0;
9629
9630   return 1;
9631 }
9632
9633 static void
9634 check_status_watchpoint (bpstat bs)
9635 {
9636   gdb_assert (is_watchpoint (bs->breakpoint_at));
9637
9638   bpstat_check_watchpoint (bs);
9639 }
9640
9641 /* Implement the "resources_needed" breakpoint_ops method for
9642    hardware watchpoints.  */
9643
9644 static int
9645 resources_needed_watchpoint (const struct bp_location *bl)
9646 {
9647   struct watchpoint *w = (struct watchpoint *) bl->owner;
9648   int length = w->exact? 1 : bl->length;
9649
9650   return target_region_ok_for_hw_watchpoint (bl->address, length);
9651 }
9652
9653 /* Implement the "works_in_software_mode" breakpoint_ops method for
9654    hardware watchpoints.  */
9655
9656 static int
9657 works_in_software_mode_watchpoint (const struct breakpoint *b)
9658 {
9659   /* Read and access watchpoints only work with hardware support.  */
9660   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
9661 }
9662
9663 static enum print_stop_action
9664 print_it_watchpoint (bpstat bs)
9665 {
9666   struct cleanup *old_chain;
9667   struct breakpoint *b;
9668   const struct bp_location *bl;
9669   struct ui_file *stb;
9670   enum print_stop_action result;
9671   struct watchpoint *w;
9672   struct ui_out *uiout = current_uiout;
9673
9674   gdb_assert (bs->bp_location_at != NULL);
9675
9676   bl = bs->bp_location_at;
9677   b = bs->breakpoint_at;
9678   w = (struct watchpoint *) b;
9679
9680   stb = mem_fileopen ();
9681   old_chain = make_cleanup_ui_file_delete (stb);
9682
9683   switch (b->type)
9684     {
9685     case bp_watchpoint:
9686     case bp_hardware_watchpoint:
9687       annotate_watchpoint (b->number);
9688       if (ui_out_is_mi_like_p (uiout))
9689         ui_out_field_string
9690           (uiout, "reason",
9691            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9692       mention (b);
9693       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9694       ui_out_text (uiout, "\nOld value = ");
9695       watchpoint_value_print (bs->old_val, stb);
9696       ui_out_field_stream (uiout, "old", stb);
9697       ui_out_text (uiout, "\nNew value = ");
9698       watchpoint_value_print (w->val, stb);
9699       ui_out_field_stream (uiout, "new", stb);
9700       ui_out_text (uiout, "\n");
9701       /* More than one watchpoint may have been triggered.  */
9702       result = PRINT_UNKNOWN;
9703       break;
9704
9705     case bp_read_watchpoint:
9706       if (ui_out_is_mi_like_p (uiout))
9707         ui_out_field_string
9708           (uiout, "reason",
9709            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9710       mention (b);
9711       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9712       ui_out_text (uiout, "\nValue = ");
9713       watchpoint_value_print (w->val, stb);
9714       ui_out_field_stream (uiout, "value", stb);
9715       ui_out_text (uiout, "\n");
9716       result = PRINT_UNKNOWN;
9717       break;
9718
9719     case bp_access_watchpoint:
9720       if (bs->old_val != NULL)
9721         {
9722           annotate_watchpoint (b->number);
9723           if (ui_out_is_mi_like_p (uiout))
9724             ui_out_field_string
9725               (uiout, "reason",
9726                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9727           mention (b);
9728           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9729           ui_out_text (uiout, "\nOld value = ");
9730           watchpoint_value_print (bs->old_val, stb);
9731           ui_out_field_stream (uiout, "old", stb);
9732           ui_out_text (uiout, "\nNew value = ");
9733         }
9734       else
9735         {
9736           mention (b);
9737           if (ui_out_is_mi_like_p (uiout))
9738             ui_out_field_string
9739               (uiout, "reason",
9740                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9741           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9742           ui_out_text (uiout, "\nValue = ");
9743         }
9744       watchpoint_value_print (w->val, stb);
9745       ui_out_field_stream (uiout, "new", stb);
9746       ui_out_text (uiout, "\n");
9747       result = PRINT_UNKNOWN;
9748       break;
9749     default:
9750       result = PRINT_UNKNOWN;
9751     }
9752
9753   do_cleanups (old_chain);
9754   return result;
9755 }
9756
9757 /* Implement the "print_mention" breakpoint_ops method for hardware
9758    watchpoints.  */
9759
9760 static void
9761 print_mention_watchpoint (struct breakpoint *b)
9762 {
9763   struct cleanup *ui_out_chain;
9764   struct watchpoint *w = (struct watchpoint *) b;
9765   struct ui_out *uiout = current_uiout;
9766
9767   switch (b->type)
9768     {
9769     case bp_watchpoint:
9770       ui_out_text (uiout, "Watchpoint ");
9771       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9772       break;
9773     case bp_hardware_watchpoint:
9774       ui_out_text (uiout, "Hardware watchpoint ");
9775       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9776       break;
9777     case bp_read_watchpoint:
9778       ui_out_text (uiout, "Hardware read watchpoint ");
9779       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9780       break;
9781     case bp_access_watchpoint:
9782       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
9783       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9784       break;
9785     default:
9786       internal_error (__FILE__, __LINE__,
9787                       _("Invalid hardware watchpoint type."));
9788     }
9789
9790   ui_out_field_int (uiout, "number", b->number);
9791   ui_out_text (uiout, ": ");
9792   ui_out_field_string (uiout, "exp", w->exp_string);
9793   do_cleanups (ui_out_chain);
9794 }
9795
9796 /* Implement the "print_recreate" breakpoint_ops method for
9797    watchpoints.  */
9798
9799 static void
9800 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
9801 {
9802   struct watchpoint *w = (struct watchpoint *) b;
9803
9804   switch (b->type)
9805     {
9806     case bp_watchpoint:
9807     case bp_hardware_watchpoint:
9808       fprintf_unfiltered (fp, "watch");
9809       break;
9810     case bp_read_watchpoint:
9811       fprintf_unfiltered (fp, "rwatch");
9812       break;
9813     case bp_access_watchpoint:
9814       fprintf_unfiltered (fp, "awatch");
9815       break;
9816     default:
9817       internal_error (__FILE__, __LINE__,
9818                       _("Invalid watchpoint type."));
9819     }
9820
9821   fprintf_unfiltered (fp, " %s", w->exp_string);
9822   print_recreate_thread (b, fp);
9823 }
9824
9825 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
9826
9827 static struct breakpoint_ops watchpoint_breakpoint_ops;
9828
9829 /* Implement the "insert" breakpoint_ops method for
9830    masked hardware watchpoints.  */
9831
9832 static int
9833 insert_masked_watchpoint (struct bp_location *bl)
9834 {
9835   struct watchpoint *w = (struct watchpoint *) bl->owner;
9836
9837   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
9838                                         bl->watchpoint_type);
9839 }
9840
9841 /* Implement the "remove" breakpoint_ops method for
9842    masked hardware watchpoints.  */
9843
9844 static int
9845 remove_masked_watchpoint (struct bp_location *bl)
9846 {
9847   struct watchpoint *w = (struct watchpoint *) bl->owner;
9848
9849   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
9850                                         bl->watchpoint_type);
9851 }
9852
9853 /* Implement the "resources_needed" breakpoint_ops method for
9854    masked hardware watchpoints.  */
9855
9856 static int
9857 resources_needed_masked_watchpoint (const struct bp_location *bl)
9858 {
9859   struct watchpoint *w = (struct watchpoint *) bl->owner;
9860
9861   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
9862 }
9863
9864 /* Implement the "works_in_software_mode" breakpoint_ops method for
9865    masked hardware watchpoints.  */
9866
9867 static int
9868 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
9869 {
9870   return 0;
9871 }
9872
9873 /* Implement the "print_it" breakpoint_ops method for
9874    masked hardware watchpoints.  */
9875
9876 static enum print_stop_action
9877 print_it_masked_watchpoint (bpstat bs)
9878 {
9879   struct breakpoint *b = bs->breakpoint_at;
9880   struct ui_out *uiout = current_uiout;
9881
9882   /* Masked watchpoints have only one location.  */
9883   gdb_assert (b->loc && b->loc->next == NULL);
9884
9885   switch (b->type)
9886     {
9887     case bp_hardware_watchpoint:
9888       annotate_watchpoint (b->number);
9889       if (ui_out_is_mi_like_p (uiout))
9890         ui_out_field_string
9891           (uiout, "reason",
9892            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9893       break;
9894
9895     case bp_read_watchpoint:
9896       if (ui_out_is_mi_like_p (uiout))
9897         ui_out_field_string
9898           (uiout, "reason",
9899            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
9900       break;
9901
9902     case bp_access_watchpoint:
9903       if (ui_out_is_mi_like_p (uiout))
9904         ui_out_field_string
9905           (uiout, "reason",
9906            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
9907       break;
9908     default:
9909       internal_error (__FILE__, __LINE__,
9910                       _("Invalid hardware watchpoint type."));
9911     }
9912
9913   mention (b);
9914   ui_out_text (uiout, _("\n\
9915 Check the underlying instruction at PC for the memory\n\
9916 address and value which triggered this watchpoint.\n"));
9917   ui_out_text (uiout, "\n");
9918
9919   /* More than one watchpoint may have been triggered.  */
9920   return PRINT_UNKNOWN;
9921 }
9922
9923 /* Implement the "print_one_detail" breakpoint_ops method for
9924    masked hardware watchpoints.  */
9925
9926 static void
9927 print_one_detail_masked_watchpoint (const struct breakpoint *b,
9928                                     struct ui_out *uiout)
9929 {
9930   struct watchpoint *w = (struct watchpoint *) b;
9931
9932   /* Masked watchpoints have only one location.  */
9933   gdb_assert (b->loc && b->loc->next == NULL);
9934
9935   ui_out_text (uiout, "\tmask ");
9936   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
9937   ui_out_text (uiout, "\n");
9938 }
9939
9940 /* Implement the "print_mention" breakpoint_ops method for
9941    masked hardware watchpoints.  */
9942
9943 static void
9944 print_mention_masked_watchpoint (struct breakpoint *b)
9945 {
9946   struct watchpoint *w = (struct watchpoint *) b;
9947   struct ui_out *uiout = current_uiout;
9948   struct cleanup *ui_out_chain;
9949
9950   switch (b->type)
9951     {
9952     case bp_hardware_watchpoint:
9953       ui_out_text (uiout, "Masked hardware watchpoint ");
9954       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
9955       break;
9956     case bp_read_watchpoint:
9957       ui_out_text (uiout, "Masked hardware read watchpoint ");
9958       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
9959       break;
9960     case bp_access_watchpoint:
9961       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
9962       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
9963       break;
9964     default:
9965       internal_error (__FILE__, __LINE__,
9966                       _("Invalid hardware watchpoint type."));
9967     }
9968
9969   ui_out_field_int (uiout, "number", b->number);
9970   ui_out_text (uiout, ": ");
9971   ui_out_field_string (uiout, "exp", w->exp_string);
9972   do_cleanups (ui_out_chain);
9973 }
9974
9975 /* Implement the "print_recreate" breakpoint_ops method for
9976    masked hardware watchpoints.  */
9977
9978 static void
9979 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
9980 {
9981   struct watchpoint *w = (struct watchpoint *) b;
9982   char tmp[40];
9983
9984   switch (b->type)
9985     {
9986     case bp_hardware_watchpoint:
9987       fprintf_unfiltered (fp, "watch");
9988       break;
9989     case bp_read_watchpoint:
9990       fprintf_unfiltered (fp, "rwatch");
9991       break;
9992     case bp_access_watchpoint:
9993       fprintf_unfiltered (fp, "awatch");
9994       break;
9995     default:
9996       internal_error (__FILE__, __LINE__,
9997                       _("Invalid hardware watchpoint type."));
9998     }
9999
10000   sprintf_vma (tmp, w->hw_wp_mask);
10001   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10002   print_recreate_thread (b, fp);
10003 }
10004
10005 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10006
10007 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10008
10009 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10010
10011 static int
10012 is_masked_watchpoint (const struct breakpoint *b)
10013 {
10014   return b->ops == &masked_watchpoint_breakpoint_ops;
10015 }
10016
10017 /* accessflag:  hw_write:  watch write, 
10018                 hw_read:   watch read, 
10019                 hw_access: watch access (read or write) */
10020 static void
10021 watch_command_1 (char *arg, int accessflag, int from_tty,
10022                  int just_location, int internal)
10023 {
10024   volatile struct gdb_exception e;
10025   struct breakpoint *b, *scope_breakpoint = NULL;
10026   struct expression *exp;
10027   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10028   struct value *val, *mark, *result;
10029   struct frame_info *frame;
10030   char *exp_start = NULL;
10031   char *exp_end = NULL;
10032   char *tok, *end_tok;
10033   int toklen = -1;
10034   char *cond_start = NULL;
10035   char *cond_end = NULL;
10036   enum bptype bp_type;
10037   int thread = -1;
10038   int pc = 0;
10039   /* Flag to indicate whether we are going to use masks for
10040      the hardware watchpoint.  */
10041   int use_mask = 0;
10042   CORE_ADDR mask = 0;
10043   struct watchpoint *w;
10044
10045   /* Make sure that we actually have parameters to parse.  */
10046   if (arg != NULL && arg[0] != '\0')
10047     {
10048       char *value_start;
10049
10050       /* Look for "parameter value" pairs at the end
10051          of the arguments string.  */
10052       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
10053         {
10054           /* Skip whitespace at the end of the argument list.  */
10055           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10056             tok--;
10057
10058           /* Find the beginning of the last token.
10059              This is the value of the parameter.  */
10060           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10061             tok--;
10062           value_start = tok + 1;
10063
10064           /* Skip whitespace.  */
10065           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10066             tok--;
10067
10068           end_tok = tok;
10069
10070           /* Find the beginning of the second to last token.
10071              This is the parameter itself.  */
10072           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10073             tok--;
10074           tok++;
10075           toklen = end_tok - tok + 1;
10076
10077           if (toklen == 6 && !strncmp (tok, "thread", 6))
10078             {
10079               /* At this point we've found a "thread" token, which means
10080                  the user is trying to set a watchpoint that triggers
10081                  only in a specific thread.  */
10082               char *endp;
10083
10084               if (thread != -1)
10085                 error(_("You can specify only one thread."));
10086
10087               /* Extract the thread ID from the next token.  */
10088               thread = strtol (value_start, &endp, 0);
10089
10090               /* Check if the user provided a valid numeric value for the
10091                  thread ID.  */
10092               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10093                 error (_("Invalid thread ID specification %s."), value_start);
10094
10095               /* Check if the thread actually exists.  */
10096               if (!valid_thread_id (thread))
10097                 error (_("Unknown thread %d."), thread);
10098             }
10099           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10100             {
10101               /* We've found a "mask" token, which means the user wants to
10102                  create a hardware watchpoint that is going to have the mask
10103                  facility.  */
10104               struct value *mask_value, *mark;
10105
10106               if (use_mask)
10107                 error(_("You can specify only one mask."));
10108
10109               use_mask = just_location = 1;
10110
10111               mark = value_mark ();
10112               mask_value = parse_to_comma_and_eval (&value_start);
10113               mask = value_as_address (mask_value);
10114               value_free_to_mark (mark);
10115             }
10116           else
10117             /* We didn't recognize what we found.  We should stop here.  */
10118             break;
10119
10120           /* Truncate the string and get rid of the "parameter value" pair before
10121              the arguments string is parsed by the parse_exp_1 function.  */
10122           *tok = '\0';
10123         }
10124     }
10125
10126   /* Parse the rest of the arguments.  */
10127   innermost_block = NULL;
10128   exp_start = arg;
10129   exp = parse_exp_1 (&arg, 0, 0);
10130   exp_end = arg;
10131   /* Remove trailing whitespace from the expression before saving it.
10132      This makes the eventual display of the expression string a bit
10133      prettier.  */
10134   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10135     --exp_end;
10136
10137   /* Checking if the expression is not constant.  */
10138   if (watchpoint_exp_is_const (exp))
10139     {
10140       int len;
10141
10142       len = exp_end - exp_start;
10143       while (len > 0 && isspace (exp_start[len - 1]))
10144         len--;
10145       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10146     }
10147
10148   exp_valid_block = innermost_block;
10149   mark = value_mark ();
10150   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10151
10152   if (just_location)
10153     {
10154       int ret;
10155
10156       exp_valid_block = NULL;
10157       val = value_addr (result);
10158       release_value (val);
10159       value_free_to_mark (mark);
10160
10161       if (use_mask)
10162         {
10163           ret = target_masked_watch_num_registers (value_as_address (val),
10164                                                    mask);
10165           if (ret == -1)
10166             error (_("This target does not support masked watchpoints."));
10167           else if (ret == -2)
10168             error (_("Invalid mask or memory region."));
10169         }
10170     }
10171   else if (val != NULL)
10172     release_value (val);
10173
10174   tok = skip_spaces (arg);
10175   end_tok = skip_to_space (tok);
10176
10177   toklen = end_tok - tok;
10178   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10179     {
10180       struct expression *cond;
10181
10182       innermost_block = NULL;
10183       tok = cond_start = end_tok + 1;
10184       cond = parse_exp_1 (&tok, 0, 0);
10185
10186       /* The watchpoint expression may not be local, but the condition
10187          may still be.  E.g.: `watch global if local > 0'.  */
10188       cond_exp_valid_block = innermost_block;
10189
10190       xfree (cond);
10191       cond_end = tok;
10192     }
10193   if (*tok)
10194     error (_("Junk at end of command."));
10195
10196   if (accessflag == hw_read)
10197     bp_type = bp_read_watchpoint;
10198   else if (accessflag == hw_access)
10199     bp_type = bp_access_watchpoint;
10200   else
10201     bp_type = bp_hardware_watchpoint;
10202
10203   frame = block_innermost_frame (exp_valid_block);
10204
10205   /* If the expression is "local", then set up a "watchpoint scope"
10206      breakpoint at the point where we've left the scope of the watchpoint
10207      expression.  Create the scope breakpoint before the watchpoint, so
10208      that we will encounter it first in bpstat_stop_status.  */
10209   if (exp_valid_block && frame)
10210     {
10211       if (frame_id_p (frame_unwind_caller_id (frame)))
10212         {
10213           scope_breakpoint
10214             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
10215                                           frame_unwind_caller_pc (frame),
10216                                           bp_watchpoint_scope,
10217                                           &momentary_breakpoint_ops);
10218
10219           scope_breakpoint->enable_state = bp_enabled;
10220
10221           /* Automatically delete the breakpoint when it hits.  */
10222           scope_breakpoint->disposition = disp_del;
10223
10224           /* Only break in the proper frame (help with recursion).  */
10225           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
10226
10227           /* Set the address at which we will stop.  */
10228           scope_breakpoint->loc->gdbarch
10229             = frame_unwind_caller_arch (frame);
10230           scope_breakpoint->loc->requested_address
10231             = frame_unwind_caller_pc (frame);
10232           scope_breakpoint->loc->address
10233             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10234                                          scope_breakpoint->loc->requested_address,
10235                                          scope_breakpoint->type);
10236         }
10237     }
10238
10239   /* Now set up the breakpoint.  */
10240
10241   w = XCNEW (struct watchpoint);
10242   b = &w->base;
10243   if (use_mask)
10244     init_raw_breakpoint_without_location (b, NULL, bp_type,
10245                                           &masked_watchpoint_breakpoint_ops);
10246   else
10247     init_raw_breakpoint_without_location (b, NULL, bp_type,
10248                                           &watchpoint_breakpoint_ops);
10249   b->thread = thread;
10250   b->disposition = disp_donttouch;
10251   b->pspace = current_program_space;
10252   w->exp = exp;
10253   w->exp_valid_block = exp_valid_block;
10254   w->cond_exp_valid_block = cond_exp_valid_block;
10255   if (just_location)
10256     {
10257       struct type *t = value_type (val);
10258       CORE_ADDR addr = value_as_address (val);
10259       char *name;
10260
10261       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
10262       name = type_to_string (t);
10263
10264       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
10265                                           core_addr_to_string (addr));
10266       xfree (name);
10267
10268       w->exp_string = xstrprintf ("-location %.*s",
10269                                   (int) (exp_end - exp_start), exp_start);
10270
10271       /* The above expression is in C.  */
10272       b->language = language_c;
10273     }
10274   else
10275     w->exp_string = savestring (exp_start, exp_end - exp_start);
10276
10277   if (use_mask)
10278     {
10279       w->hw_wp_mask = mask;
10280     }
10281   else
10282     {
10283       w->val = val;
10284       w->val_valid = 1;
10285     }
10286
10287   if (cond_start)
10288     b->cond_string = savestring (cond_start, cond_end - cond_start);
10289   else
10290     b->cond_string = 0;
10291
10292   if (frame)
10293     {
10294       w->watchpoint_frame = get_frame_id (frame);
10295       w->watchpoint_thread = inferior_ptid;
10296     }
10297   else
10298     {
10299       w->watchpoint_frame = null_frame_id;
10300       w->watchpoint_thread = null_ptid;
10301     }
10302
10303   if (scope_breakpoint != NULL)
10304     {
10305       /* The scope breakpoint is related to the watchpoint.  We will
10306          need to act on them together.  */
10307       b->related_breakpoint = scope_breakpoint;
10308       scope_breakpoint->related_breakpoint = b;
10309     }
10310
10311   if (!just_location)
10312     value_free_to_mark (mark);
10313
10314   TRY_CATCH (e, RETURN_MASK_ALL)
10315     {
10316       /* Finally update the new watchpoint.  This creates the locations
10317          that should be inserted.  */
10318       update_watchpoint (w, 1);
10319     }
10320   if (e.reason < 0)
10321     {
10322       delete_breakpoint (b);
10323       throw_exception (e);
10324     }
10325
10326   install_breakpoint (internal, b, 1);
10327 }
10328
10329 /* Return count of debug registers needed to watch the given expression.
10330    If the watchpoint cannot be handled in hardware return zero.  */
10331
10332 static int
10333 can_use_hardware_watchpoint (struct value *v)
10334 {
10335   int found_memory_cnt = 0;
10336   struct value *head = v;
10337
10338   /* Did the user specifically forbid us to use hardware watchpoints? */
10339   if (!can_use_hw_watchpoints)
10340     return 0;
10341
10342   /* Make sure that the value of the expression depends only upon
10343      memory contents, and values computed from them within GDB.  If we
10344      find any register references or function calls, we can't use a
10345      hardware watchpoint.
10346
10347      The idea here is that evaluating an expression generates a series
10348      of values, one holding the value of every subexpression.  (The
10349      expression a*b+c has five subexpressions: a, b, a*b, c, and
10350      a*b+c.)  GDB's values hold almost enough information to establish
10351      the criteria given above --- they identify memory lvalues,
10352      register lvalues, computed values, etcetera.  So we can evaluate
10353      the expression, and then scan the chain of values that leaves
10354      behind to decide whether we can detect any possible change to the
10355      expression's final value using only hardware watchpoints.
10356
10357      However, I don't think that the values returned by inferior
10358      function calls are special in any way.  So this function may not
10359      notice that an expression involving an inferior function call
10360      can't be watched with hardware watchpoints.  FIXME.  */
10361   for (; v; v = value_next (v))
10362     {
10363       if (VALUE_LVAL (v) == lval_memory)
10364         {
10365           if (v != head && value_lazy (v))
10366             /* A lazy memory lvalue in the chain is one that GDB never
10367                needed to fetch; we either just used its address (e.g.,
10368                `a' in `a.b') or we never needed it at all (e.g., `a'
10369                in `a,b').  This doesn't apply to HEAD; if that is
10370                lazy then it was not readable, but watch it anyway.  */
10371             ;
10372           else
10373             {
10374               /* Ahh, memory we actually used!  Check if we can cover
10375                  it with hardware watchpoints.  */
10376               struct type *vtype = check_typedef (value_type (v));
10377
10378               /* We only watch structs and arrays if user asked for it
10379                  explicitly, never if they just happen to appear in a
10380                  middle of some value chain.  */
10381               if (v == head
10382                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10383                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10384                 {
10385                   CORE_ADDR vaddr = value_address (v);
10386                   int len;
10387                   int num_regs;
10388
10389                   len = (target_exact_watchpoints
10390                          && is_scalar_type_recursive (vtype))?
10391                     1 : TYPE_LENGTH (value_type (v));
10392
10393                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10394                   if (!num_regs)
10395                     return 0;
10396                   else
10397                     found_memory_cnt += num_regs;
10398                 }
10399             }
10400         }
10401       else if (VALUE_LVAL (v) != not_lval
10402                && deprecated_value_modifiable (v) == 0)
10403         return 0;       /* These are values from the history (e.g., $1).  */
10404       else if (VALUE_LVAL (v) == lval_register)
10405         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10406     }
10407
10408   /* The expression itself looks suitable for using a hardware
10409      watchpoint, but give the target machine a chance to reject it.  */
10410   return found_memory_cnt;
10411 }
10412
10413 void
10414 watch_command_wrapper (char *arg, int from_tty, int internal)
10415 {
10416   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10417 }
10418
10419 /* A helper function that looks for an argument at the start of a
10420    string.  The argument must also either be at the end of the string,
10421    or be followed by whitespace.  Returns 1 if it finds the argument,
10422    0 otherwise.  If the argument is found, it updates *STR.  */
10423
10424 static int
10425 check_for_argument (char **str, char *arg, int arg_len)
10426 {
10427   if (strncmp (*str, arg, arg_len) == 0
10428       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
10429     {
10430       *str += arg_len;
10431       return 1;
10432     }
10433   return 0;
10434 }
10435
10436 /* A helper function that looks for the "-location" argument and then
10437    calls watch_command_1.  */
10438
10439 static void
10440 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
10441 {
10442   int just_location = 0;
10443
10444   if (arg
10445       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10446           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10447     {
10448       arg = skip_spaces (arg);
10449       just_location = 1;
10450     }
10451
10452   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10453 }
10454
10455 static void
10456 watch_command (char *arg, int from_tty)
10457 {
10458   watch_maybe_just_location (arg, hw_write, from_tty);
10459 }
10460
10461 void
10462 rwatch_command_wrapper (char *arg, int from_tty, int internal)
10463 {
10464   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10465 }
10466
10467 static void
10468 rwatch_command (char *arg, int from_tty)
10469 {
10470   watch_maybe_just_location (arg, hw_read, from_tty);
10471 }
10472
10473 void
10474 awatch_command_wrapper (char *arg, int from_tty, int internal)
10475 {
10476   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10477 }
10478
10479 static void
10480 awatch_command (char *arg, int from_tty)
10481 {
10482   watch_maybe_just_location (arg, hw_access, from_tty);
10483 }
10484 \f
10485
10486 /* Helper routines for the until_command routine in infcmd.c.  Here
10487    because it uses the mechanisms of breakpoints.  */
10488
10489 struct until_break_command_continuation_args
10490 {
10491   struct breakpoint *breakpoint;
10492   struct breakpoint *breakpoint2;
10493   int thread_num;
10494 };
10495
10496 /* This function is called by fetch_inferior_event via the
10497    cmd_continuation pointer, to complete the until command.  It takes
10498    care of cleaning up the temporary breakpoints set up by the until
10499    command.  */
10500 static void
10501 until_break_command_continuation (void *arg, int err)
10502 {
10503   struct until_break_command_continuation_args *a = arg;
10504
10505   delete_breakpoint (a->breakpoint);
10506   if (a->breakpoint2)
10507     delete_breakpoint (a->breakpoint2);
10508   delete_longjmp_breakpoint (a->thread_num);
10509 }
10510
10511 void
10512 until_break_command (char *arg, int from_tty, int anywhere)
10513 {
10514   struct symtabs_and_lines sals;
10515   struct symtab_and_line sal;
10516   struct frame_info *frame = get_selected_frame (NULL);
10517   struct gdbarch *frame_gdbarch = get_frame_arch (frame);
10518   struct frame_id stack_frame_id = get_stack_frame_id (frame);
10519   struct frame_id caller_frame_id = frame_unwind_caller_id (frame);
10520   struct breakpoint *breakpoint;
10521   struct breakpoint *breakpoint2 = NULL;
10522   struct cleanup *old_chain;
10523   int thread;
10524   struct thread_info *tp;
10525
10526   clear_proceed_status ();
10527
10528   /* Set a breakpoint where the user wants it and at return from
10529      this function.  */
10530
10531   if (last_displayed_sal_is_valid ())
10532     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10533                           get_last_displayed_symtab (),
10534                           get_last_displayed_line ());
10535   else
10536     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10537                           (struct symtab *) NULL, 0);
10538
10539   if (sals.nelts != 1)
10540     error (_("Couldn't get information on specified line."));
10541
10542   sal = sals.sals[0];
10543   xfree (sals.sals);    /* malloc'd, so freed.  */
10544
10545   if (*arg)
10546     error (_("Junk at end of arguments."));
10547
10548   resolve_sal_pc (&sal);
10549
10550   tp = inferior_thread ();
10551   thread = tp->num;
10552
10553   old_chain = make_cleanup (null_cleanup, NULL);
10554
10555   /* Installing a breakpoint invalidates the frame chain (as it may
10556      need to switch threads), so do any frame handling first.  */
10557
10558   /* Keep within the current frame, or in frames called by the current
10559      one.  */
10560
10561   if (frame_id_p (caller_frame_id))
10562     {
10563       struct symtab_and_line sal2;
10564
10565       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10566       sal2.pc = frame_unwind_caller_pc (frame);
10567       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
10568                                               sal2,
10569                                               caller_frame_id,
10570                                               bp_until);
10571       make_cleanup_delete_breakpoint (breakpoint2);
10572
10573       set_longjmp_breakpoint (tp, caller_frame_id);
10574       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
10575     }
10576
10577   /* set_momentary_breakpoint could invalidate FRAME.  */
10578   frame = NULL;
10579
10580   if (anywhere)
10581     /* If the user told us to continue until a specified location,
10582        we don't specify a frame at which we need to stop.  */
10583     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10584                                            null_frame_id, bp_until);
10585   else
10586     /* Otherwise, specify the selected frame, because we want to stop
10587        only at the very same frame.  */
10588     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10589                                            stack_frame_id, bp_until);
10590   make_cleanup_delete_breakpoint (breakpoint);
10591
10592   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
10593
10594   /* If we are running asynchronously, and proceed call above has
10595      actually managed to start the target, arrange for breakpoints to
10596      be deleted when the target stops.  Otherwise, we're already
10597      stopped and delete breakpoints via cleanup chain.  */
10598
10599   if (target_can_async_p () && is_running (inferior_ptid))
10600     {
10601       struct until_break_command_continuation_args *args;
10602       args = xmalloc (sizeof (*args));
10603
10604       args->breakpoint = breakpoint;
10605       args->breakpoint2 = breakpoint2;
10606       args->thread_num = thread;
10607
10608       discard_cleanups (old_chain);
10609       add_continuation (inferior_thread (),
10610                         until_break_command_continuation, args,
10611                         xfree);
10612     }
10613   else
10614     do_cleanups (old_chain);
10615 }
10616
10617 /* This function attempts to parse an optional "if <cond>" clause
10618    from the arg string.  If one is not found, it returns NULL.
10619
10620    Else, it returns a pointer to the condition string.  (It does not
10621    attempt to evaluate the string against a particular block.)  And,
10622    it updates arg to point to the first character following the parsed
10623    if clause in the arg string.  */
10624
10625 static char *
10626 ep_parse_optional_if_clause (char **arg)
10627 {
10628   char *cond_string;
10629
10630   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
10631     return NULL;
10632
10633   /* Skip the "if" keyword.  */
10634   (*arg) += 2;
10635
10636   /* Skip any extra leading whitespace, and record the start of the
10637      condition string.  */
10638   *arg = skip_spaces (*arg);
10639   cond_string = *arg;
10640
10641   /* Assume that the condition occupies the remainder of the arg
10642      string.  */
10643   (*arg) += strlen (cond_string);
10644
10645   return cond_string;
10646 }
10647
10648 /* Commands to deal with catching events, such as signals, exceptions,
10649    process start/exit, etc.  */
10650
10651 typedef enum
10652 {
10653   catch_fork_temporary, catch_vfork_temporary,
10654   catch_fork_permanent, catch_vfork_permanent
10655 }
10656 catch_fork_kind;
10657
10658 static void
10659 catch_fork_command_1 (char *arg, int from_tty, 
10660                       struct cmd_list_element *command)
10661 {
10662   struct gdbarch *gdbarch = get_current_arch ();
10663   char *cond_string = NULL;
10664   catch_fork_kind fork_kind;
10665   int tempflag;
10666
10667   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
10668   tempflag = (fork_kind == catch_fork_temporary
10669               || fork_kind == catch_vfork_temporary);
10670
10671   if (!arg)
10672     arg = "";
10673   arg = skip_spaces (arg);
10674
10675   /* The allowed syntax is:
10676      catch [v]fork
10677      catch [v]fork if <cond>
10678
10679      First, check if there's an if clause.  */
10680   cond_string = ep_parse_optional_if_clause (&arg);
10681
10682   if ((*arg != '\0') && !isspace (*arg))
10683     error (_("Junk at end of arguments."));
10684
10685   /* If this target supports it, create a fork or vfork catchpoint
10686      and enable reporting of such events.  */
10687   switch (fork_kind)
10688     {
10689     case catch_fork_temporary:
10690     case catch_fork_permanent:
10691       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10692                                           &catch_fork_breakpoint_ops);
10693       break;
10694     case catch_vfork_temporary:
10695     case catch_vfork_permanent:
10696       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10697                                           &catch_vfork_breakpoint_ops);
10698       break;
10699     default:
10700       error (_("unsupported or unknown fork kind; cannot catch it"));
10701       break;
10702     }
10703 }
10704
10705 static void
10706 catch_exec_command_1 (char *arg, int from_tty, 
10707                       struct cmd_list_element *command)
10708 {
10709   struct exec_catchpoint *c;
10710   struct gdbarch *gdbarch = get_current_arch ();
10711   int tempflag;
10712   char *cond_string = NULL;
10713
10714   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10715
10716   if (!arg)
10717     arg = "";
10718   arg = skip_spaces (arg);
10719
10720   /* The allowed syntax is:
10721      catch exec
10722      catch exec if <cond>
10723
10724      First, check if there's an if clause.  */
10725   cond_string = ep_parse_optional_if_clause (&arg);
10726
10727   if ((*arg != '\0') && !isspace (*arg))
10728     error (_("Junk at end of arguments."));
10729
10730   c = XNEW (struct exec_catchpoint);
10731   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
10732                    &catch_exec_breakpoint_ops);
10733   c->exec_pathname = NULL;
10734
10735   install_breakpoint (0, &c->base, 1);
10736 }
10737
10738 static enum print_stop_action
10739 print_it_exception_catchpoint (bpstat bs)
10740 {
10741   struct ui_out *uiout = current_uiout;
10742   struct breakpoint *b = bs->breakpoint_at;
10743   int bp_temp, bp_throw;
10744
10745   annotate_catchpoint (b->number);
10746
10747   bp_throw = strstr (b->addr_string, "throw") != NULL;
10748   if (b->loc->address != b->loc->requested_address)
10749     breakpoint_adjustment_warning (b->loc->requested_address,
10750                                    b->loc->address,
10751                                    b->number, 1);
10752   bp_temp = b->disposition == disp_del;
10753   ui_out_text (uiout, 
10754                bp_temp ? "Temporary catchpoint "
10755                        : "Catchpoint ");
10756   if (!ui_out_is_mi_like_p (uiout))
10757     ui_out_field_int (uiout, "bkptno", b->number);
10758   ui_out_text (uiout,
10759                bp_throw ? " (exception thrown), "
10760                         : " (exception caught), ");
10761   if (ui_out_is_mi_like_p (uiout))
10762     {
10763       ui_out_field_string (uiout, "reason", 
10764                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10765       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10766       ui_out_field_int (uiout, "bkptno", b->number);
10767     }
10768   return PRINT_SRC_AND_LOC;
10769 }
10770
10771 static void
10772 print_one_exception_catchpoint (struct breakpoint *b, 
10773                                 struct bp_location **last_loc)
10774 {
10775   struct value_print_options opts;
10776   struct ui_out *uiout = current_uiout;
10777
10778   get_user_print_options (&opts);
10779   if (opts.addressprint)
10780     {
10781       annotate_field (4);
10782       if (b->loc == NULL || b->loc->shlib_disabled)
10783         ui_out_field_string (uiout, "addr", "<PENDING>");
10784       else
10785         ui_out_field_core_addr (uiout, "addr",
10786                                 b->loc->gdbarch, b->loc->address);
10787     }
10788   annotate_field (5);
10789   if (b->loc)
10790     *last_loc = b->loc;
10791   if (strstr (b->addr_string, "throw") != NULL)
10792     ui_out_field_string (uiout, "what", "exception throw");
10793   else
10794     ui_out_field_string (uiout, "what", "exception catch");
10795 }
10796
10797 static void
10798 print_mention_exception_catchpoint (struct breakpoint *b)
10799 {
10800   struct ui_out *uiout = current_uiout;
10801   int bp_temp;
10802   int bp_throw;
10803
10804   bp_temp = b->disposition == disp_del;
10805   bp_throw = strstr (b->addr_string, "throw") != NULL;
10806   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
10807                               : _("Catchpoint "));
10808   ui_out_field_int (uiout, "bkptno", b->number);
10809   ui_out_text (uiout, bp_throw ? _(" (throw)")
10810                                : _(" (catch)"));
10811 }
10812
10813 /* Implement the "print_recreate" breakpoint_ops method for throw and
10814    catch catchpoints.  */
10815
10816 static void
10817 print_recreate_exception_catchpoint (struct breakpoint *b, 
10818                                      struct ui_file *fp)
10819 {
10820   int bp_temp;
10821   int bp_throw;
10822
10823   bp_temp = b->disposition == disp_del;
10824   bp_throw = strstr (b->addr_string, "throw") != NULL;
10825   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
10826   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
10827   print_recreate_thread (b, fp);
10828 }
10829
10830 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
10831
10832 static int
10833 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
10834                           enum exception_event_kind ex_event, int from_tty)
10835 {
10836   char *trigger_func_name;
10837  
10838   if (ex_event == EX_EVENT_CATCH)
10839     trigger_func_name = "__cxa_begin_catch";
10840   else
10841     trigger_func_name = "__cxa_throw";
10842
10843   create_breakpoint (get_current_arch (),
10844                      trigger_func_name, cond_string, -1,
10845                      0 /* condition and thread are valid.  */,
10846                      tempflag, bp_breakpoint,
10847                      0,
10848                      AUTO_BOOLEAN_TRUE /* pending */,
10849                      &gnu_v3_exception_catchpoint_ops, from_tty,
10850                      1 /* enabled */,
10851                      0 /* internal */,
10852                      0);
10853
10854   return 1;
10855 }
10856
10857 /* Deal with "catch catch" and "catch throw" commands.  */
10858
10859 static void
10860 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
10861                            int tempflag, int from_tty)
10862 {
10863   char *cond_string = NULL;
10864
10865   if (!arg)
10866     arg = "";
10867   arg = skip_spaces (arg);
10868
10869   cond_string = ep_parse_optional_if_clause (&arg);
10870
10871   if ((*arg != '\0') && !isspace (*arg))
10872     error (_("Junk at end of arguments."));
10873
10874   if (ex_event != EX_EVENT_THROW
10875       && ex_event != EX_EVENT_CATCH)
10876     error (_("Unsupported or unknown exception event; cannot catch it"));
10877
10878   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
10879     return;
10880
10881   warning (_("Unsupported with this platform/compiler combination."));
10882 }
10883
10884 /* Implementation of "catch catch" command.  */
10885
10886 static void
10887 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
10888 {
10889   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10890
10891   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
10892 }
10893
10894 /* Implementation of "catch throw" command.  */
10895
10896 static void
10897 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
10898 {
10899   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
10900
10901   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
10902 }
10903
10904 void
10905 init_ada_exception_breakpoint (struct breakpoint *b,
10906                                struct gdbarch *gdbarch,
10907                                struct symtab_and_line sal,
10908                                char *addr_string,
10909                                const struct breakpoint_ops *ops,
10910                                int tempflag,
10911                                int from_tty)
10912 {
10913   if (from_tty)
10914     {
10915       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
10916       if (!loc_gdbarch)
10917         loc_gdbarch = gdbarch;
10918
10919       describe_other_breakpoints (loc_gdbarch,
10920                                   sal.pspace, sal.pc, sal.section, -1);
10921       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
10922          version for exception catchpoints, because two catchpoints
10923          used for different exception names will use the same address.
10924          In this case, a "breakpoint ... also set at..." warning is
10925          unproductive.  Besides, the warning phrasing is also a bit
10926          inappropriate, we should use the word catchpoint, and tell
10927          the user what type of catchpoint it is.  The above is good
10928          enough for now, though.  */
10929     }
10930
10931   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
10932
10933   b->enable_state = bp_enabled;
10934   b->disposition = tempflag ? disp_del : disp_donttouch;
10935   b->addr_string = addr_string;
10936   b->language = language_ada;
10937 }
10938
10939 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
10940    filter list, or NULL if no filtering is required.  */
10941 static VEC(int) *
10942 catch_syscall_split_args (char *arg)
10943 {
10944   VEC(int) *result = NULL;
10945   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
10946
10947   while (*arg != '\0')
10948     {
10949       int i, syscall_number;
10950       char *endptr;
10951       char cur_name[128];
10952       struct syscall s;
10953
10954       /* Skip whitespace.  */
10955       while (isspace (*arg))
10956         arg++;
10957
10958       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
10959         cur_name[i] = arg[i];
10960       cur_name[i] = '\0';
10961       arg += i;
10962
10963       /* Check if the user provided a syscall name or a number.  */
10964       syscall_number = (int) strtol (cur_name, &endptr, 0);
10965       if (*endptr == '\0')
10966         get_syscall_by_number (syscall_number, &s);
10967       else
10968         {
10969           /* We have a name.  Let's check if it's valid and convert it
10970              to a number.  */
10971           get_syscall_by_name (cur_name, &s);
10972
10973           if (s.number == UNKNOWN_SYSCALL)
10974             /* Here we have to issue an error instead of a warning,
10975                because GDB cannot do anything useful if there's no
10976                syscall number to be caught.  */
10977             error (_("Unknown syscall name '%s'."), cur_name);
10978         }
10979
10980       /* Ok, it's valid.  */
10981       VEC_safe_push (int, result, s.number);
10982     }
10983
10984   discard_cleanups (cleanup);
10985   return result;
10986 }
10987
10988 /* Implement the "catch syscall" command.  */
10989
10990 static void
10991 catch_syscall_command_1 (char *arg, int from_tty, 
10992                          struct cmd_list_element *command)
10993 {
10994   int tempflag;
10995   VEC(int) *filter;
10996   struct syscall s;
10997   struct gdbarch *gdbarch = get_current_arch ();
10998
10999   /* Checking if the feature if supported.  */
11000   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11001     error (_("The feature 'catch syscall' is not supported on \
11002 this architecture yet."));
11003
11004   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11005
11006   arg = skip_spaces (arg);
11007
11008   /* We need to do this first "dummy" translation in order
11009      to get the syscall XML file loaded or, most important,
11010      to display a warning to the user if there's no XML file
11011      for his/her architecture.  */
11012   get_syscall_by_number (0, &s);
11013
11014   /* The allowed syntax is:
11015      catch syscall
11016      catch syscall <name | number> [<name | number> ... <name | number>]
11017
11018      Let's check if there's a syscall name.  */
11019
11020   if (arg != NULL)
11021     filter = catch_syscall_split_args (arg);
11022   else
11023     filter = NULL;
11024
11025   create_syscall_event_catchpoint (tempflag, filter,
11026                                    &catch_syscall_breakpoint_ops);
11027 }
11028
11029 static void
11030 catch_command (char *arg, int from_tty)
11031 {
11032   error (_("Catch requires an event name."));
11033 }
11034 \f
11035
11036 static void
11037 tcatch_command (char *arg, int from_tty)
11038 {
11039   error (_("Catch requires an event name."));
11040 }
11041
11042 /* A qsort comparison function that sorts breakpoints in order.  */
11043
11044 static int
11045 compare_breakpoints (const void *a, const void *b)
11046 {
11047   const breakpoint_p *ba = a;
11048   uintptr_t ua = (uintptr_t) *ba;
11049   const breakpoint_p *bb = b;
11050   uintptr_t ub = (uintptr_t) *bb;
11051
11052   if ((*ba)->number < (*bb)->number)
11053     return -1;
11054   else if ((*ba)->number > (*bb)->number)
11055     return 1;
11056
11057   /* Now sort by address, in case we see, e..g, two breakpoints with
11058      the number 0.  */
11059   if (ua < ub)
11060     return -1;
11061   return ub > ub ? 1 : 0;
11062 }
11063
11064 /* Delete breakpoints by address or line.  */
11065
11066 static void
11067 clear_command (char *arg, int from_tty)
11068 {
11069   struct breakpoint *b, *prev;
11070   VEC(breakpoint_p) *found = 0;
11071   int ix;
11072   int default_match;
11073   struct symtabs_and_lines sals;
11074   struct symtab_and_line sal;
11075   int i;
11076   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11077
11078   if (arg)
11079     {
11080       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
11081                                      | DECODE_LINE_LIST_MODE));
11082       default_match = 0;
11083     }
11084   else
11085     {
11086       sals.sals = (struct symtab_and_line *)
11087         xmalloc (sizeof (struct symtab_and_line));
11088       make_cleanup (xfree, sals.sals);
11089       init_sal (&sal);          /* Initialize to zeroes.  */
11090
11091       /* Set sal's line, symtab, pc, and pspace to the values
11092          corresponding to the last call to print_frame_info.  If the
11093          codepoint is not valid, this will set all the fields to 0.  */
11094       get_last_displayed_sal (&sal);
11095       if (sal.symtab == 0)
11096         error (_("No source file specified."));
11097
11098       sals.sals[0] = sal;
11099       sals.nelts = 1;
11100
11101       default_match = 1;
11102     }
11103
11104   /* We don't call resolve_sal_pc here.  That's not as bad as it
11105      seems, because all existing breakpoints typically have both
11106      file/line and pc set.  So, if clear is given file/line, we can
11107      match this to existing breakpoint without obtaining pc at all.
11108
11109      We only support clearing given the address explicitly 
11110      present in breakpoint table.  Say, we've set breakpoint 
11111      at file:line.  There were several PC values for that file:line,
11112      due to optimization, all in one block.
11113
11114      We've picked one PC value.  If "clear" is issued with another
11115      PC corresponding to the same file:line, the breakpoint won't
11116      be cleared.  We probably can still clear the breakpoint, but 
11117      since the other PC value is never presented to user, user
11118      can only find it by guessing, and it does not seem important
11119      to support that.  */
11120
11121   /* For each line spec given, delete bps which correspond to it.  Do
11122      it in two passes, solely to preserve the current behavior that
11123      from_tty is forced true if we delete more than one
11124      breakpoint.  */
11125
11126   found = NULL;
11127   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11128   for (i = 0; i < sals.nelts; i++)
11129     {
11130       int is_abs, sal_name_len;
11131
11132       /* If exact pc given, clear bpts at that pc.
11133          If line given (pc == 0), clear all bpts on specified line.
11134          If defaulting, clear all bpts on default line
11135          or at default pc.
11136
11137          defaulting    sal.pc != 0    tests to do
11138
11139          0              1             pc
11140          1              1             pc _and_ line
11141          0              0             line
11142          1              0             <can't happen> */
11143
11144       sal = sals.sals[i];
11145       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
11146       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
11147
11148       /* Find all matching breakpoints and add them to 'found'.  */
11149       ALL_BREAKPOINTS (b)
11150         {
11151           int match = 0;
11152           /* Are we going to delete b?  */
11153           if (b->type != bp_none && !is_watchpoint (b))
11154             {
11155               struct bp_location *loc = b->loc;
11156               for (; loc; loc = loc->next)
11157                 {
11158                   /* If the user specified file:line, don't allow a PC
11159                      match.  This matches historical gdb behavior.  */
11160                   int pc_match = (!sal.explicit_line
11161                                   && sal.pc
11162                                   && (loc->pspace == sal.pspace)
11163                                   && (loc->address == sal.pc)
11164                                   && (!section_is_overlay (loc->section)
11165                                       || loc->section == sal.section));
11166                   int line_match = 0;
11167
11168                   if ((default_match || sal.explicit_line)
11169                       && loc->source_file != NULL
11170                       && sal.symtab != NULL
11171                       && sal.pspace == loc->pspace
11172                       && loc->line_number == sal.line)
11173                     {
11174                       if (filename_cmp (loc->source_file,
11175                                         sal.symtab->filename) == 0)
11176                         line_match = 1;
11177                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
11178                                && compare_filenames_for_search (loc->source_file,
11179                                                                 sal.symtab->filename,
11180                                                                 sal_name_len))
11181                         line_match = 1;
11182                     }
11183
11184                   if (pc_match || line_match)
11185                     {
11186                       match = 1;
11187                       break;
11188                     }
11189                 }
11190             }
11191
11192           if (match)
11193             VEC_safe_push(breakpoint_p, found, b);
11194         }
11195     }
11196
11197   /* Now go thru the 'found' chain and delete them.  */
11198   if (VEC_empty(breakpoint_p, found))
11199     {
11200       if (arg)
11201         error (_("No breakpoint at %s."), arg);
11202       else
11203         error (_("No breakpoint at this line."));
11204     }
11205
11206   /* Remove duplicates from the vec.  */
11207   qsort (VEC_address (breakpoint_p, found),
11208          VEC_length (breakpoint_p, found),
11209          sizeof (breakpoint_p),
11210          compare_breakpoints);
11211   prev = VEC_index (breakpoint_p, found, 0);
11212   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11213     {
11214       if (b == prev)
11215         {
11216           VEC_ordered_remove (breakpoint_p, found, ix);
11217           --ix;
11218         }
11219     }
11220
11221   if (VEC_length(breakpoint_p, found) > 1)
11222     from_tty = 1;       /* Always report if deleted more than one.  */
11223   if (from_tty)
11224     {
11225       if (VEC_length(breakpoint_p, found) == 1)
11226         printf_unfiltered (_("Deleted breakpoint "));
11227       else
11228         printf_unfiltered (_("Deleted breakpoints "));
11229     }
11230   breakpoints_changed ();
11231
11232   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11233     {
11234       if (from_tty)
11235         printf_unfiltered ("%d ", b->number);
11236       delete_breakpoint (b);
11237     }
11238   if (from_tty)
11239     putchar_unfiltered ('\n');
11240
11241   do_cleanups (cleanups);
11242 }
11243 \f
11244 /* Delete breakpoint in BS if they are `delete' breakpoints and
11245    all breakpoints that are marked for deletion, whether hit or not.
11246    This is called after any breakpoint is hit, or after errors.  */
11247
11248 void
11249 breakpoint_auto_delete (bpstat bs)
11250 {
11251   struct breakpoint *b, *b_tmp;
11252
11253   for (; bs; bs = bs->next)
11254     if (bs->breakpoint_at
11255         && bs->breakpoint_at->disposition == disp_del
11256         && bs->stop)
11257       delete_breakpoint (bs->breakpoint_at);
11258
11259   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11260   {
11261     if (b->disposition == disp_del_at_next_stop)
11262       delete_breakpoint (b);
11263   }
11264 }
11265
11266 /* A comparison function for bp_location AP and BP being interfaced to
11267    qsort.  Sort elements primarily by their ADDRESS (no matter what
11268    does breakpoint_address_is_meaningful say for its OWNER),
11269    secondarily by ordering first bp_permanent OWNERed elements and
11270    terciarily just ensuring the array is sorted stable way despite
11271    qsort being an unstable algorithm.  */
11272
11273 static int
11274 bp_location_compare (const void *ap, const void *bp)
11275 {
11276   struct bp_location *a = *(void **) ap;
11277   struct bp_location *b = *(void **) bp;
11278   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11279   int a_perm = a->owner->enable_state == bp_permanent;
11280   int b_perm = b->owner->enable_state == bp_permanent;
11281
11282   if (a->address != b->address)
11283     return (a->address > b->address) - (a->address < b->address);
11284
11285   /* Sort locations at the same address by their pspace number, keeping
11286      locations of the same inferior (in a multi-inferior environment)
11287      grouped.  */
11288
11289   if (a->pspace->num != b->pspace->num)
11290     return ((a->pspace->num > b->pspace->num)
11291             - (a->pspace->num < b->pspace->num));
11292
11293   /* Sort permanent breakpoints first.  */
11294   if (a_perm != b_perm)
11295     return (a_perm < b_perm) - (a_perm > b_perm);
11296
11297   /* Make the internal GDB representation stable across GDB runs
11298      where A and B memory inside GDB can differ.  Breakpoint locations of
11299      the same type at the same address can be sorted in arbitrary order.  */
11300
11301   if (a->owner->number != b->owner->number)
11302     return ((a->owner->number > b->owner->number)
11303             - (a->owner->number < b->owner->number));
11304
11305   return (a > b) - (a < b);
11306 }
11307
11308 /* Set bp_location_placed_address_before_address_max and
11309    bp_location_shadow_len_after_address_max according to the current
11310    content of the bp_location array.  */
11311
11312 static void
11313 bp_location_target_extensions_update (void)
11314 {
11315   struct bp_location *bl, **blp_tmp;
11316
11317   bp_location_placed_address_before_address_max = 0;
11318   bp_location_shadow_len_after_address_max = 0;
11319
11320   ALL_BP_LOCATIONS (bl, blp_tmp)
11321     {
11322       CORE_ADDR start, end, addr;
11323
11324       if (!bp_location_has_shadow (bl))
11325         continue;
11326
11327       start = bl->target_info.placed_address;
11328       end = start + bl->target_info.shadow_len;
11329
11330       gdb_assert (bl->address >= start);
11331       addr = bl->address - start;
11332       if (addr > bp_location_placed_address_before_address_max)
11333         bp_location_placed_address_before_address_max = addr;
11334
11335       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11336
11337       gdb_assert (bl->address < end);
11338       addr = end - bl->address;
11339       if (addr > bp_location_shadow_len_after_address_max)
11340         bp_location_shadow_len_after_address_max = addr;
11341     }
11342 }
11343
11344 /* Download tracepoint locations if they haven't been.  */
11345
11346 static void
11347 download_tracepoint_locations (void)
11348 {
11349   struct bp_location *bl, **blp_tmp;
11350   struct cleanup *old_chain;
11351
11352   if (!target_can_download_tracepoint ())
11353     return;
11354
11355   old_chain = save_current_space_and_thread ();
11356
11357   ALL_BP_LOCATIONS (bl, blp_tmp)
11358     {
11359       struct tracepoint *t;
11360
11361       if (!is_tracepoint (bl->owner))
11362         continue;
11363
11364       if ((bl->owner->type == bp_fast_tracepoint
11365            ? !may_insert_fast_tracepoints
11366            : !may_insert_tracepoints))
11367         continue;
11368
11369       /* In tracepoint, locations are _never_ duplicated, so
11370          should_be_inserted is equivalent to
11371          unduplicated_should_be_inserted.  */
11372       if (!should_be_inserted (bl) || bl->inserted)
11373         continue;
11374
11375       switch_to_program_space_and_thread (bl->pspace);
11376
11377       target_download_tracepoint (bl);
11378
11379       bl->inserted = 1;
11380       t = (struct tracepoint *) bl->owner;
11381       t->number_on_target = bl->owner->number;
11382     }
11383
11384   do_cleanups (old_chain);
11385 }
11386
11387 /* Swap the insertion/duplication state between two locations.  */
11388
11389 static void
11390 swap_insertion (struct bp_location *left, struct bp_location *right)
11391 {
11392   const int left_inserted = left->inserted;
11393   const int left_duplicate = left->duplicate;
11394   const int left_needs_update = left->needs_update;
11395   const struct bp_target_info left_target_info = left->target_info;
11396
11397   /* Locations of tracepoints can never be duplicated.  */
11398   if (is_tracepoint (left->owner))
11399     gdb_assert (!left->duplicate);
11400   if (is_tracepoint (right->owner))
11401     gdb_assert (!right->duplicate);
11402
11403   left->inserted = right->inserted;
11404   left->duplicate = right->duplicate;
11405   left->needs_update = right->needs_update;
11406   left->target_info = right->target_info;
11407   right->inserted = left_inserted;
11408   right->duplicate = left_duplicate;
11409   right->needs_update = left_needs_update;
11410   right->target_info = left_target_info;
11411 }
11412
11413 /* Force the re-insertion of the locations at ADDRESS.  This is called
11414    once a new/deleted/modified duplicate location is found and we are evaluating
11415    conditions on the target's side.  Such conditions need to be updated on
11416    the target.  */
11417
11418 static void
11419 force_breakpoint_reinsertion (struct bp_location *bl)
11420 {
11421   struct bp_location **locp = NULL, **loc2p;
11422   struct bp_location *loc;
11423   CORE_ADDR address = 0;
11424   int pspace_num;
11425
11426   address = bl->address;
11427   pspace_num = bl->pspace->num;
11428
11429   /* This is only meaningful if the target is
11430      evaluating conditions and if the user has
11431      opted for condition evaluation on the target's
11432      side.  */
11433   if (gdb_evaluates_breakpoint_condition_p ()
11434       || !target_supports_evaluation_of_breakpoint_conditions ())
11435     return;
11436
11437   /* Flag all breakpoint locations with this address and
11438      the same program space as the location
11439      as "its condition has changed".  We need to
11440      update the conditions on the target's side.  */
11441   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11442     {
11443       loc = *loc2p;
11444
11445       if (!is_breakpoint (loc->owner)
11446           || pspace_num != loc->pspace->num)
11447         continue;
11448
11449       /* Flag the location appropriately.  We use a different state to
11450          let everyone know that we already updated the set of locations
11451          with addr bl->address and program space bl->pspace.  This is so
11452          we don't have to keep calling these functions just to mark locations
11453          that have already been marked.  */
11454       loc->condition_changed = condition_updated;
11455
11456       /* Free the agent expression bytecode as well.  We will compute
11457          it later on.  */
11458       if (loc->cond_bytecode)
11459         {
11460           free_agent_expr (loc->cond_bytecode);
11461           loc->cond_bytecode = NULL;
11462         }
11463     }
11464 }
11465
11466 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
11467    into the inferior, only remove already-inserted locations that no
11468    longer should be inserted.  Functions that delete a breakpoint or
11469    breakpoints should pass false, so that deleting a breakpoint
11470    doesn't have the side effect of inserting the locations of other
11471    breakpoints that are marked not-inserted, but should_be_inserted
11472    returns true on them.
11473
11474    This behaviour is useful is situations close to tear-down -- e.g.,
11475    after an exec, while the target still has execution, but breakpoint
11476    shadows of the previous executable image should *NOT* be restored
11477    to the new image; or before detaching, where the target still has
11478    execution and wants to delete breakpoints from GDB's lists, and all
11479    breakpoints had already been removed from the inferior.  */
11480
11481 static void
11482 update_global_location_list (int should_insert)
11483 {
11484   struct breakpoint *b;
11485   struct bp_location **locp, *loc;
11486   struct cleanup *cleanups;
11487   /* Last breakpoint location address that was marked for update.  */
11488   CORE_ADDR last_addr = 0;
11489   /* Last breakpoint location program space that was marked for update.  */
11490   int last_pspace_num = -1;
11491
11492   /* Used in the duplicates detection below.  When iterating over all
11493      bp_locations, points to the first bp_location of a given address.
11494      Breakpoints and watchpoints of different types are never
11495      duplicates of each other.  Keep one pointer for each type of
11496      breakpoint/watchpoint, so we only need to loop over all locations
11497      once.  */
11498   struct bp_location *bp_loc_first;  /* breakpoint */
11499   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11500   struct bp_location *awp_loc_first; /* access watchpoint */
11501   struct bp_location *rwp_loc_first; /* read watchpoint */
11502
11503   /* Saved former bp_location array which we compare against the newly
11504      built bp_location from the current state of ALL_BREAKPOINTS.  */
11505   struct bp_location **old_location, **old_locp;
11506   unsigned old_location_count;
11507
11508   old_location = bp_location;
11509   old_location_count = bp_location_count;
11510   bp_location = NULL;
11511   bp_location_count = 0;
11512   cleanups = make_cleanup (xfree, old_location);
11513
11514   ALL_BREAKPOINTS (b)
11515     for (loc = b->loc; loc; loc = loc->next)
11516       bp_location_count++;
11517
11518   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
11519   locp = bp_location;
11520   ALL_BREAKPOINTS (b)
11521     for (loc = b->loc; loc; loc = loc->next)
11522       *locp++ = loc;
11523   qsort (bp_location, bp_location_count, sizeof (*bp_location),
11524          bp_location_compare);
11525
11526   bp_location_target_extensions_update ();
11527
11528   /* Identify bp_location instances that are no longer present in the
11529      new list, and therefore should be freed.  Note that it's not
11530      necessary that those locations should be removed from inferior --
11531      if there's another location at the same address (previously
11532      marked as duplicate), we don't need to remove/insert the
11533      location.
11534      
11535      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11536      and former bp_location array state respectively.  */
11537
11538   locp = bp_location;
11539   for (old_locp = old_location; old_locp < old_location + old_location_count;
11540        old_locp++)
11541     {
11542       struct bp_location *old_loc = *old_locp;
11543       struct bp_location **loc2p;
11544
11545       /* Tells if 'old_loc' is found among the new locations.  If
11546          not, we have to free it.  */
11547       int found_object = 0;
11548       /* Tells if the location should remain inserted in the target.  */
11549       int keep_in_target = 0;
11550       int removed = 0;
11551
11552       /* Skip LOCP entries which will definitely never be needed.
11553          Stop either at or being the one matching OLD_LOC.  */
11554       while (locp < bp_location + bp_location_count
11555              && (*locp)->address < old_loc->address)
11556         locp++;
11557
11558       for (loc2p = locp;
11559            (loc2p < bp_location + bp_location_count
11560             && (*loc2p)->address == old_loc->address);
11561            loc2p++)
11562         {
11563           /* Check if this is a new/duplicated location or a duplicated
11564              location that had its condition modified.  If so, we want to send
11565              its condition to the target if evaluation of conditions is taking
11566              place there.  */
11567           if ((*loc2p)->condition_changed == condition_modified
11568               && (last_addr != old_loc->address
11569                   || last_pspace_num != old_loc->pspace->num))
11570             {
11571               force_breakpoint_reinsertion (*loc2p);
11572               last_pspace_num = old_loc->pspace->num;
11573             }
11574
11575           if (*loc2p == old_loc)
11576             found_object = 1;
11577         }
11578
11579       /* We have already handled this address, update it so that we don't
11580          have to go through updates again.  */
11581       last_addr = old_loc->address;
11582
11583       /* Target-side condition evaluation: Handle deleted locations.  */
11584       if (!found_object)
11585         force_breakpoint_reinsertion (old_loc);
11586
11587       /* If this location is no longer present, and inserted, look if
11588          there's maybe a new location at the same address.  If so,
11589          mark that one inserted, and don't remove this one.  This is
11590          needed so that we don't have a time window where a breakpoint
11591          at certain location is not inserted.  */
11592
11593       if (old_loc->inserted)
11594         {
11595           /* If the location is inserted now, we might have to remove
11596              it.  */
11597
11598           if (found_object && should_be_inserted (old_loc))
11599             {
11600               /* The location is still present in the location list,
11601                  and still should be inserted.  Don't do anything.  */
11602               keep_in_target = 1;
11603             }
11604           else
11605             {
11606               /* This location still exists, but it won't be kept in the
11607                  target since it may have been disabled.  We proceed to
11608                  remove its target-side condition.  */
11609
11610               /* The location is either no longer present, or got
11611                  disabled.  See if there's another location at the
11612                  same address, in which case we don't need to remove
11613                  this one from the target.  */
11614
11615               /* OLD_LOC comes from existing struct breakpoint.  */
11616               if (breakpoint_address_is_meaningful (old_loc->owner))
11617                 {
11618                   for (loc2p = locp;
11619                        (loc2p < bp_location + bp_location_count
11620                         && (*loc2p)->address == old_loc->address);
11621                        loc2p++)
11622                     {
11623                       struct bp_location *loc2 = *loc2p;
11624
11625                       if (breakpoint_locations_match (loc2, old_loc))
11626                         {
11627                           /* Read watchpoint locations are switched to
11628                              access watchpoints, if the former are not
11629                              supported, but the latter are.  */
11630                           if (is_hardware_watchpoint (old_loc->owner))
11631                             {
11632                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11633                               loc2->watchpoint_type = old_loc->watchpoint_type;
11634                             }
11635
11636                           /* loc2 is a duplicated location. We need to check
11637                              if it should be inserted in case it will be
11638                              unduplicated.  */
11639                           if (loc2 != old_loc
11640                               && unduplicated_should_be_inserted (loc2))
11641                             {
11642                               swap_insertion (old_loc, loc2);
11643                               keep_in_target = 1;
11644                               break;
11645                             }
11646                         }
11647                     }
11648                 }
11649             }
11650
11651           if (!keep_in_target)
11652             {
11653               if (remove_breakpoint (old_loc, mark_uninserted))
11654                 {
11655                   /* This is just about all we can do.  We could keep
11656                      this location on the global list, and try to
11657                      remove it next time, but there's no particular
11658                      reason why we will succeed next time.
11659                      
11660                      Note that at this point, old_loc->owner is still
11661                      valid, as delete_breakpoint frees the breakpoint
11662                      only after calling us.  */
11663                   printf_filtered (_("warning: Error removing "
11664                                      "breakpoint %d\n"), 
11665                                    old_loc->owner->number);
11666                 }
11667               removed = 1;
11668             }
11669         }
11670
11671       if (!found_object)
11672         {
11673           if (removed && non_stop
11674               && breakpoint_address_is_meaningful (old_loc->owner)
11675               && !is_hardware_watchpoint (old_loc->owner))
11676             {
11677               /* This location was removed from the target.  In
11678                  non-stop mode, a race condition is possible where
11679                  we've removed a breakpoint, but stop events for that
11680                  breakpoint are already queued and will arrive later.
11681                  We apply an heuristic to be able to distinguish such
11682                  SIGTRAPs from other random SIGTRAPs: we keep this
11683                  breakpoint location for a bit, and will retire it
11684                  after we see some number of events.  The theory here
11685                  is that reporting of events should, "on the average",
11686                  be fair, so after a while we'll see events from all
11687                  threads that have anything of interest, and no longer
11688                  need to keep this breakpoint location around.  We
11689                  don't hold locations forever so to reduce chances of
11690                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11691                  SIGTRAP.
11692
11693                  The heuristic failing can be disastrous on
11694                  decr_pc_after_break targets.
11695
11696                  On decr_pc_after_break targets, like e.g., x86-linux,
11697                  if we fail to recognize a late breakpoint SIGTRAP,
11698                  because events_till_retirement has reached 0 too
11699                  soon, we'll fail to do the PC adjustment, and report
11700                  a random SIGTRAP to the user.  When the user resumes
11701                  the inferior, it will most likely immediately crash
11702                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
11703                  corrupted, because of being resumed e.g., in the
11704                  middle of a multi-byte instruction, or skipped a
11705                  one-byte instruction.  This was actually seen happen
11706                  on native x86-linux, and should be less rare on
11707                  targets that do not support new thread events, like
11708                  remote, due to the heuristic depending on
11709                  thread_count.
11710
11711                  Mistaking a random SIGTRAP for a breakpoint trap
11712                  causes similar symptoms (PC adjustment applied when
11713                  it shouldn't), but then again, playing with SIGTRAPs
11714                  behind the debugger's back is asking for trouble.
11715
11716                  Since hardware watchpoint traps are always
11717                  distinguishable from other traps, so we don't need to
11718                  apply keep hardware watchpoint moribund locations
11719                  around.  We simply always ignore hardware watchpoint
11720                  traps we can no longer explain.  */
11721
11722               old_loc->events_till_retirement = 3 * (thread_count () + 1);
11723               old_loc->owner = NULL;
11724
11725               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
11726             }
11727           else
11728             {
11729               old_loc->owner = NULL;
11730               decref_bp_location (&old_loc);
11731             }
11732         }
11733     }
11734
11735   /* Rescan breakpoints at the same address and section, marking the
11736      first one as "first" and any others as "duplicates".  This is so
11737      that the bpt instruction is only inserted once.  If we have a
11738      permanent breakpoint at the same place as BPT, make that one the
11739      official one, and the rest as duplicates.  Permanent breakpoints
11740      are sorted first for the same address.
11741
11742      Do the same for hardware watchpoints, but also considering the
11743      watchpoint's type (regular/access/read) and length.  */
11744
11745   bp_loc_first = NULL;
11746   wp_loc_first = NULL;
11747   awp_loc_first = NULL;
11748   rwp_loc_first = NULL;
11749   ALL_BP_LOCATIONS (loc, locp)
11750     {
11751       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
11752          non-NULL.  */
11753       struct bp_location **loc_first_p;
11754       b = loc->owner;
11755
11756       if (!should_be_inserted (loc)
11757           || !breakpoint_address_is_meaningful (b)
11758           /* Don't detect duplicate for tracepoint locations because they are
11759            never duplicated.  See the comments in field `duplicate' of
11760            `struct bp_location'.  */
11761           || is_tracepoint (b))
11762         {
11763           /* Clear the condition modification flag.  */
11764           loc->condition_changed = condition_unchanged;
11765           continue;
11766         }
11767
11768       /* Permanent breakpoint should always be inserted.  */
11769       if (b->enable_state == bp_permanent && ! loc->inserted)
11770         internal_error (__FILE__, __LINE__,
11771                         _("allegedly permanent breakpoint is not "
11772                         "actually inserted"));
11773
11774       if (b->type == bp_hardware_watchpoint)
11775         loc_first_p = &wp_loc_first;
11776       else if (b->type == bp_read_watchpoint)
11777         loc_first_p = &rwp_loc_first;
11778       else if (b->type == bp_access_watchpoint)
11779         loc_first_p = &awp_loc_first;
11780       else
11781         loc_first_p = &bp_loc_first;
11782
11783       if (*loc_first_p == NULL
11784           || (overlay_debugging && loc->section != (*loc_first_p)->section)
11785           || !breakpoint_locations_match (loc, *loc_first_p))
11786         {
11787           *loc_first_p = loc;
11788           loc->duplicate = 0;
11789
11790           if (is_breakpoint (loc->owner) && loc->condition_changed)
11791             {
11792               loc->needs_update = 1;
11793               /* Clear the condition modification flag.  */
11794               loc->condition_changed = condition_unchanged;
11795             }
11796           continue;
11797         }
11798
11799
11800       /* This and the above ensure the invariant that the first location
11801          is not duplicated, and is the inserted one.
11802          All following are marked as duplicated, and are not inserted.  */
11803       if (loc->inserted)
11804         swap_insertion (loc, *loc_first_p);
11805       loc->duplicate = 1;
11806
11807       /* Clear the condition modification flag.  */
11808       loc->condition_changed = condition_unchanged;
11809
11810       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
11811           && b->enable_state != bp_permanent)
11812         internal_error (__FILE__, __LINE__,
11813                         _("another breakpoint was inserted on top of "
11814                         "a permanent breakpoint"));
11815     }
11816
11817   if (breakpoints_always_inserted_mode ()
11818       && (have_live_inferiors ()
11819           || (gdbarch_has_global_breakpoints (target_gdbarch))))
11820     {
11821       if (should_insert)
11822         insert_breakpoint_locations ();
11823       else
11824         {
11825           /* Though should_insert is false, we may need to update conditions
11826              on the target's side if it is evaluating such conditions.  We
11827              only update conditions for locations that are marked
11828              "needs_update".  */
11829           update_inserted_breakpoint_locations ();
11830         }
11831     }
11832
11833   if (should_insert)
11834     download_tracepoint_locations ();
11835
11836   do_cleanups (cleanups);
11837 }
11838
11839 void
11840 breakpoint_retire_moribund (void)
11841 {
11842   struct bp_location *loc;
11843   int ix;
11844
11845   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
11846     if (--(loc->events_till_retirement) == 0)
11847       {
11848         decref_bp_location (&loc);
11849         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
11850         --ix;
11851       }
11852 }
11853
11854 static void
11855 update_global_location_list_nothrow (int inserting)
11856 {
11857   volatile struct gdb_exception e;
11858
11859   TRY_CATCH (e, RETURN_MASK_ERROR)
11860     update_global_location_list (inserting);
11861 }
11862
11863 /* Clear BKP from a BPS.  */
11864
11865 static void
11866 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
11867 {
11868   bpstat bs;
11869
11870   for (bs = bps; bs; bs = bs->next)
11871     if (bs->breakpoint_at == bpt)
11872       {
11873         bs->breakpoint_at = NULL;
11874         bs->old_val = NULL;
11875         /* bs->commands will be freed later.  */
11876       }
11877 }
11878
11879 /* Callback for iterate_over_threads.  */
11880 static int
11881 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
11882 {
11883   struct breakpoint *bpt = data;
11884
11885   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
11886   return 0;
11887 }
11888
11889 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
11890    callbacks.  */
11891
11892 static void
11893 say_where (struct breakpoint *b)
11894 {
11895   struct ui_out *uiout = current_uiout;
11896   struct value_print_options opts;
11897
11898   get_user_print_options (&opts);
11899
11900   /* i18n: cagney/2005-02-11: Below needs to be merged into a
11901      single string.  */
11902   if (b->loc == NULL)
11903     {
11904       printf_filtered (_(" (%s) pending."), b->addr_string);
11905     }
11906   else
11907     {
11908       if (opts.addressprint || b->loc->source_file == NULL)
11909         {
11910           printf_filtered (" at ");
11911           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
11912                           gdb_stdout);
11913         }
11914       if (b->loc->source_file)
11915         {
11916           /* If there is a single location, we can print the location
11917              more nicely.  */
11918           if (b->loc->next == NULL)
11919             printf_filtered (": file %s, line %d.",
11920                              b->loc->source_file, b->loc->line_number);
11921           else
11922             /* This is not ideal, but each location may have a
11923                different file name, and this at least reflects the
11924                real situation somewhat.  */
11925             printf_filtered (": %s.", b->addr_string);
11926         }
11927
11928       if (b->loc->next)
11929         {
11930           struct bp_location *loc = b->loc;
11931           int n = 0;
11932           for (; loc; loc = loc->next)
11933             ++n;
11934           printf_filtered (" (%d locations)", n);
11935         }
11936     }
11937 }
11938
11939 /* Default bp_location_ops methods.  */
11940
11941 static void
11942 bp_location_dtor (struct bp_location *self)
11943 {
11944   xfree (self->cond);
11945   if (self->cond_bytecode)
11946     free_agent_expr (self->cond_bytecode);
11947   xfree (self->function_name);
11948   xfree (self->source_file);
11949 }
11950
11951 static const struct bp_location_ops bp_location_ops =
11952 {
11953   bp_location_dtor
11954 };
11955
11956 /* Default breakpoint_ops methods all breakpoint_ops ultimately
11957    inherit from.  */
11958
11959 static void
11960 base_breakpoint_dtor (struct breakpoint *self)
11961 {
11962   decref_counted_command_line (&self->commands);
11963   xfree (self->cond_string);
11964   xfree (self->addr_string);
11965   xfree (self->filter);
11966   xfree (self->addr_string_range_end);
11967 }
11968
11969 static struct bp_location *
11970 base_breakpoint_allocate_location (struct breakpoint *self)
11971 {
11972   struct bp_location *loc;
11973
11974   loc = XNEW (struct bp_location);
11975   init_bp_location (loc, &bp_location_ops, self);
11976   return loc;
11977 }
11978
11979 static void
11980 base_breakpoint_re_set (struct breakpoint *b)
11981 {
11982   /* Nothing to re-set. */
11983 }
11984
11985 #define internal_error_pure_virtual_called() \
11986   gdb_assert_not_reached ("pure virtual function called")
11987
11988 static int
11989 base_breakpoint_insert_location (struct bp_location *bl)
11990 {
11991   internal_error_pure_virtual_called ();
11992 }
11993
11994 static int
11995 base_breakpoint_remove_location (struct bp_location *bl)
11996 {
11997   internal_error_pure_virtual_called ();
11998 }
11999
12000 static int
12001 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12002                                 struct address_space *aspace,
12003                                 CORE_ADDR bp_addr,
12004                                 const struct target_waitstatus *ws)
12005 {
12006   internal_error_pure_virtual_called ();
12007 }
12008
12009 static void
12010 base_breakpoint_check_status (bpstat bs)
12011 {
12012   /* Always stop.   */
12013 }
12014
12015 /* A "works_in_software_mode" breakpoint_ops method that just internal
12016    errors.  */
12017
12018 static int
12019 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12020 {
12021   internal_error_pure_virtual_called ();
12022 }
12023
12024 /* A "resources_needed" breakpoint_ops method that just internal
12025    errors.  */
12026
12027 static int
12028 base_breakpoint_resources_needed (const struct bp_location *bl)
12029 {
12030   internal_error_pure_virtual_called ();
12031 }
12032
12033 static enum print_stop_action
12034 base_breakpoint_print_it (bpstat bs)
12035 {
12036   internal_error_pure_virtual_called ();
12037 }
12038
12039 static void
12040 base_breakpoint_print_one_detail (const struct breakpoint *self,
12041                                   struct ui_out *uiout)
12042 {
12043   /* nothing */
12044 }
12045
12046 static void
12047 base_breakpoint_print_mention (struct breakpoint *b)
12048 {
12049   internal_error_pure_virtual_called ();
12050 }
12051
12052 static void
12053 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12054 {
12055   internal_error_pure_virtual_called ();
12056 }
12057
12058 static void
12059 base_breakpoint_create_sals_from_address (char **arg,
12060                                           struct linespec_result *canonical,
12061                                           enum bptype type_wanted,
12062                                           char *addr_start,
12063                                           char **copy_arg)
12064 {
12065   internal_error_pure_virtual_called ();
12066 }
12067
12068 static void
12069 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12070                                         struct linespec_result *c,
12071                                         struct linespec_sals *lsal,
12072                                         char *cond_string,
12073                                         enum bptype type_wanted,
12074                                         enum bpdisp disposition,
12075                                         int thread,
12076                                         int task, int ignore_count,
12077                                         const struct breakpoint_ops *o,
12078                                         int from_tty, int enabled,
12079                                         int internal, unsigned flags)
12080 {
12081   internal_error_pure_virtual_called ();
12082 }
12083
12084 static void
12085 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12086                                  struct symtabs_and_lines *sals)
12087 {
12088   internal_error_pure_virtual_called ();
12089 }
12090
12091 static struct breakpoint_ops base_breakpoint_ops =
12092 {
12093   base_breakpoint_dtor,
12094   base_breakpoint_allocate_location,
12095   base_breakpoint_re_set,
12096   base_breakpoint_insert_location,
12097   base_breakpoint_remove_location,
12098   base_breakpoint_breakpoint_hit,
12099   base_breakpoint_check_status,
12100   base_breakpoint_resources_needed,
12101   base_breakpoint_works_in_software_mode,
12102   base_breakpoint_print_it,
12103   NULL,
12104   base_breakpoint_print_one_detail,
12105   base_breakpoint_print_mention,
12106   base_breakpoint_print_recreate,
12107   base_breakpoint_create_sals_from_address,
12108   base_breakpoint_create_breakpoints_sal,
12109   base_breakpoint_decode_linespec,
12110 };
12111
12112 /* Default breakpoint_ops methods.  */
12113
12114 static void
12115 bkpt_re_set (struct breakpoint *b)
12116 {
12117   /* FIXME: is this still reachable?  */
12118   if (b->addr_string == NULL)
12119     {
12120       /* Anything without a string can't be re-set.  */
12121       delete_breakpoint (b);
12122       return;
12123     }
12124
12125   breakpoint_re_set_default (b);
12126 }
12127
12128 static int
12129 bkpt_insert_location (struct bp_location *bl)
12130 {
12131   if (bl->loc_type == bp_loc_hardware_breakpoint)
12132     return target_insert_hw_breakpoint (bl->gdbarch,
12133                                         &bl->target_info);
12134   else
12135     return target_insert_breakpoint (bl->gdbarch,
12136                                      &bl->target_info);
12137 }
12138
12139 static int
12140 bkpt_remove_location (struct bp_location *bl)
12141 {
12142   if (bl->loc_type == bp_loc_hardware_breakpoint)
12143     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12144   else
12145     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12146 }
12147
12148 static int
12149 bkpt_breakpoint_hit (const struct bp_location *bl,
12150                      struct address_space *aspace, CORE_ADDR bp_addr,
12151                      const struct target_waitstatus *ws)
12152 {
12153   struct breakpoint *b = bl->owner;
12154
12155   if (ws->kind != TARGET_WAITKIND_STOPPED
12156       || ws->value.sig != TARGET_SIGNAL_TRAP)
12157     return 0;
12158
12159   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12160                                  aspace, bp_addr))
12161     return 0;
12162
12163   if (overlay_debugging         /* unmapped overlay section */
12164       && section_is_overlay (bl->section)
12165       && !section_is_mapped (bl->section))
12166     return 0;
12167
12168   return 1;
12169 }
12170
12171 static int
12172 bkpt_resources_needed (const struct bp_location *bl)
12173 {
12174   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12175
12176   return 1;
12177 }
12178
12179 static enum print_stop_action
12180 bkpt_print_it (bpstat bs)
12181 {
12182   struct breakpoint *b;
12183   const struct bp_location *bl;
12184   int bp_temp;
12185   struct ui_out *uiout = current_uiout;
12186
12187   gdb_assert (bs->bp_location_at != NULL);
12188
12189   bl = bs->bp_location_at;
12190   b = bs->breakpoint_at;
12191
12192   bp_temp = b->disposition == disp_del;
12193   if (bl->address != bl->requested_address)
12194     breakpoint_adjustment_warning (bl->requested_address,
12195                                    bl->address,
12196                                    b->number, 1);
12197   annotate_breakpoint (b->number);
12198   if (bp_temp)
12199     ui_out_text (uiout, "\nTemporary breakpoint ");
12200   else
12201     ui_out_text (uiout, "\nBreakpoint ");
12202   if (ui_out_is_mi_like_p (uiout))
12203     {
12204       ui_out_field_string (uiout, "reason",
12205                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12206       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12207     }
12208   ui_out_field_int (uiout, "bkptno", b->number);
12209   ui_out_text (uiout, ", ");
12210
12211   return PRINT_SRC_AND_LOC;
12212 }
12213
12214 static void
12215 bkpt_print_mention (struct breakpoint *b)
12216 {
12217   if (ui_out_is_mi_like_p (current_uiout))
12218     return;
12219
12220   switch (b->type)
12221     {
12222     case bp_breakpoint:
12223     case bp_gnu_ifunc_resolver:
12224       if (b->disposition == disp_del)
12225         printf_filtered (_("Temporary breakpoint"));
12226       else
12227         printf_filtered (_("Breakpoint"));
12228       printf_filtered (_(" %d"), b->number);
12229       if (b->type == bp_gnu_ifunc_resolver)
12230         printf_filtered (_(" at gnu-indirect-function resolver"));
12231       break;
12232     case bp_hardware_breakpoint:
12233       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12234       break;
12235     }
12236
12237   say_where (b);
12238 }
12239
12240 static void
12241 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12242 {
12243   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12244     fprintf_unfiltered (fp, "tbreak");
12245   else if (tp->type == bp_breakpoint)
12246     fprintf_unfiltered (fp, "break");
12247   else if (tp->type == bp_hardware_breakpoint
12248            && tp->disposition == disp_del)
12249     fprintf_unfiltered (fp, "thbreak");
12250   else if (tp->type == bp_hardware_breakpoint)
12251     fprintf_unfiltered (fp, "hbreak");
12252   else
12253     internal_error (__FILE__, __LINE__,
12254                     _("unhandled breakpoint type %d"), (int) tp->type);
12255
12256   fprintf_unfiltered (fp, " %s", tp->addr_string);
12257   print_recreate_thread (tp, fp);
12258 }
12259
12260 static void
12261 bkpt_create_sals_from_address (char **arg,
12262                                struct linespec_result *canonical,
12263                                enum bptype type_wanted,
12264                                char *addr_start, char **copy_arg)
12265 {
12266   create_sals_from_address_default (arg, canonical, type_wanted,
12267                                     addr_start, copy_arg);
12268 }
12269
12270 static void
12271 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12272                              struct linespec_result *canonical,
12273                              struct linespec_sals *lsal,
12274                              char *cond_string,
12275                              enum bptype type_wanted,
12276                              enum bpdisp disposition,
12277                              int thread,
12278                              int task, int ignore_count,
12279                              const struct breakpoint_ops *ops,
12280                              int from_tty, int enabled,
12281                              int internal, unsigned flags)
12282 {
12283   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12284                                   cond_string, type_wanted,
12285                                   disposition, thread, task,
12286                                   ignore_count, ops, from_tty,
12287                                   enabled, internal, flags);
12288 }
12289
12290 static void
12291 bkpt_decode_linespec (struct breakpoint *b, char **s,
12292                       struct symtabs_and_lines *sals)
12293 {
12294   decode_linespec_default (b, s, sals);
12295 }
12296
12297 /* Virtual table for internal breakpoints.  */
12298
12299 static void
12300 internal_bkpt_re_set (struct breakpoint *b)
12301 {
12302   switch (b->type)
12303     {
12304       /* Delete overlay event and longjmp master breakpoints; they
12305          will be reset later by breakpoint_re_set.  */
12306     case bp_overlay_event:
12307     case bp_longjmp_master:
12308     case bp_std_terminate_master:
12309     case bp_exception_master:
12310       delete_breakpoint (b);
12311       break;
12312
12313       /* This breakpoint is special, it's set up when the inferior
12314          starts and we really don't want to touch it.  */
12315     case bp_shlib_event:
12316
12317       /* Like bp_shlib_event, this breakpoint type is special.  Once
12318          it is set up, we do not want to touch it.  */
12319     case bp_thread_event:
12320       break;
12321     }
12322 }
12323
12324 static void
12325 internal_bkpt_check_status (bpstat bs)
12326 {
12327   if (bs->breakpoint_at->type == bp_shlib_event)
12328     {
12329       /* If requested, stop when the dynamic linker notifies GDB of
12330          events.  This allows the user to get control and place
12331          breakpoints in initializer routines for dynamically loaded
12332          objects (among other things).  */
12333       bs->stop = stop_on_solib_events;
12334       bs->print = stop_on_solib_events;
12335     }
12336   else
12337     bs->stop = 0;
12338 }
12339
12340 static enum print_stop_action
12341 internal_bkpt_print_it (bpstat bs)
12342 {
12343   struct ui_out *uiout = current_uiout;
12344   struct breakpoint *b;
12345
12346   b = bs->breakpoint_at;
12347
12348   switch (b->type)
12349     {
12350     case bp_shlib_event:
12351       /* Did we stop because the user set the stop_on_solib_events
12352          variable?  (If so, we report this as a generic, "Stopped due
12353          to shlib event" message.) */
12354       print_solib_event (0);
12355       break;
12356
12357     case bp_thread_event:
12358       /* Not sure how we will get here.
12359          GDB should not stop for these breakpoints.  */
12360       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12361       break;
12362
12363     case bp_overlay_event:
12364       /* By analogy with the thread event, GDB should not stop for these.  */
12365       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12366       break;
12367
12368     case bp_longjmp_master:
12369       /* These should never be enabled.  */
12370       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12371       break;
12372
12373     case bp_std_terminate_master:
12374       /* These should never be enabled.  */
12375       printf_filtered (_("std::terminate Master Breakpoint: "
12376                          "gdb should not stop!\n"));
12377       break;
12378
12379     case bp_exception_master:
12380       /* These should never be enabled.  */
12381       printf_filtered (_("Exception Master Breakpoint: "
12382                          "gdb should not stop!\n"));
12383       break;
12384     }
12385
12386   return PRINT_NOTHING;
12387 }
12388
12389 static void
12390 internal_bkpt_print_mention (struct breakpoint *b)
12391 {
12392   /* Nothing to mention.  These breakpoints are internal.  */
12393 }
12394
12395 /* Virtual table for momentary breakpoints  */
12396
12397 static void
12398 momentary_bkpt_re_set (struct breakpoint *b)
12399 {
12400   /* Keep temporary breakpoints, which can be encountered when we step
12401      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
12402      Otherwise these should have been blown away via the cleanup chain
12403      or by breakpoint_init_inferior when we rerun the executable.  */
12404 }
12405
12406 static void
12407 momentary_bkpt_check_status (bpstat bs)
12408 {
12409   /* Nothing.  The point of these breakpoints is causing a stop.  */
12410 }
12411
12412 static enum print_stop_action
12413 momentary_bkpt_print_it (bpstat bs)
12414 {
12415   struct ui_out *uiout = current_uiout;
12416
12417   if (ui_out_is_mi_like_p (uiout))
12418     {
12419       struct breakpoint *b = bs->breakpoint_at;
12420
12421       switch (b->type)
12422         {
12423         case bp_finish:
12424           ui_out_field_string
12425             (uiout, "reason",
12426              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
12427           break;
12428
12429         case bp_until:
12430           ui_out_field_string
12431             (uiout, "reason",
12432              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
12433           break;
12434         }
12435     }
12436
12437   return PRINT_UNKNOWN;
12438 }
12439
12440 static void
12441 momentary_bkpt_print_mention (struct breakpoint *b)
12442 {
12443   /* Nothing to mention.  These breakpoints are internal.  */
12444 }
12445
12446 /* The breakpoint_ops structure to be used in tracepoints.  */
12447
12448 static void
12449 tracepoint_re_set (struct breakpoint *b)
12450 {
12451   breakpoint_re_set_default (b);
12452 }
12453
12454 static int
12455 tracepoint_breakpoint_hit (const struct bp_location *bl,
12456                            struct address_space *aspace, CORE_ADDR bp_addr,
12457                            const struct target_waitstatus *ws)
12458 {
12459   /* By definition, the inferior does not report stops at
12460      tracepoints.  */
12461   return 0;
12462 }
12463
12464 static void
12465 tracepoint_print_one_detail (const struct breakpoint *self,
12466                              struct ui_out *uiout)
12467 {
12468   struct tracepoint *tp = (struct tracepoint *) self;
12469   if (tp->static_trace_marker_id)
12470     {
12471       gdb_assert (self->type == bp_static_tracepoint);
12472
12473       ui_out_text (uiout, "\tmarker id is ");
12474       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
12475                            tp->static_trace_marker_id);
12476       ui_out_text (uiout, "\n");
12477     }
12478 }
12479
12480 static void
12481 tracepoint_print_mention (struct breakpoint *b)
12482 {
12483   if (ui_out_is_mi_like_p (current_uiout))
12484     return;
12485
12486   switch (b->type)
12487     {
12488     case bp_tracepoint:
12489       printf_filtered (_("Tracepoint"));
12490       printf_filtered (_(" %d"), b->number);
12491       break;
12492     case bp_fast_tracepoint:
12493       printf_filtered (_("Fast tracepoint"));
12494       printf_filtered (_(" %d"), b->number);
12495       break;
12496     case bp_static_tracepoint:
12497       printf_filtered (_("Static tracepoint"));
12498       printf_filtered (_(" %d"), b->number);
12499       break;
12500     default:
12501       internal_error (__FILE__, __LINE__,
12502                       _("unhandled tracepoint type %d"), (int) b->type);
12503     }
12504
12505   say_where (b);
12506 }
12507
12508 static void
12509 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12510 {
12511   struct tracepoint *tp = (struct tracepoint *) self;
12512
12513   if (self->type == bp_fast_tracepoint)
12514     fprintf_unfiltered (fp, "ftrace");
12515   if (self->type == bp_static_tracepoint)
12516     fprintf_unfiltered (fp, "strace");
12517   else if (self->type == bp_tracepoint)
12518     fprintf_unfiltered (fp, "trace");
12519   else
12520     internal_error (__FILE__, __LINE__,
12521                     _("unhandled tracepoint type %d"), (int) self->type);
12522
12523   fprintf_unfiltered (fp, " %s", self->addr_string);
12524   print_recreate_thread (self, fp);
12525
12526   if (tp->pass_count)
12527     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12528 }
12529
12530 static void
12531 tracepoint_create_sals_from_address (char **arg,
12532                                      struct linespec_result *canonical,
12533                                      enum bptype type_wanted,
12534                                      char *addr_start, char **copy_arg)
12535 {
12536   create_sals_from_address_default (arg, canonical, type_wanted,
12537                                     addr_start, copy_arg);
12538 }
12539
12540 static void
12541 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12542                                    struct linespec_result *canonical,
12543                                    struct linespec_sals *lsal,
12544                                    char *cond_string,
12545                                    enum bptype type_wanted,
12546                                    enum bpdisp disposition,
12547                                    int thread,
12548                                    int task, int ignore_count,
12549                                    const struct breakpoint_ops *ops,
12550                                    int from_tty, int enabled,
12551                                    int internal, unsigned flags)
12552 {
12553   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12554                                   cond_string, type_wanted,
12555                                   disposition, thread, task,
12556                                   ignore_count, ops, from_tty,
12557                                   enabled, internal, flags);
12558 }
12559
12560 static void
12561 tracepoint_decode_linespec (struct breakpoint *b, char **s,
12562                             struct symtabs_and_lines *sals)
12563 {
12564   decode_linespec_default (b, s, sals);
12565 }
12566
12567 struct breakpoint_ops tracepoint_breakpoint_ops;
12568
12569 /* The breakpoint_ops structure to be used on static tracepoints with
12570    markers (`-m').  */
12571
12572 static void
12573 strace_marker_create_sals_from_address (char **arg,
12574                                         struct linespec_result *canonical,
12575                                         enum bptype type_wanted,
12576                                         char *addr_start, char **copy_arg)
12577 {
12578   struct linespec_sals lsal;
12579
12580   lsal.sals = decode_static_tracepoint_spec (arg);
12581
12582   *copy_arg = savestring (addr_start, *arg - addr_start);
12583
12584   canonical->addr_string = xstrdup (*copy_arg);
12585   lsal.canonical = xstrdup (*copy_arg);
12586   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12587 }
12588
12589 static void
12590 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12591                                       struct linespec_result *canonical,
12592                                       struct linespec_sals *lsal,
12593                                       char *cond_string,
12594                                       enum bptype type_wanted,
12595                                       enum bpdisp disposition,
12596                                       int thread,
12597                                       int task, int ignore_count,
12598                                       const struct breakpoint_ops *ops,
12599                                       int from_tty, int enabled,
12600                                       int internal, unsigned flags)
12601 {
12602   int i;
12603
12604   /* If the user is creating a static tracepoint by marker id
12605      (strace -m MARKER_ID), then store the sals index, so that
12606      breakpoint_re_set can try to match up which of the newly
12607      found markers corresponds to this one, and, don't try to
12608      expand multiple locations for each sal, given than SALS
12609      already should contain all sals for MARKER_ID.  */
12610
12611   for (i = 0; i < lsal->sals.nelts; ++i)
12612     {
12613       struct symtabs_and_lines expanded;
12614       struct tracepoint *tp;
12615       struct cleanup *old_chain;
12616       char *addr_string;
12617
12618       expanded.nelts = 1;
12619       expanded.sals = &lsal->sals.sals[i];
12620
12621       addr_string = xstrdup (canonical->addr_string);
12622       old_chain = make_cleanup (xfree, addr_string);
12623
12624       tp = XCNEW (struct tracepoint);
12625       init_breakpoint_sal (&tp->base, gdbarch, expanded,
12626                            addr_string, NULL,
12627                            cond_string, type_wanted, disposition,
12628                            thread, task, ignore_count, ops,
12629                            from_tty, enabled, internal, flags,
12630                            canonical->special_display);
12631       /* Given that its possible to have multiple markers with
12632          the same string id, if the user is creating a static
12633          tracepoint by marker id ("strace -m MARKER_ID"), then
12634          store the sals index, so that breakpoint_re_set can
12635          try to match up which of the newly found markers
12636          corresponds to this one  */
12637       tp->static_trace_marker_id_idx = i;
12638
12639       install_breakpoint (internal, &tp->base, 0);
12640
12641       discard_cleanups (old_chain);
12642     }
12643 }
12644
12645 static void
12646 strace_marker_decode_linespec (struct breakpoint *b, char **s,
12647                                struct symtabs_and_lines *sals)
12648 {
12649   struct tracepoint *tp = (struct tracepoint *) b;
12650
12651   *sals = decode_static_tracepoint_spec (s);
12652   if (sals->nelts > tp->static_trace_marker_id_idx)
12653     {
12654       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
12655       sals->nelts = 1;
12656     }
12657   else
12658     error (_("marker %s not found"), tp->static_trace_marker_id);
12659 }
12660
12661 static struct breakpoint_ops strace_marker_breakpoint_ops;
12662
12663 static int
12664 strace_marker_p (struct breakpoint *b)
12665 {
12666   return b->ops == &strace_marker_breakpoint_ops;
12667 }
12668
12669 /* Delete a breakpoint and clean up all traces of it in the data
12670    structures.  */
12671
12672 void
12673 delete_breakpoint (struct breakpoint *bpt)
12674 {
12675   struct breakpoint *b;
12676
12677   gdb_assert (bpt != NULL);
12678
12679   /* Has this bp already been deleted?  This can happen because
12680      multiple lists can hold pointers to bp's.  bpstat lists are
12681      especial culprits.
12682
12683      One example of this happening is a watchpoint's scope bp.  When
12684      the scope bp triggers, we notice that the watchpoint is out of
12685      scope, and delete it.  We also delete its scope bp.  But the
12686      scope bp is marked "auto-deleting", and is already on a bpstat.
12687      That bpstat is then checked for auto-deleting bp's, which are
12688      deleted.
12689
12690      A real solution to this problem might involve reference counts in
12691      bp's, and/or giving them pointers back to their referencing
12692      bpstat's, and teaching delete_breakpoint to only free a bp's
12693      storage when no more references were extent.  A cheaper bandaid
12694      was chosen.  */
12695   if (bpt->type == bp_none)
12696     return;
12697
12698   /* At least avoid this stale reference until the reference counting
12699      of breakpoints gets resolved.  */
12700   if (bpt->related_breakpoint != bpt)
12701     {
12702       struct breakpoint *related;
12703       struct watchpoint *w;
12704
12705       if (bpt->type == bp_watchpoint_scope)
12706         w = (struct watchpoint *) bpt->related_breakpoint;
12707       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
12708         w = (struct watchpoint *) bpt;
12709       else
12710         w = NULL;
12711       if (w != NULL)
12712         watchpoint_del_at_next_stop (w);
12713
12714       /* Unlink bpt from the bpt->related_breakpoint ring.  */
12715       for (related = bpt; related->related_breakpoint != bpt;
12716            related = related->related_breakpoint);
12717       related->related_breakpoint = bpt->related_breakpoint;
12718       bpt->related_breakpoint = bpt;
12719     }
12720
12721   /* watch_command_1 creates a watchpoint but only sets its number if
12722      update_watchpoint succeeds in creating its bp_locations.  If there's
12723      a problem in that process, we'll be asked to delete the half-created
12724      watchpoint.  In that case, don't announce the deletion.  */
12725   if (bpt->number)
12726     observer_notify_breakpoint_deleted (bpt);
12727
12728   if (breakpoint_chain == bpt)
12729     breakpoint_chain = bpt->next;
12730
12731   ALL_BREAKPOINTS (b)
12732     if (b->next == bpt)
12733     {
12734       b->next = bpt->next;
12735       break;
12736     }
12737
12738   /* Be sure no bpstat's are pointing at the breakpoint after it's
12739      been freed.  */
12740   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
12741      in all threads for now.  Note that we cannot just remove bpstats
12742      pointing at bpt from the stop_bpstat list entirely, as breakpoint
12743      commands are associated with the bpstat; if we remove it here,
12744      then the later call to bpstat_do_actions (&stop_bpstat); in
12745      event-top.c won't do anything, and temporary breakpoints with
12746      commands won't work.  */
12747
12748   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
12749
12750   /* Now that breakpoint is removed from breakpoint list, update the
12751      global location list.  This will remove locations that used to
12752      belong to this breakpoint.  Do this before freeing the breakpoint
12753      itself, since remove_breakpoint looks at location's owner.  It
12754      might be better design to have location completely
12755      self-contained, but it's not the case now.  */
12756   update_global_location_list (0);
12757
12758   bpt->ops->dtor (bpt);
12759   /* On the chance that someone will soon try again to delete this
12760      same bp, we mark it as deleted before freeing its storage.  */
12761   bpt->type = bp_none;
12762   xfree (bpt);
12763 }
12764
12765 static void
12766 do_delete_breakpoint_cleanup (void *b)
12767 {
12768   delete_breakpoint (b);
12769 }
12770
12771 struct cleanup *
12772 make_cleanup_delete_breakpoint (struct breakpoint *b)
12773 {
12774   return make_cleanup (do_delete_breakpoint_cleanup, b);
12775 }
12776
12777 /* Iterator function to call a user-provided callback function once
12778    for each of B and its related breakpoints.  */
12779
12780 static void
12781 iterate_over_related_breakpoints (struct breakpoint *b,
12782                                   void (*function) (struct breakpoint *,
12783                                                     void *),
12784                                   void *data)
12785 {
12786   struct breakpoint *related;
12787
12788   related = b;
12789   do
12790     {
12791       struct breakpoint *next;
12792
12793       /* FUNCTION may delete RELATED.  */
12794       next = related->related_breakpoint;
12795
12796       if (next == related)
12797         {
12798           /* RELATED is the last ring entry.  */
12799           function (related, data);
12800
12801           /* FUNCTION may have deleted it, so we'd never reach back to
12802              B.  There's nothing left to do anyway, so just break
12803              out.  */
12804           break;
12805         }
12806       else
12807         function (related, data);
12808
12809       related = next;
12810     }
12811   while (related != b);
12812 }
12813
12814 static void
12815 do_delete_breakpoint (struct breakpoint *b, void *ignore)
12816 {
12817   delete_breakpoint (b);
12818 }
12819
12820 /* A callback for map_breakpoint_numbers that calls
12821    delete_breakpoint.  */
12822
12823 static void
12824 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
12825 {
12826   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
12827 }
12828
12829 void
12830 delete_command (char *arg, int from_tty)
12831 {
12832   struct breakpoint *b, *b_tmp;
12833
12834   dont_repeat ();
12835
12836   if (arg == 0)
12837     {
12838       int breaks_to_delete = 0;
12839
12840       /* Delete all breakpoints if no argument.  Do not delete
12841          internal breakpoints, these have to be deleted with an
12842          explicit breakpoint number argument.  */
12843       ALL_BREAKPOINTS (b)
12844         if (user_breakpoint_p (b))
12845           {
12846             breaks_to_delete = 1;
12847             break;
12848           }
12849
12850       /* Ask user only if there are some breakpoints to delete.  */
12851       if (!from_tty
12852           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
12853         {
12854           ALL_BREAKPOINTS_SAFE (b, b_tmp)
12855             if (user_breakpoint_p (b))
12856               delete_breakpoint (b);
12857         }
12858     }
12859   else
12860     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
12861 }
12862
12863 static int
12864 all_locations_are_pending (struct bp_location *loc)
12865 {
12866   for (; loc; loc = loc->next)
12867     if (!loc->shlib_disabled
12868         && !loc->pspace->executing_startup)
12869       return 0;
12870   return 1;
12871 }
12872
12873 /* Subroutine of update_breakpoint_locations to simplify it.
12874    Return non-zero if multiple fns in list LOC have the same name.
12875    Null names are ignored.  */
12876
12877 static int
12878 ambiguous_names_p (struct bp_location *loc)
12879 {
12880   struct bp_location *l;
12881   htab_t htab = htab_create_alloc (13, htab_hash_string,
12882                                    (int (*) (const void *, 
12883                                              const void *)) streq,
12884                                    NULL, xcalloc, xfree);
12885
12886   for (l = loc; l != NULL; l = l->next)
12887     {
12888       const char **slot;
12889       const char *name = l->function_name;
12890
12891       /* Allow for some names to be NULL, ignore them.  */
12892       if (name == NULL)
12893         continue;
12894
12895       slot = (const char **) htab_find_slot (htab, (const void *) name,
12896                                              INSERT);
12897       /* NOTE: We can assume slot != NULL here because xcalloc never
12898          returns NULL.  */
12899       if (*slot != NULL)
12900         {
12901           htab_delete (htab);
12902           return 1;
12903         }
12904       *slot = name;
12905     }
12906
12907   htab_delete (htab);
12908   return 0;
12909 }
12910
12911 /* When symbols change, it probably means the sources changed as well,
12912    and it might mean the static tracepoint markers are no longer at
12913    the same address or line numbers they used to be at last we
12914    checked.  Losing your static tracepoints whenever you rebuild is
12915    undesirable.  This function tries to resync/rematch gdb static
12916    tracepoints with the markers on the target, for static tracepoints
12917    that have not been set by marker id.  Static tracepoint that have
12918    been set by marker id are reset by marker id in breakpoint_re_set.
12919    The heuristic is:
12920
12921    1) For a tracepoint set at a specific address, look for a marker at
12922    the old PC.  If one is found there, assume to be the same marker.
12923    If the name / string id of the marker found is different from the
12924    previous known name, assume that means the user renamed the marker
12925    in the sources, and output a warning.
12926
12927    2) For a tracepoint set at a given line number, look for a marker
12928    at the new address of the old line number.  If one is found there,
12929    assume to be the same marker.  If the name / string id of the
12930    marker found is different from the previous known name, assume that
12931    means the user renamed the marker in the sources, and output a
12932    warning.
12933
12934    3) If a marker is no longer found at the same address or line, it
12935    may mean the marker no longer exists.  But it may also just mean
12936    the code changed a bit.  Maybe the user added a few lines of code
12937    that made the marker move up or down (in line number terms).  Ask
12938    the target for info about the marker with the string id as we knew
12939    it.  If found, update line number and address in the matching
12940    static tracepoint.  This will get confused if there's more than one
12941    marker with the same ID (possible in UST, although unadvised
12942    precisely because it confuses tools).  */
12943
12944 static struct symtab_and_line
12945 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
12946 {
12947   struct tracepoint *tp = (struct tracepoint *) b;
12948   struct static_tracepoint_marker marker;
12949   CORE_ADDR pc;
12950   int i;
12951
12952   pc = sal.pc;
12953   if (sal.line)
12954     find_line_pc (sal.symtab, sal.line, &pc);
12955
12956   if (target_static_tracepoint_marker_at (pc, &marker))
12957     {
12958       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
12959         warning (_("static tracepoint %d changed probed marker from %s to %s"),
12960                  b->number,
12961                  tp->static_trace_marker_id, marker.str_id);
12962
12963       xfree (tp->static_trace_marker_id);
12964       tp->static_trace_marker_id = xstrdup (marker.str_id);
12965       release_static_tracepoint_marker (&marker);
12966
12967       return sal;
12968     }
12969
12970   /* Old marker wasn't found on target at lineno.  Try looking it up
12971      by string ID.  */
12972   if (!sal.explicit_pc
12973       && sal.line != 0
12974       && sal.symtab != NULL
12975       && tp->static_trace_marker_id != NULL)
12976     {
12977       VEC(static_tracepoint_marker_p) *markers;
12978
12979       markers
12980         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
12981
12982       if (!VEC_empty(static_tracepoint_marker_p, markers))
12983         {
12984           struct symtab_and_line sal2;
12985           struct symbol *sym;
12986           struct static_tracepoint_marker *tpmarker;
12987           struct ui_out *uiout = current_uiout;
12988
12989           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
12990
12991           xfree (tp->static_trace_marker_id);
12992           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
12993
12994           warning (_("marker for static tracepoint %d (%s) not "
12995                      "found at previous line number"),
12996                    b->number, tp->static_trace_marker_id);
12997
12998           init_sal (&sal2);
12999
13000           sal2.pc = tpmarker->address;
13001
13002           sal2 = find_pc_line (tpmarker->address, 0);
13003           sym = find_pc_sect_function (tpmarker->address, NULL);
13004           ui_out_text (uiout, "Now in ");
13005           if (sym)
13006             {
13007               ui_out_field_string (uiout, "func",
13008                                    SYMBOL_PRINT_NAME (sym));
13009               ui_out_text (uiout, " at ");
13010             }
13011           ui_out_field_string (uiout, "file", sal2.symtab->filename);
13012           ui_out_text (uiout, ":");
13013
13014           if (ui_out_is_mi_like_p (uiout))
13015             {
13016               char *fullname = symtab_to_fullname (sal2.symtab);
13017
13018               if (fullname)
13019                 ui_out_field_string (uiout, "fullname", fullname);
13020             }
13021
13022           ui_out_field_int (uiout, "line", sal2.line);
13023           ui_out_text (uiout, "\n");
13024
13025           b->loc->line_number = sal2.line;
13026
13027           xfree (b->loc->source_file);
13028           if (sym)
13029             b->loc->source_file = xstrdup (sal2.symtab->filename);
13030           else
13031             b->loc->source_file = NULL;
13032
13033           xfree (b->addr_string);
13034           b->addr_string = xstrprintf ("%s:%d",
13035                                        sal2.symtab->filename,
13036                                        b->loc->line_number);
13037
13038           /* Might be nice to check if function changed, and warn if
13039              so.  */
13040
13041           release_static_tracepoint_marker (tpmarker);
13042         }
13043     }
13044   return sal;
13045 }
13046
13047 /* Returns 1 iff locations A and B are sufficiently same that
13048    we don't need to report breakpoint as changed.  */
13049
13050 static int
13051 locations_are_equal (struct bp_location *a, struct bp_location *b)
13052 {
13053   while (a && b)
13054     {
13055       if (a->address != b->address)
13056         return 0;
13057
13058       if (a->shlib_disabled != b->shlib_disabled)
13059         return 0;
13060
13061       if (a->enabled != b->enabled)
13062         return 0;
13063
13064       a = a->next;
13065       b = b->next;
13066     }
13067
13068   if ((a == NULL) != (b == NULL))
13069     return 0;
13070
13071   return 1;
13072 }
13073
13074 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13075    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13076    a ranged breakpoint.  */
13077
13078 void
13079 update_breakpoint_locations (struct breakpoint *b,
13080                              struct symtabs_and_lines sals,
13081                              struct symtabs_and_lines sals_end)
13082 {
13083   int i;
13084   struct bp_location *existing_locations = b->loc;
13085
13086   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13087     {
13088       /* Ranged breakpoints have only one start location and one end
13089          location.  */
13090       b->enable_state = bp_disabled;
13091       update_global_location_list (1);
13092       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13093                            "multiple locations found\n"),
13094                          b->number);
13095       return;
13096     }
13097
13098   /* If there's no new locations, and all existing locations are
13099      pending, don't do anything.  This optimizes the common case where
13100      all locations are in the same shared library, that was unloaded.
13101      We'd like to retain the location, so that when the library is
13102      loaded again, we don't loose the enabled/disabled status of the
13103      individual locations.  */
13104   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13105     return;
13106
13107   b->loc = NULL;
13108
13109   for (i = 0; i < sals.nelts; ++i)
13110     {
13111       struct bp_location *new_loc;
13112
13113       switch_to_program_space_and_thread (sals.sals[i].pspace);
13114
13115       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13116
13117       /* Reparse conditions, they might contain references to the
13118          old symtab.  */
13119       if (b->cond_string != NULL)
13120         {
13121           char *s;
13122           volatile struct gdb_exception e;
13123
13124           s = b->cond_string;
13125           TRY_CATCH (e, RETURN_MASK_ERROR)
13126             {
13127               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
13128                                            0);
13129             }
13130           if (e.reason < 0)
13131             {
13132               warning (_("failed to reevaluate condition "
13133                          "for breakpoint %d: %s"), 
13134                        b->number, e.message);
13135               new_loc->enabled = 0;
13136             }
13137         }
13138
13139       if (sals_end.nelts)
13140         {
13141           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
13142
13143           new_loc->length = end - sals.sals[0].pc + 1;
13144         }
13145     }
13146
13147   /* Update locations of permanent breakpoints.  */
13148   if (b->enable_state == bp_permanent)
13149     make_breakpoint_permanent (b);
13150
13151   /* If possible, carry over 'disable' status from existing
13152      breakpoints.  */
13153   {
13154     struct bp_location *e = existing_locations;
13155     /* If there are multiple breakpoints with the same function name,
13156        e.g. for inline functions, comparing function names won't work.
13157        Instead compare pc addresses; this is just a heuristic as things
13158        may have moved, but in practice it gives the correct answer
13159        often enough until a better solution is found.  */
13160     int have_ambiguous_names = ambiguous_names_p (b->loc);
13161
13162     for (; e; e = e->next)
13163       {
13164         if (!e->enabled && e->function_name)
13165           {
13166             struct bp_location *l = b->loc;
13167             if (have_ambiguous_names)
13168               {
13169                 for (; l; l = l->next)
13170                   if (breakpoint_locations_match (e, l))
13171                     {
13172                       l->enabled = 0;
13173                       break;
13174                     }
13175               }
13176             else
13177               {
13178                 for (; l; l = l->next)
13179                   if (l->function_name
13180                       && strcmp (e->function_name, l->function_name) == 0)
13181                     {
13182                       l->enabled = 0;
13183                       break;
13184                     }
13185               }
13186           }
13187       }
13188   }
13189
13190   if (!locations_are_equal (existing_locations, b->loc))
13191     observer_notify_breakpoint_modified (b);
13192
13193   update_global_location_list (1);
13194 }
13195
13196 /* Find the SaL locations corresponding to the given ADDR_STRING.
13197    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13198
13199 static struct symtabs_and_lines
13200 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
13201 {
13202   char *s;
13203   struct symtabs_and_lines sals = {0};
13204   volatile struct gdb_exception e;
13205
13206   gdb_assert (b->ops != NULL);
13207   s = addr_string;
13208
13209   TRY_CATCH (e, RETURN_MASK_ERROR)
13210     {
13211       b->ops->decode_linespec (b, &s, &sals);
13212     }
13213   if (e.reason < 0)
13214     {
13215       int not_found_and_ok = 0;
13216       /* For pending breakpoints, it's expected that parsing will
13217          fail until the right shared library is loaded.  User has
13218          already told to create pending breakpoints and don't need
13219          extra messages.  If breakpoint is in bp_shlib_disabled
13220          state, then user already saw the message about that
13221          breakpoint being disabled, and don't want to see more
13222          errors.  */
13223       if (e.error == NOT_FOUND_ERROR
13224           && (b->condition_not_parsed 
13225               || (b->loc && b->loc->shlib_disabled)
13226               || (b->loc && b->loc->pspace->executing_startup)
13227               || b->enable_state == bp_disabled))
13228         not_found_and_ok = 1;
13229
13230       if (!not_found_and_ok)
13231         {
13232           /* We surely don't want to warn about the same breakpoint
13233              10 times.  One solution, implemented here, is disable
13234              the breakpoint on error.  Another solution would be to
13235              have separate 'warning emitted' flag.  Since this
13236              happens only when a binary has changed, I don't know
13237              which approach is better.  */
13238           b->enable_state = bp_disabled;
13239           throw_exception (e);
13240         }
13241     }
13242
13243   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
13244     {
13245       int i;
13246
13247       for (i = 0; i < sals.nelts; ++i)
13248         resolve_sal_pc (&sals.sals[i]);
13249       if (b->condition_not_parsed && s && s[0])
13250         {
13251           char *cond_string = 0;
13252           int thread = -1;
13253           int task = 0;
13254
13255           find_condition_and_thread (s, sals.sals[0].pc,
13256                                      &cond_string, &thread, &task);
13257           if (cond_string)
13258             b->cond_string = cond_string;
13259           b->thread = thread;
13260           b->task = task;
13261           b->condition_not_parsed = 0;
13262         }
13263
13264       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13265         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
13266
13267       *found = 1;
13268     }
13269   else
13270     *found = 0;
13271
13272   return sals;
13273 }
13274
13275 /* The default re_set method, for typical hardware or software
13276    breakpoints.  Reevaluate the breakpoint and recreate its
13277    locations.  */
13278
13279 static void
13280 breakpoint_re_set_default (struct breakpoint *b)
13281 {
13282   int found;
13283   struct symtabs_and_lines sals, sals_end;
13284   struct symtabs_and_lines expanded = {0};
13285   struct symtabs_and_lines expanded_end = {0};
13286
13287   sals = addr_string_to_sals (b, b->addr_string, &found);
13288   if (found)
13289     {
13290       make_cleanup (xfree, sals.sals);
13291       expanded = sals;
13292     }
13293
13294   if (b->addr_string_range_end)
13295     {
13296       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
13297       if (found)
13298         {
13299           make_cleanup (xfree, sals_end.sals);
13300           expanded_end = sals_end;
13301         }
13302     }
13303
13304   update_breakpoint_locations (b, expanded, expanded_end);
13305 }
13306
13307 /* Default method for creating SALs from an address string.  It basically
13308    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13309
13310 static void
13311 create_sals_from_address_default (char **arg,
13312                                   struct linespec_result *canonical,
13313                                   enum bptype type_wanted,
13314                                   char *addr_start, char **copy_arg)
13315 {
13316   parse_breakpoint_sals (arg, canonical);
13317 }
13318
13319 /* Call create_breakpoints_sal for the given arguments.  This is the default
13320    function for the `create_breakpoints_sal' method of
13321    breakpoint_ops.  */
13322
13323 static void
13324 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13325                                 struct linespec_result *canonical,
13326                                 struct linespec_sals *lsal,
13327                                 char *cond_string,
13328                                 enum bptype type_wanted,
13329                                 enum bpdisp disposition,
13330                                 int thread,
13331                                 int task, int ignore_count,
13332                                 const struct breakpoint_ops *ops,
13333                                 int from_tty, int enabled,
13334                                 int internal, unsigned flags)
13335 {
13336   create_breakpoints_sal (gdbarch, canonical, cond_string,
13337                           type_wanted, disposition,
13338                           thread, task, ignore_count, ops, from_tty,
13339                           enabled, internal, flags);
13340 }
13341
13342 /* Decode the line represented by S by calling decode_line_full.  This is the
13343    default function for the `decode_linespec' method of breakpoint_ops.  */
13344
13345 static void
13346 decode_linespec_default (struct breakpoint *b, char **s,
13347                          struct symtabs_and_lines *sals)
13348 {
13349   struct linespec_result canonical;
13350
13351   init_linespec_result (&canonical);
13352   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
13353                     (struct symtab *) NULL, 0,
13354                     &canonical, multiple_symbols_all,
13355                     b->filter);
13356
13357   /* We should get 0 or 1 resulting SALs.  */
13358   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
13359
13360   if (VEC_length (linespec_sals, canonical.sals) > 0)
13361     {
13362       struct linespec_sals *lsal;
13363
13364       lsal = VEC_index (linespec_sals, canonical.sals, 0);
13365       *sals = lsal->sals;
13366       /* Arrange it so the destructor does not free the
13367          contents.  */
13368       lsal->sals.sals = NULL;
13369     }
13370
13371   destroy_linespec_result (&canonical);
13372 }
13373
13374 /* Prepare the global context for a re-set of breakpoint B.  */
13375
13376 static struct cleanup *
13377 prepare_re_set_context (struct breakpoint *b)
13378 {
13379   struct cleanup *cleanups;
13380
13381   input_radix = b->input_radix;
13382   cleanups = save_current_space_and_thread ();
13383   if (b->pspace != NULL)
13384     switch_to_program_space_and_thread (b->pspace);
13385   set_language (b->language);
13386
13387   return cleanups;
13388 }
13389
13390 /* Reset a breakpoint given it's struct breakpoint * BINT.
13391    The value we return ends up being the return value from catch_errors.
13392    Unused in this case.  */
13393
13394 static int
13395 breakpoint_re_set_one (void *bint)
13396 {
13397   /* Get past catch_errs.  */
13398   struct breakpoint *b = (struct breakpoint *) bint;
13399   struct cleanup *cleanups;
13400
13401   cleanups = prepare_re_set_context (b);
13402   b->ops->re_set (b);
13403   do_cleanups (cleanups);
13404   return 0;
13405 }
13406
13407 /* Re-set all breakpoints after symbols have been re-loaded.  */
13408 void
13409 breakpoint_re_set (void)
13410 {
13411   struct breakpoint *b, *b_tmp;
13412   enum language save_language;
13413   int save_input_radix;
13414   struct cleanup *old_chain;
13415
13416   save_language = current_language->la_language;
13417   save_input_radix = input_radix;
13418   old_chain = save_current_program_space ();
13419
13420   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13421   {
13422     /* Format possible error msg.  */
13423     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
13424                                 b->number);
13425     struct cleanup *cleanups = make_cleanup (xfree, message);
13426     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
13427     do_cleanups (cleanups);
13428   }
13429   set_language (save_language);
13430   input_radix = save_input_radix;
13431
13432   jit_breakpoint_re_set ();
13433
13434   do_cleanups (old_chain);
13435
13436   create_overlay_event_breakpoint ();
13437   create_longjmp_master_breakpoint ();
13438   create_std_terminate_master_breakpoint ();
13439   create_exception_master_breakpoint ();
13440
13441   /* While we're at it, reset the skip list too.  */
13442   skip_re_set ();
13443 }
13444 \f
13445 /* Reset the thread number of this breakpoint:
13446
13447    - If the breakpoint is for all threads, leave it as-is.
13448    - Else, reset it to the current thread for inferior_ptid.  */
13449 void
13450 breakpoint_re_set_thread (struct breakpoint *b)
13451 {
13452   if (b->thread != -1)
13453     {
13454       if (in_thread_list (inferior_ptid))
13455         b->thread = pid_to_thread_id (inferior_ptid);
13456
13457       /* We're being called after following a fork.  The new fork is
13458          selected as current, and unless this was a vfork will have a
13459          different program space from the original thread.  Reset that
13460          as well.  */
13461       b->loc->pspace = current_program_space;
13462     }
13463 }
13464
13465 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13466    If from_tty is nonzero, it prints a message to that effect,
13467    which ends with a period (no newline).  */
13468
13469 void
13470 set_ignore_count (int bptnum, int count, int from_tty)
13471 {
13472   struct breakpoint *b;
13473
13474   if (count < 0)
13475     count = 0;
13476
13477   ALL_BREAKPOINTS (b)
13478     if (b->number == bptnum)
13479     {
13480       if (is_tracepoint (b))
13481         {
13482           if (from_tty && count != 0)
13483             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13484                              bptnum);
13485           return;
13486         }
13487       
13488       b->ignore_count = count;
13489       if (from_tty)
13490         {
13491           if (count == 0)
13492             printf_filtered (_("Will stop next time "
13493                                "breakpoint %d is reached."),
13494                              bptnum);
13495           else if (count == 1)
13496             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13497                              bptnum);
13498           else
13499             printf_filtered (_("Will ignore next %d "
13500                                "crossings of breakpoint %d."),
13501                              count, bptnum);
13502         }
13503       breakpoints_changed ();
13504       observer_notify_breakpoint_modified (b);
13505       return;
13506     }
13507
13508   error (_("No breakpoint number %d."), bptnum);
13509 }
13510
13511 /* Command to set ignore-count of breakpoint N to COUNT.  */
13512
13513 static void
13514 ignore_command (char *args, int from_tty)
13515 {
13516   char *p = args;
13517   int num;
13518
13519   if (p == 0)
13520     error_no_arg (_("a breakpoint number"));
13521
13522   num = get_number (&p);
13523   if (num == 0)
13524     error (_("bad breakpoint number: '%s'"), args);
13525   if (*p == 0)
13526     error (_("Second argument (specified ignore-count) is missing."));
13527
13528   set_ignore_count (num,
13529                     longest_to_int (value_as_long (parse_and_eval (p))),
13530                     from_tty);
13531   if (from_tty)
13532     printf_filtered ("\n");
13533 }
13534 \f
13535 /* Call FUNCTION on each of the breakpoints
13536    whose numbers are given in ARGS.  */
13537
13538 static void
13539 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
13540                                                       void *),
13541                         void *data)
13542 {
13543   int num;
13544   struct breakpoint *b, *tmp;
13545   int match;
13546   struct get_number_or_range_state state;
13547
13548   if (args == 0)
13549     error_no_arg (_("one or more breakpoint numbers"));
13550
13551   init_number_or_range (&state, args);
13552
13553   while (!state.finished)
13554     {
13555       char *p = state.string;
13556
13557       match = 0;
13558
13559       num = get_number_or_range (&state);
13560       if (num == 0)
13561         {
13562           warning (_("bad breakpoint number at or near '%s'"), p);
13563         }
13564       else
13565         {
13566           ALL_BREAKPOINTS_SAFE (b, tmp)
13567             if (b->number == num)
13568               {
13569                 match = 1;
13570                 function (b, data);
13571                 break;
13572               }
13573           if (match == 0)
13574             printf_unfiltered (_("No breakpoint number %d.\n"), num);
13575         }
13576     }
13577 }
13578
13579 static struct bp_location *
13580 find_location_by_number (char *number)
13581 {
13582   char *dot = strchr (number, '.');
13583   char *p1;
13584   int bp_num;
13585   int loc_num;
13586   struct breakpoint *b;
13587   struct bp_location *loc;  
13588
13589   *dot = '\0';
13590
13591   p1 = number;
13592   bp_num = get_number (&p1);
13593   if (bp_num == 0)
13594     error (_("Bad breakpoint number '%s'"), number);
13595
13596   ALL_BREAKPOINTS (b)
13597     if (b->number == bp_num)
13598       {
13599         break;
13600       }
13601
13602   if (!b || b->number != bp_num)
13603     error (_("Bad breakpoint number '%s'"), number);
13604   
13605   p1 = dot+1;
13606   loc_num = get_number (&p1);
13607   if (loc_num == 0)
13608     error (_("Bad breakpoint location number '%s'"), number);
13609
13610   --loc_num;
13611   loc = b->loc;
13612   for (;loc_num && loc; --loc_num, loc = loc->next)
13613     ;
13614   if (!loc)
13615     error (_("Bad breakpoint location number '%s'"), dot+1);
13616     
13617   return loc;  
13618 }
13619
13620
13621 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13622    If from_tty is nonzero, it prints a message to that effect,
13623    which ends with a period (no newline).  */
13624
13625 void
13626 disable_breakpoint (struct breakpoint *bpt)
13627 {
13628   /* Never disable a watchpoint scope breakpoint; we want to
13629      hit them when we leave scope so we can delete both the
13630      watchpoint and its scope breakpoint at that time.  */
13631   if (bpt->type == bp_watchpoint_scope)
13632     return;
13633
13634   /* You can't disable permanent breakpoints.  */
13635   if (bpt->enable_state == bp_permanent)
13636     return;
13637
13638   bpt->enable_state = bp_disabled;
13639
13640   /* Mark breakpoint locations modified.  */
13641   mark_breakpoint_modified (bpt);
13642
13643   if (target_supports_enable_disable_tracepoint ()
13644       && current_trace_status ()->running && is_tracepoint (bpt))
13645     {
13646       struct bp_location *location;
13647      
13648       for (location = bpt->loc; location; location = location->next)
13649         target_disable_tracepoint (location);
13650     }
13651
13652   update_global_location_list (0);
13653
13654   observer_notify_breakpoint_modified (bpt);
13655 }
13656
13657 /* A callback for iterate_over_related_breakpoints.  */
13658
13659 static void
13660 do_disable_breakpoint (struct breakpoint *b, void *ignore)
13661 {
13662   disable_breakpoint (b);
13663 }
13664
13665 /* A callback for map_breakpoint_numbers that calls
13666    disable_breakpoint.  */
13667
13668 static void
13669 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
13670 {
13671   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
13672 }
13673
13674 static void
13675 disable_command (char *args, int from_tty)
13676 {
13677   if (args == 0)
13678     {
13679       struct breakpoint *bpt;
13680
13681       ALL_BREAKPOINTS (bpt)
13682         if (user_breakpoint_p (bpt))
13683           disable_breakpoint (bpt);
13684     }
13685   else if (strchr (args, '.'))
13686     {
13687       struct bp_location *loc = find_location_by_number (args);
13688       if (loc)
13689         {
13690           if (loc->enabled)
13691             {
13692               loc->enabled = 0;
13693               mark_breakpoint_location_modified (loc);
13694             }
13695           if (target_supports_enable_disable_tracepoint ()
13696               && current_trace_status ()->running && loc->owner
13697               && is_tracepoint (loc->owner))
13698             target_disable_tracepoint (loc);
13699         }
13700       update_global_location_list (0);
13701     }
13702   else
13703     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
13704 }
13705
13706 static void
13707 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
13708                         int count)
13709 {
13710   int target_resources_ok;
13711
13712   if (bpt->type == bp_hardware_breakpoint)
13713     {
13714       int i;
13715       i = hw_breakpoint_used_count ();
13716       target_resources_ok = 
13717         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
13718                                             i + 1, 0);
13719       if (target_resources_ok == 0)
13720         error (_("No hardware breakpoint support in the target."));
13721       else if (target_resources_ok < 0)
13722         error (_("Hardware breakpoints used exceeds limit."));
13723     }
13724
13725   if (is_watchpoint (bpt))
13726     {
13727       /* Initialize it just to avoid a GCC false warning.  */
13728       enum enable_state orig_enable_state = 0;
13729       volatile struct gdb_exception e;
13730
13731       TRY_CATCH (e, RETURN_MASK_ALL)
13732         {
13733           struct watchpoint *w = (struct watchpoint *) bpt;
13734
13735           orig_enable_state = bpt->enable_state;
13736           bpt->enable_state = bp_enabled;
13737           update_watchpoint (w, 1 /* reparse */);
13738         }
13739       if (e.reason < 0)
13740         {
13741           bpt->enable_state = orig_enable_state;
13742           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
13743                              bpt->number);
13744           return;
13745         }
13746     }
13747
13748   if (bpt->enable_state != bp_permanent)
13749     bpt->enable_state = bp_enabled;
13750
13751   bpt->enable_state = bp_enabled;
13752
13753   /* Mark breakpoint locations modified.  */
13754   mark_breakpoint_modified (bpt);
13755
13756   if (target_supports_enable_disable_tracepoint ()
13757       && current_trace_status ()->running && is_tracepoint (bpt))
13758     {
13759       struct bp_location *location;
13760
13761       for (location = bpt->loc; location; location = location->next)
13762         target_enable_tracepoint (location);
13763     }
13764
13765   bpt->disposition = disposition;
13766   bpt->enable_count = count;
13767   update_global_location_list (1);
13768   breakpoints_changed ();
13769   
13770   observer_notify_breakpoint_modified (bpt);
13771 }
13772
13773
13774 void
13775 enable_breakpoint (struct breakpoint *bpt)
13776 {
13777   enable_breakpoint_disp (bpt, bpt->disposition, 0);
13778 }
13779
13780 static void
13781 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
13782 {
13783   enable_breakpoint (bpt);
13784 }
13785
13786 /* A callback for map_breakpoint_numbers that calls
13787    enable_breakpoint.  */
13788
13789 static void
13790 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
13791 {
13792   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
13793 }
13794
13795 /* The enable command enables the specified breakpoints (or all defined
13796    breakpoints) so they once again become (or continue to be) effective
13797    in stopping the inferior.  */
13798
13799 static void
13800 enable_command (char *args, int from_tty)
13801 {
13802   if (args == 0)
13803     {
13804       struct breakpoint *bpt;
13805
13806       ALL_BREAKPOINTS (bpt)
13807         if (user_breakpoint_p (bpt))
13808           enable_breakpoint (bpt);
13809     }
13810   else if (strchr (args, '.'))
13811     {
13812       struct bp_location *loc = find_location_by_number (args);
13813       if (loc)
13814         {
13815           if (!loc->enabled)
13816             {
13817               loc->enabled = 1;
13818               mark_breakpoint_location_modified (loc);
13819             }
13820           if (target_supports_enable_disable_tracepoint ()
13821               && current_trace_status ()->running && loc->owner
13822               && is_tracepoint (loc->owner))
13823             target_enable_tracepoint (loc);
13824         }
13825       update_global_location_list (1);
13826     }
13827   else
13828     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
13829 }
13830
13831 /* This struct packages up disposition data for application to multiple
13832    breakpoints.  */
13833
13834 struct disp_data
13835 {
13836   enum bpdisp disp;
13837   int count;
13838 };
13839
13840 static void
13841 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
13842 {
13843   struct disp_data disp_data = *(struct disp_data *) arg;
13844
13845   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
13846 }
13847
13848 static void
13849 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
13850 {
13851   struct disp_data disp = { disp_disable, 1 };
13852
13853   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13854 }
13855
13856 static void
13857 enable_once_command (char *args, int from_tty)
13858 {
13859   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
13860 }
13861
13862 static void
13863 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
13864 {
13865   struct disp_data disp = { disp_disable, *(int *) countptr };
13866
13867   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13868 }
13869
13870 static void
13871 enable_count_command (char *args, int from_tty)
13872 {
13873   int count = get_number (&args);
13874
13875   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
13876 }
13877
13878 static void
13879 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
13880 {
13881   struct disp_data disp = { disp_del, 1 };
13882
13883   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
13884 }
13885
13886 static void
13887 enable_delete_command (char *args, int from_tty)
13888 {
13889   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
13890 }
13891 \f
13892 static void
13893 set_breakpoint_cmd (char *args, int from_tty)
13894 {
13895 }
13896
13897 static void
13898 show_breakpoint_cmd (char *args, int from_tty)
13899 {
13900 }
13901
13902 /* Invalidate last known value of any hardware watchpoint if
13903    the memory which that value represents has been written to by
13904    GDB itself.  */
13905
13906 static void
13907 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
13908                                       const bfd_byte *data)
13909 {
13910   struct breakpoint *bp;
13911
13912   ALL_BREAKPOINTS (bp)
13913     if (bp->enable_state == bp_enabled
13914         && bp->type == bp_hardware_watchpoint)
13915       {
13916         struct watchpoint *wp = (struct watchpoint *) bp;
13917
13918         if (wp->val_valid && wp->val)
13919           {
13920             struct bp_location *loc;
13921
13922             for (loc = bp->loc; loc != NULL; loc = loc->next)
13923               if (loc->loc_type == bp_loc_hardware_watchpoint
13924                   && loc->address + loc->length > addr
13925                   && addr + len > loc->address)
13926                 {
13927                   value_free (wp->val);
13928                   wp->val = NULL;
13929                   wp->val_valid = 0;
13930                 }
13931           }
13932       }
13933 }
13934
13935 /* Use the last displayed codepoint's values, or nothing
13936    if they aren't valid.  */
13937
13938 struct symtabs_and_lines
13939 decode_line_spec_1 (char *string, int flags)
13940 {
13941   struct symtabs_and_lines sals;
13942
13943   if (string == 0)
13944     error (_("Empty line specification."));
13945   if (last_displayed_sal_is_valid ())
13946     sals = decode_line_1 (&string, flags,
13947                           get_last_displayed_symtab (),
13948                           get_last_displayed_line ());
13949   else
13950     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
13951   if (*string)
13952     error (_("Junk at end of line specification: %s"), string);
13953   return sals;
13954 }
13955
13956 /* Create and insert a raw software breakpoint at PC.  Return an
13957    identifier, which should be used to remove the breakpoint later.
13958    In general, places which call this should be using something on the
13959    breakpoint chain instead; this function should be eliminated
13960    someday.  */
13961
13962 void *
13963 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
13964                                   struct address_space *aspace, CORE_ADDR pc)
13965 {
13966   struct bp_target_info *bp_tgt;
13967
13968   bp_tgt = XZALLOC (struct bp_target_info);
13969
13970   bp_tgt->placed_address_space = aspace;
13971   bp_tgt->placed_address = pc;
13972
13973   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
13974     {
13975       /* Could not insert the breakpoint.  */
13976       xfree (bp_tgt);
13977       return NULL;
13978     }
13979
13980   return bp_tgt;
13981 }
13982
13983 /* Remove a breakpoint BP inserted by
13984    deprecated_insert_raw_breakpoint.  */
13985
13986 int
13987 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
13988 {
13989   struct bp_target_info *bp_tgt = bp;
13990   int ret;
13991
13992   ret = target_remove_breakpoint (gdbarch, bp_tgt);
13993   xfree (bp_tgt);
13994
13995   return ret;
13996 }
13997
13998 /* One (or perhaps two) breakpoints used for software single
13999    stepping.  */
14000
14001 static void *single_step_breakpoints[2];
14002 static struct gdbarch *single_step_gdbarch[2];
14003
14004 /* Create and insert a breakpoint for software single step.  */
14005
14006 void
14007 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14008                                struct address_space *aspace, 
14009                                CORE_ADDR next_pc)
14010 {
14011   void **bpt_p;
14012
14013   if (single_step_breakpoints[0] == NULL)
14014     {
14015       bpt_p = &single_step_breakpoints[0];
14016       single_step_gdbarch[0] = gdbarch;
14017     }
14018   else
14019     {
14020       gdb_assert (single_step_breakpoints[1] == NULL);
14021       bpt_p = &single_step_breakpoints[1];
14022       single_step_gdbarch[1] = gdbarch;
14023     }
14024
14025   /* NOTE drow/2006-04-11: A future improvement to this function would
14026      be to only create the breakpoints once, and actually put them on
14027      the breakpoint chain.  That would let us use set_raw_breakpoint.
14028      We could adjust the addresses each time they were needed.  Doing
14029      this requires corresponding changes elsewhere where single step
14030      breakpoints are handled, however.  So, for now, we use this.  */
14031
14032   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14033   if (*bpt_p == NULL)
14034     error (_("Could not insert single-step breakpoint at %s"),
14035              paddress (gdbarch, next_pc));
14036 }
14037
14038 /* Check if the breakpoints used for software single stepping
14039    were inserted or not.  */
14040
14041 int
14042 single_step_breakpoints_inserted (void)
14043 {
14044   return (single_step_breakpoints[0] != NULL
14045           || single_step_breakpoints[1] != NULL);
14046 }
14047
14048 /* Remove and delete any breakpoints used for software single step.  */
14049
14050 void
14051 remove_single_step_breakpoints (void)
14052 {
14053   gdb_assert (single_step_breakpoints[0] != NULL);
14054
14055   /* See insert_single_step_breakpoint for more about this deprecated
14056      call.  */
14057   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14058                                     single_step_breakpoints[0]);
14059   single_step_gdbarch[0] = NULL;
14060   single_step_breakpoints[0] = NULL;
14061
14062   if (single_step_breakpoints[1] != NULL)
14063     {
14064       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14065                                         single_step_breakpoints[1]);
14066       single_step_gdbarch[1] = NULL;
14067       single_step_breakpoints[1] = NULL;
14068     }
14069 }
14070
14071 /* Delete software single step breakpoints without removing them from
14072    the inferior.  This is intended to be used if the inferior's address
14073    space where they were inserted is already gone, e.g. after exit or
14074    exec.  */
14075
14076 void
14077 cancel_single_step_breakpoints (void)
14078 {
14079   int i;
14080
14081   for (i = 0; i < 2; i++)
14082     if (single_step_breakpoints[i])
14083       {
14084         xfree (single_step_breakpoints[i]);
14085         single_step_breakpoints[i] = NULL;
14086         single_step_gdbarch[i] = NULL;
14087       }
14088 }
14089
14090 /* Detach software single-step breakpoints from INFERIOR_PTID without
14091    removing them.  */
14092
14093 static void
14094 detach_single_step_breakpoints (void)
14095 {
14096   int i;
14097
14098   for (i = 0; i < 2; i++)
14099     if (single_step_breakpoints[i])
14100       target_remove_breakpoint (single_step_gdbarch[i],
14101                                 single_step_breakpoints[i]);
14102 }
14103
14104 /* Check whether a software single-step breakpoint is inserted at
14105    PC.  */
14106
14107 static int
14108 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
14109                                         CORE_ADDR pc)
14110 {
14111   int i;
14112
14113   for (i = 0; i < 2; i++)
14114     {
14115       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
14116       if (bp_tgt
14117           && breakpoint_address_match (bp_tgt->placed_address_space,
14118                                        bp_tgt->placed_address,
14119                                        aspace, pc))
14120         return 1;
14121     }
14122
14123   return 0;
14124 }
14125
14126 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
14127    non-zero otherwise.  */
14128 static int
14129 is_syscall_catchpoint_enabled (struct breakpoint *bp)
14130 {
14131   if (syscall_catchpoint_p (bp)
14132       && bp->enable_state != bp_disabled
14133       && bp->enable_state != bp_call_disabled)
14134     return 1;
14135   else
14136     return 0;
14137 }
14138
14139 int
14140 catch_syscall_enabled (void)
14141 {
14142   struct catch_syscall_inferior_data *inf_data
14143     = get_catch_syscall_inferior_data (current_inferior ());
14144
14145   return inf_data->total_syscalls_count != 0;
14146 }
14147
14148 int
14149 catching_syscall_number (int syscall_number)
14150 {
14151   struct breakpoint *bp;
14152
14153   ALL_BREAKPOINTS (bp)
14154     if (is_syscall_catchpoint_enabled (bp))
14155       {
14156         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
14157
14158         if (c->syscalls_to_be_caught)
14159           {
14160             int i, iter;
14161             for (i = 0;
14162                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
14163                  i++)
14164               if (syscall_number == iter)
14165                 return 1;
14166           }
14167         else
14168           return 1;
14169       }
14170
14171   return 0;
14172 }
14173
14174 /* Complete syscall names.  Used by "catch syscall".  */
14175 static char **
14176 catch_syscall_completer (struct cmd_list_element *cmd,
14177                          char *text, char *word)
14178 {
14179   const char **list = get_syscall_names ();
14180   char **retlist
14181     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
14182
14183   xfree (list);
14184   return retlist;
14185 }
14186
14187 /* Tracepoint-specific operations.  */
14188
14189 /* Set tracepoint count to NUM.  */
14190 static void
14191 set_tracepoint_count (int num)
14192 {
14193   tracepoint_count = num;
14194   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14195 }
14196
14197 static void
14198 trace_command (char *arg, int from_tty)
14199 {
14200   if (create_breakpoint (get_current_arch (),
14201                          arg,
14202                          NULL, 0, 1 /* parse arg */,
14203                          0 /* tempflag */,
14204                          bp_tracepoint /* type_wanted */,
14205                          0 /* Ignore count */,
14206                          pending_break_support,
14207                          &tracepoint_breakpoint_ops,
14208                          from_tty,
14209                          1 /* enabled */,
14210                          0 /* internal */, 0))
14211     set_tracepoint_count (breakpoint_count);
14212 }
14213
14214 static void
14215 ftrace_command (char *arg, int from_tty)
14216 {
14217   if (create_breakpoint (get_current_arch (),
14218                          arg,
14219                          NULL, 0, 1 /* parse arg */,
14220                          0 /* tempflag */,
14221                          bp_fast_tracepoint /* type_wanted */,
14222                          0 /* Ignore count */,
14223                          pending_break_support,
14224                          &tracepoint_breakpoint_ops,
14225                          from_tty,
14226                          1 /* enabled */,
14227                          0 /* internal */, 0))
14228     set_tracepoint_count (breakpoint_count);
14229 }
14230
14231 /* strace command implementation.  Creates a static tracepoint.  */
14232
14233 static void
14234 strace_command (char *arg, int from_tty)
14235 {
14236   struct breakpoint_ops *ops;
14237
14238   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14239      or with a normal static tracepoint.  */
14240   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
14241     ops = &strace_marker_breakpoint_ops;
14242   else
14243     ops = &tracepoint_breakpoint_ops;
14244
14245   if (create_breakpoint (get_current_arch (),
14246                          arg,
14247                          NULL, 0, 1 /* parse arg */,
14248                          0 /* tempflag */,
14249                          bp_static_tracepoint /* type_wanted */,
14250                          0 /* Ignore count */,
14251                          pending_break_support,
14252                          ops,
14253                          from_tty,
14254                          1 /* enabled */,
14255                          0 /* internal */, 0))
14256     set_tracepoint_count (breakpoint_count);
14257 }
14258
14259 /* Set up a fake reader function that gets command lines from a linked
14260    list that was acquired during tracepoint uploading.  */
14261
14262 static struct uploaded_tp *this_utp;
14263 static int next_cmd;
14264
14265 static char *
14266 read_uploaded_action (void)
14267 {
14268   char *rslt;
14269
14270   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14271
14272   next_cmd++;
14273
14274   return rslt;
14275 }
14276
14277 /* Given information about a tracepoint as recorded on a target (which
14278    can be either a live system or a trace file), attempt to create an
14279    equivalent GDB tracepoint.  This is not a reliable process, since
14280    the target does not necessarily have all the information used when
14281    the tracepoint was originally defined.  */
14282   
14283 struct tracepoint *
14284 create_tracepoint_from_upload (struct uploaded_tp *utp)
14285 {
14286   char *addr_str, small_buf[100];
14287   struct tracepoint *tp;
14288
14289   if (utp->at_string)
14290     addr_str = utp->at_string;
14291   else
14292     {
14293       /* In the absence of a source location, fall back to raw
14294          address.  Since there is no way to confirm that the address
14295          means the same thing as when the trace was started, warn the
14296          user.  */
14297       warning (_("Uploaded tracepoint %d has no "
14298                  "source location, using raw address"),
14299                utp->number);
14300       sprintf (small_buf, "*%s", hex_string (utp->addr));
14301       addr_str = small_buf;
14302     }
14303
14304   /* There's not much we can do with a sequence of bytecodes.  */
14305   if (utp->cond && !utp->cond_string)
14306     warning (_("Uploaded tracepoint %d condition "
14307                "has no source form, ignoring it"),
14308              utp->number);
14309
14310   if (!create_breakpoint (get_current_arch (),
14311                           addr_str,
14312                           utp->cond_string, -1, 0 /* parse cond/thread */,
14313                           0 /* tempflag */,
14314                           utp->type /* type_wanted */,
14315                           0 /* Ignore count */,
14316                           pending_break_support,
14317                           &tracepoint_breakpoint_ops,
14318                           0 /* from_tty */,
14319                           utp->enabled /* enabled */,
14320                           0 /* internal */,
14321                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14322     return NULL;
14323
14324   set_tracepoint_count (breakpoint_count);
14325   
14326   /* Get the tracepoint we just created.  */
14327   tp = get_tracepoint (tracepoint_count);
14328   gdb_assert (tp != NULL);
14329
14330   if (utp->pass > 0)
14331     {
14332       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
14333
14334       trace_pass_command (small_buf, 0);
14335     }
14336
14337   /* If we have uploaded versions of the original commands, set up a
14338      special-purpose "reader" function and call the usual command line
14339      reader, then pass the result to the breakpoint command-setting
14340      function.  */
14341   if (!VEC_empty (char_ptr, utp->cmd_strings))
14342     {
14343       struct command_line *cmd_list;
14344
14345       this_utp = utp;
14346       next_cmd = 0;
14347
14348       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14349
14350       breakpoint_set_commands (&tp->base, cmd_list);
14351     }
14352   else if (!VEC_empty (char_ptr, utp->actions)
14353            || !VEC_empty (char_ptr, utp->step_actions))
14354     warning (_("Uploaded tracepoint %d actions "
14355                "have no source form, ignoring them"),
14356              utp->number);
14357
14358   /* Copy any status information that might be available.  */
14359   tp->base.hit_count = utp->hit_count;
14360   tp->traceframe_usage = utp->traceframe_usage;
14361
14362   return tp;
14363 }
14364   
14365 /* Print information on tracepoint number TPNUM_EXP, or all if
14366    omitted.  */
14367
14368 static void
14369 tracepoints_info (char *args, int from_tty)
14370 {
14371   struct ui_out *uiout = current_uiout;
14372   int num_printed;
14373
14374   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14375
14376   if (num_printed == 0)
14377     {
14378       if (args == NULL || *args == '\0')
14379         ui_out_message (uiout, 0, "No tracepoints.\n");
14380       else
14381         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
14382     }
14383
14384   default_collect_info ();
14385 }
14386
14387 /* The 'enable trace' command enables tracepoints.
14388    Not supported by all targets.  */
14389 static void
14390 enable_trace_command (char *args, int from_tty)
14391 {
14392   enable_command (args, from_tty);
14393 }
14394
14395 /* The 'disable trace' command disables tracepoints.
14396    Not supported by all targets.  */
14397 static void
14398 disable_trace_command (char *args, int from_tty)
14399 {
14400   disable_command (args, from_tty);
14401 }
14402
14403 /* Remove a tracepoint (or all if no argument).  */
14404 static void
14405 delete_trace_command (char *arg, int from_tty)
14406 {
14407   struct breakpoint *b, *b_tmp;
14408
14409   dont_repeat ();
14410
14411   if (arg == 0)
14412     {
14413       int breaks_to_delete = 0;
14414
14415       /* Delete all breakpoints if no argument.
14416          Do not delete internal or call-dummy breakpoints, these
14417          have to be deleted with an explicit breakpoint number 
14418          argument.  */
14419       ALL_TRACEPOINTS (b)
14420         if (is_tracepoint (b) && user_breakpoint_p (b))
14421           {
14422             breaks_to_delete = 1;
14423             break;
14424           }
14425
14426       /* Ask user only if there are some breakpoints to delete.  */
14427       if (!from_tty
14428           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14429         {
14430           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14431             if (is_tracepoint (b) && user_breakpoint_p (b))
14432               delete_breakpoint (b);
14433         }
14434     }
14435   else
14436     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14437 }
14438
14439 /* Helper function for trace_pass_command.  */
14440
14441 static void
14442 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14443 {
14444   tp->pass_count = count;
14445   observer_notify_tracepoint_modified (tp->base.number);
14446   if (from_tty)
14447     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14448                      tp->base.number, count);
14449 }
14450
14451 /* Set passcount for tracepoint.
14452
14453    First command argument is passcount, second is tracepoint number.
14454    If tracepoint number omitted, apply to most recently defined.
14455    Also accepts special argument "all".  */
14456
14457 static void
14458 trace_pass_command (char *args, int from_tty)
14459 {
14460   struct tracepoint *t1;
14461   unsigned int count;
14462
14463   if (args == 0 || *args == 0)
14464     error (_("passcount command requires an "
14465              "argument (count + optional TP num)"));
14466
14467   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
14468
14469   while (*args && isspace ((int) *args))
14470     args++;
14471
14472   if (*args && strncasecmp (args, "all", 3) == 0)
14473     {
14474       struct breakpoint *b;
14475
14476       args += 3;                        /* Skip special argument "all".  */
14477       if (*args)
14478         error (_("Junk at end of arguments."));
14479
14480       ALL_TRACEPOINTS (b)
14481       {
14482         t1 = (struct tracepoint *) b;
14483         trace_pass_set_count (t1, count, from_tty);
14484       }
14485     }
14486   else if (*args == '\0')
14487     {
14488       t1 = get_tracepoint_by_number (&args, NULL, 1);
14489       if (t1)
14490         trace_pass_set_count (t1, count, from_tty);
14491     }
14492   else
14493     {
14494       struct get_number_or_range_state state;
14495
14496       init_number_or_range (&state, args);
14497       while (!state.finished)
14498         {
14499           t1 = get_tracepoint_by_number (&args, &state, 1);
14500           if (t1)
14501             trace_pass_set_count (t1, count, from_tty);
14502         }
14503     }
14504 }
14505
14506 struct tracepoint *
14507 get_tracepoint (int num)
14508 {
14509   struct breakpoint *t;
14510
14511   ALL_TRACEPOINTS (t)
14512     if (t->number == num)
14513       return (struct tracepoint *) t;
14514
14515   return NULL;
14516 }
14517
14518 /* Find the tracepoint with the given target-side number (which may be
14519    different from the tracepoint number after disconnecting and
14520    reconnecting).  */
14521
14522 struct tracepoint *
14523 get_tracepoint_by_number_on_target (int num)
14524 {
14525   struct breakpoint *b;
14526
14527   ALL_TRACEPOINTS (b)
14528     {
14529       struct tracepoint *t = (struct tracepoint *) b;
14530
14531       if (t->number_on_target == num)
14532         return t;
14533     }
14534
14535   return NULL;
14536 }
14537
14538 /* Utility: parse a tracepoint number and look it up in the list.
14539    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14540    If OPTIONAL_P is true, then if the argument is missing, the most
14541    recent tracepoint (tracepoint_count) is returned.  */
14542 struct tracepoint *
14543 get_tracepoint_by_number (char **arg,
14544                           struct get_number_or_range_state *state,
14545                           int optional_p)
14546 {
14547   extern int tracepoint_count;
14548   struct breakpoint *t;
14549   int tpnum;
14550   char *instring = arg == NULL ? NULL : *arg;
14551
14552   if (state)
14553     {
14554       gdb_assert (!state->finished);
14555       tpnum = get_number_or_range (state);
14556     }
14557   else if (arg == NULL || *arg == NULL || ! **arg)
14558     {
14559       if (optional_p)
14560         tpnum = tracepoint_count;
14561       else
14562         error_no_arg (_("tracepoint number"));
14563     }
14564   else
14565     tpnum = get_number (arg);
14566
14567   if (tpnum <= 0)
14568     {
14569       if (instring && *instring)
14570         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14571                          instring);
14572       else
14573         printf_filtered (_("Tracepoint argument missing "
14574                            "and no previous tracepoint\n"));
14575       return NULL;
14576     }
14577
14578   ALL_TRACEPOINTS (t)
14579     if (t->number == tpnum)
14580     {
14581       return (struct tracepoint *) t;
14582     }
14583
14584   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14585   return NULL;
14586 }
14587
14588 void
14589 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14590 {
14591   if (b->thread != -1)
14592     fprintf_unfiltered (fp, " thread %d", b->thread);
14593
14594   if (b->task != 0)
14595     fprintf_unfiltered (fp, " task %d", b->task);
14596
14597   fprintf_unfiltered (fp, "\n");
14598 }
14599
14600 /* Save information on user settable breakpoints (watchpoints, etc) to
14601    a new script file named FILENAME.  If FILTER is non-NULL, call it
14602    on each breakpoint and only include the ones for which it returns
14603    non-zero.  */
14604
14605 static void
14606 save_breakpoints (char *filename, int from_tty,
14607                   int (*filter) (const struct breakpoint *))
14608 {
14609   struct breakpoint *tp;
14610   int any = 0;
14611   char *pathname;
14612   struct cleanup *cleanup;
14613   struct ui_file *fp;
14614   int extra_trace_bits = 0;
14615
14616   if (filename == 0 || *filename == 0)
14617     error (_("Argument required (file name in which to save)"));
14618
14619   /* See if we have anything to save.  */
14620   ALL_BREAKPOINTS (tp)
14621   {
14622     /* Skip internal and momentary breakpoints.  */
14623     if (!user_breakpoint_p (tp))
14624       continue;
14625
14626     /* If we have a filter, only save the breakpoints it accepts.  */
14627     if (filter && !filter (tp))
14628       continue;
14629
14630     any = 1;
14631
14632     if (is_tracepoint (tp))
14633       {
14634         extra_trace_bits = 1;
14635
14636         /* We can stop searching.  */
14637         break;
14638       }
14639   }
14640
14641   if (!any)
14642     {
14643       warning (_("Nothing to save."));
14644       return;
14645     }
14646
14647   pathname = tilde_expand (filename);
14648   cleanup = make_cleanup (xfree, pathname);
14649   fp = gdb_fopen (pathname, "w");
14650   if (!fp)
14651     error (_("Unable to open file '%s' for saving (%s)"),
14652            filename, safe_strerror (errno));
14653   make_cleanup_ui_file_delete (fp);
14654
14655   if (extra_trace_bits)
14656     save_trace_state_variables (fp);
14657
14658   ALL_BREAKPOINTS (tp)
14659   {
14660     /* Skip internal and momentary breakpoints.  */
14661     if (!user_breakpoint_p (tp))
14662       continue;
14663
14664     /* If we have a filter, only save the breakpoints it accepts.  */
14665     if (filter && !filter (tp))
14666       continue;
14667
14668     tp->ops->print_recreate (tp, fp);
14669
14670     /* Note, we can't rely on tp->number for anything, as we can't
14671        assume the recreated breakpoint numbers will match.  Use $bpnum
14672        instead.  */
14673
14674     if (tp->cond_string)
14675       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
14676
14677     if (tp->ignore_count)
14678       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
14679
14680     if (tp->commands)
14681       {
14682         volatile struct gdb_exception ex;       
14683
14684         fprintf_unfiltered (fp, "  commands\n");
14685         
14686         ui_out_redirect (current_uiout, fp);
14687         TRY_CATCH (ex, RETURN_MASK_ALL)
14688           {
14689             print_command_lines (current_uiout, tp->commands->commands, 2);
14690           }
14691         ui_out_redirect (current_uiout, NULL);
14692
14693         if (ex.reason < 0)
14694           throw_exception (ex);
14695
14696         fprintf_unfiltered (fp, "  end\n");
14697       }
14698
14699     if (tp->enable_state == bp_disabled)
14700       fprintf_unfiltered (fp, "disable\n");
14701
14702     /* If this is a multi-location breakpoint, check if the locations
14703        should be individually disabled.  Watchpoint locations are
14704        special, and not user visible.  */
14705     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
14706       {
14707         struct bp_location *loc;
14708         int n = 1;
14709
14710         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
14711           if (!loc->enabled)
14712             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
14713       }
14714   }
14715
14716   if (extra_trace_bits && *default_collect)
14717     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
14718
14719   do_cleanups (cleanup);
14720   if (from_tty)
14721     printf_filtered (_("Saved to file '%s'.\n"), filename);
14722 }
14723
14724 /* The `save breakpoints' command.  */
14725
14726 static void
14727 save_breakpoints_command (char *args, int from_tty)
14728 {
14729   save_breakpoints (args, from_tty, NULL);
14730 }
14731
14732 /* The `save tracepoints' command.  */
14733
14734 static void
14735 save_tracepoints_command (char *args, int from_tty)
14736 {
14737   save_breakpoints (args, from_tty, is_tracepoint);
14738 }
14739
14740 /* Create a vector of all tracepoints.  */
14741
14742 VEC(breakpoint_p) *
14743 all_tracepoints (void)
14744 {
14745   VEC(breakpoint_p) *tp_vec = 0;
14746   struct breakpoint *tp;
14747
14748   ALL_TRACEPOINTS (tp)
14749   {
14750     VEC_safe_push (breakpoint_p, tp_vec, tp);
14751   }
14752
14753   return tp_vec;
14754 }
14755
14756 \f
14757 /* This help string is used for the break, hbreak, tbreak and thbreak
14758    commands.  It is defined as a macro to prevent duplication.
14759    COMMAND should be a string constant containing the name of the
14760    command.  */
14761 #define BREAK_ARGS_HELP(command) \
14762 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
14763 LOCATION may be a line number, function name, or \"*\" and an address.\n\
14764 If a line number is specified, break at start of code for that line.\n\
14765 If a function is specified, break at start of code for that function.\n\
14766 If an address is specified, break at that exact address.\n\
14767 With no LOCATION, uses current execution address of the selected\n\
14768 stack frame.  This is useful for breaking on return to a stack frame.\n\
14769 \n\
14770 THREADNUM is the number from \"info threads\".\n\
14771 CONDITION is a boolean expression.\n\
14772 \n\
14773 Multiple breakpoints at one place are permitted, and useful if their\n\
14774 conditions are different.\n\
14775 \n\
14776 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
14777
14778 /* List of subcommands for "catch".  */
14779 static struct cmd_list_element *catch_cmdlist;
14780
14781 /* List of subcommands for "tcatch".  */
14782 static struct cmd_list_element *tcatch_cmdlist;
14783
14784 void
14785 add_catch_command (char *name, char *docstring,
14786                    void (*sfunc) (char *args, int from_tty,
14787                                   struct cmd_list_element *command),
14788                    char **(*completer) (struct cmd_list_element *cmd,
14789                                          char *text, char *word),
14790                    void *user_data_catch,
14791                    void *user_data_tcatch)
14792 {
14793   struct cmd_list_element *command;
14794
14795   command = add_cmd (name, class_breakpoint, NULL, docstring,
14796                      &catch_cmdlist);
14797   set_cmd_sfunc (command, sfunc);
14798   set_cmd_context (command, user_data_catch);
14799   set_cmd_completer (command, completer);
14800
14801   command = add_cmd (name, class_breakpoint, NULL, docstring,
14802                      &tcatch_cmdlist);
14803   set_cmd_sfunc (command, sfunc);
14804   set_cmd_context (command, user_data_tcatch);
14805   set_cmd_completer (command, completer);
14806 }
14807
14808 static void
14809 clear_syscall_counts (struct inferior *inf)
14810 {
14811   struct catch_syscall_inferior_data *inf_data
14812     = get_catch_syscall_inferior_data (inf);
14813
14814   inf_data->total_syscalls_count = 0;
14815   inf_data->any_syscall_count = 0;
14816   VEC_free (int, inf_data->syscalls_counts);
14817 }
14818
14819 static void
14820 save_command (char *arg, int from_tty)
14821 {
14822   printf_unfiltered (_("\"save\" must be followed by "
14823                        "the name of a save subcommand.\n"));
14824   help_list (save_cmdlist, "save ", -1, gdb_stdout);
14825 }
14826
14827 struct breakpoint *
14828 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
14829                           void *data)
14830 {
14831   struct breakpoint *b, *b_tmp;
14832
14833   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14834     {
14835       if ((*callback) (b, data))
14836         return b;
14837     }
14838
14839   return NULL;
14840 }
14841
14842 /* Zero if any of the breakpoint's locations could be a location where
14843    functions have been inlined, nonzero otherwise.  */
14844
14845 static int
14846 is_non_inline_function (struct breakpoint *b)
14847 {
14848   /* The shared library event breakpoint is set on the address of a
14849      non-inline function.  */
14850   if (b->type == bp_shlib_event)
14851     return 1;
14852
14853   return 0;
14854 }
14855
14856 /* Nonzero if the specified PC cannot be a location where functions
14857    have been inlined.  */
14858
14859 int
14860 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
14861                            const struct target_waitstatus *ws)
14862 {
14863   struct breakpoint *b;
14864   struct bp_location *bl;
14865
14866   ALL_BREAKPOINTS (b)
14867     {
14868       if (!is_non_inline_function (b))
14869         continue;
14870
14871       for (bl = b->loc; bl != NULL; bl = bl->next)
14872         {
14873           if (!bl->shlib_disabled
14874               && bpstat_check_location (bl, aspace, pc, ws))
14875             return 1;
14876         }
14877     }
14878
14879   return 0;
14880 }
14881
14882 void
14883 initialize_breakpoint_ops (void)
14884 {
14885   static int initialized = 0;
14886
14887   struct breakpoint_ops *ops;
14888
14889   if (initialized)
14890     return;
14891   initialized = 1;
14892
14893   /* The breakpoint_ops structure to be inherit by all kinds of
14894      breakpoints (real breakpoints, i.e., user "break" breakpoints,
14895      internal and momentary breakpoints, etc.).  */
14896   ops = &bkpt_base_breakpoint_ops;
14897   *ops = base_breakpoint_ops;
14898   ops->re_set = bkpt_re_set;
14899   ops->insert_location = bkpt_insert_location;
14900   ops->remove_location = bkpt_remove_location;
14901   ops->breakpoint_hit = bkpt_breakpoint_hit;
14902   ops->create_sals_from_address = bkpt_create_sals_from_address;
14903   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
14904   ops->decode_linespec = bkpt_decode_linespec;
14905
14906   /* The breakpoint_ops structure to be used in regular breakpoints.  */
14907   ops = &bkpt_breakpoint_ops;
14908   *ops = bkpt_base_breakpoint_ops;
14909   ops->re_set = bkpt_re_set;
14910   ops->resources_needed = bkpt_resources_needed;
14911   ops->print_it = bkpt_print_it;
14912   ops->print_mention = bkpt_print_mention;
14913   ops->print_recreate = bkpt_print_recreate;
14914
14915   /* Ranged breakpoints.  */
14916   ops = &ranged_breakpoint_ops;
14917   *ops = bkpt_breakpoint_ops;
14918   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
14919   ops->resources_needed = resources_needed_ranged_breakpoint;
14920   ops->print_it = print_it_ranged_breakpoint;
14921   ops->print_one = print_one_ranged_breakpoint;
14922   ops->print_one_detail = print_one_detail_ranged_breakpoint;
14923   ops->print_mention = print_mention_ranged_breakpoint;
14924   ops->print_recreate = print_recreate_ranged_breakpoint;
14925
14926   /* Internal breakpoints.  */
14927   ops = &internal_breakpoint_ops;
14928   *ops = bkpt_base_breakpoint_ops;
14929   ops->re_set = internal_bkpt_re_set;
14930   ops->check_status = internal_bkpt_check_status;
14931   ops->print_it = internal_bkpt_print_it;
14932   ops->print_mention = internal_bkpt_print_mention;
14933
14934   /* Momentary breakpoints.  */
14935   ops = &momentary_breakpoint_ops;
14936   *ops = bkpt_base_breakpoint_ops;
14937   ops->re_set = momentary_bkpt_re_set;
14938   ops->check_status = momentary_bkpt_check_status;
14939   ops->print_it = momentary_bkpt_print_it;
14940   ops->print_mention = momentary_bkpt_print_mention;
14941
14942   /* GNU v3 exception catchpoints.  */
14943   ops = &gnu_v3_exception_catchpoint_ops;
14944   *ops = bkpt_breakpoint_ops;
14945   ops->print_it = print_it_exception_catchpoint;
14946   ops->print_one = print_one_exception_catchpoint;
14947   ops->print_mention = print_mention_exception_catchpoint;
14948   ops->print_recreate = print_recreate_exception_catchpoint;
14949
14950   /* Watchpoints.  */
14951   ops = &watchpoint_breakpoint_ops;
14952   *ops = base_breakpoint_ops;
14953   ops->dtor = dtor_watchpoint;
14954   ops->re_set = re_set_watchpoint;
14955   ops->insert_location = insert_watchpoint;
14956   ops->remove_location = remove_watchpoint;
14957   ops->breakpoint_hit = breakpoint_hit_watchpoint;
14958   ops->check_status = check_status_watchpoint;
14959   ops->resources_needed = resources_needed_watchpoint;
14960   ops->works_in_software_mode = works_in_software_mode_watchpoint;
14961   ops->print_it = print_it_watchpoint;
14962   ops->print_mention = print_mention_watchpoint;
14963   ops->print_recreate = print_recreate_watchpoint;
14964
14965   /* Masked watchpoints.  */
14966   ops = &masked_watchpoint_breakpoint_ops;
14967   *ops = watchpoint_breakpoint_ops;
14968   ops->insert_location = insert_masked_watchpoint;
14969   ops->remove_location = remove_masked_watchpoint;
14970   ops->resources_needed = resources_needed_masked_watchpoint;
14971   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
14972   ops->print_it = print_it_masked_watchpoint;
14973   ops->print_one_detail = print_one_detail_masked_watchpoint;
14974   ops->print_mention = print_mention_masked_watchpoint;
14975   ops->print_recreate = print_recreate_masked_watchpoint;
14976
14977   /* Tracepoints.  */
14978   ops = &tracepoint_breakpoint_ops;
14979   *ops = base_breakpoint_ops;
14980   ops->re_set = tracepoint_re_set;
14981   ops->breakpoint_hit = tracepoint_breakpoint_hit;
14982   ops->print_one_detail = tracepoint_print_one_detail;
14983   ops->print_mention = tracepoint_print_mention;
14984   ops->print_recreate = tracepoint_print_recreate;
14985   ops->create_sals_from_address = tracepoint_create_sals_from_address;
14986   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
14987   ops->decode_linespec = tracepoint_decode_linespec;
14988
14989   /* Static tracepoints with marker (`-m').  */
14990   ops = &strace_marker_breakpoint_ops;
14991   *ops = tracepoint_breakpoint_ops;
14992   ops->create_sals_from_address = strace_marker_create_sals_from_address;
14993   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
14994   ops->decode_linespec = strace_marker_decode_linespec;
14995
14996   /* Fork catchpoints.  */
14997   ops = &catch_fork_breakpoint_ops;
14998   *ops = base_breakpoint_ops;
14999   ops->insert_location = insert_catch_fork;
15000   ops->remove_location = remove_catch_fork;
15001   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15002   ops->print_it = print_it_catch_fork;
15003   ops->print_one = print_one_catch_fork;
15004   ops->print_mention = print_mention_catch_fork;
15005   ops->print_recreate = print_recreate_catch_fork;
15006
15007   /* Vfork catchpoints.  */
15008   ops = &catch_vfork_breakpoint_ops;
15009   *ops = base_breakpoint_ops;
15010   ops->insert_location = insert_catch_vfork;
15011   ops->remove_location = remove_catch_vfork;
15012   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15013   ops->print_it = print_it_catch_vfork;
15014   ops->print_one = print_one_catch_vfork;
15015   ops->print_mention = print_mention_catch_vfork;
15016   ops->print_recreate = print_recreate_catch_vfork;
15017
15018   /* Exec catchpoints.  */
15019   ops = &catch_exec_breakpoint_ops;
15020   *ops = base_breakpoint_ops;
15021   ops->dtor = dtor_catch_exec;
15022   ops->insert_location = insert_catch_exec;
15023   ops->remove_location = remove_catch_exec;
15024   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15025   ops->print_it = print_it_catch_exec;
15026   ops->print_one = print_one_catch_exec;
15027   ops->print_mention = print_mention_catch_exec;
15028   ops->print_recreate = print_recreate_catch_exec;
15029
15030   /* Syscall catchpoints.  */
15031   ops = &catch_syscall_breakpoint_ops;
15032   *ops = base_breakpoint_ops;
15033   ops->dtor = dtor_catch_syscall;
15034   ops->insert_location = insert_catch_syscall;
15035   ops->remove_location = remove_catch_syscall;
15036   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15037   ops->print_it = print_it_catch_syscall;
15038   ops->print_one = print_one_catch_syscall;
15039   ops->print_mention = print_mention_catch_syscall;
15040   ops->print_recreate = print_recreate_catch_syscall;
15041
15042   /* Solib-related catchpoints.  */
15043   ops = &catch_solib_breakpoint_ops;
15044   *ops = base_breakpoint_ops;
15045   ops->dtor = dtor_catch_solib;
15046   ops->insert_location = insert_catch_solib;
15047   ops->remove_location = remove_catch_solib;
15048   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15049   ops->check_status = check_status_catch_solib;
15050   ops->print_it = print_it_catch_solib;
15051   ops->print_one = print_one_catch_solib;
15052   ops->print_mention = print_mention_catch_solib;
15053   ops->print_recreate = print_recreate_catch_solib;
15054 }
15055
15056 void
15057 _initialize_breakpoint (void)
15058 {
15059   struct cmd_list_element *c;
15060
15061   initialize_breakpoint_ops ();
15062
15063   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15064   observer_attach_inferior_exit (clear_syscall_counts);
15065   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15066
15067   breakpoint_objfile_key = register_objfile_data ();
15068
15069   catch_syscall_inferior_data
15070     = register_inferior_data_with_cleanup (catch_syscall_inferior_data_cleanup);
15071
15072   breakpoint_chain = 0;
15073   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15074      before a breakpoint is set.  */
15075   breakpoint_count = 0;
15076
15077   tracepoint_count = 0;
15078
15079   add_com ("ignore", class_breakpoint, ignore_command, _("\
15080 Set ignore-count of breakpoint number N to COUNT.\n\
15081 Usage is `ignore N COUNT'."));
15082   if (xdb_commands)
15083     add_com_alias ("bc", "ignore", class_breakpoint, 1);
15084
15085   add_com ("commands", class_breakpoint, commands_command, _("\
15086 Set commands to be executed when a breakpoint is hit.\n\
15087 Give breakpoint number as argument after \"commands\".\n\
15088 With no argument, the targeted breakpoint is the last one set.\n\
15089 The commands themselves follow starting on the next line.\n\
15090 Type a line containing \"end\" to indicate the end of them.\n\
15091 Give \"silent\" as the first line to make the breakpoint silent;\n\
15092 then no output is printed when it is hit, except what the commands print."));
15093
15094   add_com ("condition", class_breakpoint, condition_command, _("\
15095 Specify breakpoint number N to break only if COND is true.\n\
15096 Usage is `condition N COND', where N is an integer and COND is an\n\
15097 expression to be evaluated whenever breakpoint N is reached."));
15098
15099   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15100 Set a temporary breakpoint.\n\
15101 Like \"break\" except the breakpoint is only temporary,\n\
15102 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15103 by using \"enable delete\" on the breakpoint number.\n\
15104 \n"
15105 BREAK_ARGS_HELP ("tbreak")));
15106   set_cmd_completer (c, location_completer);
15107
15108   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15109 Set a hardware assisted breakpoint.\n\
15110 Like \"break\" except the breakpoint requires hardware support,\n\
15111 some target hardware may not have this support.\n\
15112 \n"
15113 BREAK_ARGS_HELP ("hbreak")));
15114   set_cmd_completer (c, location_completer);
15115
15116   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15117 Set a temporary hardware assisted breakpoint.\n\
15118 Like \"hbreak\" except the breakpoint is only temporary,\n\
15119 so it will be deleted when hit.\n\
15120 \n"
15121 BREAK_ARGS_HELP ("thbreak")));
15122   set_cmd_completer (c, location_completer);
15123
15124   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15125 Enable some breakpoints.\n\
15126 Give breakpoint numbers (separated by spaces) as arguments.\n\
15127 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15128 This is used to cancel the effect of the \"disable\" command.\n\
15129 With a subcommand you can enable temporarily."),
15130                   &enablelist, "enable ", 1, &cmdlist);
15131   if (xdb_commands)
15132     add_com ("ab", class_breakpoint, enable_command, _("\
15133 Enable some breakpoints.\n\
15134 Give breakpoint numbers (separated by spaces) as arguments.\n\
15135 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15136 This is used to cancel the effect of the \"disable\" command.\n\
15137 With a subcommand you can enable temporarily."));
15138
15139   add_com_alias ("en", "enable", class_breakpoint, 1);
15140
15141   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15142 Enable some breakpoints.\n\
15143 Give breakpoint numbers (separated by spaces) as arguments.\n\
15144 This is used to cancel the effect of the \"disable\" command.\n\
15145 May be abbreviated to simply \"enable\".\n"),
15146                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15147
15148   add_cmd ("once", no_class, enable_once_command, _("\
15149 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15150 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15151            &enablebreaklist);
15152
15153   add_cmd ("delete", no_class, enable_delete_command, _("\
15154 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15155 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15156            &enablebreaklist);
15157
15158   add_cmd ("count", no_class, enable_count_command, _("\
15159 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15160 If a breakpoint is hit while enabled in this fashion,\n\
15161 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15162            &enablebreaklist);
15163
15164   add_cmd ("delete", no_class, enable_delete_command, _("\
15165 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15166 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15167            &enablelist);
15168
15169   add_cmd ("once", no_class, enable_once_command, _("\
15170 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15171 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15172            &enablelist);
15173
15174   add_cmd ("count", no_class, enable_count_command, _("\
15175 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15176 If a breakpoint is hit while enabled in this fashion,\n\
15177 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15178            &enablelist);
15179
15180   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15181 Disable some breakpoints.\n\
15182 Arguments are breakpoint numbers with spaces in between.\n\
15183 To disable all breakpoints, give no argument.\n\
15184 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15185                   &disablelist, "disable ", 1, &cmdlist);
15186   add_com_alias ("dis", "disable", class_breakpoint, 1);
15187   add_com_alias ("disa", "disable", class_breakpoint, 1);
15188   if (xdb_commands)
15189     add_com ("sb", class_breakpoint, disable_command, _("\
15190 Disable some breakpoints.\n\
15191 Arguments are breakpoint numbers with spaces in between.\n\
15192 To disable all breakpoints, give no argument.\n\
15193 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
15194
15195   add_cmd ("breakpoints", class_alias, disable_command, _("\
15196 Disable some breakpoints.\n\
15197 Arguments are breakpoint numbers with spaces in between.\n\
15198 To disable all breakpoints, give no argument.\n\
15199 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15200 This command may be abbreviated \"disable\"."),
15201            &disablelist);
15202
15203   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15204 Delete some breakpoints or auto-display expressions.\n\
15205 Arguments are breakpoint numbers with spaces in between.\n\
15206 To delete all breakpoints, give no argument.\n\
15207 \n\
15208 Also a prefix command for deletion of other GDB objects.\n\
15209 The \"unset\" command is also an alias for \"delete\"."),
15210                   &deletelist, "delete ", 1, &cmdlist);
15211   add_com_alias ("d", "delete", class_breakpoint, 1);
15212   add_com_alias ("del", "delete", class_breakpoint, 1);
15213   if (xdb_commands)
15214     add_com ("db", class_breakpoint, delete_command, _("\
15215 Delete some breakpoints.\n\
15216 Arguments are breakpoint numbers with spaces in between.\n\
15217 To delete all breakpoints, give no argument.\n"));
15218
15219   add_cmd ("breakpoints", class_alias, delete_command, _("\
15220 Delete some breakpoints or auto-display expressions.\n\
15221 Arguments are breakpoint numbers with spaces in between.\n\
15222 To delete all breakpoints, give no argument.\n\
15223 This command may be abbreviated \"delete\"."),
15224            &deletelist);
15225
15226   add_com ("clear", class_breakpoint, clear_command, _("\
15227 Clear breakpoint at specified line or function.\n\
15228 Argument may be line number, function name, or \"*\" and an address.\n\
15229 If line number is specified, all breakpoints in that line are cleared.\n\
15230 If function is specified, breakpoints at beginning of function are cleared.\n\
15231 If an address is specified, breakpoints at that address are cleared.\n\
15232 \n\
15233 With no argument, clears all breakpoints in the line that the selected frame\n\
15234 is executing in.\n\
15235 \n\
15236 See also the \"delete\" command which clears breakpoints by number."));
15237   add_com_alias ("cl", "clear", class_breakpoint, 1);
15238
15239   c = add_com ("break", class_breakpoint, break_command, _("\
15240 Set breakpoint at specified line or function.\n"
15241 BREAK_ARGS_HELP ("break")));
15242   set_cmd_completer (c, location_completer);
15243
15244   add_com_alias ("b", "break", class_run, 1);
15245   add_com_alias ("br", "break", class_run, 1);
15246   add_com_alias ("bre", "break", class_run, 1);
15247   add_com_alias ("brea", "break", class_run, 1);
15248
15249   if (xdb_commands)
15250    add_com_alias ("ba", "break", class_breakpoint, 1);
15251
15252   if (dbx_commands)
15253     {
15254       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15255 Break in function/address or break at a line in the current file."),
15256                              &stoplist, "stop ", 1, &cmdlist);
15257       add_cmd ("in", class_breakpoint, stopin_command,
15258                _("Break in function or address."), &stoplist);
15259       add_cmd ("at", class_breakpoint, stopat_command,
15260                _("Break at a line in the current file."), &stoplist);
15261       add_com ("status", class_info, breakpoints_info, _("\
15262 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15263 The \"Type\" column indicates one of:\n\
15264 \tbreakpoint     - normal breakpoint\n\
15265 \twatchpoint     - watchpoint\n\
15266 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15267 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15268 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15269 address and file/line number respectively.\n\
15270 \n\
15271 Convenience variable \"$_\" and default examine address for \"x\"\n\
15272 are set to the address of the last breakpoint listed unless the command\n\
15273 is prefixed with \"server \".\n\n\
15274 Convenience variable \"$bpnum\" contains the number of the last\n\
15275 breakpoint set."));
15276     }
15277
15278   add_info ("breakpoints", breakpoints_info, _("\
15279 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15280 The \"Type\" column indicates one of:\n\
15281 \tbreakpoint     - normal breakpoint\n\
15282 \twatchpoint     - watchpoint\n\
15283 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15284 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15285 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15286 address and file/line number respectively.\n\
15287 \n\
15288 Convenience variable \"$_\" and default examine address for \"x\"\n\
15289 are set to the address of the last breakpoint listed unless the command\n\
15290 is prefixed with \"server \".\n\n\
15291 Convenience variable \"$bpnum\" contains the number of the last\n\
15292 breakpoint set."));
15293
15294   add_info_alias ("b", "breakpoints", 1);
15295
15296   if (xdb_commands)
15297     add_com ("lb", class_breakpoint, breakpoints_info, _("\
15298 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15299 The \"Type\" column indicates one of:\n\
15300 \tbreakpoint     - normal breakpoint\n\
15301 \twatchpoint     - watchpoint\n\
15302 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15303 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15304 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15305 address and file/line number respectively.\n\
15306 \n\
15307 Convenience variable \"$_\" and default examine address for \"x\"\n\
15308 are set to the address of the last breakpoint listed unless the command\n\
15309 is prefixed with \"server \".\n\n\
15310 Convenience variable \"$bpnum\" contains the number of the last\n\
15311 breakpoint set."));
15312
15313   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15314 Status of all breakpoints, or breakpoint number NUMBER.\n\
15315 The \"Type\" column indicates one of:\n\
15316 \tbreakpoint     - normal breakpoint\n\
15317 \twatchpoint     - watchpoint\n\
15318 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15319 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15320 \tuntil          - internal breakpoint used by the \"until\" command\n\
15321 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15322 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15323 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15324 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15325 address and file/line number respectively.\n\
15326 \n\
15327 Convenience variable \"$_\" and default examine address for \"x\"\n\
15328 are set to the address of the last breakpoint listed unless the command\n\
15329 is prefixed with \"server \".\n\n\
15330 Convenience variable \"$bpnum\" contains the number of the last\n\
15331 breakpoint set."),
15332            &maintenanceinfolist);
15333
15334   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15335 Set catchpoints to catch events."),
15336                   &catch_cmdlist, "catch ",
15337                   0/*allow-unknown*/, &cmdlist);
15338
15339   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15340 Set temporary catchpoints to catch events."),
15341                   &tcatch_cmdlist, "tcatch ",
15342                   0/*allow-unknown*/, &cmdlist);
15343
15344   /* Add catch and tcatch sub-commands.  */
15345   add_catch_command ("catch", _("\
15346 Catch an exception, when caught."),
15347                      catch_catch_command,
15348                      NULL,
15349                      CATCH_PERMANENT,
15350                      CATCH_TEMPORARY);
15351   add_catch_command ("throw", _("\
15352 Catch an exception, when thrown."),
15353                      catch_throw_command,
15354                      NULL,
15355                      CATCH_PERMANENT,
15356                      CATCH_TEMPORARY);
15357   add_catch_command ("fork", _("Catch calls to fork."),
15358                      catch_fork_command_1,
15359                      NULL,
15360                      (void *) (uintptr_t) catch_fork_permanent,
15361                      (void *) (uintptr_t) catch_fork_temporary);
15362   add_catch_command ("vfork", _("Catch calls to vfork."),
15363                      catch_fork_command_1,
15364                      NULL,
15365                      (void *) (uintptr_t) catch_vfork_permanent,
15366                      (void *) (uintptr_t) catch_vfork_temporary);
15367   add_catch_command ("exec", _("Catch calls to exec."),
15368                      catch_exec_command_1,
15369                      NULL,
15370                      CATCH_PERMANENT,
15371                      CATCH_TEMPORARY);
15372   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15373 Usage: catch load [REGEX]\n\
15374 If REGEX is given, only stop for libraries matching the regular expression."),
15375                      catch_load_command_1,
15376                      NULL,
15377                      CATCH_PERMANENT,
15378                      CATCH_TEMPORARY);
15379   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15380 Usage: catch unload [REGEX]\n\
15381 If REGEX is given, only stop for libraries matching the regular expression."),
15382                      catch_unload_command_1,
15383                      NULL,
15384                      CATCH_PERMANENT,
15385                      CATCH_TEMPORARY);
15386   add_catch_command ("syscall", _("\
15387 Catch system calls by their names and/or numbers.\n\
15388 Arguments say which system calls to catch.  If no arguments\n\
15389 are given, every system call will be caught.\n\
15390 Arguments, if given, should be one or more system call names\n\
15391 (if your system supports that), or system call numbers."),
15392                      catch_syscall_command_1,
15393                      catch_syscall_completer,
15394                      CATCH_PERMANENT,
15395                      CATCH_TEMPORARY);
15396
15397   c = add_com ("watch", class_breakpoint, watch_command, _("\
15398 Set a watchpoint for an expression.\n\
15399 Usage: watch [-l|-location] EXPRESSION\n\
15400 A watchpoint stops execution of your program whenever the value of\n\
15401 an expression changes.\n\
15402 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15403 the memory to which it refers."));
15404   set_cmd_completer (c, expression_completer);
15405
15406   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15407 Set a read watchpoint for an expression.\n\
15408 Usage: rwatch [-l|-location] EXPRESSION\n\
15409 A watchpoint stops execution of your program whenever the value of\n\
15410 an expression is read.\n\
15411 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15412 the memory to which it refers."));
15413   set_cmd_completer (c, expression_completer);
15414
15415   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15416 Set a watchpoint for an expression.\n\
15417 Usage: awatch [-l|-location] EXPRESSION\n\
15418 A watchpoint stops execution of your program whenever the value of\n\
15419 an expression is either read or written.\n\
15420 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15421 the memory to which it refers."));
15422   set_cmd_completer (c, expression_completer);
15423
15424   add_info ("watchpoints", watchpoints_info, _("\
15425 Status of specified watchpoints (all watchpoints if no argument)."));
15426
15427   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15428      respond to changes - contrary to the description.  */
15429   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15430                             &can_use_hw_watchpoints, _("\
15431 Set debugger's willingness to use watchpoint hardware."), _("\
15432 Show debugger's willingness to use watchpoint hardware."), _("\
15433 If zero, gdb will not use hardware for new watchpoints, even if\n\
15434 such is available.  (However, any hardware watchpoints that were\n\
15435 created before setting this to nonzero, will continue to use watchpoint\n\
15436 hardware.)"),
15437                             NULL,
15438                             show_can_use_hw_watchpoints,
15439                             &setlist, &showlist);
15440
15441   can_use_hw_watchpoints = 1;
15442
15443   /* Tracepoint manipulation commands.  */
15444
15445   c = add_com ("trace", class_breakpoint, trace_command, _("\
15446 Set a tracepoint at specified line or function.\n\
15447 \n"
15448 BREAK_ARGS_HELP ("trace") "\n\
15449 Do \"help tracepoints\" for info on other tracepoint commands."));
15450   set_cmd_completer (c, location_completer);
15451
15452   add_com_alias ("tp", "trace", class_alias, 0);
15453   add_com_alias ("tr", "trace", class_alias, 1);
15454   add_com_alias ("tra", "trace", class_alias, 1);
15455   add_com_alias ("trac", "trace", class_alias, 1);
15456
15457   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15458 Set a fast tracepoint at specified line or function.\n\
15459 \n"
15460 BREAK_ARGS_HELP ("ftrace") "\n\
15461 Do \"help tracepoints\" for info on other tracepoint commands."));
15462   set_cmd_completer (c, location_completer);
15463
15464   c = add_com ("strace", class_breakpoint, strace_command, _("\
15465 Set a static tracepoint at specified line, function or marker.\n\
15466 \n\
15467 strace [LOCATION] [if CONDITION]\n\
15468 LOCATION may be a line number, function name, \"*\" and an address,\n\
15469 or -m MARKER_ID.\n\
15470 If a line number is specified, probe the marker at start of code\n\
15471 for that line.  If a function is specified, probe the marker at start\n\
15472 of code for that function.  If an address is specified, probe the marker\n\
15473 at that exact address.  If a marker id is specified, probe the marker\n\
15474 with that name.  With no LOCATION, uses current execution address of\n\
15475 the selected stack frame.\n\
15476 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15477 This collects arbitrary user data passed in the probe point call to the\n\
15478 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15479 by printing the $_sdata variable like any other convenience variable.\n\
15480 \n\
15481 CONDITION is a boolean expression.\n\
15482 \n\
15483 Multiple tracepoints at one place are permitted, and useful if their\n\
15484 conditions are different.\n\
15485 \n\
15486 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15487 Do \"help tracepoints\" for info on other tracepoint commands."));
15488   set_cmd_completer (c, location_completer);
15489
15490   add_info ("tracepoints", tracepoints_info, _("\
15491 Status of specified tracepoints (all tracepoints if no argument).\n\
15492 Convenience variable \"$tpnum\" contains the number of the\n\
15493 last tracepoint set."));
15494
15495   add_info_alias ("tp", "tracepoints", 1);
15496
15497   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15498 Delete specified tracepoints.\n\
15499 Arguments are tracepoint numbers, separated by spaces.\n\
15500 No argument means delete all tracepoints."),
15501            &deletelist);
15502
15503   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15504 Disable specified tracepoints.\n\
15505 Arguments are tracepoint numbers, separated by spaces.\n\
15506 No argument means disable all tracepoints."),
15507            &disablelist);
15508   deprecate_cmd (c, "disable");
15509
15510   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15511 Enable specified tracepoints.\n\
15512 Arguments are tracepoint numbers, separated by spaces.\n\
15513 No argument means enable all tracepoints."),
15514            &enablelist);
15515   deprecate_cmd (c, "enable");
15516
15517   add_com ("passcount", class_trace, trace_pass_command, _("\
15518 Set the passcount for a tracepoint.\n\
15519 The trace will end when the tracepoint has been passed 'count' times.\n\
15520 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15521 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15522
15523   add_prefix_cmd ("save", class_breakpoint, save_command,
15524                   _("Save breakpoint definitions as a script."),
15525                   &save_cmdlist, "save ",
15526                   0/*allow-unknown*/, &cmdlist);
15527
15528   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15529 Save current breakpoint definitions as a script.\n\
15530 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15531 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15532 session to restore them."),
15533                &save_cmdlist);
15534   set_cmd_completer (c, filename_completer);
15535
15536   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15537 Save current tracepoint definitions as a script.\n\
15538 Use the 'source' command in another debug session to restore them."),
15539                &save_cmdlist);
15540   set_cmd_completer (c, filename_completer);
15541
15542   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15543   deprecate_cmd (c, "save tracepoints");
15544
15545   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15546 Breakpoint specific settings\n\
15547 Configure various breakpoint-specific variables such as\n\
15548 pending breakpoint behavior"),
15549                   &breakpoint_set_cmdlist, "set breakpoint ",
15550                   0/*allow-unknown*/, &setlist);
15551   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15552 Breakpoint specific settings\n\
15553 Configure various breakpoint-specific variables such as\n\
15554 pending breakpoint behavior"),
15555                   &breakpoint_show_cmdlist, "show breakpoint ",
15556                   0/*allow-unknown*/, &showlist);
15557
15558   add_setshow_auto_boolean_cmd ("pending", no_class,
15559                                 &pending_break_support, _("\
15560 Set debugger's behavior regarding pending breakpoints."), _("\
15561 Show debugger's behavior regarding pending breakpoints."), _("\
15562 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15563 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15564 an error.  If auto, an unrecognized breakpoint location results in a\n\
15565 user-query to see if a pending breakpoint should be created."),
15566                                 NULL,
15567                                 show_pending_break_support,
15568                                 &breakpoint_set_cmdlist,
15569                                 &breakpoint_show_cmdlist);
15570
15571   pending_break_support = AUTO_BOOLEAN_AUTO;
15572
15573   add_setshow_boolean_cmd ("auto-hw", no_class,
15574                            &automatic_hardware_breakpoints, _("\
15575 Set automatic usage of hardware breakpoints."), _("\
15576 Show automatic usage of hardware breakpoints."), _("\
15577 If set, the debugger will automatically use hardware breakpoints for\n\
15578 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
15579 a warning will be emitted for such breakpoints."),
15580                            NULL,
15581                            show_automatic_hardware_breakpoints,
15582                            &breakpoint_set_cmdlist,
15583                            &breakpoint_show_cmdlist);
15584
15585   add_setshow_enum_cmd ("always-inserted", class_support,
15586                         always_inserted_enums, &always_inserted_mode, _("\
15587 Set mode for inserting breakpoints."), _("\
15588 Show mode for inserting breakpoints."), _("\
15589 When this mode is off, breakpoints are inserted in inferior when it is\n\
15590 resumed, and removed when execution stops.  When this mode is on,\n\
15591 breakpoints are inserted immediately and removed only when the user\n\
15592 deletes the breakpoint.  When this mode is auto (which is the default),\n\
15593 the behaviour depends on the non-stop setting (see help set non-stop).\n\
15594 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
15595 behaves as if always-inserted mode is on; if gdb is controlling the\n\
15596 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
15597                            NULL,
15598                            &show_always_inserted_mode,
15599                            &breakpoint_set_cmdlist,
15600                            &breakpoint_show_cmdlist);
15601
15602   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
15603                         condition_evaluation_enums,
15604                         &condition_evaluation_mode_1, _("\
15605 Set mode of breakpoint condition evaluation."), _("\
15606 Show mode of breakpoint condition evaluation."), _("\
15607 When this is set to \"host\", breakpoint conditions will be\n\
15608 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
15609 breakpoint conditions will be downloaded to the target (if the target\n\
15610 supports such feature) and conditions will be evaluated on the target's side.\n\
15611 If this is set to \"auto\" (default), this will be automatically set to\n\
15612 \"target\" if it supports condition evaluation, otherwise it will\n\
15613 be set to \"gdb\""),
15614                            &set_condition_evaluation_mode,
15615                            &show_condition_evaluation_mode,
15616                            &breakpoint_set_cmdlist,
15617                            &breakpoint_show_cmdlist);
15618
15619   add_com ("break-range", class_breakpoint, break_range_command, _("\
15620 Set a breakpoint for an address range.\n\
15621 break-range START-LOCATION, END-LOCATION\n\
15622 where START-LOCATION and END-LOCATION can be one of the following:\n\
15623   LINENUM, for that line in the current file,\n\
15624   FILE:LINENUM, for that line in that file,\n\
15625   +OFFSET, for that number of lines after the current line\n\
15626            or the start of the range\n\
15627   FUNCTION, for the first line in that function,\n\
15628   FILE:FUNCTION, to distinguish among like-named static functions.\n\
15629   *ADDRESS, for the instruction at that address.\n\
15630 \n\
15631 The breakpoint will stop execution of the inferior whenever it executes\n\
15632 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
15633 range (including START-LOCATION and END-LOCATION)."));
15634
15635   automatic_hardware_breakpoints = 1;
15636
15637   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
15638 }