breakpoint.c: debug output when we skip inserting a breakpoint
[platform/upstream/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "infrun.h"
36 #include "gdbthread.h"
37 #include "target.h"
38 #include "language.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 "block.h"
51 #include "solib.h"
52 #include "solist.h"
53 #include "observer.h"
54 #include "exceptions.h"
55 #include "memattr.h"
56 #include "ada-lang.h"
57 #include "top.h"
58 #include "valprint.h"
59 #include "jit.h"
60 #include "xml-syscall.h"
61 #include "parser-defs.h"
62 #include "gdb_regex.h"
63 #include "probe.h"
64 #include "cli/cli-utils.h"
65 #include "continuations.h"
66 #include "stack.h"
67 #include "skip.h"
68 #include "ax-gdb.h"
69 #include "dummy-frame.h"
70
71 #include "format.h"
72
73 /* readline include files */
74 #include "readline/readline.h"
75 #include "readline/history.h"
76
77 /* readline defines this.  */
78 #undef savestring
79
80 #include "mi/mi-common.h"
81 #include "extension.h"
82
83 /* Enums for exception-handling support.  */
84 enum exception_event_kind
85 {
86   EX_EVENT_THROW,
87   EX_EVENT_RETHROW,
88   EX_EVENT_CATCH
89 };
90
91 /* Prototypes for local functions.  */
92
93 static void enable_delete_command (char *, int);
94
95 static void enable_once_command (char *, int);
96
97 static void enable_count_command (char *, int);
98
99 static void disable_command (char *, int);
100
101 static void enable_command (char *, int);
102
103 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
104                                                       void *),
105                                     void *);
106
107 static void ignore_command (char *, int);
108
109 static int breakpoint_re_set_one (void *);
110
111 static void breakpoint_re_set_default (struct breakpoint *);
112
113 static void create_sals_from_address_default (char **,
114                                               struct linespec_result *,
115                                               enum bptype, char *,
116                                               char **);
117
118 static void create_breakpoints_sal_default (struct gdbarch *,
119                                             struct linespec_result *,
120                                             char *, char *, enum bptype,
121                                             enum bpdisp, int, int,
122                                             int,
123                                             const struct breakpoint_ops *,
124                                             int, int, int, unsigned);
125
126 static void decode_linespec_default (struct breakpoint *, char **,
127                                      struct symtabs_and_lines *);
128
129 static void clear_command (char *, int);
130
131 static void catch_command (char *, int);
132
133 static int can_use_hardware_watchpoint (struct value *);
134
135 static void break_command_1 (char *, int, int);
136
137 static void mention (struct breakpoint *);
138
139 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
140                                                                enum bptype,
141                                                                const struct breakpoint_ops *);
142 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
143                                                        const struct symtab_and_line *);
144
145 /* This function is used in gdbtk sources and thus can not be made
146    static.  */
147 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
148                                        struct symtab_and_line,
149                                        enum bptype,
150                                        const struct breakpoint_ops *);
151
152 static struct breakpoint *
153   momentary_breakpoint_from_master (struct breakpoint *orig,
154                                     enum bptype type,
155                                     const struct breakpoint_ops *ops,
156                                     int loc_enabled);
157
158 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
159
160 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
161                                             CORE_ADDR bpaddr,
162                                             enum bptype bptype);
163
164 static void describe_other_breakpoints (struct gdbarch *,
165                                         struct program_space *, CORE_ADDR,
166                                         struct obj_section *, int);
167
168 static int watchpoint_locations_match (struct bp_location *loc1,
169                                        struct bp_location *loc2);
170
171 static int breakpoint_location_address_match (struct bp_location *bl,
172                                               struct address_space *aspace,
173                                               CORE_ADDR addr);
174
175 static void breakpoints_info (char *, int);
176
177 static void watchpoints_info (char *, int);
178
179 static int breakpoint_1 (char *, int, 
180                          int (*) (const struct breakpoint *));
181
182 static int breakpoint_cond_eval (void *);
183
184 static void cleanup_executing_breakpoints (void *);
185
186 static void commands_command (char *, int);
187
188 static void condition_command (char *, int);
189
190 typedef enum
191   {
192     mark_inserted,
193     mark_uninserted
194   }
195 insertion_state_t;
196
197 static int remove_breakpoint (struct bp_location *, insertion_state_t);
198 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
199
200 static enum print_stop_action print_bp_stop_message (bpstat bs);
201
202 static int watchpoint_check (void *);
203
204 static void maintenance_info_breakpoints (char *, int);
205
206 static int hw_breakpoint_used_count (void);
207
208 static int hw_watchpoint_use_count (struct breakpoint *);
209
210 static int hw_watchpoint_used_count_others (struct breakpoint *except,
211                                             enum bptype type,
212                                             int *other_type_used);
213
214 static void hbreak_command (char *, int);
215
216 static void thbreak_command (char *, int);
217
218 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
219                                     int count);
220
221 static void stop_command (char *arg, int from_tty);
222
223 static void stopin_command (char *arg, int from_tty);
224
225 static void stopat_command (char *arg, int from_tty);
226
227 static void tcatch_command (char *arg, int from_tty);
228
229 static void detach_single_step_breakpoints (void);
230
231 static int find_single_step_breakpoint (struct address_space *aspace,
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 /* update_global_location_list's modes of operation wrt to whether to
241    insert locations now.  */
242 enum ugll_insert_mode
243 {
244   /* Don't insert any breakpoint locations into the inferior, only
245      remove already-inserted locations that no longer should be
246      inserted.  Functions that delete a breakpoint or breakpoints
247      should specify this mode, so that deleting a breakpoint doesn't
248      have the side effect of inserting the locations of other
249      breakpoints that are marked not-inserted, but should_be_inserted
250      returns true on them.
251
252      This behavior is useful is situations close to tear-down -- e.g.,
253      after an exec, while the target still has execution, but
254      breakpoint shadows of the previous executable image should *NOT*
255      be restored to the new image; or before detaching, where the
256      target still has execution and wants to delete breakpoints from
257      GDB's lists, and all breakpoints had already been removed from
258      the inferior.  */
259   UGLL_DONT_INSERT,
260
261   /* May insert breakpoints iff breakpoints_should_be_inserted_now
262      claims breakpoints should be inserted now.  */
263   UGLL_MAY_INSERT,
264
265   /* Insert locations now, irrespective of
266      breakpoints_should_be_inserted_now.  E.g., say all threads are
267      stopped right now, and the user did "continue".  We need to
268      insert breakpoints _before_ resuming the target, but
269      UGLL_MAY_INSERT wouldn't insert them, because
270      breakpoints_should_be_inserted_now returns false at that point,
271      as no thread is running yet.  */
272   UGLL_INSERT
273 };
274
275 static void update_global_location_list (enum ugll_insert_mode);
276
277 static void update_global_location_list_nothrow (enum ugll_insert_mode);
278
279 static int is_hardware_watchpoint (const struct breakpoint *bpt);
280
281 static void insert_breakpoint_locations (void);
282
283 static int syscall_catchpoint_p (struct breakpoint *b);
284
285 static void tracepoints_info (char *, int);
286
287 static void delete_trace_command (char *, int);
288
289 static void enable_trace_command (char *, int);
290
291 static void disable_trace_command (char *, int);
292
293 static void trace_pass_command (char *, int);
294
295 static void set_tracepoint_count (int num);
296
297 static int is_masked_watchpoint (const struct breakpoint *b);
298
299 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
300
301 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
302    otherwise.  */
303
304 static int strace_marker_p (struct breakpoint *b);
305
306 /* The abstract base class all breakpoint_ops structures inherit
307    from.  */
308 struct breakpoint_ops base_breakpoint_ops;
309
310 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
311    that are implemented on top of software or hardware breakpoints
312    (user breakpoints, internal and momentary breakpoints, etc.).  */
313 static struct breakpoint_ops bkpt_base_breakpoint_ops;
314
315 /* Internal breakpoints class type.  */
316 static struct breakpoint_ops internal_breakpoint_ops;
317
318 /* Momentary breakpoints class type.  */
319 static struct breakpoint_ops momentary_breakpoint_ops;
320
321 /* Momentary breakpoints for bp_longjmp and bp_exception class type.  */
322 static struct breakpoint_ops longjmp_breakpoint_ops;
323
324 /* The breakpoint_ops structure to be used in regular user created
325    breakpoints.  */
326 struct breakpoint_ops bkpt_breakpoint_ops;
327
328 /* Breakpoints set on probes.  */
329 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
330
331 /* Dynamic printf class type.  */
332 struct breakpoint_ops dprintf_breakpoint_ops;
333
334 /* One (or perhaps two) breakpoints used for software single
335    stepping.  */
336
337 static void *single_step_breakpoints[2];
338 static struct gdbarch *single_step_gdbarch[2];
339
340 /* The style in which to perform a dynamic printf.  This is a user
341    option because different output options have different tradeoffs;
342    if GDB does the printing, there is better error handling if there
343    is a problem with any of the arguments, but using an inferior
344    function lets you have special-purpose printers and sending of
345    output to the same place as compiled-in print functions.  */
346
347 static const char dprintf_style_gdb[] = "gdb";
348 static const char dprintf_style_call[] = "call";
349 static const char dprintf_style_agent[] = "agent";
350 static const char *const dprintf_style_enums[] = {
351   dprintf_style_gdb,
352   dprintf_style_call,
353   dprintf_style_agent,
354   NULL
355 };
356 static const char *dprintf_style = dprintf_style_gdb;
357
358 /* The function to use for dynamic printf if the preferred style is to
359    call into the inferior.  The value is simply a string that is
360    copied into the command, so it can be anything that GDB can
361    evaluate to a callable address, not necessarily a function name.  */
362
363 static char *dprintf_function = "";
364
365 /* The channel to use for dynamic printf if the preferred style is to
366    call into the inferior; if a nonempty string, it will be passed to
367    the call as the first argument, with the format string as the
368    second.  As with the dprintf function, this can be anything that
369    GDB knows how to evaluate, so in addition to common choices like
370    "stderr", this could be an app-specific expression like
371    "mystreams[curlogger]".  */
372
373 static char *dprintf_channel = "";
374
375 /* True if dprintf commands should continue to operate even if GDB
376    has disconnected.  */
377 static int disconnected_dprintf = 1;
378
379 /* A reference-counted struct command_line.  This lets multiple
380    breakpoints share a single command list.  */
381 struct counted_command_line
382 {
383   /* The reference count.  */
384   int refc;
385
386   /* The command list.  */
387   struct command_line *commands;
388 };
389
390 struct command_line *
391 breakpoint_commands (struct breakpoint *b)
392 {
393   return b->commands ? b->commands->commands : NULL;
394 }
395
396 /* Flag indicating that a command has proceeded the inferior past the
397    current breakpoint.  */
398
399 static int breakpoint_proceeded;
400
401 const char *
402 bpdisp_text (enum bpdisp disp)
403 {
404   /* NOTE: the following values are a part of MI protocol and
405      represent values of 'disp' field returned when inferior stops at
406      a breakpoint.  */
407   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
408
409   return bpdisps[(int) disp];
410 }
411
412 /* Prototypes for exported functions.  */
413 /* If FALSE, gdb will not use hardware support for watchpoints, even
414    if such is available.  */
415 static int can_use_hw_watchpoints;
416
417 static void
418 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
419                              struct cmd_list_element *c,
420                              const char *value)
421 {
422   fprintf_filtered (file,
423                     _("Debugger's willingness to use "
424                       "watchpoint hardware is %s.\n"),
425                     value);
426 }
427
428 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
429    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
430    for unrecognized breakpoint locations.
431    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
432 static enum auto_boolean pending_break_support;
433 static void
434 show_pending_break_support (struct ui_file *file, int from_tty,
435                             struct cmd_list_element *c,
436                             const char *value)
437 {
438   fprintf_filtered (file,
439                     _("Debugger's behavior regarding "
440                       "pending breakpoints is %s.\n"),
441                     value);
442 }
443
444 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
445    set with "break" but falling in read-only memory.
446    If 0, gdb will warn about such breakpoints, but won't automatically
447    use hardware breakpoints.  */
448 static int automatic_hardware_breakpoints;
449 static void
450 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
451                                      struct cmd_list_element *c,
452                                      const char *value)
453 {
454   fprintf_filtered (file,
455                     _("Automatic usage of hardware breakpoints is %s.\n"),
456                     value);
457 }
458
459 /* If on, GDB keeps breakpoints inserted even if the inferior is
460    stopped, and immediately inserts any new breakpoints as soon as
461    they're created.  If off (default), GDB keeps breakpoints off of
462    the target as long as possible.  That is, it delays inserting
463    breakpoints until the next resume, and removes them again when the
464    target fully stops.  This is a bit safer in case GDB crashes while
465    processing user input.  */
466 static int always_inserted_mode = 0;
467
468 static void
469 show_always_inserted_mode (struct ui_file *file, int from_tty,
470                      struct cmd_list_element *c, const char *value)
471 {
472   fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
473                     value);
474 }
475
476 int
477 breakpoints_should_be_inserted_now (void)
478 {
479   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
480     {
481       /* If breakpoints are global, they should be inserted even if no
482          thread under gdb's control is running, or even if there are
483          no threads under GDB's control yet.  */
484       return 1;
485     }
486   else if (target_has_execution)
487     {
488       struct thread_info *tp;
489
490       if (always_inserted_mode)
491         {
492           /* The user wants breakpoints inserted even if all threads
493              are stopped.  */
494           return 1;
495         }
496
497       ALL_NON_EXITED_THREADS (tp)
498         {
499           if (tp->executing)
500             return 1;
501         }
502     }
503   return 0;
504 }
505
506 static const char condition_evaluation_both[] = "host or target";
507
508 /* Modes for breakpoint condition evaluation.  */
509 static const char condition_evaluation_auto[] = "auto";
510 static const char condition_evaluation_host[] = "host";
511 static const char condition_evaluation_target[] = "target";
512 static const char *const condition_evaluation_enums[] = {
513   condition_evaluation_auto,
514   condition_evaluation_host,
515   condition_evaluation_target,
516   NULL
517 };
518
519 /* Global that holds the current mode for breakpoint condition evaluation.  */
520 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
521
522 /* Global that we use to display information to the user (gets its value from
523    condition_evaluation_mode_1.  */
524 static const char *condition_evaluation_mode = condition_evaluation_auto;
525
526 /* Translate a condition evaluation mode MODE into either "host"
527    or "target".  This is used mostly to translate from "auto" to the
528    real setting that is being used.  It returns the translated
529    evaluation mode.  */
530
531 static const char *
532 translate_condition_evaluation_mode (const char *mode)
533 {
534   if (mode == condition_evaluation_auto)
535     {
536       if (target_supports_evaluation_of_breakpoint_conditions ())
537         return condition_evaluation_target;
538       else
539         return condition_evaluation_host;
540     }
541   else
542     return mode;
543 }
544
545 /* Discovers what condition_evaluation_auto translates to.  */
546
547 static const char *
548 breakpoint_condition_evaluation_mode (void)
549 {
550   return translate_condition_evaluation_mode (condition_evaluation_mode);
551 }
552
553 /* Return true if GDB should evaluate breakpoint conditions or false
554    otherwise.  */
555
556 static int
557 gdb_evaluates_breakpoint_condition_p (void)
558 {
559   const char *mode = breakpoint_condition_evaluation_mode ();
560
561   return (mode == condition_evaluation_host);
562 }
563
564 void _initialize_breakpoint (void);
565
566 /* Are we executing breakpoint commands?  */
567 static int executing_breakpoint_commands;
568
569 /* Are overlay event breakpoints enabled? */
570 static int overlay_events_enabled;
571
572 /* See description in breakpoint.h. */
573 int target_exact_watchpoints = 0;
574
575 /* Walk the following statement or block through all breakpoints.
576    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
577    current breakpoint.  */
578
579 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
580
581 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
582         for (B = breakpoint_chain;      \
583              B ? (TMP=B->next, 1): 0;   \
584              B = TMP)
585
586 /* Similar iterator for the low-level breakpoints.  SAFE variant is
587    not provided so update_global_location_list must not be called
588    while executing the block of ALL_BP_LOCATIONS.  */
589
590 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
591         for (BP_TMP = bp_location;                                      \
592              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
593              BP_TMP++)
594
595 /* Iterates through locations with address ADDRESS for the currently selected
596    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
597    to where the loop should start from.
598    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
599    appropriate location to start with.  */
600
601 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
602         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
603              BP_LOCP_TMP = BP_LOCP_START;                               \
604              BP_LOCP_START                                              \
605              && (BP_LOCP_TMP < bp_location + bp_location_count          \
606              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
607              BP_LOCP_TMP++)
608
609 /* Iterator for tracepoints only.  */
610
611 #define ALL_TRACEPOINTS(B)  \
612   for (B = breakpoint_chain; B; B = B->next)  \
613     if (is_tracepoint (B))
614
615 /* Chains of all breakpoints defined.  */
616
617 struct breakpoint *breakpoint_chain;
618
619 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
620
621 static struct bp_location **bp_location;
622
623 /* Number of elements of BP_LOCATION.  */
624
625 static unsigned bp_location_count;
626
627 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
628    ADDRESS for the current elements of BP_LOCATION which get a valid
629    result from bp_location_has_shadow.  You can use it for roughly
630    limiting the subrange of BP_LOCATION to scan for shadow bytes for
631    an address you need to read.  */
632
633 static CORE_ADDR bp_location_placed_address_before_address_max;
634
635 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
636    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
637    BP_LOCATION which get a valid result from bp_location_has_shadow.
638    You can use it for roughly limiting the subrange of BP_LOCATION to
639    scan for shadow bytes for an address you need to read.  */
640
641 static CORE_ADDR bp_location_shadow_len_after_address_max;
642
643 /* The locations that no longer correspond to any breakpoint, unlinked
644    from bp_location array, but for which a hit may still be reported
645    by a target.  */
646 VEC(bp_location_p) *moribund_locations = NULL;
647
648 /* Number of last breakpoint made.  */
649
650 static int breakpoint_count;
651
652 /* The value of `breakpoint_count' before the last command that
653    created breakpoints.  If the last (break-like) command created more
654    than one breakpoint, then the difference between BREAKPOINT_COUNT
655    and PREV_BREAKPOINT_COUNT is more than one.  */
656 static int prev_breakpoint_count;
657
658 /* Number of last tracepoint made.  */
659
660 static int tracepoint_count;
661
662 static struct cmd_list_element *breakpoint_set_cmdlist;
663 static struct cmd_list_element *breakpoint_show_cmdlist;
664 struct cmd_list_element *save_cmdlist;
665
666 /* Return whether a breakpoint is an active enabled breakpoint.  */
667 static int
668 breakpoint_enabled (struct breakpoint *b)
669 {
670   return (b->enable_state == bp_enabled);
671 }
672
673 /* Set breakpoint count to NUM.  */
674
675 static void
676 set_breakpoint_count (int num)
677 {
678   prev_breakpoint_count = breakpoint_count;
679   breakpoint_count = num;
680   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
681 }
682
683 /* Used by `start_rbreak_breakpoints' below, to record the current
684    breakpoint count before "rbreak" creates any breakpoint.  */
685 static int rbreak_start_breakpoint_count;
686
687 /* Called at the start an "rbreak" command to record the first
688    breakpoint made.  */
689
690 void
691 start_rbreak_breakpoints (void)
692 {
693   rbreak_start_breakpoint_count = breakpoint_count;
694 }
695
696 /* Called at the end of an "rbreak" command to record the last
697    breakpoint made.  */
698
699 void
700 end_rbreak_breakpoints (void)
701 {
702   prev_breakpoint_count = rbreak_start_breakpoint_count;
703 }
704
705 /* Used in run_command to zero the hit count when a new run starts.  */
706
707 void
708 clear_breakpoint_hit_counts (void)
709 {
710   struct breakpoint *b;
711
712   ALL_BREAKPOINTS (b)
713     b->hit_count = 0;
714 }
715
716 /* Allocate a new counted_command_line with reference count of 1.
717    The new structure owns COMMANDS.  */
718
719 static struct counted_command_line *
720 alloc_counted_command_line (struct command_line *commands)
721 {
722   struct counted_command_line *result
723     = xmalloc (sizeof (struct counted_command_line));
724
725   result->refc = 1;
726   result->commands = commands;
727   return result;
728 }
729
730 /* Increment reference count.  This does nothing if CMD is NULL.  */
731
732 static void
733 incref_counted_command_line (struct counted_command_line *cmd)
734 {
735   if (cmd)
736     ++cmd->refc;
737 }
738
739 /* Decrement reference count.  If the reference count reaches 0,
740    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
741    nothing if *CMDP is NULL.  */
742
743 static void
744 decref_counted_command_line (struct counted_command_line **cmdp)
745 {
746   if (*cmdp)
747     {
748       if (--(*cmdp)->refc == 0)
749         {
750           free_command_lines (&(*cmdp)->commands);
751           xfree (*cmdp);
752         }
753       *cmdp = NULL;
754     }
755 }
756
757 /* A cleanup function that calls decref_counted_command_line.  */
758
759 static void
760 do_cleanup_counted_command_line (void *arg)
761 {
762   decref_counted_command_line (arg);
763 }
764
765 /* Create a cleanup that calls decref_counted_command_line on the
766    argument.  */
767
768 static struct cleanup *
769 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
770 {
771   return make_cleanup (do_cleanup_counted_command_line, cmdp);
772 }
773
774 \f
775 /* Return the breakpoint with the specified number, or NULL
776    if the number does not refer to an existing breakpoint.  */
777
778 struct breakpoint *
779 get_breakpoint (int num)
780 {
781   struct breakpoint *b;
782
783   ALL_BREAKPOINTS (b)
784     if (b->number == num)
785       return b;
786   
787   return NULL;
788 }
789
790 \f
791
792 /* Mark locations as "conditions have changed" in case the target supports
793    evaluating conditions on its side.  */
794
795 static void
796 mark_breakpoint_modified (struct breakpoint *b)
797 {
798   struct bp_location *loc;
799
800   /* This is only meaningful if the target is
801      evaluating conditions and if the user has
802      opted for condition evaluation on the target's
803      side.  */
804   if (gdb_evaluates_breakpoint_condition_p ()
805       || !target_supports_evaluation_of_breakpoint_conditions ())
806     return;
807
808   if (!is_breakpoint (b))
809     return;
810
811   for (loc = b->loc; loc; loc = loc->next)
812     loc->condition_changed = condition_modified;
813 }
814
815 /* Mark location as "conditions have changed" in case the target supports
816    evaluating conditions on its side.  */
817
818 static void
819 mark_breakpoint_location_modified (struct bp_location *loc)
820 {
821   /* This is only meaningful if the target is
822      evaluating conditions and if the user has
823      opted for condition evaluation on the target's
824      side.  */
825   if (gdb_evaluates_breakpoint_condition_p ()
826       || !target_supports_evaluation_of_breakpoint_conditions ())
827
828     return;
829
830   if (!is_breakpoint (loc->owner))
831     return;
832
833   loc->condition_changed = condition_modified;
834 }
835
836 /* Sets the condition-evaluation mode using the static global
837    condition_evaluation_mode.  */
838
839 static void
840 set_condition_evaluation_mode (char *args, int from_tty,
841                                struct cmd_list_element *c)
842 {
843   const char *old_mode, *new_mode;
844
845   if ((condition_evaluation_mode_1 == condition_evaluation_target)
846       && !target_supports_evaluation_of_breakpoint_conditions ())
847     {
848       condition_evaluation_mode_1 = condition_evaluation_mode;
849       warning (_("Target does not support breakpoint condition evaluation.\n"
850                  "Using host evaluation mode instead."));
851       return;
852     }
853
854   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
855   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
856
857   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
858      settings was "auto".  */
859   condition_evaluation_mode = condition_evaluation_mode_1;
860
861   /* Only update the mode if the user picked a different one.  */
862   if (new_mode != old_mode)
863     {
864       struct bp_location *loc, **loc_tmp;
865       /* If the user switched to a different evaluation mode, we
866          need to synch the changes with the target as follows:
867
868          "host" -> "target": Send all (valid) conditions to the target.
869          "target" -> "host": Remove all the conditions from the target.
870       */
871
872       if (new_mode == condition_evaluation_target)
873         {
874           /* Mark everything modified and synch conditions with the
875              target.  */
876           ALL_BP_LOCATIONS (loc, loc_tmp)
877             mark_breakpoint_location_modified (loc);
878         }
879       else
880         {
881           /* Manually mark non-duplicate locations to synch conditions
882              with the target.  We do this to remove all the conditions the
883              target knows about.  */
884           ALL_BP_LOCATIONS (loc, loc_tmp)
885             if (is_breakpoint (loc->owner) && loc->inserted)
886               loc->needs_update = 1;
887         }
888
889       /* Do the update.  */
890       update_global_location_list (UGLL_MAY_INSERT);
891     }
892
893   return;
894 }
895
896 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
897    what "auto" is translating to.  */
898
899 static void
900 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
901                                 struct cmd_list_element *c, const char *value)
902 {
903   if (condition_evaluation_mode == condition_evaluation_auto)
904     fprintf_filtered (file,
905                       _("Breakpoint condition evaluation "
906                         "mode is %s (currently %s).\n"),
907                       value,
908                       breakpoint_condition_evaluation_mode ());
909   else
910     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
911                       value);
912 }
913
914 /* A comparison function for bp_location AP and BP that is used by
915    bsearch.  This comparison function only cares about addresses, unlike
916    the more general bp_location_compare function.  */
917
918 static int
919 bp_location_compare_addrs (const void *ap, const void *bp)
920 {
921   struct bp_location *a = *(void **) ap;
922   struct bp_location *b = *(void **) bp;
923
924   if (a->address == b->address)
925     return 0;
926   else
927     return ((a->address > b->address) - (a->address < b->address));
928 }
929
930 /* Helper function to skip all bp_locations with addresses
931    less than ADDRESS.  It returns the first bp_location that
932    is greater than or equal to ADDRESS.  If none is found, just
933    return NULL.  */
934
935 static struct bp_location **
936 get_first_locp_gte_addr (CORE_ADDR address)
937 {
938   struct bp_location dummy_loc;
939   struct bp_location *dummy_locp = &dummy_loc;
940   struct bp_location **locp_found = NULL;
941
942   /* Initialize the dummy location's address field.  */
943   memset (&dummy_loc, 0, sizeof (struct bp_location));
944   dummy_loc.address = address;
945
946   /* Find a close match to the first location at ADDRESS.  */
947   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
948                         sizeof (struct bp_location **),
949                         bp_location_compare_addrs);
950
951   /* Nothing was found, nothing left to do.  */
952   if (locp_found == NULL)
953     return NULL;
954
955   /* We may have found a location that is at ADDRESS but is not the first in the
956      location's list.  Go backwards (if possible) and locate the first one.  */
957   while ((locp_found - 1) >= bp_location
958          && (*(locp_found - 1))->address == address)
959     locp_found--;
960
961   return locp_found;
962 }
963
964 void
965 set_breakpoint_condition (struct breakpoint *b, char *exp,
966                           int from_tty)
967 {
968   xfree (b->cond_string);
969   b->cond_string = NULL;
970
971   if (is_watchpoint (b))
972     {
973       struct watchpoint *w = (struct watchpoint *) b;
974
975       xfree (w->cond_exp);
976       w->cond_exp = NULL;
977     }
978   else
979     {
980       struct bp_location *loc;
981
982       for (loc = b->loc; loc; loc = loc->next)
983         {
984           xfree (loc->cond);
985           loc->cond = NULL;
986
987           /* No need to free the condition agent expression
988              bytecode (if we have one).  We will handle this
989              when we go through update_global_location_list.  */
990         }
991     }
992
993   if (*exp == 0)
994     {
995       if (from_tty)
996         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
997     }
998   else
999     {
1000       const char *arg = exp;
1001
1002       /* I don't know if it matters whether this is the string the user
1003          typed in or the decompiled expression.  */
1004       b->cond_string = xstrdup (arg);
1005       b->condition_not_parsed = 0;
1006
1007       if (is_watchpoint (b))
1008         {
1009           struct watchpoint *w = (struct watchpoint *) b;
1010
1011           innermost_block = NULL;
1012           arg = exp;
1013           w->cond_exp = parse_exp_1 (&arg, 0, 0, 0);
1014           if (*arg)
1015             error (_("Junk at end of expression"));
1016           w->cond_exp_valid_block = innermost_block;
1017         }
1018       else
1019         {
1020           struct bp_location *loc;
1021
1022           for (loc = b->loc; loc; loc = loc->next)
1023             {
1024               arg = exp;
1025               loc->cond =
1026                 parse_exp_1 (&arg, loc->address,
1027                              block_for_pc (loc->address), 0);
1028               if (*arg)
1029                 error (_("Junk at end of expression"));
1030             }
1031         }
1032     }
1033   mark_breakpoint_modified (b);
1034
1035   observer_notify_breakpoint_modified (b);
1036 }
1037
1038 /* Completion for the "condition" command.  */
1039
1040 static VEC (char_ptr) *
1041 condition_completer (struct cmd_list_element *cmd,
1042                      const char *text, const char *word)
1043 {
1044   const char *space;
1045
1046   text = skip_spaces_const (text);
1047   space = skip_to_space_const (text);
1048   if (*space == '\0')
1049     {
1050       int len;
1051       struct breakpoint *b;
1052       VEC (char_ptr) *result = NULL;
1053
1054       if (text[0] == '$')
1055         {
1056           /* We don't support completion of history indices.  */
1057           if (isdigit (text[1]))
1058             return NULL;
1059           return complete_internalvar (&text[1]);
1060         }
1061
1062       /* We're completing the breakpoint number.  */
1063       len = strlen (text);
1064
1065       ALL_BREAKPOINTS (b)
1066         {
1067           char number[50];
1068
1069           xsnprintf (number, sizeof (number), "%d", b->number);
1070
1071           if (strncmp (number, text, len) == 0)
1072             VEC_safe_push (char_ptr, result, xstrdup (number));
1073         }
1074
1075       return result;
1076     }
1077
1078   /* We're completing the expression part.  */
1079   text = skip_spaces_const (space);
1080   return expression_completer (cmd, text, word);
1081 }
1082
1083 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
1084
1085 static void
1086 condition_command (char *arg, int from_tty)
1087 {
1088   struct breakpoint *b;
1089   char *p;
1090   int bnum;
1091
1092   if (arg == 0)
1093     error_no_arg (_("breakpoint number"));
1094
1095   p = arg;
1096   bnum = get_number (&p);
1097   if (bnum == 0)
1098     error (_("Bad breakpoint argument: '%s'"), arg);
1099
1100   ALL_BREAKPOINTS (b)
1101     if (b->number == bnum)
1102       {
1103         /* Check if this breakpoint has a "stop" method implemented in an
1104            extension language.  This method and conditions entered into GDB
1105            from the CLI are mutually exclusive.  */
1106         const struct extension_language_defn *extlang
1107           = get_breakpoint_cond_ext_lang (b, EXT_LANG_NONE);
1108
1109         if (extlang != NULL)
1110           {
1111             error (_("Only one stop condition allowed.  There is currently"
1112                      " a %s stop condition defined for this breakpoint."),
1113                    ext_lang_capitalized_name (extlang));
1114           }
1115         set_breakpoint_condition (b, p, from_tty);
1116
1117         if (is_breakpoint (b))
1118           update_global_location_list (UGLL_MAY_INSERT);
1119
1120         return;
1121       }
1122
1123   error (_("No breakpoint number %d."), bnum);
1124 }
1125
1126 /* Check that COMMAND do not contain commands that are suitable
1127    only for tracepoints and not suitable for ordinary breakpoints.
1128    Throw if any such commands is found.  */
1129
1130 static void
1131 check_no_tracepoint_commands (struct command_line *commands)
1132 {
1133   struct command_line *c;
1134
1135   for (c = commands; c; c = c->next)
1136     {
1137       int i;
1138
1139       if (c->control_type == while_stepping_control)
1140         error (_("The 'while-stepping' command can "
1141                  "only be used for tracepoints"));
1142
1143       for (i = 0; i < c->body_count; ++i)
1144         check_no_tracepoint_commands ((c->body_list)[i]);
1145
1146       /* Not that command parsing removes leading whitespace and comment
1147          lines and also empty lines.  So, we only need to check for
1148          command directly.  */
1149       if (strstr (c->line, "collect ") == c->line)
1150         error (_("The 'collect' command can only be used for tracepoints"));
1151
1152       if (strstr (c->line, "teval ") == c->line)
1153         error (_("The 'teval' command can only be used for tracepoints"));
1154     }
1155 }
1156
1157 /* Encapsulate tests for different types of tracepoints.  */
1158
1159 static int
1160 is_tracepoint_type (enum bptype type)
1161 {
1162   return (type == bp_tracepoint
1163           || type == bp_fast_tracepoint
1164           || type == bp_static_tracepoint);
1165 }
1166
1167 int
1168 is_tracepoint (const struct breakpoint *b)
1169 {
1170   return is_tracepoint_type (b->type);
1171 }
1172
1173 /* A helper function that validates that COMMANDS are valid for a
1174    breakpoint.  This function will throw an exception if a problem is
1175    found.  */
1176
1177 static void
1178 validate_commands_for_breakpoint (struct breakpoint *b,
1179                                   struct command_line *commands)
1180 {
1181   if (is_tracepoint (b))
1182     {
1183       struct tracepoint *t = (struct tracepoint *) b;
1184       struct command_line *c;
1185       struct command_line *while_stepping = 0;
1186
1187       /* Reset the while-stepping step count.  The previous commands
1188          might have included a while-stepping action, while the new
1189          ones might not.  */
1190       t->step_count = 0;
1191
1192       /* We need to verify that each top-level element of commands is
1193          valid for tracepoints, that there's at most one
1194          while-stepping element, and that the while-stepping's body
1195          has valid tracing commands excluding nested while-stepping.
1196          We also need to validate the tracepoint action line in the
1197          context of the tracepoint --- validate_actionline actually
1198          has side effects, like setting the tracepoint's
1199          while-stepping STEP_COUNT, in addition to checking if the
1200          collect/teval actions parse and make sense in the
1201          tracepoint's context.  */
1202       for (c = commands; c; c = c->next)
1203         {
1204           if (c->control_type == while_stepping_control)
1205             {
1206               if (b->type == bp_fast_tracepoint)
1207                 error (_("The 'while-stepping' command "
1208                          "cannot be used for fast tracepoint"));
1209               else if (b->type == bp_static_tracepoint)
1210                 error (_("The 'while-stepping' command "
1211                          "cannot be used for static tracepoint"));
1212
1213               if (while_stepping)
1214                 error (_("The 'while-stepping' command "
1215                          "can be used only once"));
1216               else
1217                 while_stepping = c;
1218             }
1219
1220           validate_actionline (c->line, b);
1221         }
1222       if (while_stepping)
1223         {
1224           struct command_line *c2;
1225
1226           gdb_assert (while_stepping->body_count == 1);
1227           c2 = while_stepping->body_list[0];
1228           for (; c2; c2 = c2->next)
1229             {
1230               if (c2->control_type == while_stepping_control)
1231                 error (_("The 'while-stepping' command cannot be nested"));
1232             }
1233         }
1234     }
1235   else
1236     {
1237       check_no_tracepoint_commands (commands);
1238     }
1239 }
1240
1241 /* Return a vector of all the static tracepoints set at ADDR.  The
1242    caller is responsible for releasing the vector.  */
1243
1244 VEC(breakpoint_p) *
1245 static_tracepoints_here (CORE_ADDR addr)
1246 {
1247   struct breakpoint *b;
1248   VEC(breakpoint_p) *found = 0;
1249   struct bp_location *loc;
1250
1251   ALL_BREAKPOINTS (b)
1252     if (b->type == bp_static_tracepoint)
1253       {
1254         for (loc = b->loc; loc; loc = loc->next)
1255           if (loc->address == addr)
1256             VEC_safe_push(breakpoint_p, found, b);
1257       }
1258
1259   return found;
1260 }
1261
1262 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1263    validate that only allowed commands are included.  */
1264
1265 void
1266 breakpoint_set_commands (struct breakpoint *b, 
1267                          struct command_line *commands)
1268 {
1269   validate_commands_for_breakpoint (b, commands);
1270
1271   decref_counted_command_line (&b->commands);
1272   b->commands = alloc_counted_command_line (commands);
1273   observer_notify_breakpoint_modified (b);
1274 }
1275
1276 /* Set the internal `silent' flag on the breakpoint.  Note that this
1277    is not the same as the "silent" that may appear in the breakpoint's
1278    commands.  */
1279
1280 void
1281 breakpoint_set_silent (struct breakpoint *b, int silent)
1282 {
1283   int old_silent = b->silent;
1284
1285   b->silent = silent;
1286   if (old_silent != silent)
1287     observer_notify_breakpoint_modified (b);
1288 }
1289
1290 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1291    breakpoint work for any thread.  */
1292
1293 void
1294 breakpoint_set_thread (struct breakpoint *b, int thread)
1295 {
1296   int old_thread = b->thread;
1297
1298   b->thread = thread;
1299   if (old_thread != thread)
1300     observer_notify_breakpoint_modified (b);
1301 }
1302
1303 /* Set the task for this breakpoint.  If TASK is 0, make the
1304    breakpoint work for any task.  */
1305
1306 void
1307 breakpoint_set_task (struct breakpoint *b, int task)
1308 {
1309   int old_task = b->task;
1310
1311   b->task = task;
1312   if (old_task != task)
1313     observer_notify_breakpoint_modified (b);
1314 }
1315
1316 void
1317 check_tracepoint_command (char *line, void *closure)
1318 {
1319   struct breakpoint *b = closure;
1320
1321   validate_actionline (line, b);
1322 }
1323
1324 /* A structure used to pass information through
1325    map_breakpoint_numbers.  */
1326
1327 struct commands_info
1328 {
1329   /* True if the command was typed at a tty.  */
1330   int from_tty;
1331
1332   /* The breakpoint range spec.  */
1333   char *arg;
1334
1335   /* Non-NULL if the body of the commands are being read from this
1336      already-parsed command.  */
1337   struct command_line *control;
1338
1339   /* The command lines read from the user, or NULL if they have not
1340      yet been read.  */
1341   struct counted_command_line *cmd;
1342 };
1343
1344 /* A callback for map_breakpoint_numbers that sets the commands for
1345    commands_command.  */
1346
1347 static void
1348 do_map_commands_command (struct breakpoint *b, void *data)
1349 {
1350   struct commands_info *info = data;
1351
1352   if (info->cmd == NULL)
1353     {
1354       struct command_line *l;
1355
1356       if (info->control != NULL)
1357         l = copy_command_lines (info->control->body_list[0]);
1358       else
1359         {
1360           struct cleanup *old_chain;
1361           char *str;
1362
1363           str = xstrprintf (_("Type commands for breakpoint(s) "
1364                               "%s, one per line."),
1365                             info->arg);
1366
1367           old_chain = make_cleanup (xfree, str);
1368
1369           l = read_command_lines (str,
1370                                   info->from_tty, 1,
1371                                   (is_tracepoint (b)
1372                                    ? check_tracepoint_command : 0),
1373                                   b);
1374
1375           do_cleanups (old_chain);
1376         }
1377
1378       info->cmd = alloc_counted_command_line (l);
1379     }
1380
1381   /* If a breakpoint was on the list more than once, we don't need to
1382      do anything.  */
1383   if (b->commands != info->cmd)
1384     {
1385       validate_commands_for_breakpoint (b, info->cmd->commands);
1386       incref_counted_command_line (info->cmd);
1387       decref_counted_command_line (&b->commands);
1388       b->commands = info->cmd;
1389       observer_notify_breakpoint_modified (b);
1390     }
1391 }
1392
1393 static void
1394 commands_command_1 (char *arg, int from_tty, 
1395                     struct command_line *control)
1396 {
1397   struct cleanup *cleanups;
1398   struct commands_info info;
1399
1400   info.from_tty = from_tty;
1401   info.control = control;
1402   info.cmd = NULL;
1403   /* If we read command lines from the user, then `info' will hold an
1404      extra reference to the commands that we must clean up.  */
1405   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1406
1407   if (arg == NULL || !*arg)
1408     {
1409       if (breakpoint_count - prev_breakpoint_count > 1)
1410         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1411                           breakpoint_count);
1412       else if (breakpoint_count > 0)
1413         arg = xstrprintf ("%d", breakpoint_count);
1414       else
1415         {
1416           /* So that we don't try to free the incoming non-NULL
1417              argument in the cleanup below.  Mapping breakpoint
1418              numbers will fail in this case.  */
1419           arg = NULL;
1420         }
1421     }
1422   else
1423     /* The command loop has some static state, so we need to preserve
1424        our argument.  */
1425     arg = xstrdup (arg);
1426
1427   if (arg != NULL)
1428     make_cleanup (xfree, arg);
1429
1430   info.arg = arg;
1431
1432   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1433
1434   if (info.cmd == NULL)
1435     error (_("No breakpoints specified."));
1436
1437   do_cleanups (cleanups);
1438 }
1439
1440 static void
1441 commands_command (char *arg, int from_tty)
1442 {
1443   commands_command_1 (arg, from_tty, NULL);
1444 }
1445
1446 /* Like commands_command, but instead of reading the commands from
1447    input stream, takes them from an already parsed command structure.
1448
1449    This is used by cli-script.c to DTRT with breakpoint commands
1450    that are part of if and while bodies.  */
1451 enum command_control_type
1452 commands_from_control_command (char *arg, struct command_line *cmd)
1453 {
1454   commands_command_1 (arg, 0, cmd);
1455   return simple_control;
1456 }
1457
1458 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1459
1460 static int
1461 bp_location_has_shadow (struct bp_location *bl)
1462 {
1463   if (bl->loc_type != bp_loc_software_breakpoint)
1464     return 0;
1465   if (!bl->inserted)
1466     return 0;
1467   if (bl->target_info.shadow_len == 0)
1468     /* BL isn't valid, or doesn't shadow memory.  */
1469     return 0;
1470   return 1;
1471 }
1472
1473 /* Update BUF, which is LEN bytes read from the target address
1474    MEMADDR, by replacing a memory breakpoint with its shadowed
1475    contents.
1476
1477    If READBUF is not NULL, this buffer must not overlap with the of
1478    the breakpoint location's shadow_contents buffer.  Otherwise, a
1479    failed assertion internal error will be raised.  */
1480
1481 static void
1482 one_breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1483                             const gdb_byte *writebuf_org,
1484                             ULONGEST memaddr, LONGEST len,
1485                             struct bp_target_info *target_info,
1486                             struct gdbarch *gdbarch)
1487 {
1488   /* Now do full processing of the found relevant range of elements.  */
1489   CORE_ADDR bp_addr = 0;
1490   int bp_size = 0;
1491   int bptoffset = 0;
1492
1493   if (!breakpoint_address_match (target_info->placed_address_space, 0,
1494                                  current_program_space->aspace, 0))
1495     {
1496       /* The breakpoint is inserted in a different address space.  */
1497       return;
1498     }
1499
1500   /* Addresses and length of the part of the breakpoint that
1501      we need to copy.  */
1502   bp_addr = target_info->placed_address;
1503   bp_size = target_info->shadow_len;
1504
1505   if (bp_addr + bp_size <= memaddr)
1506     {
1507       /* The breakpoint is entirely before the chunk of memory we are
1508          reading.  */
1509       return;
1510     }
1511
1512   if (bp_addr >= memaddr + len)
1513     {
1514       /* The breakpoint is entirely after the chunk of memory we are
1515          reading.  */
1516       return;
1517     }
1518
1519   /* Offset within shadow_contents.  */
1520   if (bp_addr < memaddr)
1521     {
1522       /* Only copy the second part of the breakpoint.  */
1523       bp_size -= memaddr - bp_addr;
1524       bptoffset = memaddr - bp_addr;
1525       bp_addr = memaddr;
1526     }
1527
1528   if (bp_addr + bp_size > memaddr + len)
1529     {
1530       /* Only copy the first part of the breakpoint.  */
1531       bp_size -= (bp_addr + bp_size) - (memaddr + len);
1532     }
1533
1534   if (readbuf != NULL)
1535     {
1536       /* Verify that the readbuf buffer does not overlap with the
1537          shadow_contents buffer.  */
1538       gdb_assert (target_info->shadow_contents >= readbuf + len
1539                   || readbuf >= (target_info->shadow_contents
1540                                  + target_info->shadow_len));
1541
1542       /* Update the read buffer with this inserted breakpoint's
1543          shadow.  */
1544       memcpy (readbuf + bp_addr - memaddr,
1545               target_info->shadow_contents + bptoffset, bp_size);
1546     }
1547   else
1548     {
1549       const unsigned char *bp;
1550       CORE_ADDR placed_address = target_info->placed_address;
1551       int placed_size = target_info->placed_size;
1552
1553       /* Update the shadow with what we want to write to memory.  */
1554       memcpy (target_info->shadow_contents + bptoffset,
1555               writebuf_org + bp_addr - memaddr, bp_size);
1556
1557       /* Determine appropriate breakpoint contents and size for this
1558          address.  */
1559       bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1560
1561       /* Update the final write buffer with this inserted
1562          breakpoint's INSN.  */
1563       memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1564     }
1565 }
1566
1567 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1568    by replacing any memory breakpoints with their shadowed contents.
1569
1570    If READBUF is not NULL, this buffer must not overlap with any of
1571    the breakpoint location's shadow_contents buffers.  Otherwise,
1572    a failed assertion internal error will be raised.
1573
1574    The range of shadowed area by each bp_location is:
1575      bl->address - bp_location_placed_address_before_address_max
1576      up to bl->address + bp_location_shadow_len_after_address_max
1577    The range we were requested to resolve shadows for is:
1578      memaddr ... memaddr + len
1579    Thus the safe cutoff boundaries for performance optimization are
1580      memaddr + len <= (bl->address
1581                        - bp_location_placed_address_before_address_max)
1582    and:
1583      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1584
1585 void
1586 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1587                         const gdb_byte *writebuf_org,
1588                         ULONGEST memaddr, LONGEST len)
1589 {
1590   /* Left boundary, right boundary and median element of our binary
1591      search.  */
1592   unsigned bc_l, bc_r, bc;
1593   size_t i;
1594
1595   /* Find BC_L which is a leftmost element which may affect BUF
1596      content.  It is safe to report lower value but a failure to
1597      report higher one.  */
1598
1599   bc_l = 0;
1600   bc_r = bp_location_count;
1601   while (bc_l + 1 < bc_r)
1602     {
1603       struct bp_location *bl;
1604
1605       bc = (bc_l + bc_r) / 2;
1606       bl = bp_location[bc];
1607
1608       /* Check first BL->ADDRESS will not overflow due to the added
1609          constant.  Then advance the left boundary only if we are sure
1610          the BC element can in no way affect the BUF content (MEMADDR
1611          to MEMADDR + LEN range).
1612
1613          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1614          offset so that we cannot miss a breakpoint with its shadow
1615          range tail still reaching MEMADDR.  */
1616
1617       if ((bl->address + bp_location_shadow_len_after_address_max
1618            >= bl->address)
1619           && (bl->address + bp_location_shadow_len_after_address_max
1620               <= memaddr))
1621         bc_l = bc;
1622       else
1623         bc_r = bc;
1624     }
1625
1626   /* Due to the binary search above, we need to make sure we pick the
1627      first location that's at BC_L's address.  E.g., if there are
1628      multiple locations at the same address, BC_L may end up pointing
1629      at a duplicate location, and miss the "master"/"inserted"
1630      location.  Say, given locations L1, L2 and L3 at addresses A and
1631      B:
1632
1633       L1@A, L2@A, L3@B, ...
1634
1635      BC_L could end up pointing at location L2, while the "master"
1636      location could be L1.  Since the `loc->inserted' flag is only set
1637      on "master" locations, we'd forget to restore the shadow of L1
1638      and L2.  */
1639   while (bc_l > 0
1640          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1641     bc_l--;
1642
1643   /* Now do full processing of the found relevant range of elements.  */
1644
1645   for (bc = bc_l; bc < bp_location_count; bc++)
1646   {
1647     struct bp_location *bl = bp_location[bc];
1648     CORE_ADDR bp_addr = 0;
1649     int bp_size = 0;
1650     int bptoffset = 0;
1651
1652     /* bp_location array has BL->OWNER always non-NULL.  */
1653     if (bl->owner->type == bp_none)
1654       warning (_("reading through apparently deleted breakpoint #%d?"),
1655                bl->owner->number);
1656
1657     /* Performance optimization: any further element can no longer affect BUF
1658        content.  */
1659
1660     if (bl->address >= bp_location_placed_address_before_address_max
1661         && memaddr + len <= (bl->address
1662                              - bp_location_placed_address_before_address_max))
1663       break;
1664
1665     if (!bp_location_has_shadow (bl))
1666       continue;
1667
1668     one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1669                                 memaddr, len, &bl->target_info, bl->gdbarch);
1670   }
1671
1672   /* Now process single-step breakpoints.  These are not found in the
1673      bp_location array.  */
1674   for (i = 0; i < 2; i++)
1675     {
1676       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
1677
1678       if (bp_tgt != NULL)
1679         {
1680           struct gdbarch *gdbarch = single_step_gdbarch[i];
1681
1682           one_breakpoint_xfer_memory (readbuf, writebuf, writebuf_org,
1683                                       memaddr, len, bp_tgt, gdbarch);
1684         }
1685     }
1686 }
1687
1688 \f
1689
1690 /* Return true if BPT is either a software breakpoint or a hardware
1691    breakpoint.  */
1692
1693 int
1694 is_breakpoint (const struct breakpoint *bpt)
1695 {
1696   return (bpt->type == bp_breakpoint
1697           || bpt->type == bp_hardware_breakpoint
1698           || bpt->type == bp_dprintf);
1699 }
1700
1701 /* Return true if BPT is of any hardware watchpoint kind.  */
1702
1703 static int
1704 is_hardware_watchpoint (const struct breakpoint *bpt)
1705 {
1706   return (bpt->type == bp_hardware_watchpoint
1707           || bpt->type == bp_read_watchpoint
1708           || bpt->type == bp_access_watchpoint);
1709 }
1710
1711 /* Return true if BPT is of any watchpoint kind, hardware or
1712    software.  */
1713
1714 int
1715 is_watchpoint (const struct breakpoint *bpt)
1716 {
1717   return (is_hardware_watchpoint (bpt)
1718           || bpt->type == bp_watchpoint);
1719 }
1720
1721 /* Returns true if the current thread and its running state are safe
1722    to evaluate or update watchpoint B.  Watchpoints on local
1723    expressions need to be evaluated in the context of the thread that
1724    was current when the watchpoint was created, and, that thread needs
1725    to be stopped to be able to select the correct frame context.
1726    Watchpoints on global expressions can be evaluated on any thread,
1727    and in any state.  It is presently left to the target allowing
1728    memory accesses when threads are running.  */
1729
1730 static int
1731 watchpoint_in_thread_scope (struct watchpoint *b)
1732 {
1733   return (b->base.pspace == current_program_space
1734           && (ptid_equal (b->watchpoint_thread, null_ptid)
1735               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1736                   && !is_executing (inferior_ptid))));
1737 }
1738
1739 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1740    associated bp_watchpoint_scope breakpoint.  */
1741
1742 static void
1743 watchpoint_del_at_next_stop (struct watchpoint *w)
1744 {
1745   struct breakpoint *b = &w->base;
1746
1747   if (b->related_breakpoint != b)
1748     {
1749       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1750       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1751       b->related_breakpoint->disposition = disp_del_at_next_stop;
1752       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1753       b->related_breakpoint = b;
1754     }
1755   b->disposition = disp_del_at_next_stop;
1756 }
1757
1758 /* Extract a bitfield value from value VAL using the bit parameters contained in
1759    watchpoint W.  */
1760
1761 static struct value *
1762 extract_bitfield_from_watchpoint_value (struct watchpoint *w, struct value *val)
1763 {
1764   struct value *bit_val;
1765
1766   if (val == NULL)
1767     return NULL;
1768
1769   bit_val = allocate_value (value_type (val));
1770
1771   unpack_value_bitfield (bit_val,
1772                          w->val_bitpos,
1773                          w->val_bitsize,
1774                          value_contents_for_printing (val),
1775                          value_offset (val),
1776                          val);
1777
1778   return bit_val;
1779 }
1780
1781 /* Assuming that B is a watchpoint:
1782    - Reparse watchpoint expression, if REPARSE is non-zero
1783    - Evaluate expression and store the result in B->val
1784    - Evaluate the condition if there is one, and store the result
1785      in b->loc->cond.
1786    - Update the list of values that must be watched in B->loc.
1787
1788    If the watchpoint disposition is disp_del_at_next_stop, then do
1789    nothing.  If this is local watchpoint that is out of scope, delete
1790    it.
1791
1792    Even with `set breakpoint always-inserted on' the watchpoints are
1793    removed + inserted on each stop here.  Normal breakpoints must
1794    never be removed because they might be missed by a running thread
1795    when debugging in non-stop mode.  On the other hand, hardware
1796    watchpoints (is_hardware_watchpoint; processed here) are specific
1797    to each LWP since they are stored in each LWP's hardware debug
1798    registers.  Therefore, such LWP must be stopped first in order to
1799    be able to modify its hardware watchpoints.
1800
1801    Hardware watchpoints must be reset exactly once after being
1802    presented to the user.  It cannot be done sooner, because it would
1803    reset the data used to present the watchpoint hit to the user.  And
1804    it must not be done later because it could display the same single
1805    watchpoint hit during multiple GDB stops.  Note that the latter is
1806    relevant only to the hardware watchpoint types bp_read_watchpoint
1807    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1808    not user-visible - its hit is suppressed if the memory content has
1809    not changed.
1810
1811    The following constraints influence the location where we can reset
1812    hardware watchpoints:
1813
1814    * target_stopped_by_watchpoint and target_stopped_data_address are
1815      called several times when GDB stops.
1816
1817    [linux] 
1818    * Multiple hardware watchpoints can be hit at the same time,
1819      causing GDB to stop.  GDB only presents one hardware watchpoint
1820      hit at a time as the reason for stopping, and all the other hits
1821      are presented later, one after the other, each time the user
1822      requests the execution to be resumed.  Execution is not resumed
1823      for the threads still having pending hit event stored in
1824      LWP_INFO->STATUS.  While the watchpoint is already removed from
1825      the inferior on the first stop the thread hit event is kept being
1826      reported from its cached value by linux_nat_stopped_data_address
1827      until the real thread resume happens after the watchpoint gets
1828      presented and thus its LWP_INFO->STATUS gets reset.
1829
1830    Therefore the hardware watchpoint hit can get safely reset on the
1831    watchpoint removal from inferior.  */
1832
1833 static void
1834 update_watchpoint (struct watchpoint *b, int reparse)
1835 {
1836   int within_current_scope;
1837   struct frame_id saved_frame_id;
1838   int frame_saved;
1839
1840   /* If this is a local watchpoint, we only want to check if the
1841      watchpoint frame is in scope if the current thread is the thread
1842      that was used to create the watchpoint.  */
1843   if (!watchpoint_in_thread_scope (b))
1844     return;
1845
1846   if (b->base.disposition == disp_del_at_next_stop)
1847     return;
1848  
1849   frame_saved = 0;
1850
1851   /* Determine if the watchpoint is within scope.  */
1852   if (b->exp_valid_block == NULL)
1853     within_current_scope = 1;
1854   else
1855     {
1856       struct frame_info *fi = get_current_frame ();
1857       struct gdbarch *frame_arch = get_frame_arch (fi);
1858       CORE_ADDR frame_pc = get_frame_pc (fi);
1859
1860       /* If we're in a function epilogue, unwinding may not work
1861          properly, so do not attempt to recreate locations at this
1862          point.  See similar comments in watchpoint_check.  */
1863       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1864         return;
1865
1866       /* Save the current frame's ID so we can restore it after
1867          evaluating the watchpoint expression on its own frame.  */
1868       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1869          took a frame parameter, so that we didn't have to change the
1870          selected frame.  */
1871       frame_saved = 1;
1872       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1873
1874       fi = frame_find_by_id (b->watchpoint_frame);
1875       within_current_scope = (fi != NULL);
1876       if (within_current_scope)
1877         select_frame (fi);
1878     }
1879
1880   /* We don't free locations.  They are stored in the bp_location array
1881      and update_global_location_list will eventually delete them and
1882      remove breakpoints if needed.  */
1883   b->base.loc = NULL;
1884
1885   if (within_current_scope && reparse)
1886     {
1887       const char *s;
1888
1889       if (b->exp)
1890         {
1891           xfree (b->exp);
1892           b->exp = NULL;
1893         }
1894       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1895       b->exp = parse_exp_1 (&s, 0, b->exp_valid_block, 0);
1896       /* If the meaning of expression itself changed, the old value is
1897          no longer relevant.  We don't want to report a watchpoint hit
1898          to the user when the old value and the new value may actually
1899          be completely different objects.  */
1900       value_free (b->val);
1901       b->val = NULL;
1902       b->val_valid = 0;
1903
1904       /* Note that unlike with breakpoints, the watchpoint's condition
1905          expression is stored in the breakpoint object, not in the
1906          locations (re)created below.  */
1907       if (b->base.cond_string != NULL)
1908         {
1909           if (b->cond_exp != NULL)
1910             {
1911               xfree (b->cond_exp);
1912               b->cond_exp = NULL;
1913             }
1914
1915           s = b->base.cond_string;
1916           b->cond_exp = parse_exp_1 (&s, 0, b->cond_exp_valid_block, 0);
1917         }
1918     }
1919
1920   /* If we failed to parse the expression, for example because
1921      it refers to a global variable in a not-yet-loaded shared library,
1922      don't try to insert watchpoint.  We don't automatically delete
1923      such watchpoint, though, since failure to parse expression
1924      is different from out-of-scope watchpoint.  */
1925   if (!target_has_execution)
1926     {
1927       /* Without execution, memory can't change.  No use to try and
1928          set watchpoint locations.  The watchpoint will be reset when
1929          the target gains execution, through breakpoint_re_set.  */
1930       if (!can_use_hw_watchpoints)
1931         {
1932           if (b->base.ops->works_in_software_mode (&b->base))
1933             b->base.type = bp_watchpoint;
1934           else
1935             error (_("Can't set read/access watchpoint when "
1936                      "hardware watchpoints are disabled."));
1937         }
1938     }
1939   else if (within_current_scope && b->exp)
1940     {
1941       int pc = 0;
1942       struct value *val_chain, *v, *result, *next;
1943       struct program_space *frame_pspace;
1944
1945       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain, 0);
1946
1947       /* Avoid setting b->val if it's already set.  The meaning of
1948          b->val is 'the last value' user saw, and we should update
1949          it only if we reported that last value to user.  As it
1950          happens, the code that reports it updates b->val directly.
1951          We don't keep track of the memory value for masked
1952          watchpoints.  */
1953       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1954         {
1955           if (b->val_bitsize != 0)
1956             {
1957               v = extract_bitfield_from_watchpoint_value (b, v);
1958               if (v != NULL)
1959                 release_value (v);
1960             }
1961           b->val = v;
1962           b->val_valid = 1;
1963         }
1964
1965       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1966
1967       /* Look at each value on the value chain.  */
1968       for (v = val_chain; v; v = value_next (v))
1969         {
1970           /* If it's a memory location, and GDB actually needed
1971              its contents to evaluate the expression, then we
1972              must watch it.  If the first value returned is
1973              still lazy, that means an error occurred reading it;
1974              watch it anyway in case it becomes readable.  */
1975           if (VALUE_LVAL (v) == lval_memory
1976               && (v == val_chain || ! value_lazy (v)))
1977             {
1978               struct type *vtype = check_typedef (value_type (v));
1979
1980               /* We only watch structs and arrays if user asked
1981                  for it explicitly, never if they just happen to
1982                  appear in the middle of some value chain.  */
1983               if (v == result
1984                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1985                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1986                 {
1987                   CORE_ADDR addr;
1988                   int type;
1989                   struct bp_location *loc, **tmp;
1990                   int bitpos = 0, bitsize = 0;
1991
1992                   if (value_bitsize (v) != 0)
1993                     {
1994                       /* Extract the bit parameters out from the bitfield
1995                          sub-expression.  */
1996                       bitpos = value_bitpos (v);
1997                       bitsize = value_bitsize (v);
1998                     }
1999                   else if (v == result && b->val_bitsize != 0)
2000                     {
2001                      /* If VAL_BITSIZE != 0 then RESULT is actually a bitfield
2002                         lvalue whose bit parameters are saved in the fields
2003                         VAL_BITPOS and VAL_BITSIZE.  */
2004                       bitpos = b->val_bitpos;
2005                       bitsize = b->val_bitsize;
2006                     }
2007
2008                   addr = value_address (v);
2009                   if (bitsize != 0)
2010                     {
2011                       /* Skip the bytes that don't contain the bitfield.  */
2012                       addr += bitpos / 8;
2013                     }
2014
2015                   type = hw_write;
2016                   if (b->base.type == bp_read_watchpoint)
2017                     type = hw_read;
2018                   else if (b->base.type == bp_access_watchpoint)
2019                     type = hw_access;
2020
2021                   loc = allocate_bp_location (&b->base);
2022                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
2023                     ;
2024                   *tmp = loc;
2025                   loc->gdbarch = get_type_arch (value_type (v));
2026
2027                   loc->pspace = frame_pspace;
2028                   loc->address = addr;
2029
2030                   if (bitsize != 0)
2031                     {
2032                       /* Just cover the bytes that make up the bitfield.  */
2033                       loc->length = ((bitpos % 8) + bitsize + 7) / 8;
2034                     }
2035                   else
2036                     loc->length = TYPE_LENGTH (value_type (v));
2037
2038                   loc->watchpoint_type = type;
2039                 }
2040             }
2041         }
2042
2043       /* Change the type of breakpoint between hardware assisted or
2044          an ordinary watchpoint depending on the hardware support
2045          and free hardware slots.  REPARSE is set when the inferior
2046          is started.  */
2047       if (reparse)
2048         {
2049           int reg_cnt;
2050           enum bp_loc_type loc_type;
2051           struct bp_location *bl;
2052
2053           reg_cnt = can_use_hardware_watchpoint (val_chain);
2054
2055           if (reg_cnt)
2056             {
2057               int i, target_resources_ok, other_type_used;
2058               enum bptype type;
2059
2060               /* Use an exact watchpoint when there's only one memory region to be
2061                  watched, and only one debug register is needed to watch it.  */
2062               b->exact = target_exact_watchpoints && reg_cnt == 1;
2063
2064               /* We need to determine how many resources are already
2065                  used for all other hardware watchpoints plus this one
2066                  to see if we still have enough resources to also fit
2067                  this watchpoint in as well.  */
2068
2069               /* If this is a software watchpoint, we try to turn it
2070                  to a hardware one -- count resources as if B was of
2071                  hardware watchpoint type.  */
2072               type = b->base.type;
2073               if (type == bp_watchpoint)
2074                 type = bp_hardware_watchpoint;
2075
2076               /* This watchpoint may or may not have been placed on
2077                  the list yet at this point (it won't be in the list
2078                  if we're trying to create it for the first time,
2079                  through watch_command), so always account for it
2080                  manually.  */
2081
2082               /* Count resources used by all watchpoints except B.  */
2083               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
2084
2085               /* Add in the resources needed for B.  */
2086               i += hw_watchpoint_use_count (&b->base);
2087
2088               target_resources_ok
2089                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
2090               if (target_resources_ok <= 0)
2091                 {
2092                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
2093
2094                   if (target_resources_ok == 0 && !sw_mode)
2095                     error (_("Target does not support this type of "
2096                              "hardware watchpoint."));
2097                   else if (target_resources_ok < 0 && !sw_mode)
2098                     error (_("There are not enough available hardware "
2099                              "resources for this watchpoint."));
2100
2101                   /* Downgrade to software watchpoint.  */
2102                   b->base.type = bp_watchpoint;
2103                 }
2104               else
2105                 {
2106                   /* If this was a software watchpoint, we've just
2107                      found we have enough resources to turn it to a
2108                      hardware watchpoint.  Otherwise, this is a
2109                      nop.  */
2110                   b->base.type = type;
2111                 }
2112             }
2113           else if (!b->base.ops->works_in_software_mode (&b->base))
2114             {
2115               if (!can_use_hw_watchpoints)
2116                 error (_("Can't set read/access watchpoint when "
2117                          "hardware watchpoints are disabled."));
2118               else
2119                 error (_("Expression cannot be implemented with "
2120                          "read/access watchpoint."));
2121             }
2122           else
2123             b->base.type = bp_watchpoint;
2124
2125           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
2126                       : bp_loc_hardware_watchpoint);
2127           for (bl = b->base.loc; bl; bl = bl->next)
2128             bl->loc_type = loc_type;
2129         }
2130
2131       for (v = val_chain; v; v = next)
2132         {
2133           next = value_next (v);
2134           if (v != b->val)
2135             value_free (v);
2136         }
2137
2138       /* If a software watchpoint is not watching any memory, then the
2139          above left it without any location set up.  But,
2140          bpstat_stop_status requires a location to be able to report
2141          stops, so make sure there's at least a dummy one.  */
2142       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
2143         {
2144           struct breakpoint *base = &b->base;
2145           base->loc = allocate_bp_location (base);
2146           base->loc->pspace = frame_pspace;
2147           base->loc->address = -1;
2148           base->loc->length = -1;
2149           base->loc->watchpoint_type = -1;
2150         }
2151     }
2152   else if (!within_current_scope)
2153     {
2154       printf_filtered (_("\
2155 Watchpoint %d deleted because the program has left the block\n\
2156 in which its expression is valid.\n"),
2157                        b->base.number);
2158       watchpoint_del_at_next_stop (b);
2159     }
2160
2161   /* Restore the selected frame.  */
2162   if (frame_saved)
2163     select_frame (frame_find_by_id (saved_frame_id));
2164 }
2165
2166
2167 /* Returns 1 iff breakpoint location should be
2168    inserted in the inferior.  We don't differentiate the type of BL's owner
2169    (breakpoint vs. tracepoint), although insert_location in tracepoint's
2170    breakpoint_ops is not defined, because in insert_bp_location,
2171    tracepoint's insert_location will not be called.  */
2172 static int
2173 should_be_inserted (struct bp_location *bl)
2174 {
2175   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
2176     return 0;
2177
2178   if (bl->owner->disposition == disp_del_at_next_stop)
2179     return 0;
2180
2181   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
2182     return 0;
2183
2184   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
2185     return 0;
2186
2187   /* This is set for example, when we're attached to the parent of a
2188      vfork, and have detached from the child.  The child is running
2189      free, and we expect it to do an exec or exit, at which point the
2190      OS makes the parent schedulable again (and the target reports
2191      that the vfork is done).  Until the child is done with the shared
2192      memory region, do not insert breakpoints in the parent, otherwise
2193      the child could still trip on the parent's breakpoints.  Since
2194      the parent is blocked anyway, it won't miss any breakpoint.  */
2195   if (bl->pspace->breakpoints_not_allowed)
2196     return 0;
2197
2198   /* Don't insert a breakpoint if we're trying to step past its
2199      location.  */
2200   if ((bl->loc_type == bp_loc_software_breakpoint
2201        || bl->loc_type == bp_loc_hardware_breakpoint)
2202       && stepping_past_instruction_at (bl->pspace->aspace,
2203                                        bl->address))
2204     {
2205       if (debug_infrun)
2206         {
2207           fprintf_unfiltered (gdb_stdlog,
2208                               "infrun: skipping breakpoint: "
2209                               "stepping past insn at: %s\n",
2210                               paddress (bl->gdbarch, bl->address));
2211         }
2212       return 0;
2213     }
2214
2215   return 1;
2216 }
2217
2218 /* Same as should_be_inserted but does the check assuming
2219    that the location is not duplicated.  */
2220
2221 static int
2222 unduplicated_should_be_inserted (struct bp_location *bl)
2223 {
2224   int result;
2225   const int save_duplicate = bl->duplicate;
2226
2227   bl->duplicate = 0;
2228   result = should_be_inserted (bl);
2229   bl->duplicate = save_duplicate;
2230   return result;
2231 }
2232
2233 /* Parses a conditional described by an expression COND into an
2234    agent expression bytecode suitable for evaluation
2235    by the bytecode interpreter.  Return NULL if there was
2236    any error during parsing.  */
2237
2238 static struct agent_expr *
2239 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2240 {
2241   struct agent_expr *aexpr = NULL;
2242   volatile struct gdb_exception ex;
2243
2244   if (!cond)
2245     return NULL;
2246
2247   /* We don't want to stop processing, so catch any errors
2248      that may show up.  */
2249   TRY_CATCH (ex, RETURN_MASK_ERROR)
2250     {
2251       aexpr = gen_eval_for_expr (scope, cond);
2252     }
2253
2254   if (ex.reason < 0)
2255     {
2256       /* If we got here, it means the condition could not be parsed to a valid
2257          bytecode expression and thus can't be evaluated on the target's side.
2258          It's no use iterating through the conditions.  */
2259       return NULL;
2260     }
2261
2262   /* We have a valid agent expression.  */
2263   return aexpr;
2264 }
2265
2266 /* Based on location BL, create a list of breakpoint conditions to be
2267    passed on to the target.  If we have duplicated locations with different
2268    conditions, we will add such conditions to the list.  The idea is that the
2269    target will evaluate the list of conditions and will only notify GDB when
2270    one of them is true.  */
2271
2272 static void
2273 build_target_condition_list (struct bp_location *bl)
2274 {
2275   struct bp_location **locp = NULL, **loc2p;
2276   int null_condition_or_parse_error = 0;
2277   int modified = bl->needs_update;
2278   struct bp_location *loc;
2279
2280   /* Release conditions left over from a previous insert.  */
2281   VEC_free (agent_expr_p, bl->target_info.conditions);
2282
2283   /* This is only meaningful if the target is
2284      evaluating conditions and if the user has
2285      opted for condition evaluation on the target's
2286      side.  */
2287   if (gdb_evaluates_breakpoint_condition_p ()
2288       || !target_supports_evaluation_of_breakpoint_conditions ())
2289     return;
2290
2291   /* Do a first pass to check for locations with no assigned
2292      conditions or conditions that fail to parse to a valid agent expression
2293      bytecode.  If any of these happen, then it's no use to send conditions
2294      to the target since this location will always trigger and generate a
2295      response back to GDB.  */
2296   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2297     {
2298       loc = (*loc2p);
2299       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2300         {
2301           if (modified)
2302             {
2303               struct agent_expr *aexpr;
2304
2305               /* Re-parse the conditions since something changed.  In that
2306                  case we already freed the condition bytecodes (see
2307                  force_breakpoint_reinsertion).  We just
2308                  need to parse the condition to bytecodes again.  */
2309               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2310               loc->cond_bytecode = aexpr;
2311
2312               /* Check if we managed to parse the conditional expression
2313                  correctly.  If not, we will not send this condition
2314                  to the target.  */
2315               if (aexpr)
2316                 continue;
2317             }
2318
2319           /* If we have a NULL bytecode expression, it means something
2320              went wrong or we have a null condition expression.  */
2321           if (!loc->cond_bytecode)
2322             {
2323               null_condition_or_parse_error = 1;
2324               break;
2325             }
2326         }
2327     }
2328
2329   /* If any of these happened, it means we will have to evaluate the conditions
2330      for the location's address on gdb's side.  It is no use keeping bytecodes
2331      for all the other duplicate locations, thus we free all of them here.
2332
2333      This is so we have a finer control over which locations' conditions are
2334      being evaluated by GDB or the remote stub.  */
2335   if (null_condition_or_parse_error)
2336     {
2337       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2338         {
2339           loc = (*loc2p);
2340           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2341             {
2342               /* Only go as far as the first NULL bytecode is
2343                  located.  */
2344               if (!loc->cond_bytecode)
2345                 return;
2346
2347               free_agent_expr (loc->cond_bytecode);
2348               loc->cond_bytecode = NULL;
2349             }
2350         }
2351     }
2352
2353   /* No NULL conditions or failed bytecode generation.  Build a condition list
2354      for this location's address.  */
2355   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2356     {
2357       loc = (*loc2p);
2358       if (loc->cond
2359           && is_breakpoint (loc->owner)
2360           && loc->pspace->num == bl->pspace->num
2361           && loc->owner->enable_state == bp_enabled
2362           && loc->enabled)
2363         /* Add the condition to the vector.  This will be used later to send the
2364            conditions to the target.  */
2365         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2366                        loc->cond_bytecode);
2367     }
2368
2369   return;
2370 }
2371
2372 /* Parses a command described by string CMD into an agent expression
2373    bytecode suitable for evaluation by the bytecode interpreter.
2374    Return NULL if there was any error during parsing.  */
2375
2376 static struct agent_expr *
2377 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2378 {
2379   struct cleanup *old_cleanups = 0;
2380   struct expression *expr, **argvec;
2381   struct agent_expr *aexpr = NULL;
2382   volatile struct gdb_exception ex;
2383   const char *cmdrest;
2384   const char *format_start, *format_end;
2385   struct format_piece *fpieces;
2386   int nargs;
2387   struct gdbarch *gdbarch = get_current_arch ();
2388
2389   if (!cmd)
2390     return NULL;
2391
2392   cmdrest = cmd;
2393
2394   if (*cmdrest == ',')
2395     ++cmdrest;
2396   cmdrest = skip_spaces_const (cmdrest);
2397
2398   if (*cmdrest++ != '"')
2399     error (_("No format string following the location"));
2400
2401   format_start = cmdrest;
2402
2403   fpieces = parse_format_string (&cmdrest);
2404
2405   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2406
2407   format_end = cmdrest;
2408
2409   if (*cmdrest++ != '"')
2410     error (_("Bad format string, non-terminated '\"'."));
2411   
2412   cmdrest = skip_spaces_const (cmdrest);
2413
2414   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2415     error (_("Invalid argument syntax"));
2416
2417   if (*cmdrest == ',')
2418     cmdrest++;
2419   cmdrest = skip_spaces_const (cmdrest);
2420
2421   /* For each argument, make an expression.  */
2422
2423   argvec = (struct expression **) alloca (strlen (cmd)
2424                                          * sizeof (struct expression *));
2425
2426   nargs = 0;
2427   while (*cmdrest != '\0')
2428     {
2429       const char *cmd1;
2430
2431       cmd1 = cmdrest;
2432       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2433       argvec[nargs++] = expr;
2434       cmdrest = cmd1;
2435       if (*cmdrest == ',')
2436         ++cmdrest;
2437     }
2438
2439   /* We don't want to stop processing, so catch any errors
2440      that may show up.  */
2441   TRY_CATCH (ex, RETURN_MASK_ERROR)
2442     {
2443       aexpr = gen_printf (scope, gdbarch, 0, 0,
2444                           format_start, format_end - format_start,
2445                           fpieces, nargs, argvec);
2446     }
2447
2448   do_cleanups (old_cleanups);
2449
2450   if (ex.reason < 0)
2451     {
2452       /* If we got here, it means the command could not be parsed to a valid
2453          bytecode expression and thus can't be evaluated on the target's side.
2454          It's no use iterating through the other commands.  */
2455       return NULL;
2456     }
2457
2458   /* We have a valid agent expression, return it.  */
2459   return aexpr;
2460 }
2461
2462 /* Based on location BL, create a list of breakpoint commands to be
2463    passed on to the target.  If we have duplicated locations with
2464    different commands, we will add any such to the list.  */
2465
2466 static void
2467 build_target_command_list (struct bp_location *bl)
2468 {
2469   struct bp_location **locp = NULL, **loc2p;
2470   int null_command_or_parse_error = 0;
2471   int modified = bl->needs_update;
2472   struct bp_location *loc;
2473
2474   /* Release commands left over from a previous insert.  */
2475   VEC_free (agent_expr_p, bl->target_info.tcommands);
2476
2477   if (!target_can_run_breakpoint_commands ())
2478     return;
2479
2480   /* For now, limit to agent-style dprintf breakpoints.  */
2481   if (dprintf_style != dprintf_style_agent)
2482     return;
2483
2484   /* For now, if we have any duplicate location that isn't a dprintf,
2485      don't install the target-side commands, as that would make the
2486      breakpoint not be reported to the core, and we'd lose
2487      control.  */
2488   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2489     {
2490       loc = (*loc2p);
2491       if (is_breakpoint (loc->owner)
2492           && loc->pspace->num == bl->pspace->num
2493           && loc->owner->type != bp_dprintf)
2494         return;
2495     }
2496
2497   /* Do a first pass to check for locations with no assigned
2498      conditions or conditions that fail to parse to a valid agent expression
2499      bytecode.  If any of these happen, then it's no use to send conditions
2500      to the target since this location will always trigger and generate a
2501      response back to GDB.  */
2502   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2503     {
2504       loc = (*loc2p);
2505       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2506         {
2507           if (modified)
2508             {
2509               struct agent_expr *aexpr;
2510
2511               /* Re-parse the commands since something changed.  In that
2512                  case we already freed the command bytecodes (see
2513                  force_breakpoint_reinsertion).  We just
2514                  need to parse the command to bytecodes again.  */
2515               aexpr = parse_cmd_to_aexpr (bl->address,
2516                                           loc->owner->extra_string);
2517               loc->cmd_bytecode = aexpr;
2518
2519               if (!aexpr)
2520                 continue;
2521             }
2522
2523           /* If we have a NULL bytecode expression, it means something
2524              went wrong or we have a null command expression.  */
2525           if (!loc->cmd_bytecode)
2526             {
2527               null_command_or_parse_error = 1;
2528               break;
2529             }
2530         }
2531     }
2532
2533   /* If anything failed, then we're not doing target-side commands,
2534      and so clean up.  */
2535   if (null_command_or_parse_error)
2536     {
2537       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2538         {
2539           loc = (*loc2p);
2540           if (is_breakpoint (loc->owner)
2541               && loc->pspace->num == bl->pspace->num)
2542             {
2543               /* Only go as far as the first NULL bytecode is
2544                  located.  */
2545               if (loc->cmd_bytecode == NULL)
2546                 return;
2547
2548               free_agent_expr (loc->cmd_bytecode);
2549               loc->cmd_bytecode = NULL;
2550             }
2551         }
2552     }
2553
2554   /* No NULL commands or failed bytecode generation.  Build a command list
2555      for this location's address.  */
2556   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2557     {
2558       loc = (*loc2p);
2559       if (loc->owner->extra_string
2560           && is_breakpoint (loc->owner)
2561           && loc->pspace->num == bl->pspace->num
2562           && loc->owner->enable_state == bp_enabled
2563           && loc->enabled)
2564         /* Add the command to the vector.  This will be used later
2565            to send the commands to the target.  */
2566         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2567                        loc->cmd_bytecode);
2568     }
2569
2570   bl->target_info.persist = 0;
2571   /* Maybe flag this location as persistent.  */
2572   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2573     bl->target_info.persist = 1;
2574 }
2575
2576 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2577    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2578    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2579    Returns 0 for success, 1 if the bp_location type is not supported or
2580    -1 for failure.
2581
2582    NOTE drow/2003-09-09: This routine could be broken down to an
2583    object-style method for each breakpoint or catchpoint type.  */
2584 static int
2585 insert_bp_location (struct bp_location *bl,
2586                     struct ui_file *tmp_error_stream,
2587                     int *disabled_breaks,
2588                     int *hw_breakpoint_error,
2589                     int *hw_bp_error_explained_already)
2590 {
2591   enum errors bp_err = GDB_NO_ERROR;
2592   const char *bp_err_message = NULL;
2593   volatile struct gdb_exception e;
2594
2595   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2596     return 0;
2597
2598   /* Note we don't initialize bl->target_info, as that wipes out
2599      the breakpoint location's shadow_contents if the breakpoint
2600      is still inserted at that location.  This in turn breaks
2601      target_read_memory which depends on these buffers when
2602      a memory read is requested at the breakpoint location:
2603      Once the target_info has been wiped, we fail to see that
2604      we have a breakpoint inserted at that address and thus
2605      read the breakpoint instead of returning the data saved in
2606      the breakpoint location's shadow contents.  */
2607   bl->target_info.placed_address = bl->address;
2608   bl->target_info.placed_address_space = bl->pspace->aspace;
2609   bl->target_info.length = bl->length;
2610
2611   /* When working with target-side conditions, we must pass all the conditions
2612      for the same breakpoint address down to the target since GDB will not
2613      insert those locations.  With a list of breakpoint conditions, the target
2614      can decide when to stop and notify GDB.  */
2615
2616   if (is_breakpoint (bl->owner))
2617     {
2618       build_target_condition_list (bl);
2619       build_target_command_list (bl);
2620       /* Reset the modification marker.  */
2621       bl->needs_update = 0;
2622     }
2623
2624   if (bl->loc_type == bp_loc_software_breakpoint
2625       || bl->loc_type == bp_loc_hardware_breakpoint)
2626     {
2627       if (bl->owner->type != bp_hardware_breakpoint)
2628         {
2629           /* If the explicitly specified breakpoint type
2630              is not hardware breakpoint, check the memory map to see
2631              if the breakpoint address is in read only memory or not.
2632
2633              Two important cases are:
2634              - location type is not hardware breakpoint, memory
2635              is readonly.  We change the type of the location to
2636              hardware breakpoint.
2637              - location type is hardware breakpoint, memory is
2638              read-write.  This means we've previously made the
2639              location hardware one, but then the memory map changed,
2640              so we undo.
2641              
2642              When breakpoints are removed, remove_breakpoints will use
2643              location types we've just set here, the only possible
2644              problem is that memory map has changed during running
2645              program, but it's not going to work anyway with current
2646              gdb.  */
2647           struct mem_region *mr 
2648             = lookup_mem_region (bl->target_info.placed_address);
2649           
2650           if (mr)
2651             {
2652               if (automatic_hardware_breakpoints)
2653                 {
2654                   enum bp_loc_type new_type;
2655                   
2656                   if (mr->attrib.mode != MEM_RW)
2657                     new_type = bp_loc_hardware_breakpoint;
2658                   else 
2659                     new_type = bp_loc_software_breakpoint;
2660                   
2661                   if (new_type != bl->loc_type)
2662                     {
2663                       static int said = 0;
2664
2665                       bl->loc_type = new_type;
2666                       if (!said)
2667                         {
2668                           fprintf_filtered (gdb_stdout,
2669                                             _("Note: automatically using "
2670                                               "hardware breakpoints for "
2671                                               "read-only addresses.\n"));
2672                           said = 1;
2673                         }
2674                     }
2675                 }
2676               else if (bl->loc_type == bp_loc_software_breakpoint
2677                        && mr->attrib.mode != MEM_RW)        
2678                 warning (_("cannot set software breakpoint "
2679                            "at readonly address %s"),
2680                          paddress (bl->gdbarch, bl->address));
2681             }
2682         }
2683         
2684       /* First check to see if we have to handle an overlay.  */
2685       if (overlay_debugging == ovly_off
2686           || bl->section == NULL
2687           || !(section_is_overlay (bl->section)))
2688         {
2689           /* No overlay handling: just set the breakpoint.  */
2690           TRY_CATCH (e, RETURN_MASK_ALL)
2691             {
2692               int val;
2693
2694               val = bl->owner->ops->insert_location (bl);
2695               if (val)
2696                 bp_err = GENERIC_ERROR;
2697             }
2698           if (e.reason < 0)
2699             {
2700               bp_err = e.error;
2701               bp_err_message = e.message;
2702             }
2703         }
2704       else
2705         {
2706           /* This breakpoint is in an overlay section.
2707              Shall we set a breakpoint at the LMA?  */
2708           if (!overlay_events_enabled)
2709             {
2710               /* Yes -- overlay event support is not active, 
2711                  so we must try to set a breakpoint at the LMA.
2712                  This will not work for a hardware breakpoint.  */
2713               if (bl->loc_type == bp_loc_hardware_breakpoint)
2714                 warning (_("hardware breakpoint %d not supported in overlay!"),
2715                          bl->owner->number);
2716               else
2717                 {
2718                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2719                                                              bl->section);
2720                   /* Set a software (trap) breakpoint at the LMA.  */
2721                   bl->overlay_target_info = bl->target_info;
2722                   bl->overlay_target_info.placed_address = addr;
2723
2724                   /* No overlay handling: just set the breakpoint.  */
2725                   TRY_CATCH (e, RETURN_MASK_ALL)
2726                     {
2727                       int val;
2728
2729                       val = target_insert_breakpoint (bl->gdbarch,
2730                                                       &bl->overlay_target_info);
2731                       if (val)
2732                         bp_err = GENERIC_ERROR;
2733                     }
2734                   if (e.reason < 0)
2735                     {
2736                       bp_err = e.error;
2737                       bp_err_message = e.message;
2738                     }
2739
2740                   if (bp_err != GDB_NO_ERROR)
2741                     fprintf_unfiltered (tmp_error_stream,
2742                                         "Overlay breakpoint %d "
2743                                         "failed: in ROM?\n",
2744                                         bl->owner->number);
2745                 }
2746             }
2747           /* Shall we set a breakpoint at the VMA? */
2748           if (section_is_mapped (bl->section))
2749             {
2750               /* Yes.  This overlay section is mapped into memory.  */
2751               TRY_CATCH (e, RETURN_MASK_ALL)
2752                 {
2753                   int val;
2754
2755                   val = bl->owner->ops->insert_location (bl);
2756                   if (val)
2757                     bp_err = GENERIC_ERROR;
2758                 }
2759               if (e.reason < 0)
2760                 {
2761                   bp_err = e.error;
2762                   bp_err_message = e.message;
2763                 }
2764             }
2765           else
2766             {
2767               /* No.  This breakpoint will not be inserted.  
2768                  No error, but do not mark the bp as 'inserted'.  */
2769               return 0;
2770             }
2771         }
2772
2773       if (bp_err != GDB_NO_ERROR)
2774         {
2775           /* Can't set the breakpoint.  */
2776
2777           /* In some cases, we might not be able to insert a
2778              breakpoint in a shared library that has already been
2779              removed, but we have not yet processed the shlib unload
2780              event.  Unfortunately, some targets that implement
2781              breakpoint insertion themselves can't tell why the
2782              breakpoint insertion failed (e.g., the remote target
2783              doesn't define error codes), so we must treat generic
2784              errors as memory errors.  */
2785           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2786               && bl->loc_type == bp_loc_software_breakpoint
2787               && (solib_name_from_address (bl->pspace, bl->address)
2788                   || shared_objfile_contains_address_p (bl->pspace,
2789                                                         bl->address)))
2790             {
2791               /* See also: disable_breakpoints_in_shlibs.  */
2792               bl->shlib_disabled = 1;
2793               observer_notify_breakpoint_modified (bl->owner);
2794               if (!*disabled_breaks)
2795                 {
2796                   fprintf_unfiltered (tmp_error_stream, 
2797                                       "Cannot insert breakpoint %d.\n", 
2798                                       bl->owner->number);
2799                   fprintf_unfiltered (tmp_error_stream, 
2800                                       "Temporarily disabling shared "
2801                                       "library breakpoints:\n");
2802                 }
2803               *disabled_breaks = 1;
2804               fprintf_unfiltered (tmp_error_stream,
2805                                   "breakpoint #%d\n", bl->owner->number);
2806               return 0;
2807             }
2808           else
2809             {
2810               if (bl->loc_type == bp_loc_hardware_breakpoint)
2811                 {
2812                   *hw_breakpoint_error = 1;
2813                   *hw_bp_error_explained_already = bp_err_message != NULL;
2814                   fprintf_unfiltered (tmp_error_stream,
2815                                       "Cannot insert hardware breakpoint %d%s",
2816                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2817                   if (bp_err_message != NULL)
2818                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2819                 }
2820               else
2821                 {
2822                   if (bp_err_message == NULL)
2823                     {
2824                       char *message
2825                         = memory_error_message (TARGET_XFER_E_IO,
2826                                                 bl->gdbarch, bl->address);
2827                       struct cleanup *old_chain = make_cleanup (xfree, message);
2828
2829                       fprintf_unfiltered (tmp_error_stream,
2830                                           "Cannot insert breakpoint %d.\n"
2831                                           "%s\n",
2832                                           bl->owner->number, message);
2833                       do_cleanups (old_chain);
2834                     }
2835                   else
2836                     {
2837                       fprintf_unfiltered (tmp_error_stream,
2838                                           "Cannot insert breakpoint %d: %s\n",
2839                                           bl->owner->number,
2840                                           bp_err_message);
2841                     }
2842                 }
2843               return 1;
2844
2845             }
2846         }
2847       else
2848         bl->inserted = 1;
2849
2850       return 0;
2851     }
2852
2853   else if (bl->loc_type == bp_loc_hardware_watchpoint
2854            /* NOTE drow/2003-09-08: This state only exists for removing
2855               watchpoints.  It's not clear that it's necessary...  */
2856            && bl->owner->disposition != disp_del_at_next_stop)
2857     {
2858       int val;
2859
2860       gdb_assert (bl->owner->ops != NULL
2861                   && bl->owner->ops->insert_location != NULL);
2862
2863       val = bl->owner->ops->insert_location (bl);
2864
2865       /* If trying to set a read-watchpoint, and it turns out it's not
2866          supported, try emulating one with an access watchpoint.  */
2867       if (val == 1 && bl->watchpoint_type == hw_read)
2868         {
2869           struct bp_location *loc, **loc_temp;
2870
2871           /* But don't try to insert it, if there's already another
2872              hw_access location that would be considered a duplicate
2873              of this one.  */
2874           ALL_BP_LOCATIONS (loc, loc_temp)
2875             if (loc != bl
2876                 && loc->watchpoint_type == hw_access
2877                 && watchpoint_locations_match (bl, loc))
2878               {
2879                 bl->duplicate = 1;
2880                 bl->inserted = 1;
2881                 bl->target_info = loc->target_info;
2882                 bl->watchpoint_type = hw_access;
2883                 val = 0;
2884                 break;
2885               }
2886
2887           if (val == 1)
2888             {
2889               bl->watchpoint_type = hw_access;
2890               val = bl->owner->ops->insert_location (bl);
2891
2892               if (val)
2893                 /* Back to the original value.  */
2894                 bl->watchpoint_type = hw_read;
2895             }
2896         }
2897
2898       bl->inserted = (val == 0);
2899     }
2900
2901   else if (bl->owner->type == bp_catchpoint)
2902     {
2903       int val;
2904
2905       gdb_assert (bl->owner->ops != NULL
2906                   && bl->owner->ops->insert_location != NULL);
2907
2908       val = bl->owner->ops->insert_location (bl);
2909       if (val)
2910         {
2911           bl->owner->enable_state = bp_disabled;
2912
2913           if (val == 1)
2914             warning (_("\
2915 Error inserting catchpoint %d: Your system does not support this type\n\
2916 of catchpoint."), bl->owner->number);
2917           else
2918             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2919         }
2920
2921       bl->inserted = (val == 0);
2922
2923       /* We've already printed an error message if there was a problem
2924          inserting this catchpoint, and we've disabled the catchpoint,
2925          so just return success.  */
2926       return 0;
2927     }
2928
2929   return 0;
2930 }
2931
2932 /* This function is called when program space PSPACE is about to be
2933    deleted.  It takes care of updating breakpoints to not reference
2934    PSPACE anymore.  */
2935
2936 void
2937 breakpoint_program_space_exit (struct program_space *pspace)
2938 {
2939   struct breakpoint *b, *b_temp;
2940   struct bp_location *loc, **loc_temp;
2941
2942   /* Remove any breakpoint that was set through this program space.  */
2943   ALL_BREAKPOINTS_SAFE (b, b_temp)
2944     {
2945       if (b->pspace == pspace)
2946         delete_breakpoint (b);
2947     }
2948
2949   /* Breakpoints set through other program spaces could have locations
2950      bound to PSPACE as well.  Remove those.  */
2951   ALL_BP_LOCATIONS (loc, loc_temp)
2952     {
2953       struct bp_location *tmp;
2954
2955       if (loc->pspace == pspace)
2956         {
2957           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2958           if (loc->owner->loc == loc)
2959             loc->owner->loc = loc->next;
2960           else
2961             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2962               if (tmp->next == loc)
2963                 {
2964                   tmp->next = loc->next;
2965                   break;
2966                 }
2967         }
2968     }
2969
2970   /* Now update the global location list to permanently delete the
2971      removed locations above.  */
2972   update_global_location_list (UGLL_DONT_INSERT);
2973 }
2974
2975 /* Make sure all breakpoints are inserted in inferior.
2976    Throws exception on any error.
2977    A breakpoint that is already inserted won't be inserted
2978    again, so calling this function twice is safe.  */
2979 void
2980 insert_breakpoints (void)
2981 {
2982   struct breakpoint *bpt;
2983
2984   ALL_BREAKPOINTS (bpt)
2985     if (is_hardware_watchpoint (bpt))
2986       {
2987         struct watchpoint *w = (struct watchpoint *) bpt;
2988
2989         update_watchpoint (w, 0 /* don't reparse.  */);
2990       }
2991
2992   /* Updating watchpoints creates new locations, so update the global
2993      location list.  Explicitly tell ugll to insert locations and
2994      ignore breakpoints_always_inserted_mode.  */
2995   update_global_location_list (UGLL_INSERT);
2996 }
2997
2998 /* Invoke CALLBACK for each of bp_location.  */
2999
3000 void
3001 iterate_over_bp_locations (walk_bp_location_callback callback)
3002 {
3003   struct bp_location *loc, **loc_tmp;
3004
3005   ALL_BP_LOCATIONS (loc, loc_tmp)
3006     {
3007       callback (loc, NULL);
3008     }
3009 }
3010
3011 /* This is used when we need to synch breakpoint conditions between GDB and the
3012    target.  It is the case with deleting and disabling of breakpoints when using
3013    always-inserted mode.  */
3014
3015 static void
3016 update_inserted_breakpoint_locations (void)
3017 {
3018   struct bp_location *bl, **blp_tmp;
3019   int error_flag = 0;
3020   int val = 0;
3021   int disabled_breaks = 0;
3022   int hw_breakpoint_error = 0;
3023   int hw_bp_details_reported = 0;
3024
3025   struct ui_file *tmp_error_stream = mem_fileopen ();
3026   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3027
3028   /* Explicitly mark the warning -- this will only be printed if
3029      there was an error.  */
3030   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3031
3032   save_current_space_and_thread ();
3033
3034   ALL_BP_LOCATIONS (bl, blp_tmp)
3035     {
3036       /* We only want to update software breakpoints and hardware
3037          breakpoints.  */
3038       if (!is_breakpoint (bl->owner))
3039         continue;
3040
3041       /* We only want to update locations that are already inserted
3042          and need updating.  This is to avoid unwanted insertion during
3043          deletion of breakpoints.  */
3044       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3045         continue;
3046
3047       switch_to_program_space_and_thread (bl->pspace);
3048
3049       /* For targets that support global breakpoints, there's no need
3050          to select an inferior to insert breakpoint to.  In fact, even
3051          if we aren't attached to any process yet, we should still
3052          insert breakpoints.  */
3053       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3054           && ptid_equal (inferior_ptid, null_ptid))
3055         continue;
3056
3057       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3058                                     &hw_breakpoint_error, &hw_bp_details_reported);
3059       if (val)
3060         error_flag = val;
3061     }
3062
3063   if (error_flag)
3064     {
3065       target_terminal_ours_for_output ();
3066       error_stream (tmp_error_stream);
3067     }
3068
3069   do_cleanups (cleanups);
3070 }
3071
3072 /* Used when starting or continuing the program.  */
3073
3074 static void
3075 insert_breakpoint_locations (void)
3076 {
3077   struct breakpoint *bpt;
3078   struct bp_location *bl, **blp_tmp;
3079   int error_flag = 0;
3080   int val = 0;
3081   int disabled_breaks = 0;
3082   int hw_breakpoint_error = 0;
3083   int hw_bp_error_explained_already = 0;
3084
3085   struct ui_file *tmp_error_stream = mem_fileopen ();
3086   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3087   
3088   /* Explicitly mark the warning -- this will only be printed if
3089      there was an error.  */
3090   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3091
3092   save_current_space_and_thread ();
3093
3094   ALL_BP_LOCATIONS (bl, blp_tmp)
3095     {
3096       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3097         continue;
3098
3099       /* There is no point inserting thread-specific breakpoints if
3100          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3101          has BL->OWNER always non-NULL.  */
3102       if (bl->owner->thread != -1
3103           && !valid_thread_id (bl->owner->thread))
3104         continue;
3105
3106       switch_to_program_space_and_thread (bl->pspace);
3107
3108       /* For targets that support global breakpoints, there's no need
3109          to select an inferior to insert breakpoint to.  In fact, even
3110          if we aren't attached to any process yet, we should still
3111          insert breakpoints.  */
3112       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3113           && ptid_equal (inferior_ptid, null_ptid))
3114         continue;
3115
3116       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3117                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3118       if (val)
3119         error_flag = val;
3120     }
3121
3122   /* If we failed to insert all locations of a watchpoint, remove
3123      them, as half-inserted watchpoint is of limited use.  */
3124   ALL_BREAKPOINTS (bpt)  
3125     {
3126       int some_failed = 0;
3127       struct bp_location *loc;
3128
3129       if (!is_hardware_watchpoint (bpt))
3130         continue;
3131
3132       if (!breakpoint_enabled (bpt))
3133         continue;
3134
3135       if (bpt->disposition == disp_del_at_next_stop)
3136         continue;
3137       
3138       for (loc = bpt->loc; loc; loc = loc->next)
3139         if (!loc->inserted && should_be_inserted (loc))
3140           {
3141             some_failed = 1;
3142             break;
3143           }
3144       if (some_failed)
3145         {
3146           for (loc = bpt->loc; loc; loc = loc->next)
3147             if (loc->inserted)
3148               remove_breakpoint (loc, mark_uninserted);
3149
3150           hw_breakpoint_error = 1;
3151           fprintf_unfiltered (tmp_error_stream,
3152                               "Could not insert hardware watchpoint %d.\n", 
3153                               bpt->number);
3154           error_flag = -1;
3155         }
3156     }
3157
3158   if (error_flag)
3159     {
3160       /* If a hardware breakpoint or watchpoint was inserted, add a
3161          message about possibly exhausted resources.  */
3162       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3163         {
3164           fprintf_unfiltered (tmp_error_stream, 
3165                               "Could not insert hardware breakpoints:\n\
3166 You may have requested too many hardware breakpoints/watchpoints.\n");
3167         }
3168       target_terminal_ours_for_output ();
3169       error_stream (tmp_error_stream);
3170     }
3171
3172   do_cleanups (cleanups);
3173 }
3174
3175 /* Used when the program stops.
3176    Returns zero if successful, or non-zero if there was a problem
3177    removing a breakpoint location.  */
3178
3179 int
3180 remove_breakpoints (void)
3181 {
3182   struct bp_location *bl, **blp_tmp;
3183   int val = 0;
3184
3185   ALL_BP_LOCATIONS (bl, blp_tmp)
3186   {
3187     if (bl->inserted && !is_tracepoint (bl->owner))
3188       val |= remove_breakpoint (bl, mark_uninserted);
3189   }
3190   return val;
3191 }
3192
3193 /* When a thread exits, remove breakpoints that are related to
3194    that thread.  */
3195
3196 static void
3197 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3198 {
3199   struct breakpoint *b, *b_tmp;
3200
3201   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3202     {
3203       if (b->thread == tp->num && user_breakpoint_p (b))
3204         {
3205           b->disposition = disp_del_at_next_stop;
3206
3207           printf_filtered (_("\
3208 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3209                           b->number, tp->num);
3210
3211           /* Hide it from the user.  */
3212           b->number = 0;
3213        }
3214     }
3215 }
3216
3217 /* Remove breakpoints of process PID.  */
3218
3219 int
3220 remove_breakpoints_pid (int pid)
3221 {
3222   struct bp_location *bl, **blp_tmp;
3223   int val;
3224   struct inferior *inf = find_inferior_pid (pid);
3225
3226   ALL_BP_LOCATIONS (bl, blp_tmp)
3227   {
3228     if (bl->pspace != inf->pspace)
3229       continue;
3230
3231     if (bl->owner->type == bp_dprintf)
3232       continue;
3233
3234     if (bl->inserted)
3235       {
3236         val = remove_breakpoint (bl, mark_uninserted);
3237         if (val != 0)
3238           return val;
3239       }
3240   }
3241   return 0;
3242 }
3243
3244 int
3245 reattach_breakpoints (int pid)
3246 {
3247   struct cleanup *old_chain;
3248   struct bp_location *bl, **blp_tmp;
3249   int val;
3250   struct ui_file *tmp_error_stream;
3251   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3252   struct inferior *inf;
3253   struct thread_info *tp;
3254
3255   tp = any_live_thread_of_process (pid);
3256   if (tp == NULL)
3257     return 1;
3258
3259   inf = find_inferior_pid (pid);
3260   old_chain = save_inferior_ptid ();
3261
3262   inferior_ptid = tp->ptid;
3263
3264   tmp_error_stream = mem_fileopen ();
3265   make_cleanup_ui_file_delete (tmp_error_stream);
3266
3267   ALL_BP_LOCATIONS (bl, blp_tmp)
3268   {
3269     if (bl->pspace != inf->pspace)
3270       continue;
3271
3272     if (bl->inserted)
3273       {
3274         bl->inserted = 0;
3275         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3276         if (val != 0)
3277           {
3278             do_cleanups (old_chain);
3279             return val;
3280           }
3281       }
3282   }
3283   do_cleanups (old_chain);
3284   return 0;
3285 }
3286
3287 static int internal_breakpoint_number = -1;
3288
3289 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3290    If INTERNAL is non-zero, the breakpoint number will be populated
3291    from internal_breakpoint_number and that variable decremented.
3292    Otherwise the breakpoint number will be populated from
3293    breakpoint_count and that value incremented.  Internal breakpoints
3294    do not set the internal var bpnum.  */
3295 static void
3296 set_breakpoint_number (int internal, struct breakpoint *b)
3297 {
3298   if (internal)
3299     b->number = internal_breakpoint_number--;
3300   else
3301     {
3302       set_breakpoint_count (breakpoint_count + 1);
3303       b->number = breakpoint_count;
3304     }
3305 }
3306
3307 static struct breakpoint *
3308 create_internal_breakpoint (struct gdbarch *gdbarch,
3309                             CORE_ADDR address, enum bptype type,
3310                             const struct breakpoint_ops *ops)
3311 {
3312   struct symtab_and_line sal;
3313   struct breakpoint *b;
3314
3315   init_sal (&sal);              /* Initialize to zeroes.  */
3316
3317   sal.pc = address;
3318   sal.section = find_pc_overlay (sal.pc);
3319   sal.pspace = current_program_space;
3320
3321   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3322   b->number = internal_breakpoint_number--;
3323   b->disposition = disp_donttouch;
3324
3325   return b;
3326 }
3327
3328 static const char *const longjmp_names[] =
3329   {
3330     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3331   };
3332 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3333
3334 /* Per-objfile data private to breakpoint.c.  */
3335 struct breakpoint_objfile_data
3336 {
3337   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3338   struct bound_minimal_symbol overlay_msym;
3339
3340   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3341   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3342
3343   /* True if we have looked for longjmp probes.  */
3344   int longjmp_searched;
3345
3346   /* SystemTap probe points for longjmp (if any).  */
3347   VEC (probe_p) *longjmp_probes;
3348
3349   /* Minimal symbol for "std::terminate()" (if any).  */
3350   struct bound_minimal_symbol terminate_msym;
3351
3352   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3353   struct bound_minimal_symbol exception_msym;
3354
3355   /* True if we have looked for exception probes.  */
3356   int exception_searched;
3357
3358   /* SystemTap probe points for unwinding (if any).  */
3359   VEC (probe_p) *exception_probes;
3360 };
3361
3362 static const struct objfile_data *breakpoint_objfile_key;
3363
3364 /* Minimal symbol not found sentinel.  */
3365 static struct minimal_symbol msym_not_found;
3366
3367 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3368
3369 static int
3370 msym_not_found_p (const struct minimal_symbol *msym)
3371 {
3372   return msym == &msym_not_found;
3373 }
3374
3375 /* Return per-objfile data needed by breakpoint.c.
3376    Allocate the data if necessary.  */
3377
3378 static struct breakpoint_objfile_data *
3379 get_breakpoint_objfile_data (struct objfile *objfile)
3380 {
3381   struct breakpoint_objfile_data *bp_objfile_data;
3382
3383   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3384   if (bp_objfile_data == NULL)
3385     {
3386       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3387                                        sizeof (*bp_objfile_data));
3388
3389       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3390       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3391     }
3392   return bp_objfile_data;
3393 }
3394
3395 static void
3396 free_breakpoint_probes (struct objfile *obj, void *data)
3397 {
3398   struct breakpoint_objfile_data *bp_objfile_data = data;
3399
3400   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3401   VEC_free (probe_p, bp_objfile_data->exception_probes);
3402 }
3403
3404 static void
3405 create_overlay_event_breakpoint (void)
3406 {
3407   struct objfile *objfile;
3408   const char *const func_name = "_ovly_debug_event";
3409
3410   ALL_OBJFILES (objfile)
3411     {
3412       struct breakpoint *b;
3413       struct breakpoint_objfile_data *bp_objfile_data;
3414       CORE_ADDR addr;
3415
3416       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3417
3418       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3419         continue;
3420
3421       if (bp_objfile_data->overlay_msym.minsym == NULL)
3422         {
3423           struct bound_minimal_symbol m;
3424
3425           m = lookup_minimal_symbol_text (func_name, objfile);
3426           if (m.minsym == NULL)
3427             {
3428               /* Avoid future lookups in this objfile.  */
3429               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3430               continue;
3431             }
3432           bp_objfile_data->overlay_msym = m;
3433         }
3434
3435       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3436       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3437                                       bp_overlay_event,
3438                                       &internal_breakpoint_ops);
3439       b->addr_string = xstrdup (func_name);
3440
3441       if (overlay_debugging == ovly_auto)
3442         {
3443           b->enable_state = bp_enabled;
3444           overlay_events_enabled = 1;
3445         }
3446       else
3447        {
3448          b->enable_state = bp_disabled;
3449          overlay_events_enabled = 0;
3450        }
3451     }
3452   update_global_location_list (UGLL_MAY_INSERT);
3453 }
3454
3455 static void
3456 create_longjmp_master_breakpoint (void)
3457 {
3458   struct program_space *pspace;
3459   struct cleanup *old_chain;
3460
3461   old_chain = save_current_program_space ();
3462
3463   ALL_PSPACES (pspace)
3464   {
3465     struct objfile *objfile;
3466
3467     set_current_program_space (pspace);
3468
3469     ALL_OBJFILES (objfile)
3470     {
3471       int i;
3472       struct gdbarch *gdbarch;
3473       struct breakpoint_objfile_data *bp_objfile_data;
3474
3475       gdbarch = get_objfile_arch (objfile);
3476
3477       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3478
3479       if (!bp_objfile_data->longjmp_searched)
3480         {
3481           VEC (probe_p) *ret;
3482
3483           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3484           if (ret != NULL)
3485             {
3486               /* We are only interested in checking one element.  */
3487               struct probe *p = VEC_index (probe_p, ret, 0);
3488
3489               if (!can_evaluate_probe_arguments (p))
3490                 {
3491                   /* We cannot use the probe interface here, because it does
3492                      not know how to evaluate arguments.  */
3493                   VEC_free (probe_p, ret);
3494                   ret = NULL;
3495                 }
3496             }
3497           bp_objfile_data->longjmp_probes = ret;
3498           bp_objfile_data->longjmp_searched = 1;
3499         }
3500
3501       if (bp_objfile_data->longjmp_probes != NULL)
3502         {
3503           int i;
3504           struct probe *probe;
3505           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3506
3507           for (i = 0;
3508                VEC_iterate (probe_p,
3509                             bp_objfile_data->longjmp_probes,
3510                             i, probe);
3511                ++i)
3512             {
3513               struct breakpoint *b;
3514
3515               b = create_internal_breakpoint (gdbarch,
3516                                               get_probe_address (probe,
3517                                                                  objfile),
3518                                               bp_longjmp_master,
3519                                               &internal_breakpoint_ops);
3520               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3521               b->enable_state = bp_disabled;
3522             }
3523
3524           continue;
3525         }
3526
3527       if (!gdbarch_get_longjmp_target_p (gdbarch))
3528         continue;
3529
3530       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3531         {
3532           struct breakpoint *b;
3533           const char *func_name;
3534           CORE_ADDR addr;
3535
3536           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3537             continue;
3538
3539           func_name = longjmp_names[i];
3540           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3541             {
3542               struct bound_minimal_symbol m;
3543
3544               m = lookup_minimal_symbol_text (func_name, objfile);
3545               if (m.minsym == NULL)
3546                 {
3547                   /* Prevent future lookups in this objfile.  */
3548                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3549                   continue;
3550                 }
3551               bp_objfile_data->longjmp_msym[i] = m;
3552             }
3553
3554           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3555           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3556                                           &internal_breakpoint_ops);
3557           b->addr_string = xstrdup (func_name);
3558           b->enable_state = bp_disabled;
3559         }
3560     }
3561   }
3562   update_global_location_list (UGLL_MAY_INSERT);
3563
3564   do_cleanups (old_chain);
3565 }
3566
3567 /* Create a master std::terminate breakpoint.  */
3568 static void
3569 create_std_terminate_master_breakpoint (void)
3570 {
3571   struct program_space *pspace;
3572   struct cleanup *old_chain;
3573   const char *const func_name = "std::terminate()";
3574
3575   old_chain = save_current_program_space ();
3576
3577   ALL_PSPACES (pspace)
3578   {
3579     struct objfile *objfile;
3580     CORE_ADDR addr;
3581
3582     set_current_program_space (pspace);
3583
3584     ALL_OBJFILES (objfile)
3585     {
3586       struct breakpoint *b;
3587       struct breakpoint_objfile_data *bp_objfile_data;
3588
3589       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3590
3591       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3592         continue;
3593
3594       if (bp_objfile_data->terminate_msym.minsym == NULL)
3595         {
3596           struct bound_minimal_symbol m;
3597
3598           m = lookup_minimal_symbol (func_name, NULL, objfile);
3599           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3600                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3601             {
3602               /* Prevent future lookups in this objfile.  */
3603               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3604               continue;
3605             }
3606           bp_objfile_data->terminate_msym = m;
3607         }
3608
3609       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3610       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3611                                       bp_std_terminate_master,
3612                                       &internal_breakpoint_ops);
3613       b->addr_string = xstrdup (func_name);
3614       b->enable_state = bp_disabled;
3615     }
3616   }
3617
3618   update_global_location_list (UGLL_MAY_INSERT);
3619
3620   do_cleanups (old_chain);
3621 }
3622
3623 /* Install a master breakpoint on the unwinder's debug hook.  */
3624
3625 static void
3626 create_exception_master_breakpoint (void)
3627 {
3628   struct objfile *objfile;
3629   const char *const func_name = "_Unwind_DebugHook";
3630
3631   ALL_OBJFILES (objfile)
3632     {
3633       struct breakpoint *b;
3634       struct gdbarch *gdbarch;
3635       struct breakpoint_objfile_data *bp_objfile_data;
3636       CORE_ADDR addr;
3637
3638       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3639
3640       /* We prefer the SystemTap probe point if it exists.  */
3641       if (!bp_objfile_data->exception_searched)
3642         {
3643           VEC (probe_p) *ret;
3644
3645           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3646
3647           if (ret != NULL)
3648             {
3649               /* We are only interested in checking one element.  */
3650               struct probe *p = VEC_index (probe_p, ret, 0);
3651
3652               if (!can_evaluate_probe_arguments (p))
3653                 {
3654                   /* We cannot use the probe interface here, because it does
3655                      not know how to evaluate arguments.  */
3656                   VEC_free (probe_p, ret);
3657                   ret = NULL;
3658                 }
3659             }
3660           bp_objfile_data->exception_probes = ret;
3661           bp_objfile_data->exception_searched = 1;
3662         }
3663
3664       if (bp_objfile_data->exception_probes != NULL)
3665         {
3666           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3667           int i;
3668           struct probe *probe;
3669
3670           for (i = 0;
3671                VEC_iterate (probe_p,
3672                             bp_objfile_data->exception_probes,
3673                             i, probe);
3674                ++i)
3675             {
3676               struct breakpoint *b;
3677
3678               b = create_internal_breakpoint (gdbarch,
3679                                               get_probe_address (probe,
3680                                                                  objfile),
3681                                               bp_exception_master,
3682                                               &internal_breakpoint_ops);
3683               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3684               b->enable_state = bp_disabled;
3685             }
3686
3687           continue;
3688         }
3689
3690       /* Otherwise, try the hook function.  */
3691
3692       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3693         continue;
3694
3695       gdbarch = get_objfile_arch (objfile);
3696
3697       if (bp_objfile_data->exception_msym.minsym == NULL)
3698         {
3699           struct bound_minimal_symbol debug_hook;
3700
3701           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3702           if (debug_hook.minsym == NULL)
3703             {
3704               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3705               continue;
3706             }
3707
3708           bp_objfile_data->exception_msym = debug_hook;
3709         }
3710
3711       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3712       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3713                                                  &current_target);
3714       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3715                                       &internal_breakpoint_ops);
3716       b->addr_string = xstrdup (func_name);
3717       b->enable_state = bp_disabled;
3718     }
3719
3720   update_global_location_list (UGLL_MAY_INSERT);
3721 }
3722
3723 void
3724 update_breakpoints_after_exec (void)
3725 {
3726   struct breakpoint *b, *b_tmp;
3727   struct bp_location *bploc, **bplocp_tmp;
3728
3729   /* We're about to delete breakpoints from GDB's lists.  If the
3730      INSERTED flag is true, GDB will try to lift the breakpoints by
3731      writing the breakpoints' "shadow contents" back into memory.  The
3732      "shadow contents" are NOT valid after an exec, so GDB should not
3733      do that.  Instead, the target is responsible from marking
3734      breakpoints out as soon as it detects an exec.  We don't do that
3735      here instead, because there may be other attempts to delete
3736      breakpoints after detecting an exec and before reaching here.  */
3737   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3738     if (bploc->pspace == current_program_space)
3739       gdb_assert (!bploc->inserted);
3740
3741   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3742   {
3743     if (b->pspace != current_program_space)
3744       continue;
3745
3746     /* Solib breakpoints must be explicitly reset after an exec().  */
3747     if (b->type == bp_shlib_event)
3748       {
3749         delete_breakpoint (b);
3750         continue;
3751       }
3752
3753     /* JIT breakpoints must be explicitly reset after an exec().  */
3754     if (b->type == bp_jit_event)
3755       {
3756         delete_breakpoint (b);
3757         continue;
3758       }
3759
3760     /* Thread event breakpoints must be set anew after an exec(),
3761        as must overlay event and longjmp master breakpoints.  */
3762     if (b->type == bp_thread_event || b->type == bp_overlay_event
3763         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3764         || b->type == bp_exception_master)
3765       {
3766         delete_breakpoint (b);
3767         continue;
3768       }
3769
3770     /* Step-resume breakpoints are meaningless after an exec().  */
3771     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3772       {
3773         delete_breakpoint (b);
3774         continue;
3775       }
3776
3777     /* Longjmp and longjmp-resume breakpoints are also meaningless
3778        after an exec.  */
3779     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3780         || b->type == bp_longjmp_call_dummy
3781         || b->type == bp_exception || b->type == bp_exception_resume)
3782       {
3783         delete_breakpoint (b);
3784         continue;
3785       }
3786
3787     if (b->type == bp_catchpoint)
3788       {
3789         /* For now, none of the bp_catchpoint breakpoints need to
3790            do anything at this point.  In the future, if some of
3791            the catchpoints need to something, we will need to add
3792            a new method, and call this method from here.  */
3793         continue;
3794       }
3795
3796     /* bp_finish is a special case.  The only way we ought to be able
3797        to see one of these when an exec() has happened, is if the user
3798        caught a vfork, and then said "finish".  Ordinarily a finish just
3799        carries them to the call-site of the current callee, by setting
3800        a temporary bp there and resuming.  But in this case, the finish
3801        will carry them entirely through the vfork & exec.
3802
3803        We don't want to allow a bp_finish to remain inserted now.  But
3804        we can't safely delete it, 'cause finish_command has a handle to
3805        the bp on a bpstat, and will later want to delete it.  There's a
3806        chance (and I've seen it happen) that if we delete the bp_finish
3807        here, that its storage will get reused by the time finish_command
3808        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3809        We really must allow finish_command to delete a bp_finish.
3810
3811        In the absence of a general solution for the "how do we know
3812        it's safe to delete something others may have handles to?"
3813        problem, what we'll do here is just uninsert the bp_finish, and
3814        let finish_command delete it.
3815
3816        (We know the bp_finish is "doomed" in the sense that it's
3817        momentary, and will be deleted as soon as finish_command sees
3818        the inferior stopped.  So it doesn't matter that the bp's
3819        address is probably bogus in the new a.out, unlike e.g., the
3820        solib breakpoints.)  */
3821
3822     if (b->type == bp_finish)
3823       {
3824         continue;
3825       }
3826
3827     /* Without a symbolic address, we have little hope of the
3828        pre-exec() address meaning the same thing in the post-exec()
3829        a.out.  */
3830     if (b->addr_string == NULL)
3831       {
3832         delete_breakpoint (b);
3833         continue;
3834       }
3835   }
3836   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3837   create_overlay_event_breakpoint ();
3838   create_longjmp_master_breakpoint ();
3839   create_std_terminate_master_breakpoint ();
3840   create_exception_master_breakpoint ();
3841 }
3842
3843 int
3844 detach_breakpoints (ptid_t ptid)
3845 {
3846   struct bp_location *bl, **blp_tmp;
3847   int val = 0;
3848   struct cleanup *old_chain = save_inferior_ptid ();
3849   struct inferior *inf = current_inferior ();
3850
3851   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3852     error (_("Cannot detach breakpoints of inferior_ptid"));
3853
3854   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3855   inferior_ptid = ptid;
3856   ALL_BP_LOCATIONS (bl, blp_tmp)
3857   {
3858     if (bl->pspace != inf->pspace)
3859       continue;
3860
3861     /* This function must physically remove breakpoints locations
3862        from the specified ptid, without modifying the breakpoint
3863        package's state.  Locations of type bp_loc_other are only
3864        maintained at GDB side.  So, there is no need to remove
3865        these bp_loc_other locations.  Moreover, removing these
3866        would modify the breakpoint package's state.  */
3867     if (bl->loc_type == bp_loc_other)
3868       continue;
3869
3870     if (bl->inserted)
3871       val |= remove_breakpoint_1 (bl, mark_inserted);
3872   }
3873
3874   /* Detach single-step breakpoints as well.  */
3875   detach_single_step_breakpoints ();
3876
3877   do_cleanups (old_chain);
3878   return val;
3879 }
3880
3881 /* Remove the breakpoint location BL from the current address space.
3882    Note that this is used to detach breakpoints from a child fork.
3883    When we get here, the child isn't in the inferior list, and neither
3884    do we have objects to represent its address space --- we should
3885    *not* look at bl->pspace->aspace here.  */
3886
3887 static int
3888 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3889 {
3890   int val;
3891
3892   /* BL is never in moribund_locations by our callers.  */
3893   gdb_assert (bl->owner != NULL);
3894
3895   if (bl->owner->enable_state == bp_permanent)
3896     /* Permanent breakpoints cannot be inserted or removed.  */
3897     return 0;
3898
3899   /* The type of none suggests that owner is actually deleted.
3900      This should not ever happen.  */
3901   gdb_assert (bl->owner->type != bp_none);
3902
3903   if (bl->loc_type == bp_loc_software_breakpoint
3904       || bl->loc_type == bp_loc_hardware_breakpoint)
3905     {
3906       /* "Normal" instruction breakpoint: either the standard
3907          trap-instruction bp (bp_breakpoint), or a
3908          bp_hardware_breakpoint.  */
3909
3910       /* First check to see if we have to handle an overlay.  */
3911       if (overlay_debugging == ovly_off
3912           || bl->section == NULL
3913           || !(section_is_overlay (bl->section)))
3914         {
3915           /* No overlay handling: just remove the breakpoint.  */
3916
3917           /* If we're trying to uninsert a memory breakpoint that we
3918              know is set in a dynamic object that is marked
3919              shlib_disabled, then either the dynamic object was
3920              removed with "remove-symbol-file" or with
3921              "nosharedlibrary".  In the former case, we don't know
3922              whether another dynamic object might have loaded over the
3923              breakpoint's address -- the user might well let us know
3924              about it next with add-symbol-file (the whole point of
3925              add-symbol-file is letting the user manually maintain a
3926              list of dynamically loaded objects).  If we have the
3927              breakpoint's shadow memory, that is, this is a software
3928              breakpoint managed by GDB, check whether the breakpoint
3929              is still inserted in memory, to avoid overwriting wrong
3930              code with stale saved shadow contents.  Note that HW
3931              breakpoints don't have shadow memory, as they're
3932              implemented using a mechanism that is not dependent on
3933              being able to modify the target's memory, and as such
3934              they should always be removed.  */
3935           if (bl->shlib_disabled
3936               && bl->target_info.shadow_len != 0
3937               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3938             val = 0;
3939           else
3940             val = bl->owner->ops->remove_location (bl);
3941         }
3942       else
3943         {
3944           /* This breakpoint is in an overlay section.
3945              Did we set a breakpoint at the LMA?  */
3946           if (!overlay_events_enabled)
3947               {
3948                 /* Yes -- overlay event support is not active, so we
3949                    should have set a breakpoint at the LMA.  Remove it.  
3950                 */
3951                 /* Ignore any failures: if the LMA is in ROM, we will
3952                    have already warned when we failed to insert it.  */
3953                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3954                   target_remove_hw_breakpoint (bl->gdbarch,
3955                                                &bl->overlay_target_info);
3956                 else
3957                   target_remove_breakpoint (bl->gdbarch,
3958                                             &bl->overlay_target_info);
3959               }
3960           /* Did we set a breakpoint at the VMA? 
3961              If so, we will have marked the breakpoint 'inserted'.  */
3962           if (bl->inserted)
3963             {
3964               /* Yes -- remove it.  Previously we did not bother to
3965                  remove the breakpoint if the section had been
3966                  unmapped, but let's not rely on that being safe.  We
3967                  don't know what the overlay manager might do.  */
3968
3969               /* However, we should remove *software* breakpoints only
3970                  if the section is still mapped, or else we overwrite
3971                  wrong code with the saved shadow contents.  */
3972               if (bl->loc_type == bp_loc_hardware_breakpoint
3973                   || section_is_mapped (bl->section))
3974                 val = bl->owner->ops->remove_location (bl);
3975               else
3976                 val = 0;
3977             }
3978           else
3979             {
3980               /* No -- not inserted, so no need to remove.  No error.  */
3981               val = 0;
3982             }
3983         }
3984
3985       /* In some cases, we might not be able to remove a breakpoint in
3986          a shared library that has already been removed, but we have
3987          not yet processed the shlib unload event.  Similarly for an
3988          unloaded add-symbol-file object - the user might not yet have
3989          had the chance to remove-symbol-file it.  shlib_disabled will
3990          be set if the library/object has already been removed, but
3991          the breakpoint hasn't been uninserted yet, e.g., after
3992          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3993          always-inserted mode.  */
3994       if (val
3995           && (bl->loc_type == bp_loc_software_breakpoint
3996               && (bl->shlib_disabled
3997                   || solib_name_from_address (bl->pspace, bl->address)
3998                   || shared_objfile_contains_address_p (bl->pspace,
3999                                                         bl->address))))
4000         val = 0;
4001
4002       if (val)
4003         return val;
4004       bl->inserted = (is == mark_inserted);
4005     }
4006   else if (bl->loc_type == bp_loc_hardware_watchpoint)
4007     {
4008       gdb_assert (bl->owner->ops != NULL
4009                   && bl->owner->ops->remove_location != NULL);
4010
4011       bl->inserted = (is == mark_inserted);
4012       bl->owner->ops->remove_location (bl);
4013
4014       /* Failure to remove any of the hardware watchpoints comes here.  */
4015       if ((is == mark_uninserted) && (bl->inserted))
4016         warning (_("Could not remove hardware watchpoint %d."),
4017                  bl->owner->number);
4018     }
4019   else if (bl->owner->type == bp_catchpoint
4020            && breakpoint_enabled (bl->owner)
4021            && !bl->duplicate)
4022     {
4023       gdb_assert (bl->owner->ops != NULL
4024                   && bl->owner->ops->remove_location != NULL);
4025
4026       val = bl->owner->ops->remove_location (bl);
4027       if (val)
4028         return val;
4029
4030       bl->inserted = (is == mark_inserted);
4031     }
4032
4033   return 0;
4034 }
4035
4036 static int
4037 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4038 {
4039   int ret;
4040   struct cleanup *old_chain;
4041
4042   /* BL is never in moribund_locations by our callers.  */
4043   gdb_assert (bl->owner != NULL);
4044
4045   if (bl->owner->enable_state == bp_permanent)
4046     /* Permanent breakpoints cannot be inserted or removed.  */
4047     return 0;
4048
4049   /* The type of none suggests that owner is actually deleted.
4050      This should not ever happen.  */
4051   gdb_assert (bl->owner->type != bp_none);
4052
4053   old_chain = save_current_space_and_thread ();
4054
4055   switch_to_program_space_and_thread (bl->pspace);
4056
4057   ret = remove_breakpoint_1 (bl, is);
4058
4059   do_cleanups (old_chain);
4060   return ret;
4061 }
4062
4063 /* Clear the "inserted" flag in all breakpoints.  */
4064
4065 void
4066 mark_breakpoints_out (void)
4067 {
4068   struct bp_location *bl, **blp_tmp;
4069
4070   ALL_BP_LOCATIONS (bl, blp_tmp)
4071     if (bl->pspace == current_program_space)
4072       bl->inserted = 0;
4073 }
4074
4075 /* Clear the "inserted" flag in all breakpoints and delete any
4076    breakpoints which should go away between runs of the program.
4077
4078    Plus other such housekeeping that has to be done for breakpoints
4079    between runs.
4080
4081    Note: this function gets called at the end of a run (by
4082    generic_mourn_inferior) and when a run begins (by
4083    init_wait_for_inferior).  */
4084
4085
4086
4087 void
4088 breakpoint_init_inferior (enum inf_context context)
4089 {
4090   struct breakpoint *b, *b_tmp;
4091   struct bp_location *bl, **blp_tmp;
4092   int ix;
4093   struct program_space *pspace = current_program_space;
4094
4095   /* If breakpoint locations are shared across processes, then there's
4096      nothing to do.  */
4097   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4098     return;
4099
4100   ALL_BP_LOCATIONS (bl, blp_tmp)
4101   {
4102     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4103     if (bl->pspace == pspace
4104         && bl->owner->enable_state != bp_permanent)
4105       bl->inserted = 0;
4106   }
4107
4108   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4109   {
4110     if (b->loc && b->loc->pspace != pspace)
4111       continue;
4112
4113     switch (b->type)
4114       {
4115       case bp_call_dummy:
4116       case bp_longjmp_call_dummy:
4117
4118         /* If the call dummy breakpoint is at the entry point it will
4119            cause problems when the inferior is rerun, so we better get
4120            rid of it.  */
4121
4122       case bp_watchpoint_scope:
4123
4124         /* Also get rid of scope breakpoints.  */
4125
4126       case bp_shlib_event:
4127
4128         /* Also remove solib event breakpoints.  Their addresses may
4129            have changed since the last time we ran the program.
4130            Actually we may now be debugging against different target;
4131            and so the solib backend that installed this breakpoint may
4132            not be used in by the target.  E.g.,
4133
4134            (gdb) file prog-linux
4135            (gdb) run               # native linux target
4136            ...
4137            (gdb) kill
4138            (gdb) file prog-win.exe
4139            (gdb) tar rem :9999     # remote Windows gdbserver.
4140         */
4141
4142       case bp_step_resume:
4143
4144         /* Also remove step-resume breakpoints.  */
4145
4146         delete_breakpoint (b);
4147         break;
4148
4149       case bp_watchpoint:
4150       case bp_hardware_watchpoint:
4151       case bp_read_watchpoint:
4152       case bp_access_watchpoint:
4153         {
4154           struct watchpoint *w = (struct watchpoint *) b;
4155
4156           /* Likewise for watchpoints on local expressions.  */
4157           if (w->exp_valid_block != NULL)
4158             delete_breakpoint (b);
4159           else if (context == inf_starting)
4160             {
4161               /* Reset val field to force reread of starting value in
4162                  insert_breakpoints.  */
4163               if (w->val)
4164                 value_free (w->val);
4165               w->val = NULL;
4166               w->val_valid = 0;
4167           }
4168         }
4169         break;
4170       default:
4171         break;
4172       }
4173   }
4174
4175   /* Get rid of the moribund locations.  */
4176   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4177     decref_bp_location (&bl);
4178   VEC_free (bp_location_p, moribund_locations);
4179 }
4180
4181 /* These functions concern about actual breakpoints inserted in the
4182    target --- to e.g. check if we need to do decr_pc adjustment or if
4183    we need to hop over the bkpt --- so we check for address space
4184    match, not program space.  */
4185
4186 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4187    exists at PC.  It returns ordinary_breakpoint_here if it's an
4188    ordinary breakpoint, or permanent_breakpoint_here if it's a
4189    permanent breakpoint.
4190    - When continuing from a location with an ordinary breakpoint, we
4191      actually single step once before calling insert_breakpoints.
4192    - When continuing from a location with a permanent breakpoint, we
4193      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4194      the target, to advance the PC past the breakpoint.  */
4195
4196 enum breakpoint_here
4197 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4198 {
4199   struct bp_location *bl, **blp_tmp;
4200   int any_breakpoint_here = 0;
4201
4202   ALL_BP_LOCATIONS (bl, blp_tmp)
4203     {
4204       if (bl->loc_type != bp_loc_software_breakpoint
4205           && bl->loc_type != bp_loc_hardware_breakpoint)
4206         continue;
4207
4208       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4209       if ((breakpoint_enabled (bl->owner)
4210            || bl->owner->enable_state == bp_permanent)
4211           && breakpoint_location_address_match (bl, aspace, pc))
4212         {
4213           if (overlay_debugging 
4214               && section_is_overlay (bl->section)
4215               && !section_is_mapped (bl->section))
4216             continue;           /* unmapped overlay -- can't be a match */
4217           else if (bl->owner->enable_state == bp_permanent)
4218             return permanent_breakpoint_here;
4219           else
4220             any_breakpoint_here = 1;
4221         }
4222     }
4223
4224   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4225 }
4226
4227 /* Return true if there's a moribund breakpoint at PC.  */
4228
4229 int
4230 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4231 {
4232   struct bp_location *loc;
4233   int ix;
4234
4235   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4236     if (breakpoint_location_address_match (loc, aspace, pc))
4237       return 1;
4238
4239   return 0;
4240 }
4241
4242 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4243    inserted using regular breakpoint_chain / bp_location array
4244    mechanism.  This does not check for single-step breakpoints, which
4245    are inserted and removed using direct target manipulation.  */
4246
4247 int
4248 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4249                                     CORE_ADDR pc)
4250 {
4251   struct bp_location *bl, **blp_tmp;
4252
4253   ALL_BP_LOCATIONS (bl, blp_tmp)
4254     {
4255       if (bl->loc_type != bp_loc_software_breakpoint
4256           && bl->loc_type != bp_loc_hardware_breakpoint)
4257         continue;
4258
4259       if (bl->inserted
4260           && breakpoint_location_address_match (bl, aspace, pc))
4261         {
4262           if (overlay_debugging 
4263               && section_is_overlay (bl->section)
4264               && !section_is_mapped (bl->section))
4265             continue;           /* unmapped overlay -- can't be a match */
4266           else
4267             return 1;
4268         }
4269     }
4270   return 0;
4271 }
4272
4273 /* Returns non-zero iff there's either regular breakpoint
4274    or a single step breakpoint inserted at PC.  */
4275
4276 int
4277 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4278 {
4279   if (regular_breakpoint_inserted_here_p (aspace, pc))
4280     return 1;
4281
4282   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4283     return 1;
4284
4285   return 0;
4286 }
4287
4288 /* Ignoring deprecated raw breakpoints, return non-zero iff there is a
4289    software breakpoint inserted at PC.  */
4290
4291 static struct bp_location *
4292 find_non_raw_software_breakpoint_inserted_here (struct address_space *aspace,
4293                                                 CORE_ADDR pc)
4294 {
4295   struct bp_location *bl, **blp_tmp;
4296
4297   ALL_BP_LOCATIONS (bl, blp_tmp)
4298     {
4299       if (bl->loc_type != bp_loc_software_breakpoint)
4300         continue;
4301
4302       if (bl->inserted
4303           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4304                                        aspace, pc))
4305         {
4306           if (overlay_debugging 
4307               && section_is_overlay (bl->section)
4308               && !section_is_mapped (bl->section))
4309             continue;           /* unmapped overlay -- can't be a match */
4310           else
4311             return bl;
4312         }
4313     }
4314
4315   return NULL;
4316 }
4317
4318 /* This function returns non-zero iff there is a software breakpoint
4319    inserted at PC.  */
4320
4321 int
4322 software_breakpoint_inserted_here_p (struct address_space *aspace,
4323                                      CORE_ADDR pc)
4324 {
4325   if (find_non_raw_software_breakpoint_inserted_here (aspace, pc) != NULL)
4326     return 1;
4327
4328   /* Also check for software single-step breakpoints.  */
4329   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4330     return 1;
4331
4332   return 0;
4333 }
4334
4335 int
4336 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4337                                        CORE_ADDR addr, ULONGEST len)
4338 {
4339   struct breakpoint *bpt;
4340
4341   ALL_BREAKPOINTS (bpt)
4342     {
4343       struct bp_location *loc;
4344
4345       if (bpt->type != bp_hardware_watchpoint
4346           && bpt->type != bp_access_watchpoint)
4347         continue;
4348
4349       if (!breakpoint_enabled (bpt))
4350         continue;
4351
4352       for (loc = bpt->loc; loc; loc = loc->next)
4353         if (loc->pspace->aspace == aspace && loc->inserted)
4354           {
4355             CORE_ADDR l, h;
4356
4357             /* Check for intersection.  */
4358             l = max (loc->address, addr);
4359             h = min (loc->address + loc->length, addr + len);
4360             if (l < h)
4361               return 1;
4362           }
4363     }
4364   return 0;
4365 }
4366
4367 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4368    PC is valid for process/thread PTID.  */
4369
4370 int
4371 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4372                          ptid_t ptid)
4373 {
4374   struct bp_location *bl, **blp_tmp;
4375   /* The thread and task IDs associated to PTID, computed lazily.  */
4376   int thread = -1;
4377   int task = 0;
4378   
4379   ALL_BP_LOCATIONS (bl, blp_tmp)
4380     {
4381       if (bl->loc_type != bp_loc_software_breakpoint
4382           && bl->loc_type != bp_loc_hardware_breakpoint)
4383         continue;
4384
4385       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4386       if (!breakpoint_enabled (bl->owner)
4387           && bl->owner->enable_state != bp_permanent)
4388         continue;
4389
4390       if (!breakpoint_location_address_match (bl, aspace, pc))
4391         continue;
4392
4393       if (bl->owner->thread != -1)
4394         {
4395           /* This is a thread-specific breakpoint.  Check that ptid
4396              matches that thread.  If thread hasn't been computed yet,
4397              it is now time to do so.  */
4398           if (thread == -1)
4399             thread = pid_to_thread_id (ptid);
4400           if (bl->owner->thread != thread)
4401             continue;
4402         }
4403
4404       if (bl->owner->task != 0)
4405         {
4406           /* This is a task-specific breakpoint.  Check that ptid
4407              matches that task.  If task hasn't been computed yet,
4408              it is now time to do so.  */
4409           if (task == 0)
4410             task = ada_get_task_number (ptid);
4411           if (bl->owner->task != task)
4412             continue;
4413         }
4414
4415       if (overlay_debugging 
4416           && section_is_overlay (bl->section)
4417           && !section_is_mapped (bl->section))
4418         continue;           /* unmapped overlay -- can't be a match */
4419
4420       return 1;
4421     }
4422
4423   return 0;
4424 }
4425 \f
4426
4427 /* bpstat stuff.  External routines' interfaces are documented
4428    in breakpoint.h.  */
4429
4430 int
4431 is_catchpoint (struct breakpoint *ep)
4432 {
4433   return (ep->type == bp_catchpoint);
4434 }
4435
4436 /* Frees any storage that is part of a bpstat.  Does not walk the
4437    'next' chain.  */
4438
4439 static void
4440 bpstat_free (bpstat bs)
4441 {
4442   if (bs->old_val != NULL)
4443     value_free (bs->old_val);
4444   decref_counted_command_line (&bs->commands);
4445   decref_bp_location (&bs->bp_location_at);
4446   xfree (bs);
4447 }
4448
4449 /* Clear a bpstat so that it says we are not at any breakpoint.
4450    Also free any storage that is part of a bpstat.  */
4451
4452 void
4453 bpstat_clear (bpstat *bsp)
4454 {
4455   bpstat p;
4456   bpstat q;
4457
4458   if (bsp == 0)
4459     return;
4460   p = *bsp;
4461   while (p != NULL)
4462     {
4463       q = p->next;
4464       bpstat_free (p);
4465       p = q;
4466     }
4467   *bsp = NULL;
4468 }
4469
4470 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4471    is part of the bpstat is copied as well.  */
4472
4473 bpstat
4474 bpstat_copy (bpstat bs)
4475 {
4476   bpstat p = NULL;
4477   bpstat tmp;
4478   bpstat retval = NULL;
4479
4480   if (bs == NULL)
4481     return bs;
4482
4483   for (; bs != NULL; bs = bs->next)
4484     {
4485       tmp = (bpstat) xmalloc (sizeof (*tmp));
4486       memcpy (tmp, bs, sizeof (*tmp));
4487       incref_counted_command_line (tmp->commands);
4488       incref_bp_location (tmp->bp_location_at);
4489       if (bs->old_val != NULL)
4490         {
4491           tmp->old_val = value_copy (bs->old_val);
4492           release_value (tmp->old_val);
4493         }
4494
4495       if (p == NULL)
4496         /* This is the first thing in the chain.  */
4497         retval = tmp;
4498       else
4499         p->next = tmp;
4500       p = tmp;
4501     }
4502   p->next = NULL;
4503   return retval;
4504 }
4505
4506 /* Find the bpstat associated with this breakpoint.  */
4507
4508 bpstat
4509 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4510 {
4511   if (bsp == NULL)
4512     return NULL;
4513
4514   for (; bsp != NULL; bsp = bsp->next)
4515     {
4516       if (bsp->breakpoint_at == breakpoint)
4517         return bsp;
4518     }
4519   return NULL;
4520 }
4521
4522 /* See breakpoint.h.  */
4523
4524 int
4525 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4526 {
4527   for (; bsp != NULL; bsp = bsp->next)
4528     {
4529       if (bsp->breakpoint_at == NULL)
4530         {
4531           /* A moribund location can never explain a signal other than
4532              GDB_SIGNAL_TRAP.  */
4533           if (sig == GDB_SIGNAL_TRAP)
4534             return 1;
4535         }
4536       else
4537         {
4538           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4539                                                         sig))
4540             return 1;
4541         }
4542     }
4543
4544   return 0;
4545 }
4546
4547 /* Put in *NUM the breakpoint number of the first breakpoint we are
4548    stopped at.  *BSP upon return is a bpstat which points to the
4549    remaining breakpoints stopped at (but which is not guaranteed to be
4550    good for anything but further calls to bpstat_num).
4551
4552    Return 0 if passed a bpstat which does not indicate any breakpoints.
4553    Return -1 if stopped at a breakpoint that has been deleted since
4554    we set it.
4555    Return 1 otherwise.  */
4556
4557 int
4558 bpstat_num (bpstat *bsp, int *num)
4559 {
4560   struct breakpoint *b;
4561
4562   if ((*bsp) == NULL)
4563     return 0;                   /* No more breakpoint values */
4564
4565   /* We assume we'll never have several bpstats that correspond to a
4566      single breakpoint -- otherwise, this function might return the
4567      same number more than once and this will look ugly.  */
4568   b = (*bsp)->breakpoint_at;
4569   *bsp = (*bsp)->next;
4570   if (b == NULL)
4571     return -1;                  /* breakpoint that's been deleted since */
4572
4573   *num = b->number;             /* We have its number */
4574   return 1;
4575 }
4576
4577 /* See breakpoint.h.  */
4578
4579 void
4580 bpstat_clear_actions (void)
4581 {
4582   struct thread_info *tp;
4583   bpstat bs;
4584
4585   if (ptid_equal (inferior_ptid, null_ptid))
4586     return;
4587
4588   tp = find_thread_ptid (inferior_ptid);
4589   if (tp == NULL)
4590     return;
4591
4592   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4593     {
4594       decref_counted_command_line (&bs->commands);
4595
4596       if (bs->old_val != NULL)
4597         {
4598           value_free (bs->old_val);
4599           bs->old_val = NULL;
4600         }
4601     }
4602 }
4603
4604 /* Called when a command is about to proceed the inferior.  */
4605
4606 static void
4607 breakpoint_about_to_proceed (void)
4608 {
4609   if (!ptid_equal (inferior_ptid, null_ptid))
4610     {
4611       struct thread_info *tp = inferior_thread ();
4612
4613       /* Allow inferior function calls in breakpoint commands to not
4614          interrupt the command list.  When the call finishes
4615          successfully, the inferior will be standing at the same
4616          breakpoint as if nothing happened.  */
4617       if (tp->control.in_infcall)
4618         return;
4619     }
4620
4621   breakpoint_proceeded = 1;
4622 }
4623
4624 /* Stub for cleaning up our state if we error-out of a breakpoint
4625    command.  */
4626 static void
4627 cleanup_executing_breakpoints (void *ignore)
4628 {
4629   executing_breakpoint_commands = 0;
4630 }
4631
4632 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4633    or its equivalent.  */
4634
4635 static int
4636 command_line_is_silent (struct command_line *cmd)
4637 {
4638   return cmd && (strcmp ("silent", cmd->line) == 0
4639                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4640 }
4641
4642 /* Execute all the commands associated with all the breakpoints at
4643    this location.  Any of these commands could cause the process to
4644    proceed beyond this point, etc.  We look out for such changes by
4645    checking the global "breakpoint_proceeded" after each command.
4646
4647    Returns true if a breakpoint command resumed the inferior.  In that
4648    case, it is the caller's responsibility to recall it again with the
4649    bpstat of the current thread.  */
4650
4651 static int
4652 bpstat_do_actions_1 (bpstat *bsp)
4653 {
4654   bpstat bs;
4655   struct cleanup *old_chain;
4656   int again = 0;
4657
4658   /* Avoid endless recursion if a `source' command is contained
4659      in bs->commands.  */
4660   if (executing_breakpoint_commands)
4661     return 0;
4662
4663   executing_breakpoint_commands = 1;
4664   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4665
4666   prevent_dont_repeat ();
4667
4668   /* This pointer will iterate over the list of bpstat's.  */
4669   bs = *bsp;
4670
4671   breakpoint_proceeded = 0;
4672   for (; bs != NULL; bs = bs->next)
4673     {
4674       struct counted_command_line *ccmd;
4675       struct command_line *cmd;
4676       struct cleanup *this_cmd_tree_chain;
4677
4678       /* Take ownership of the BSP's command tree, if it has one.
4679
4680          The command tree could legitimately contain commands like
4681          'step' and 'next', which call clear_proceed_status, which
4682          frees stop_bpstat's command tree.  To make sure this doesn't
4683          free the tree we're executing out from under us, we need to
4684          take ownership of the tree ourselves.  Since a given bpstat's
4685          commands are only executed once, we don't need to copy it; we
4686          can clear the pointer in the bpstat, and make sure we free
4687          the tree when we're done.  */
4688       ccmd = bs->commands;
4689       bs->commands = NULL;
4690       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4691       cmd = ccmd ? ccmd->commands : NULL;
4692       if (command_line_is_silent (cmd))
4693         {
4694           /* The action has been already done by bpstat_stop_status.  */
4695           cmd = cmd->next;
4696         }
4697
4698       while (cmd != NULL)
4699         {
4700           execute_control_command (cmd);
4701
4702           if (breakpoint_proceeded)
4703             break;
4704           else
4705             cmd = cmd->next;
4706         }
4707
4708       /* We can free this command tree now.  */
4709       do_cleanups (this_cmd_tree_chain);
4710
4711       if (breakpoint_proceeded)
4712         {
4713           if (target_can_async_p ())
4714             /* If we are in async mode, then the target might be still
4715                running, not stopped at any breakpoint, so nothing for
4716                us to do here -- just return to the event loop.  */
4717             ;
4718           else
4719             /* In sync mode, when execute_control_command returns
4720                we're already standing on the next breakpoint.
4721                Breakpoint commands for that stop were not run, since
4722                execute_command does not run breakpoint commands --
4723                only command_line_handler does, but that one is not
4724                involved in execution of breakpoint commands.  So, we
4725                can now execute breakpoint commands.  It should be
4726                noted that making execute_command do bpstat actions is
4727                not an option -- in this case we'll have recursive
4728                invocation of bpstat for each breakpoint with a
4729                command, and can easily blow up GDB stack.  Instead, we
4730                return true, which will trigger the caller to recall us
4731                with the new stop_bpstat.  */
4732             again = 1;
4733           break;
4734         }
4735     }
4736   do_cleanups (old_chain);
4737   return again;
4738 }
4739
4740 void
4741 bpstat_do_actions (void)
4742 {
4743   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4744
4745   /* Do any commands attached to breakpoint we are stopped at.  */
4746   while (!ptid_equal (inferior_ptid, null_ptid)
4747          && target_has_execution
4748          && !is_exited (inferior_ptid)
4749          && !is_executing (inferior_ptid))
4750     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4751        and only return when it is stopped at the next breakpoint, we
4752        keep doing breakpoint actions until it returns false to
4753        indicate the inferior was not resumed.  */
4754     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4755       break;
4756
4757   discard_cleanups (cleanup_if_error);
4758 }
4759
4760 /* Print out the (old or new) value associated with a watchpoint.  */
4761
4762 static void
4763 watchpoint_value_print (struct value *val, struct ui_file *stream)
4764 {
4765   if (val == NULL)
4766     fprintf_unfiltered (stream, _("<unreadable>"));
4767   else
4768     {
4769       struct value_print_options opts;
4770       get_user_print_options (&opts);
4771       value_print (val, stream, &opts);
4772     }
4773 }
4774
4775 /* Generic routine for printing messages indicating why we
4776    stopped.  The behavior of this function depends on the value
4777    'print_it' in the bpstat structure.  Under some circumstances we
4778    may decide not to print anything here and delegate the task to
4779    normal_stop().  */
4780
4781 static enum print_stop_action
4782 print_bp_stop_message (bpstat bs)
4783 {
4784   switch (bs->print_it)
4785     {
4786     case print_it_noop:
4787       /* Nothing should be printed for this bpstat entry.  */
4788       return PRINT_UNKNOWN;
4789       break;
4790
4791     case print_it_done:
4792       /* We still want to print the frame, but we already printed the
4793          relevant messages.  */
4794       return PRINT_SRC_AND_LOC;
4795       break;
4796
4797     case print_it_normal:
4798       {
4799         struct breakpoint *b = bs->breakpoint_at;
4800
4801         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4802            which has since been deleted.  */
4803         if (b == NULL)
4804           return PRINT_UNKNOWN;
4805
4806         /* Normal case.  Call the breakpoint's print_it method.  */
4807         return b->ops->print_it (bs);
4808       }
4809       break;
4810
4811     default:
4812       internal_error (__FILE__, __LINE__,
4813                       _("print_bp_stop_message: unrecognized enum value"));
4814       break;
4815     }
4816 }
4817
4818 /* A helper function that prints a shared library stopped event.  */
4819
4820 static void
4821 print_solib_event (int is_catchpoint)
4822 {
4823   int any_deleted
4824     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4825   int any_added
4826     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4827
4828   if (!is_catchpoint)
4829     {
4830       if (any_added || any_deleted)
4831         ui_out_text (current_uiout,
4832                      _("Stopped due to shared library event:\n"));
4833       else
4834         ui_out_text (current_uiout,
4835                      _("Stopped due to shared library event (no "
4836                        "libraries added or removed)\n"));
4837     }
4838
4839   if (ui_out_is_mi_like_p (current_uiout))
4840     ui_out_field_string (current_uiout, "reason",
4841                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4842
4843   if (any_deleted)
4844     {
4845       struct cleanup *cleanup;
4846       char *name;
4847       int ix;
4848
4849       ui_out_text (current_uiout, _("  Inferior unloaded "));
4850       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4851                                                     "removed");
4852       for (ix = 0;
4853            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4854                         ix, name);
4855            ++ix)
4856         {
4857           if (ix > 0)
4858             ui_out_text (current_uiout, "    ");
4859           ui_out_field_string (current_uiout, "library", name);
4860           ui_out_text (current_uiout, "\n");
4861         }
4862
4863       do_cleanups (cleanup);
4864     }
4865
4866   if (any_added)
4867     {
4868       struct so_list *iter;
4869       int ix;
4870       struct cleanup *cleanup;
4871
4872       ui_out_text (current_uiout, _("  Inferior loaded "));
4873       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4874                                                     "added");
4875       for (ix = 0;
4876            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4877                         ix, iter);
4878            ++ix)
4879         {
4880           if (ix > 0)
4881             ui_out_text (current_uiout, "    ");
4882           ui_out_field_string (current_uiout, "library", iter->so_name);
4883           ui_out_text (current_uiout, "\n");
4884         }
4885
4886       do_cleanups (cleanup);
4887     }
4888 }
4889
4890 /* Print a message indicating what happened.  This is called from
4891    normal_stop().  The input to this routine is the head of the bpstat
4892    list - a list of the eventpoints that caused this stop.  KIND is
4893    the target_waitkind for the stopping event.  This
4894    routine calls the generic print routine for printing a message
4895    about reasons for stopping.  This will print (for example) the
4896    "Breakpoint n," part of the output.  The return value of this
4897    routine is one of:
4898
4899    PRINT_UNKNOWN: Means we printed nothing.
4900    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4901    code to print the location.  An example is 
4902    "Breakpoint 1, " which should be followed by
4903    the location.
4904    PRINT_SRC_ONLY: Means we printed something, but there is no need
4905    to also print the location part of the message.
4906    An example is the catch/throw messages, which
4907    don't require a location appended to the end.
4908    PRINT_NOTHING: We have done some printing and we don't need any 
4909    further info to be printed.  */
4910
4911 enum print_stop_action
4912 bpstat_print (bpstat bs, int kind)
4913 {
4914   int val;
4915
4916   /* Maybe another breakpoint in the chain caused us to stop.
4917      (Currently all watchpoints go on the bpstat whether hit or not.
4918      That probably could (should) be changed, provided care is taken
4919      with respect to bpstat_explains_signal).  */
4920   for (; bs; bs = bs->next)
4921     {
4922       val = print_bp_stop_message (bs);
4923       if (val == PRINT_SRC_ONLY 
4924           || val == PRINT_SRC_AND_LOC 
4925           || val == PRINT_NOTHING)
4926         return val;
4927     }
4928
4929   /* If we had hit a shared library event breakpoint,
4930      print_bp_stop_message would print out this message.  If we hit an
4931      OS-level shared library event, do the same thing.  */
4932   if (kind == TARGET_WAITKIND_LOADED)
4933     {
4934       print_solib_event (0);
4935       return PRINT_NOTHING;
4936     }
4937
4938   /* We reached the end of the chain, or we got a null BS to start
4939      with and nothing was printed.  */
4940   return PRINT_UNKNOWN;
4941 }
4942
4943 /* Evaluate the expression EXP and return 1 if value is zero.
4944    This returns the inverse of the condition because it is called
4945    from catch_errors which returns 0 if an exception happened, and if an
4946    exception happens we want execution to stop.
4947    The argument is a "struct expression *" that has been cast to a
4948    "void *" to make it pass through catch_errors.  */
4949
4950 static int
4951 breakpoint_cond_eval (void *exp)
4952 {
4953   struct value *mark = value_mark ();
4954   int i = !value_true (evaluate_expression ((struct expression *) exp));
4955
4956   value_free_to_mark (mark);
4957   return i;
4958 }
4959
4960 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4961
4962 static bpstat
4963 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4964 {
4965   bpstat bs;
4966
4967   bs = (bpstat) xmalloc (sizeof (*bs));
4968   bs->next = NULL;
4969   **bs_link_pointer = bs;
4970   *bs_link_pointer = &bs->next;
4971   bs->breakpoint_at = bl->owner;
4972   bs->bp_location_at = bl;
4973   incref_bp_location (bl);
4974   /* If the condition is false, etc., don't do the commands.  */
4975   bs->commands = NULL;
4976   bs->old_val = NULL;
4977   bs->print_it = print_it_normal;
4978   return bs;
4979 }
4980 \f
4981 /* The target has stopped with waitstatus WS.  Check if any hardware
4982    watchpoints have triggered, according to the target.  */
4983
4984 int
4985 watchpoints_triggered (struct target_waitstatus *ws)
4986 {
4987   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4988   CORE_ADDR addr;
4989   struct breakpoint *b;
4990
4991   if (!stopped_by_watchpoint)
4992     {
4993       /* We were not stopped by a watchpoint.  Mark all watchpoints
4994          as not triggered.  */
4995       ALL_BREAKPOINTS (b)
4996         if (is_hardware_watchpoint (b))
4997           {
4998             struct watchpoint *w = (struct watchpoint *) b;
4999
5000             w->watchpoint_triggered = watch_triggered_no;
5001           }
5002
5003       return 0;
5004     }
5005
5006   if (!target_stopped_data_address (&current_target, &addr))
5007     {
5008       /* We were stopped by a watchpoint, but we don't know where.
5009          Mark all watchpoints as unknown.  */
5010       ALL_BREAKPOINTS (b)
5011         if (is_hardware_watchpoint (b))
5012           {
5013             struct watchpoint *w = (struct watchpoint *) b;
5014
5015             w->watchpoint_triggered = watch_triggered_unknown;
5016           }
5017
5018       return 1;
5019     }
5020
5021   /* The target could report the data address.  Mark watchpoints
5022      affected by this data address as triggered, and all others as not
5023      triggered.  */
5024
5025   ALL_BREAKPOINTS (b)
5026     if (is_hardware_watchpoint (b))
5027       {
5028         struct watchpoint *w = (struct watchpoint *) b;
5029         struct bp_location *loc;
5030
5031         w->watchpoint_triggered = watch_triggered_no;
5032         for (loc = b->loc; loc; loc = loc->next)
5033           {
5034             if (is_masked_watchpoint (b))
5035               {
5036                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
5037                 CORE_ADDR start = loc->address & w->hw_wp_mask;
5038
5039                 if (newaddr == start)
5040                   {
5041                     w->watchpoint_triggered = watch_triggered_yes;
5042                     break;
5043                   }
5044               }
5045             /* Exact match not required.  Within range is sufficient.  */
5046             else if (target_watchpoint_addr_within_range (&current_target,
5047                                                          addr, loc->address,
5048                                                          loc->length))
5049               {
5050                 w->watchpoint_triggered = watch_triggered_yes;
5051                 break;
5052               }
5053           }
5054       }
5055
5056   return 1;
5057 }
5058
5059 /* Possible return values for watchpoint_check (this can't be an enum
5060    because of check_errors).  */
5061 /* The watchpoint has been deleted.  */
5062 #define WP_DELETED 1
5063 /* The value has changed.  */
5064 #define WP_VALUE_CHANGED 2
5065 /* The value has not changed.  */
5066 #define WP_VALUE_NOT_CHANGED 3
5067 /* Ignore this watchpoint, no matter if the value changed or not.  */
5068 #define WP_IGNORE 4
5069
5070 #define BP_TEMPFLAG 1
5071 #define BP_HARDWAREFLAG 2
5072
5073 /* Evaluate watchpoint condition expression and check if its value
5074    changed.
5075
5076    P should be a pointer to struct bpstat, but is defined as a void *
5077    in order for this function to be usable with catch_errors.  */
5078
5079 static int
5080 watchpoint_check (void *p)
5081 {
5082   bpstat bs = (bpstat) p;
5083   struct watchpoint *b;
5084   struct frame_info *fr;
5085   int within_current_scope;
5086
5087   /* BS is built from an existing struct breakpoint.  */
5088   gdb_assert (bs->breakpoint_at != NULL);
5089   b = (struct watchpoint *) bs->breakpoint_at;
5090
5091   /* If this is a local watchpoint, we only want to check if the
5092      watchpoint frame is in scope if the current thread is the thread
5093      that was used to create the watchpoint.  */
5094   if (!watchpoint_in_thread_scope (b))
5095     return WP_IGNORE;
5096
5097   if (b->exp_valid_block == NULL)
5098     within_current_scope = 1;
5099   else
5100     {
5101       struct frame_info *frame = get_current_frame ();
5102       struct gdbarch *frame_arch = get_frame_arch (frame);
5103       CORE_ADDR frame_pc = get_frame_pc (frame);
5104
5105       /* in_function_epilogue_p() returns a non-zero value if we're
5106          still in the function but the stack frame has already been
5107          invalidated.  Since we can't rely on the values of local
5108          variables after the stack has been destroyed, we are treating
5109          the watchpoint in that state as `not changed' without further
5110          checking.  Don't mark watchpoints as changed if the current
5111          frame is in an epilogue - even if they are in some other
5112          frame, our view of the stack is likely to be wrong and
5113          frame_find_by_id could error out.  */
5114       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
5115         return WP_IGNORE;
5116
5117       fr = frame_find_by_id (b->watchpoint_frame);
5118       within_current_scope = (fr != NULL);
5119
5120       /* If we've gotten confused in the unwinder, we might have
5121          returned a frame that can't describe this variable.  */
5122       if (within_current_scope)
5123         {
5124           struct symbol *function;
5125
5126           function = get_frame_function (fr);
5127           if (function == NULL
5128               || !contained_in (b->exp_valid_block,
5129                                 SYMBOL_BLOCK_VALUE (function)))
5130             within_current_scope = 0;
5131         }
5132
5133       if (within_current_scope)
5134         /* If we end up stopping, the current frame will get selected
5135            in normal_stop.  So this call to select_frame won't affect
5136            the user.  */
5137         select_frame (fr);
5138     }
5139
5140   if (within_current_scope)
5141     {
5142       /* We use value_{,free_to_}mark because it could be a *long*
5143          time before we return to the command level and call
5144          free_all_values.  We can't call free_all_values because we
5145          might be in the middle of evaluating a function call.  */
5146
5147       int pc = 0;
5148       struct value *mark;
5149       struct value *new_val;
5150
5151       if (is_masked_watchpoint (&b->base))
5152         /* Since we don't know the exact trigger address (from
5153            stopped_data_address), just tell the user we've triggered
5154            a mask watchpoint.  */
5155         return WP_VALUE_CHANGED;
5156
5157       mark = value_mark ();
5158       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5159
5160       if (b->val_bitsize != 0)
5161         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5162
5163       /* We use value_equal_contents instead of value_equal because
5164          the latter coerces an array to a pointer, thus comparing just
5165          the address of the array instead of its contents.  This is
5166          not what we want.  */
5167       if ((b->val != NULL) != (new_val != NULL)
5168           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5169         {
5170           if (new_val != NULL)
5171             {
5172               release_value (new_val);
5173               value_free_to_mark (mark);
5174             }
5175           bs->old_val = b->val;
5176           b->val = new_val;
5177           b->val_valid = 1;
5178           return WP_VALUE_CHANGED;
5179         }
5180       else
5181         {
5182           /* Nothing changed.  */
5183           value_free_to_mark (mark);
5184           return WP_VALUE_NOT_CHANGED;
5185         }
5186     }
5187   else
5188     {
5189       struct ui_out *uiout = current_uiout;
5190
5191       /* This seems like the only logical thing to do because
5192          if we temporarily ignored the watchpoint, then when
5193          we reenter the block in which it is valid it contains
5194          garbage (in the case of a function, it may have two
5195          garbage values, one before and one after the prologue).
5196          So we can't even detect the first assignment to it and
5197          watch after that (since the garbage may or may not equal
5198          the first value assigned).  */
5199       /* We print all the stop information in
5200          breakpoint_ops->print_it, but in this case, by the time we
5201          call breakpoint_ops->print_it this bp will be deleted
5202          already.  So we have no choice but print the information
5203          here.  */
5204       if (ui_out_is_mi_like_p (uiout))
5205         ui_out_field_string
5206           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5207       ui_out_text (uiout, "\nWatchpoint ");
5208       ui_out_field_int (uiout, "wpnum", b->base.number);
5209       ui_out_text (uiout,
5210                    " deleted because the program has left the block in\n\
5211 which its expression is valid.\n");     
5212
5213       /* Make sure the watchpoint's commands aren't executed.  */
5214       decref_counted_command_line (&b->base.commands);
5215       watchpoint_del_at_next_stop (b);
5216
5217       return WP_DELETED;
5218     }
5219 }
5220
5221 /* Return true if it looks like target has stopped due to hitting
5222    breakpoint location BL.  This function does not check if we should
5223    stop, only if BL explains the stop.  */
5224
5225 static int
5226 bpstat_check_location (const struct bp_location *bl,
5227                        struct address_space *aspace, CORE_ADDR bp_addr,
5228                        const struct target_waitstatus *ws)
5229 {
5230   struct breakpoint *b = bl->owner;
5231
5232   /* BL is from an existing breakpoint.  */
5233   gdb_assert (b != NULL);
5234
5235   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5236 }
5237
5238 /* Determine if the watched values have actually changed, and we
5239    should stop.  If not, set BS->stop to 0.  */
5240
5241 static void
5242 bpstat_check_watchpoint (bpstat bs)
5243 {
5244   const struct bp_location *bl;
5245   struct watchpoint *b;
5246
5247   /* BS is built for existing struct breakpoint.  */
5248   bl = bs->bp_location_at;
5249   gdb_assert (bl != NULL);
5250   b = (struct watchpoint *) bs->breakpoint_at;
5251   gdb_assert (b != NULL);
5252
5253     {
5254       int must_check_value = 0;
5255       
5256       if (b->base.type == bp_watchpoint)
5257         /* For a software watchpoint, we must always check the
5258            watched value.  */
5259         must_check_value = 1;
5260       else if (b->watchpoint_triggered == watch_triggered_yes)
5261         /* We have a hardware watchpoint (read, write, or access)
5262            and the target earlier reported an address watched by
5263            this watchpoint.  */
5264         must_check_value = 1;
5265       else if (b->watchpoint_triggered == watch_triggered_unknown
5266                && b->base.type == bp_hardware_watchpoint)
5267         /* We were stopped by a hardware watchpoint, but the target could
5268            not report the data address.  We must check the watchpoint's
5269            value.  Access and read watchpoints are out of luck; without
5270            a data address, we can't figure it out.  */
5271         must_check_value = 1;
5272
5273       if (must_check_value)
5274         {
5275           char *message
5276             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5277                           b->base.number);
5278           struct cleanup *cleanups = make_cleanup (xfree, message);
5279           int e = catch_errors (watchpoint_check, bs, message,
5280                                 RETURN_MASK_ALL);
5281           do_cleanups (cleanups);
5282           switch (e)
5283             {
5284             case WP_DELETED:
5285               /* We've already printed what needs to be printed.  */
5286               bs->print_it = print_it_done;
5287               /* Stop.  */
5288               break;
5289             case WP_IGNORE:
5290               bs->print_it = print_it_noop;
5291               bs->stop = 0;
5292               break;
5293             case WP_VALUE_CHANGED:
5294               if (b->base.type == bp_read_watchpoint)
5295                 {
5296                   /* There are two cases to consider here:
5297
5298                      1. We're watching the triggered memory for reads.
5299                      In that case, trust the target, and always report
5300                      the watchpoint hit to the user.  Even though
5301                      reads don't cause value changes, the value may
5302                      have changed since the last time it was read, and
5303                      since we're not trapping writes, we will not see
5304                      those, and as such we should ignore our notion of
5305                      old value.
5306
5307                      2. We're watching the triggered memory for both
5308                      reads and writes.  There are two ways this may
5309                      happen:
5310
5311                      2.1. This is a target that can't break on data
5312                      reads only, but can break on accesses (reads or
5313                      writes), such as e.g., x86.  We detect this case
5314                      at the time we try to insert read watchpoints.
5315
5316                      2.2. Otherwise, the target supports read
5317                      watchpoints, but, the user set an access or write
5318                      watchpoint watching the same memory as this read
5319                      watchpoint.
5320
5321                      If we're watching memory writes as well as reads,
5322                      ignore watchpoint hits when we find that the
5323                      value hasn't changed, as reads don't cause
5324                      changes.  This still gives false positives when
5325                      the program writes the same value to memory as
5326                      what there was already in memory (we will confuse
5327                      it for a read), but it's much better than
5328                      nothing.  */
5329
5330                   int other_write_watchpoint = 0;
5331
5332                   if (bl->watchpoint_type == hw_read)
5333                     {
5334                       struct breakpoint *other_b;
5335
5336                       ALL_BREAKPOINTS (other_b)
5337                         if (other_b->type == bp_hardware_watchpoint
5338                             || other_b->type == bp_access_watchpoint)
5339                           {
5340                             struct watchpoint *other_w =
5341                               (struct watchpoint *) other_b;
5342
5343                             if (other_w->watchpoint_triggered
5344                                 == watch_triggered_yes)
5345                               {
5346                                 other_write_watchpoint = 1;
5347                                 break;
5348                               }
5349                           }
5350                     }
5351
5352                   if (other_write_watchpoint
5353                       || bl->watchpoint_type == hw_access)
5354                     {
5355                       /* We're watching the same memory for writes,
5356                          and the value changed since the last time we
5357                          updated it, so this trap must be for a write.
5358                          Ignore it.  */
5359                       bs->print_it = print_it_noop;
5360                       bs->stop = 0;
5361                     }
5362                 }
5363               break;
5364             case WP_VALUE_NOT_CHANGED:
5365               if (b->base.type == bp_hardware_watchpoint
5366                   || b->base.type == bp_watchpoint)
5367                 {
5368                   /* Don't stop: write watchpoints shouldn't fire if
5369                      the value hasn't changed.  */
5370                   bs->print_it = print_it_noop;
5371                   bs->stop = 0;
5372                 }
5373               /* Stop.  */
5374               break;
5375             default:
5376               /* Can't happen.  */
5377             case 0:
5378               /* Error from catch_errors.  */
5379               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5380               watchpoint_del_at_next_stop (b);
5381               /* We've already printed what needs to be printed.  */
5382               bs->print_it = print_it_done;
5383               break;
5384             }
5385         }
5386       else      /* must_check_value == 0 */
5387         {
5388           /* This is a case where some watchpoint(s) triggered, but
5389              not at the address of this watchpoint, or else no
5390              watchpoint triggered after all.  So don't print
5391              anything for this watchpoint.  */
5392           bs->print_it = print_it_noop;
5393           bs->stop = 0;
5394         }
5395     }
5396 }
5397
5398 /* For breakpoints that are currently marked as telling gdb to stop,
5399    check conditions (condition proper, frame, thread and ignore count)
5400    of breakpoint referred to by BS.  If we should not stop for this
5401    breakpoint, set BS->stop to 0.  */
5402
5403 static void
5404 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5405 {
5406   const struct bp_location *bl;
5407   struct breakpoint *b;
5408   int value_is_zero = 0;
5409   struct expression *cond;
5410
5411   gdb_assert (bs->stop);
5412
5413   /* BS is built for existing struct breakpoint.  */
5414   bl = bs->bp_location_at;
5415   gdb_assert (bl != NULL);
5416   b = bs->breakpoint_at;
5417   gdb_assert (b != NULL);
5418
5419   /* Even if the target evaluated the condition on its end and notified GDB, we
5420      need to do so again since GDB does not know if we stopped due to a
5421      breakpoint or a single step breakpoint.  */
5422
5423   if (frame_id_p (b->frame_id)
5424       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5425     {
5426       bs->stop = 0;
5427       return;
5428     }
5429
5430   /* If this is a thread/task-specific breakpoint, don't waste cpu
5431      evaluating the condition if this isn't the specified
5432      thread/task.  */
5433   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5434       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5435
5436     {
5437       bs->stop = 0;
5438       return;
5439     }
5440
5441   /* Evaluate extension language breakpoints that have a "stop" method
5442      implemented.  */
5443   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5444
5445   if (is_watchpoint (b))
5446     {
5447       struct watchpoint *w = (struct watchpoint *) b;
5448
5449       cond = w->cond_exp;
5450     }
5451   else
5452     cond = bl->cond;
5453
5454   if (cond && b->disposition != disp_del_at_next_stop)
5455     {
5456       int within_current_scope = 1;
5457       struct watchpoint * w;
5458
5459       /* We use value_mark and value_free_to_mark because it could
5460          be a long time before we return to the command level and
5461          call free_all_values.  We can't call free_all_values
5462          because we might be in the middle of evaluating a
5463          function call.  */
5464       struct value *mark = value_mark ();
5465
5466       if (is_watchpoint (b))
5467         w = (struct watchpoint *) b;
5468       else
5469         w = NULL;
5470
5471       /* Need to select the frame, with all that implies so that
5472          the conditions will have the right context.  Because we
5473          use the frame, we will not see an inlined function's
5474          variables when we arrive at a breakpoint at the start
5475          of the inlined function; the current frame will be the
5476          call site.  */
5477       if (w == NULL || w->cond_exp_valid_block == NULL)
5478         select_frame (get_current_frame ());
5479       else
5480         {
5481           struct frame_info *frame;
5482
5483           /* For local watchpoint expressions, which particular
5484              instance of a local is being watched matters, so we
5485              keep track of the frame to evaluate the expression
5486              in.  To evaluate the condition however, it doesn't
5487              really matter which instantiation of the function
5488              where the condition makes sense triggers the
5489              watchpoint.  This allows an expression like "watch
5490              global if q > 10" set in `func', catch writes to
5491              global on all threads that call `func', or catch
5492              writes on all recursive calls of `func' by a single
5493              thread.  We simply always evaluate the condition in
5494              the innermost frame that's executing where it makes
5495              sense to evaluate the condition.  It seems
5496              intuitive.  */
5497           frame = block_innermost_frame (w->cond_exp_valid_block);
5498           if (frame != NULL)
5499             select_frame (frame);
5500           else
5501             within_current_scope = 0;
5502         }
5503       if (within_current_scope)
5504         value_is_zero
5505           = catch_errors (breakpoint_cond_eval, cond,
5506                           "Error in testing breakpoint condition:\n",
5507                           RETURN_MASK_ALL);
5508       else
5509         {
5510           warning (_("Watchpoint condition cannot be tested "
5511                      "in the current scope"));
5512           /* If we failed to set the right context for this
5513              watchpoint, unconditionally report it.  */
5514           value_is_zero = 0;
5515         }
5516       /* FIXME-someday, should give breakpoint #.  */
5517       value_free_to_mark (mark);
5518     }
5519
5520   if (cond && value_is_zero)
5521     {
5522       bs->stop = 0;
5523     }
5524   else if (b->ignore_count > 0)
5525     {
5526       b->ignore_count--;
5527       bs->stop = 0;
5528       /* Increase the hit count even though we don't stop.  */
5529       ++(b->hit_count);
5530       observer_notify_breakpoint_modified (b);
5531     }   
5532 }
5533
5534
5535 /* Get a bpstat associated with having just stopped at address
5536    BP_ADDR in thread PTID.
5537
5538    Determine whether we stopped at a breakpoint, etc, or whether we
5539    don't understand this stop.  Result is a chain of bpstat's such
5540    that:
5541
5542    if we don't understand the stop, the result is a null pointer.
5543
5544    if we understand why we stopped, the result is not null.
5545
5546    Each element of the chain refers to a particular breakpoint or
5547    watchpoint at which we have stopped.  (We may have stopped for
5548    several reasons concurrently.)
5549
5550    Each element of the chain has valid next, breakpoint_at,
5551    commands, FIXME??? fields.  */
5552
5553 bpstat
5554 bpstat_stop_status (struct address_space *aspace,
5555                     CORE_ADDR bp_addr, ptid_t ptid,
5556                     const struct target_waitstatus *ws)
5557 {
5558   struct breakpoint *b = NULL;
5559   struct bp_location *bl;
5560   struct bp_location *loc;
5561   /* First item of allocated bpstat's.  */
5562   bpstat bs_head = NULL, *bs_link = &bs_head;
5563   /* Pointer to the last thing in the chain currently.  */
5564   bpstat bs;
5565   int ix;
5566   int need_remove_insert;
5567   int removed_any;
5568
5569   /* First, build the bpstat chain with locations that explain a
5570      target stop, while being careful to not set the target running,
5571      as that may invalidate locations (in particular watchpoint
5572      locations are recreated).  Resuming will happen here with
5573      breakpoint conditions or watchpoint expressions that include
5574      inferior function calls.  */
5575
5576   ALL_BREAKPOINTS (b)
5577     {
5578       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5579         continue;
5580
5581       for (bl = b->loc; bl != NULL; bl = bl->next)
5582         {
5583           /* For hardware watchpoints, we look only at the first
5584              location.  The watchpoint_check function will work on the
5585              entire expression, not the individual locations.  For
5586              read watchpoints, the watchpoints_triggered function has
5587              checked all locations already.  */
5588           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5589             break;
5590
5591           if (!bl->enabled || bl->shlib_disabled)
5592             continue;
5593
5594           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5595             continue;
5596
5597           /* Come here if it's a watchpoint, or if the break address
5598              matches.  */
5599
5600           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5601                                                    explain stop.  */
5602
5603           /* Assume we stop.  Should we find a watchpoint that is not
5604              actually triggered, or if the condition of the breakpoint
5605              evaluates as false, we'll reset 'stop' to 0.  */
5606           bs->stop = 1;
5607           bs->print = 1;
5608
5609           /* If this is a scope breakpoint, mark the associated
5610              watchpoint as triggered so that we will handle the
5611              out-of-scope event.  We'll get to the watchpoint next
5612              iteration.  */
5613           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5614             {
5615               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5616
5617               w->watchpoint_triggered = watch_triggered_yes;
5618             }
5619         }
5620     }
5621
5622   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5623     {
5624       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5625         {
5626           bs = bpstat_alloc (loc, &bs_link);
5627           /* For hits of moribund locations, we should just proceed.  */
5628           bs->stop = 0;
5629           bs->print = 0;
5630           bs->print_it = print_it_noop;
5631         }
5632     }
5633
5634   /* A bit of special processing for shlib breakpoints.  We need to
5635      process solib loading here, so that the lists of loaded and
5636      unloaded libraries are correct before we handle "catch load" and
5637      "catch unload".  */
5638   for (bs = bs_head; bs != NULL; bs = bs->next)
5639     {
5640       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5641         {
5642           handle_solib_event ();
5643           break;
5644         }
5645     }
5646
5647   /* Now go through the locations that caused the target to stop, and
5648      check whether we're interested in reporting this stop to higher
5649      layers, or whether we should resume the target transparently.  */
5650
5651   removed_any = 0;
5652
5653   for (bs = bs_head; bs != NULL; bs = bs->next)
5654     {
5655       if (!bs->stop)
5656         continue;
5657
5658       b = bs->breakpoint_at;
5659       b->ops->check_status (bs);
5660       if (bs->stop)
5661         {
5662           bpstat_check_breakpoint_conditions (bs, ptid);
5663
5664           if (bs->stop)
5665             {
5666               ++(b->hit_count);
5667               observer_notify_breakpoint_modified (b);
5668
5669               /* We will stop here.  */
5670               if (b->disposition == disp_disable)
5671                 {
5672                   --(b->enable_count);
5673                   if (b->enable_count <= 0
5674                       && b->enable_state != bp_permanent)
5675                     b->enable_state = bp_disabled;
5676                   removed_any = 1;
5677                 }
5678               if (b->silent)
5679                 bs->print = 0;
5680               bs->commands = b->commands;
5681               incref_counted_command_line (bs->commands);
5682               if (command_line_is_silent (bs->commands
5683                                           ? bs->commands->commands : NULL))
5684                 bs->print = 0;
5685
5686               b->ops->after_condition_true (bs);
5687             }
5688
5689         }
5690
5691       /* Print nothing for this entry if we don't stop or don't
5692          print.  */
5693       if (!bs->stop || !bs->print)
5694         bs->print_it = print_it_noop;
5695     }
5696
5697   /* If we aren't stopping, the value of some hardware watchpoint may
5698      not have changed, but the intermediate memory locations we are
5699      watching may have.  Don't bother if we're stopping; this will get
5700      done later.  */
5701   need_remove_insert = 0;
5702   if (! bpstat_causes_stop (bs_head))
5703     for (bs = bs_head; bs != NULL; bs = bs->next)
5704       if (!bs->stop
5705           && bs->breakpoint_at
5706           && is_hardware_watchpoint (bs->breakpoint_at))
5707         {
5708           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5709
5710           update_watchpoint (w, 0 /* don't reparse.  */);
5711           need_remove_insert = 1;
5712         }
5713
5714   if (need_remove_insert)
5715     update_global_location_list (UGLL_MAY_INSERT);
5716   else if (removed_any)
5717     update_global_location_list (UGLL_DONT_INSERT);
5718
5719   return bs_head;
5720 }
5721
5722 static void
5723 handle_jit_event (void)
5724 {
5725   struct frame_info *frame;
5726   struct gdbarch *gdbarch;
5727
5728   /* Switch terminal for any messages produced by
5729      breakpoint_re_set.  */
5730   target_terminal_ours_for_output ();
5731
5732   frame = get_current_frame ();
5733   gdbarch = get_frame_arch (frame);
5734
5735   jit_event_handler (gdbarch);
5736
5737   target_terminal_inferior ();
5738 }
5739
5740 /* Prepare WHAT final decision for infrun.  */
5741
5742 /* Decide what infrun needs to do with this bpstat.  */
5743
5744 struct bpstat_what
5745 bpstat_what (bpstat bs_head)
5746 {
5747   struct bpstat_what retval;
5748   int jit_event = 0;
5749   bpstat bs;
5750
5751   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5752   retval.call_dummy = STOP_NONE;
5753   retval.is_longjmp = 0;
5754
5755   for (bs = bs_head; bs != NULL; bs = bs->next)
5756     {
5757       /* Extract this BS's action.  After processing each BS, we check
5758          if its action overrides all we've seem so far.  */
5759       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5760       enum bptype bptype;
5761
5762       if (bs->breakpoint_at == NULL)
5763         {
5764           /* I suspect this can happen if it was a momentary
5765              breakpoint which has since been deleted.  */
5766           bptype = bp_none;
5767         }
5768       else
5769         bptype = bs->breakpoint_at->type;
5770
5771       switch (bptype)
5772         {
5773         case bp_none:
5774           break;
5775         case bp_breakpoint:
5776         case bp_hardware_breakpoint:
5777         case bp_until:
5778         case bp_finish:
5779         case bp_shlib_event:
5780           if (bs->stop)
5781             {
5782               if (bs->print)
5783                 this_action = BPSTAT_WHAT_STOP_NOISY;
5784               else
5785                 this_action = BPSTAT_WHAT_STOP_SILENT;
5786             }
5787           else
5788             this_action = BPSTAT_WHAT_SINGLE;
5789           break;
5790         case bp_watchpoint:
5791         case bp_hardware_watchpoint:
5792         case bp_read_watchpoint:
5793         case bp_access_watchpoint:
5794           if (bs->stop)
5795             {
5796               if (bs->print)
5797                 this_action = BPSTAT_WHAT_STOP_NOISY;
5798               else
5799                 this_action = BPSTAT_WHAT_STOP_SILENT;
5800             }
5801           else
5802             {
5803               /* There was a watchpoint, but we're not stopping.
5804                  This requires no further action.  */
5805             }
5806           break;
5807         case bp_longjmp:
5808         case bp_longjmp_call_dummy:
5809         case bp_exception:
5810           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5811           retval.is_longjmp = bptype != bp_exception;
5812           break;
5813         case bp_longjmp_resume:
5814         case bp_exception_resume:
5815           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5816           retval.is_longjmp = bptype == bp_longjmp_resume;
5817           break;
5818         case bp_step_resume:
5819           if (bs->stop)
5820             this_action = BPSTAT_WHAT_STEP_RESUME;
5821           else
5822             {
5823               /* It is for the wrong frame.  */
5824               this_action = BPSTAT_WHAT_SINGLE;
5825             }
5826           break;
5827         case bp_hp_step_resume:
5828           if (bs->stop)
5829             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5830           else
5831             {
5832               /* It is for the wrong frame.  */
5833               this_action = BPSTAT_WHAT_SINGLE;
5834             }
5835           break;
5836         case bp_watchpoint_scope:
5837         case bp_thread_event:
5838         case bp_overlay_event:
5839         case bp_longjmp_master:
5840         case bp_std_terminate_master:
5841         case bp_exception_master:
5842           this_action = BPSTAT_WHAT_SINGLE;
5843           break;
5844         case bp_catchpoint:
5845           if (bs->stop)
5846             {
5847               if (bs->print)
5848                 this_action = BPSTAT_WHAT_STOP_NOISY;
5849               else
5850                 this_action = BPSTAT_WHAT_STOP_SILENT;
5851             }
5852           else
5853             {
5854               /* There was a catchpoint, but we're not stopping.
5855                  This requires no further action.  */
5856             }
5857           break;
5858         case bp_jit_event:
5859           jit_event = 1;
5860           this_action = BPSTAT_WHAT_SINGLE;
5861           break;
5862         case bp_call_dummy:
5863           /* Make sure the action is stop (silent or noisy),
5864              so infrun.c pops the dummy frame.  */
5865           retval.call_dummy = STOP_STACK_DUMMY;
5866           this_action = BPSTAT_WHAT_STOP_SILENT;
5867           break;
5868         case bp_std_terminate:
5869           /* Make sure the action is stop (silent or noisy),
5870              so infrun.c pops the dummy frame.  */
5871           retval.call_dummy = STOP_STD_TERMINATE;
5872           this_action = BPSTAT_WHAT_STOP_SILENT;
5873           break;
5874         case bp_tracepoint:
5875         case bp_fast_tracepoint:
5876         case bp_static_tracepoint:
5877           /* Tracepoint hits should not be reported back to GDB, and
5878              if one got through somehow, it should have been filtered
5879              out already.  */
5880           internal_error (__FILE__, __LINE__,
5881                           _("bpstat_what: tracepoint encountered"));
5882           break;
5883         case bp_gnu_ifunc_resolver:
5884           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5885           this_action = BPSTAT_WHAT_SINGLE;
5886           break;
5887         case bp_gnu_ifunc_resolver_return:
5888           /* The breakpoint will be removed, execution will restart from the
5889              PC of the former breakpoint.  */
5890           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5891           break;
5892
5893         case bp_dprintf:
5894           if (bs->stop)
5895             this_action = BPSTAT_WHAT_STOP_SILENT;
5896           else
5897             this_action = BPSTAT_WHAT_SINGLE;
5898           break;
5899
5900         default:
5901           internal_error (__FILE__, __LINE__,
5902                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5903         }
5904
5905       retval.main_action = max (retval.main_action, this_action);
5906     }
5907
5908   /* These operations may affect the bs->breakpoint_at state so they are
5909      delayed after MAIN_ACTION is decided above.  */
5910
5911   if (jit_event)
5912     {
5913       if (debug_infrun)
5914         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5915
5916       handle_jit_event ();
5917     }
5918
5919   for (bs = bs_head; bs != NULL; bs = bs->next)
5920     {
5921       struct breakpoint *b = bs->breakpoint_at;
5922
5923       if (b == NULL)
5924         continue;
5925       switch (b->type)
5926         {
5927         case bp_gnu_ifunc_resolver:
5928           gnu_ifunc_resolver_stop (b);
5929           break;
5930         case bp_gnu_ifunc_resolver_return:
5931           gnu_ifunc_resolver_return_stop (b);
5932           break;
5933         }
5934     }
5935
5936   return retval;
5937 }
5938
5939 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5940    without hardware support).  This isn't related to a specific bpstat,
5941    just to things like whether watchpoints are set.  */
5942
5943 int
5944 bpstat_should_step (void)
5945 {
5946   struct breakpoint *b;
5947
5948   ALL_BREAKPOINTS (b)
5949     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5950       return 1;
5951   return 0;
5952 }
5953
5954 int
5955 bpstat_causes_stop (bpstat bs)
5956 {
5957   for (; bs != NULL; bs = bs->next)
5958     if (bs->stop)
5959       return 1;
5960
5961   return 0;
5962 }
5963
5964 \f
5965
5966 /* Compute a string of spaces suitable to indent the next line
5967    so it starts at the position corresponding to the table column
5968    named COL_NAME in the currently active table of UIOUT.  */
5969
5970 static char *
5971 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5972 {
5973   static char wrap_indent[80];
5974   int i, total_width, width, align;
5975   char *text;
5976
5977   total_width = 0;
5978   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5979     {
5980       if (strcmp (text, col_name) == 0)
5981         {
5982           gdb_assert (total_width < sizeof wrap_indent);
5983           memset (wrap_indent, ' ', total_width);
5984           wrap_indent[total_width] = 0;
5985
5986           return wrap_indent;
5987         }
5988
5989       total_width += width + 1;
5990     }
5991
5992   return NULL;
5993 }
5994
5995 /* Determine if the locations of this breakpoint will have their conditions
5996    evaluated by the target, host or a mix of both.  Returns the following:
5997
5998     "host": Host evals condition.
5999     "host or target": Host or Target evals condition.
6000     "target": Target evals condition.
6001 */
6002
6003 static const char *
6004 bp_condition_evaluator (struct breakpoint *b)
6005 {
6006   struct bp_location *bl;
6007   char host_evals = 0;
6008   char target_evals = 0;
6009
6010   if (!b)
6011     return NULL;
6012
6013   if (!is_breakpoint (b))
6014     return NULL;
6015
6016   if (gdb_evaluates_breakpoint_condition_p ()
6017       || !target_supports_evaluation_of_breakpoint_conditions ())
6018     return condition_evaluation_host;
6019
6020   for (bl = b->loc; bl; bl = bl->next)
6021     {
6022       if (bl->cond_bytecode)
6023         target_evals++;
6024       else
6025         host_evals++;
6026     }
6027
6028   if (host_evals && target_evals)
6029     return condition_evaluation_both;
6030   else if (target_evals)
6031     return condition_evaluation_target;
6032   else
6033     return condition_evaluation_host;
6034 }
6035
6036 /* Determine the breakpoint location's condition evaluator.  This is
6037    similar to bp_condition_evaluator, but for locations.  */
6038
6039 static const char *
6040 bp_location_condition_evaluator (struct bp_location *bl)
6041 {
6042   if (bl && !is_breakpoint (bl->owner))
6043     return NULL;
6044
6045   if (gdb_evaluates_breakpoint_condition_p ()
6046       || !target_supports_evaluation_of_breakpoint_conditions ())
6047     return condition_evaluation_host;
6048
6049   if (bl && bl->cond_bytecode)
6050     return condition_evaluation_target;
6051   else
6052     return condition_evaluation_host;
6053 }
6054
6055 /* Print the LOC location out of the list of B->LOC locations.  */
6056
6057 static void
6058 print_breakpoint_location (struct breakpoint *b,
6059                            struct bp_location *loc)
6060 {
6061   struct ui_out *uiout = current_uiout;
6062   struct cleanup *old_chain = save_current_program_space ();
6063
6064   if (loc != NULL && loc->shlib_disabled)
6065     loc = NULL;
6066
6067   if (loc != NULL)
6068     set_current_program_space (loc->pspace);
6069
6070   if (b->display_canonical)
6071     ui_out_field_string (uiout, "what", b->addr_string);
6072   else if (loc && loc->symtab)
6073     {
6074       struct symbol *sym 
6075         = find_pc_sect_function (loc->address, loc->section);
6076       if (sym)
6077         {
6078           ui_out_text (uiout, "in ");
6079           ui_out_field_string (uiout, "func",
6080                                SYMBOL_PRINT_NAME (sym));
6081           ui_out_text (uiout, " ");
6082           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6083           ui_out_text (uiout, "at ");
6084         }
6085       ui_out_field_string (uiout, "file",
6086                            symtab_to_filename_for_display (loc->symtab));
6087       ui_out_text (uiout, ":");
6088
6089       if (ui_out_is_mi_like_p (uiout))
6090         ui_out_field_string (uiout, "fullname",
6091                              symtab_to_fullname (loc->symtab));
6092       
6093       ui_out_field_int (uiout, "line", loc->line_number);
6094     }
6095   else if (loc)
6096     {
6097       struct ui_file *stb = mem_fileopen ();
6098       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6099
6100       print_address_symbolic (loc->gdbarch, loc->address, stb,
6101                               demangle, "");
6102       ui_out_field_stream (uiout, "at", stb);
6103
6104       do_cleanups (stb_chain);
6105     }
6106   else
6107     ui_out_field_string (uiout, "pending", b->addr_string);
6108
6109   if (loc && is_breakpoint (b)
6110       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6111       && bp_condition_evaluator (b) == condition_evaluation_both)
6112     {
6113       ui_out_text (uiout, " (");
6114       ui_out_field_string (uiout, "evaluated-by",
6115                            bp_location_condition_evaluator (loc));
6116       ui_out_text (uiout, ")");
6117     }
6118
6119   do_cleanups (old_chain);
6120 }
6121
6122 static const char *
6123 bptype_string (enum bptype type)
6124 {
6125   struct ep_type_description
6126     {
6127       enum bptype type;
6128       char *description;
6129     };
6130   static struct ep_type_description bptypes[] =
6131   {
6132     {bp_none, "?deleted?"},
6133     {bp_breakpoint, "breakpoint"},
6134     {bp_hardware_breakpoint, "hw breakpoint"},
6135     {bp_until, "until"},
6136     {bp_finish, "finish"},
6137     {bp_watchpoint, "watchpoint"},
6138     {bp_hardware_watchpoint, "hw watchpoint"},
6139     {bp_read_watchpoint, "read watchpoint"},
6140     {bp_access_watchpoint, "acc watchpoint"},
6141     {bp_longjmp, "longjmp"},
6142     {bp_longjmp_resume, "longjmp resume"},
6143     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6144     {bp_exception, "exception"},
6145     {bp_exception_resume, "exception resume"},
6146     {bp_step_resume, "step resume"},
6147     {bp_hp_step_resume, "high-priority step resume"},
6148     {bp_watchpoint_scope, "watchpoint scope"},
6149     {bp_call_dummy, "call dummy"},
6150     {bp_std_terminate, "std::terminate"},
6151     {bp_shlib_event, "shlib events"},
6152     {bp_thread_event, "thread events"},
6153     {bp_overlay_event, "overlay events"},
6154     {bp_longjmp_master, "longjmp master"},
6155     {bp_std_terminate_master, "std::terminate master"},
6156     {bp_exception_master, "exception master"},
6157     {bp_catchpoint, "catchpoint"},
6158     {bp_tracepoint, "tracepoint"},
6159     {bp_fast_tracepoint, "fast tracepoint"},
6160     {bp_static_tracepoint, "static tracepoint"},
6161     {bp_dprintf, "dprintf"},
6162     {bp_jit_event, "jit events"},
6163     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6164     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6165   };
6166
6167   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6168       || ((int) type != bptypes[(int) type].type))
6169     internal_error (__FILE__, __LINE__,
6170                     _("bptypes table does not describe type #%d."),
6171                     (int) type);
6172
6173   return bptypes[(int) type].description;
6174 }
6175
6176 /* For MI, output a field named 'thread-groups' with a list as the value.
6177    For CLI, prefix the list with the string 'inf'. */
6178
6179 static void
6180 output_thread_groups (struct ui_out *uiout,
6181                       const char *field_name,
6182                       VEC(int) *inf_num,
6183                       int mi_only)
6184 {
6185   struct cleanup *back_to;
6186   int is_mi = ui_out_is_mi_like_p (uiout);
6187   int inf;
6188   int i;
6189
6190   /* For backward compatibility, don't display inferiors in CLI unless
6191      there are several.  Always display them for MI. */
6192   if (!is_mi && mi_only)
6193     return;
6194
6195   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6196
6197   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6198     {
6199       if (is_mi)
6200         {
6201           char mi_group[10];
6202
6203           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6204           ui_out_field_string (uiout, NULL, mi_group);
6205         }
6206       else
6207         {
6208           if (i == 0)
6209             ui_out_text (uiout, " inf ");
6210           else
6211             ui_out_text (uiout, ", ");
6212         
6213           ui_out_text (uiout, plongest (inf));
6214         }
6215     }
6216
6217   do_cleanups (back_to);
6218 }
6219
6220 /* Print B to gdb_stdout.  */
6221
6222 static void
6223 print_one_breakpoint_location (struct breakpoint *b,
6224                                struct bp_location *loc,
6225                                int loc_number,
6226                                struct bp_location **last_loc,
6227                                int allflag)
6228 {
6229   struct command_line *l;
6230   static char bpenables[] = "nynny";
6231
6232   struct ui_out *uiout = current_uiout;
6233   int header_of_multiple = 0;
6234   int part_of_multiple = (loc != NULL);
6235   struct value_print_options opts;
6236
6237   get_user_print_options (&opts);
6238
6239   gdb_assert (!loc || loc_number != 0);
6240   /* See comment in print_one_breakpoint concerning treatment of
6241      breakpoints with single disabled location.  */
6242   if (loc == NULL 
6243       && (b->loc != NULL 
6244           && (b->loc->next != NULL || !b->loc->enabled)))
6245     header_of_multiple = 1;
6246   if (loc == NULL)
6247     loc = b->loc;
6248
6249   annotate_record ();
6250
6251   /* 1 */
6252   annotate_field (0);
6253   if (part_of_multiple)
6254     {
6255       char *formatted;
6256       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6257       ui_out_field_string (uiout, "number", formatted);
6258       xfree (formatted);
6259     }
6260   else
6261     {
6262       ui_out_field_int (uiout, "number", b->number);
6263     }
6264
6265   /* 2 */
6266   annotate_field (1);
6267   if (part_of_multiple)
6268     ui_out_field_skip (uiout, "type");
6269   else
6270     ui_out_field_string (uiout, "type", bptype_string (b->type));
6271
6272   /* 3 */
6273   annotate_field (2);
6274   if (part_of_multiple)
6275     ui_out_field_skip (uiout, "disp");
6276   else
6277     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6278
6279
6280   /* 4 */
6281   annotate_field (3);
6282   if (part_of_multiple)
6283     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6284   else
6285     ui_out_field_fmt (uiout, "enabled", "%c", 
6286                       bpenables[(int) b->enable_state]);
6287   ui_out_spaces (uiout, 2);
6288
6289   
6290   /* 5 and 6 */
6291   if (b->ops != NULL && b->ops->print_one != NULL)
6292     {
6293       /* Although the print_one can possibly print all locations,
6294          calling it here is not likely to get any nice result.  So,
6295          make sure there's just one location.  */
6296       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6297       b->ops->print_one (b, last_loc);
6298     }
6299   else
6300     switch (b->type)
6301       {
6302       case bp_none:
6303         internal_error (__FILE__, __LINE__,
6304                         _("print_one_breakpoint: bp_none encountered\n"));
6305         break;
6306
6307       case bp_watchpoint:
6308       case bp_hardware_watchpoint:
6309       case bp_read_watchpoint:
6310       case bp_access_watchpoint:
6311         {
6312           struct watchpoint *w = (struct watchpoint *) b;
6313
6314           /* Field 4, the address, is omitted (which makes the columns
6315              not line up too nicely with the headers, but the effect
6316              is relatively readable).  */
6317           if (opts.addressprint)
6318             ui_out_field_skip (uiout, "addr");
6319           annotate_field (5);
6320           ui_out_field_string (uiout, "what", w->exp_string);
6321         }
6322         break;
6323
6324       case bp_breakpoint:
6325       case bp_hardware_breakpoint:
6326       case bp_until:
6327       case bp_finish:
6328       case bp_longjmp:
6329       case bp_longjmp_resume:
6330       case bp_longjmp_call_dummy:
6331       case bp_exception:
6332       case bp_exception_resume:
6333       case bp_step_resume:
6334       case bp_hp_step_resume:
6335       case bp_watchpoint_scope:
6336       case bp_call_dummy:
6337       case bp_std_terminate:
6338       case bp_shlib_event:
6339       case bp_thread_event:
6340       case bp_overlay_event:
6341       case bp_longjmp_master:
6342       case bp_std_terminate_master:
6343       case bp_exception_master:
6344       case bp_tracepoint:
6345       case bp_fast_tracepoint:
6346       case bp_static_tracepoint:
6347       case bp_dprintf:
6348       case bp_jit_event:
6349       case bp_gnu_ifunc_resolver:
6350       case bp_gnu_ifunc_resolver_return:
6351         if (opts.addressprint)
6352           {
6353             annotate_field (4);
6354             if (header_of_multiple)
6355               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6356             else if (b->loc == NULL || loc->shlib_disabled)
6357               ui_out_field_string (uiout, "addr", "<PENDING>");
6358             else
6359               ui_out_field_core_addr (uiout, "addr",
6360                                       loc->gdbarch, loc->address);
6361           }
6362         annotate_field (5);
6363         if (!header_of_multiple)
6364           print_breakpoint_location (b, loc);
6365         if (b->loc)
6366           *last_loc = b->loc;
6367         break;
6368       }
6369
6370
6371   if (loc != NULL && !header_of_multiple)
6372     {
6373       struct inferior *inf;
6374       VEC(int) *inf_num = NULL;
6375       int mi_only = 1;
6376
6377       ALL_INFERIORS (inf)
6378         {
6379           if (inf->pspace == loc->pspace)
6380             VEC_safe_push (int, inf_num, inf->num);
6381         }
6382
6383         /* For backward compatibility, don't display inferiors in CLI unless
6384            there are several.  Always display for MI. */
6385         if (allflag
6386             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6387                 && (number_of_program_spaces () > 1
6388                     || number_of_inferiors () > 1)
6389                 /* LOC is for existing B, it cannot be in
6390                    moribund_locations and thus having NULL OWNER.  */
6391                 && loc->owner->type != bp_catchpoint))
6392         mi_only = 0;
6393       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6394       VEC_free (int, inf_num);
6395     }
6396
6397   if (!part_of_multiple)
6398     {
6399       if (b->thread != -1)
6400         {
6401           /* FIXME: This seems to be redundant and lost here; see the
6402              "stop only in" line a little further down.  */
6403           ui_out_text (uiout, " thread ");
6404           ui_out_field_int (uiout, "thread", b->thread);
6405         }
6406       else if (b->task != 0)
6407         {
6408           ui_out_text (uiout, " task ");
6409           ui_out_field_int (uiout, "task", b->task);
6410         }
6411     }
6412
6413   ui_out_text (uiout, "\n");
6414
6415   if (!part_of_multiple)
6416     b->ops->print_one_detail (b, uiout);
6417
6418   if (part_of_multiple && frame_id_p (b->frame_id))
6419     {
6420       annotate_field (6);
6421       ui_out_text (uiout, "\tstop only in stack frame at ");
6422       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6423          the frame ID.  */
6424       ui_out_field_core_addr (uiout, "frame",
6425                               b->gdbarch, b->frame_id.stack_addr);
6426       ui_out_text (uiout, "\n");
6427     }
6428   
6429   if (!part_of_multiple && b->cond_string)
6430     {
6431       annotate_field (7);
6432       if (is_tracepoint (b))
6433         ui_out_text (uiout, "\ttrace only if ");
6434       else
6435         ui_out_text (uiout, "\tstop only if ");
6436       ui_out_field_string (uiout, "cond", b->cond_string);
6437
6438       /* Print whether the target is doing the breakpoint's condition
6439          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6440       if (is_breakpoint (b)
6441           && breakpoint_condition_evaluation_mode ()
6442           == condition_evaluation_target)
6443         {
6444           ui_out_text (uiout, " (");
6445           ui_out_field_string (uiout, "evaluated-by",
6446                                bp_condition_evaluator (b));
6447           ui_out_text (uiout, " evals)");
6448         }
6449       ui_out_text (uiout, "\n");
6450     }
6451
6452   if (!part_of_multiple && b->thread != -1)
6453     {
6454       /* FIXME should make an annotation for this.  */
6455       ui_out_text (uiout, "\tstop only in thread ");
6456       ui_out_field_int (uiout, "thread", b->thread);
6457       ui_out_text (uiout, "\n");
6458     }
6459   
6460   if (!part_of_multiple)
6461     {
6462       if (b->hit_count)
6463         {
6464           /* FIXME should make an annotation for this.  */
6465           if (is_catchpoint (b))
6466             ui_out_text (uiout, "\tcatchpoint");
6467           else if (is_tracepoint (b))
6468             ui_out_text (uiout, "\ttracepoint");
6469           else
6470             ui_out_text (uiout, "\tbreakpoint");
6471           ui_out_text (uiout, " already hit ");
6472           ui_out_field_int (uiout, "times", b->hit_count);
6473           if (b->hit_count == 1)
6474             ui_out_text (uiout, " time\n");
6475           else
6476             ui_out_text (uiout, " times\n");
6477         }
6478       else
6479         {
6480           /* Output the count also if it is zero, but only if this is mi.  */
6481           if (ui_out_is_mi_like_p (uiout))
6482             ui_out_field_int (uiout, "times", b->hit_count);
6483         }
6484     }
6485
6486   if (!part_of_multiple && b->ignore_count)
6487     {
6488       annotate_field (8);
6489       ui_out_text (uiout, "\tignore next ");
6490       ui_out_field_int (uiout, "ignore", b->ignore_count);
6491       ui_out_text (uiout, " hits\n");
6492     }
6493
6494   /* Note that an enable count of 1 corresponds to "enable once"
6495      behavior, which is reported by the combination of enablement and
6496      disposition, so we don't need to mention it here.  */
6497   if (!part_of_multiple && b->enable_count > 1)
6498     {
6499       annotate_field (8);
6500       ui_out_text (uiout, "\tdisable after ");
6501       /* Tweak the wording to clarify that ignore and enable counts
6502          are distinct, and have additive effect.  */
6503       if (b->ignore_count)
6504         ui_out_text (uiout, "additional ");
6505       else
6506         ui_out_text (uiout, "next ");
6507       ui_out_field_int (uiout, "enable", b->enable_count);
6508       ui_out_text (uiout, " hits\n");
6509     }
6510
6511   if (!part_of_multiple && is_tracepoint (b))
6512     {
6513       struct tracepoint *tp = (struct tracepoint *) b;
6514
6515       if (tp->traceframe_usage)
6516         {
6517           ui_out_text (uiout, "\ttrace buffer usage ");
6518           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6519           ui_out_text (uiout, " bytes\n");
6520         }
6521     }
6522
6523   l = b->commands ? b->commands->commands : NULL;
6524   if (!part_of_multiple && l)
6525     {
6526       struct cleanup *script_chain;
6527
6528       annotate_field (9);
6529       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6530       print_command_lines (uiout, l, 4);
6531       do_cleanups (script_chain);
6532     }
6533
6534   if (is_tracepoint (b))
6535     {
6536       struct tracepoint *t = (struct tracepoint *) b;
6537
6538       if (!part_of_multiple && t->pass_count)
6539         {
6540           annotate_field (10);
6541           ui_out_text (uiout, "\tpass count ");
6542           ui_out_field_int (uiout, "pass", t->pass_count);
6543           ui_out_text (uiout, " \n");
6544         }
6545
6546       /* Don't display it when tracepoint or tracepoint location is
6547          pending.   */
6548       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6549         {
6550           annotate_field (11);
6551
6552           if (ui_out_is_mi_like_p (uiout))
6553             ui_out_field_string (uiout, "installed",
6554                                  loc->inserted ? "y" : "n");
6555           else
6556             {
6557               if (loc->inserted)
6558                 ui_out_text (uiout, "\t");
6559               else
6560                 ui_out_text (uiout, "\tnot ");
6561               ui_out_text (uiout, "installed on target\n");
6562             }
6563         }
6564     }
6565
6566   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6567     {
6568       if (is_watchpoint (b))
6569         {
6570           struct watchpoint *w = (struct watchpoint *) b;
6571
6572           ui_out_field_string (uiout, "original-location", w->exp_string);
6573         }
6574       else if (b->addr_string)
6575         ui_out_field_string (uiout, "original-location", b->addr_string);
6576     }
6577 }
6578
6579 static void
6580 print_one_breakpoint (struct breakpoint *b,
6581                       struct bp_location **last_loc, 
6582                       int allflag)
6583 {
6584   struct cleanup *bkpt_chain;
6585   struct ui_out *uiout = current_uiout;
6586
6587   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6588
6589   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6590   do_cleanups (bkpt_chain);
6591
6592   /* If this breakpoint has custom print function,
6593      it's already printed.  Otherwise, print individual
6594      locations, if any.  */
6595   if (b->ops == NULL || b->ops->print_one == NULL)
6596     {
6597       /* If breakpoint has a single location that is disabled, we
6598          print it as if it had several locations, since otherwise it's
6599          hard to represent "breakpoint enabled, location disabled"
6600          situation.
6601
6602          Note that while hardware watchpoints have several locations
6603          internally, that's not a property exposed to user.  */
6604       if (b->loc 
6605           && !is_hardware_watchpoint (b)
6606           && (b->loc->next || !b->loc->enabled))
6607         {
6608           struct bp_location *loc;
6609           int n = 1;
6610
6611           for (loc = b->loc; loc; loc = loc->next, ++n)
6612             {
6613               struct cleanup *inner2 =
6614                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6615               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6616               do_cleanups (inner2);
6617             }
6618         }
6619     }
6620 }
6621
6622 static int
6623 breakpoint_address_bits (struct breakpoint *b)
6624 {
6625   int print_address_bits = 0;
6626   struct bp_location *loc;
6627
6628   for (loc = b->loc; loc; loc = loc->next)
6629     {
6630       int addr_bit;
6631
6632       /* Software watchpoints that aren't watching memory don't have
6633          an address to print.  */
6634       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6635         continue;
6636
6637       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6638       if (addr_bit > print_address_bits)
6639         print_address_bits = addr_bit;
6640     }
6641
6642   return print_address_bits;
6643 }
6644
6645 struct captured_breakpoint_query_args
6646   {
6647     int bnum;
6648   };
6649
6650 static int
6651 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6652 {
6653   struct captured_breakpoint_query_args *args = data;
6654   struct breakpoint *b;
6655   struct bp_location *dummy_loc = NULL;
6656
6657   ALL_BREAKPOINTS (b)
6658     {
6659       if (args->bnum == b->number)
6660         {
6661           print_one_breakpoint (b, &dummy_loc, 0);
6662           return GDB_RC_OK;
6663         }
6664     }
6665   return GDB_RC_NONE;
6666 }
6667
6668 enum gdb_rc
6669 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6670                       char **error_message)
6671 {
6672   struct captured_breakpoint_query_args args;
6673
6674   args.bnum = bnum;
6675   /* For the moment we don't trust print_one_breakpoint() to not throw
6676      an error.  */
6677   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6678                                  error_message, RETURN_MASK_ALL) < 0)
6679     return GDB_RC_FAIL;
6680   else
6681     return GDB_RC_OK;
6682 }
6683
6684 /* Return true if this breakpoint was set by the user, false if it is
6685    internal or momentary.  */
6686
6687 int
6688 user_breakpoint_p (struct breakpoint *b)
6689 {
6690   return b->number > 0;
6691 }
6692
6693 /* Print information on user settable breakpoint (watchpoint, etc)
6694    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6695    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6696    FILTER is non-NULL, call it on each breakpoint and only include the
6697    ones for which it returns non-zero.  Return the total number of
6698    breakpoints listed.  */
6699
6700 static int
6701 breakpoint_1 (char *args, int allflag, 
6702               int (*filter) (const struct breakpoint *))
6703 {
6704   struct breakpoint *b;
6705   struct bp_location *last_loc = NULL;
6706   int nr_printable_breakpoints;
6707   struct cleanup *bkpttbl_chain;
6708   struct value_print_options opts;
6709   int print_address_bits = 0;
6710   int print_type_col_width = 14;
6711   struct ui_out *uiout = current_uiout;
6712
6713   get_user_print_options (&opts);
6714
6715   /* Compute the number of rows in the table, as well as the size
6716      required for address fields.  */
6717   nr_printable_breakpoints = 0;
6718   ALL_BREAKPOINTS (b)
6719     {
6720       /* If we have a filter, only list the breakpoints it accepts.  */
6721       if (filter && !filter (b))
6722         continue;
6723
6724       /* If we have an "args" string, it is a list of breakpoints to 
6725          accept.  Skip the others.  */
6726       if (args != NULL && *args != '\0')
6727         {
6728           if (allflag && parse_and_eval_long (args) != b->number)
6729             continue;
6730           if (!allflag && !number_is_in_list (args, b->number))
6731             continue;
6732         }
6733
6734       if (allflag || user_breakpoint_p (b))
6735         {
6736           int addr_bit, type_len;
6737
6738           addr_bit = breakpoint_address_bits (b);
6739           if (addr_bit > print_address_bits)
6740             print_address_bits = addr_bit;
6741
6742           type_len = strlen (bptype_string (b->type));
6743           if (type_len > print_type_col_width)
6744             print_type_col_width = type_len;
6745
6746           nr_printable_breakpoints++;
6747         }
6748     }
6749
6750   if (opts.addressprint)
6751     bkpttbl_chain 
6752       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6753                                              nr_printable_breakpoints,
6754                                              "BreakpointTable");
6755   else
6756     bkpttbl_chain 
6757       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6758                                              nr_printable_breakpoints,
6759                                              "BreakpointTable");
6760
6761   if (nr_printable_breakpoints > 0)
6762     annotate_breakpoints_headers ();
6763   if (nr_printable_breakpoints > 0)
6764     annotate_field (0);
6765   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6766   if (nr_printable_breakpoints > 0)
6767     annotate_field (1);
6768   ui_out_table_header (uiout, print_type_col_width, ui_left,
6769                        "type", "Type");                         /* 2 */
6770   if (nr_printable_breakpoints > 0)
6771     annotate_field (2);
6772   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6773   if (nr_printable_breakpoints > 0)
6774     annotate_field (3);
6775   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6776   if (opts.addressprint)
6777     {
6778       if (nr_printable_breakpoints > 0)
6779         annotate_field (4);
6780       if (print_address_bits <= 32)
6781         ui_out_table_header (uiout, 10, ui_left, 
6782                              "addr", "Address");                /* 5 */
6783       else
6784         ui_out_table_header (uiout, 18, ui_left, 
6785                              "addr", "Address");                /* 5 */
6786     }
6787   if (nr_printable_breakpoints > 0)
6788     annotate_field (5);
6789   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6790   ui_out_table_body (uiout);
6791   if (nr_printable_breakpoints > 0)
6792     annotate_breakpoints_table ();
6793
6794   ALL_BREAKPOINTS (b)
6795     {
6796       QUIT;
6797       /* If we have a filter, only list the breakpoints it accepts.  */
6798       if (filter && !filter (b))
6799         continue;
6800
6801       /* If we have an "args" string, it is a list of breakpoints to 
6802          accept.  Skip the others.  */
6803
6804       if (args != NULL && *args != '\0')
6805         {
6806           if (allflag)  /* maintenance info breakpoint */
6807             {
6808               if (parse_and_eval_long (args) != b->number)
6809                 continue;
6810             }
6811           else          /* all others */
6812             {
6813               if (!number_is_in_list (args, b->number))
6814                 continue;
6815             }
6816         }
6817       /* We only print out user settable breakpoints unless the
6818          allflag is set.  */
6819       if (allflag || user_breakpoint_p (b))
6820         print_one_breakpoint (b, &last_loc, allflag);
6821     }
6822
6823   do_cleanups (bkpttbl_chain);
6824
6825   if (nr_printable_breakpoints == 0)
6826     {
6827       /* If there's a filter, let the caller decide how to report
6828          empty list.  */
6829       if (!filter)
6830         {
6831           if (args == NULL || *args == '\0')
6832             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6833           else
6834             ui_out_message (uiout, 0, 
6835                             "No breakpoint or watchpoint matching '%s'.\n",
6836                             args);
6837         }
6838     }
6839   else
6840     {
6841       if (last_loc && !server_command)
6842         set_next_address (last_loc->gdbarch, last_loc->address);
6843     }
6844
6845   /* FIXME?  Should this be moved up so that it is only called when
6846      there have been breakpoints? */
6847   annotate_breakpoints_table_end ();
6848
6849   return nr_printable_breakpoints;
6850 }
6851
6852 /* Display the value of default-collect in a way that is generally
6853    compatible with the breakpoint list.  */
6854
6855 static void
6856 default_collect_info (void)
6857 {
6858   struct ui_out *uiout = current_uiout;
6859
6860   /* If it has no value (which is frequently the case), say nothing; a
6861      message like "No default-collect." gets in user's face when it's
6862      not wanted.  */
6863   if (!*default_collect)
6864     return;
6865
6866   /* The following phrase lines up nicely with per-tracepoint collect
6867      actions.  */
6868   ui_out_text (uiout, "default collect ");
6869   ui_out_field_string (uiout, "default-collect", default_collect);
6870   ui_out_text (uiout, " \n");
6871 }
6872   
6873 static void
6874 breakpoints_info (char *args, int from_tty)
6875 {
6876   breakpoint_1 (args, 0, NULL);
6877
6878   default_collect_info ();
6879 }
6880
6881 static void
6882 watchpoints_info (char *args, int from_tty)
6883 {
6884   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6885   struct ui_out *uiout = current_uiout;
6886
6887   if (num_printed == 0)
6888     {
6889       if (args == NULL || *args == '\0')
6890         ui_out_message (uiout, 0, "No watchpoints.\n");
6891       else
6892         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6893     }
6894 }
6895
6896 static void
6897 maintenance_info_breakpoints (char *args, int from_tty)
6898 {
6899   breakpoint_1 (args, 1, NULL);
6900
6901   default_collect_info ();
6902 }
6903
6904 static int
6905 breakpoint_has_pc (struct breakpoint *b,
6906                    struct program_space *pspace,
6907                    CORE_ADDR pc, struct obj_section *section)
6908 {
6909   struct bp_location *bl = b->loc;
6910
6911   for (; bl; bl = bl->next)
6912     {
6913       if (bl->pspace == pspace
6914           && bl->address == pc
6915           && (!overlay_debugging || bl->section == section))
6916         return 1;         
6917     }
6918   return 0;
6919 }
6920
6921 /* Print a message describing any user-breakpoints set at PC.  This
6922    concerns with logical breakpoints, so we match program spaces, not
6923    address spaces.  */
6924
6925 static void
6926 describe_other_breakpoints (struct gdbarch *gdbarch,
6927                             struct program_space *pspace, CORE_ADDR pc,
6928                             struct obj_section *section, int thread)
6929 {
6930   int others = 0;
6931   struct breakpoint *b;
6932
6933   ALL_BREAKPOINTS (b)
6934     others += (user_breakpoint_p (b)
6935                && breakpoint_has_pc (b, pspace, pc, section));
6936   if (others > 0)
6937     {
6938       if (others == 1)
6939         printf_filtered (_("Note: breakpoint "));
6940       else /* if (others == ???) */
6941         printf_filtered (_("Note: breakpoints "));
6942       ALL_BREAKPOINTS (b)
6943         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6944           {
6945             others--;
6946             printf_filtered ("%d", b->number);
6947             if (b->thread == -1 && thread != -1)
6948               printf_filtered (" (all threads)");
6949             else if (b->thread != -1)
6950               printf_filtered (" (thread %d)", b->thread);
6951             printf_filtered ("%s%s ",
6952                              ((b->enable_state == bp_disabled
6953                                || b->enable_state == bp_call_disabled)
6954                               ? " (disabled)"
6955                               : b->enable_state == bp_permanent 
6956                               ? " (permanent)"
6957                               : ""),
6958                              (others > 1) ? "," 
6959                              : ((others == 1) ? " and" : ""));
6960           }
6961       printf_filtered (_("also set at pc "));
6962       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6963       printf_filtered (".\n");
6964     }
6965 }
6966 \f
6967
6968 /* Return true iff it is meaningful to use the address member of
6969    BPT.  For some breakpoint types, the address member is irrelevant
6970    and it makes no sense to attempt to compare it to other addresses
6971    (or use it for any other purpose either).
6972
6973    More specifically, each of the following breakpoint types will
6974    always have a zero valued address and we don't want to mark
6975    breakpoints of any of these types to be a duplicate of an actual
6976    breakpoint at address zero:
6977
6978       bp_watchpoint
6979       bp_catchpoint
6980
6981 */
6982
6983 static int
6984 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6985 {
6986   enum bptype type = bpt->type;
6987
6988   return (type != bp_watchpoint && type != bp_catchpoint);
6989 }
6990
6991 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6992    true if LOC1 and LOC2 represent the same watchpoint location.  */
6993
6994 static int
6995 watchpoint_locations_match (struct bp_location *loc1, 
6996                             struct bp_location *loc2)
6997 {
6998   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6999   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
7000
7001   /* Both of them must exist.  */
7002   gdb_assert (w1 != NULL);
7003   gdb_assert (w2 != NULL);
7004
7005   /* If the target can evaluate the condition expression in hardware,
7006      then we we need to insert both watchpoints even if they are at
7007      the same place.  Otherwise the watchpoint will only trigger when
7008      the condition of whichever watchpoint was inserted evaluates to
7009      true, not giving a chance for GDB to check the condition of the
7010      other watchpoint.  */
7011   if ((w1->cond_exp
7012        && target_can_accel_watchpoint_condition (loc1->address, 
7013                                                  loc1->length,
7014                                                  loc1->watchpoint_type,
7015                                                  w1->cond_exp))
7016       || (w2->cond_exp
7017           && target_can_accel_watchpoint_condition (loc2->address, 
7018                                                     loc2->length,
7019                                                     loc2->watchpoint_type,
7020                                                     w2->cond_exp)))
7021     return 0;
7022
7023   /* Note that this checks the owner's type, not the location's.  In
7024      case the target does not support read watchpoints, but does
7025      support access watchpoints, we'll have bp_read_watchpoint
7026      watchpoints with hw_access locations.  Those should be considered
7027      duplicates of hw_read locations.  The hw_read locations will
7028      become hw_access locations later.  */
7029   return (loc1->owner->type == loc2->owner->type
7030           && loc1->pspace->aspace == loc2->pspace->aspace
7031           && loc1->address == loc2->address
7032           && loc1->length == loc2->length);
7033 }
7034
7035 /* See breakpoint.h.  */
7036
7037 int
7038 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7039                           struct address_space *aspace2, CORE_ADDR addr2)
7040 {
7041   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7042            || aspace1 == aspace2)
7043           && addr1 == addr2);
7044 }
7045
7046 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7047    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7048    matches ASPACE2.  On targets that have global breakpoints, the address
7049    space doesn't really matter.  */
7050
7051 static int
7052 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7053                                 int len1, struct address_space *aspace2,
7054                                 CORE_ADDR addr2)
7055 {
7056   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7057            || aspace1 == aspace2)
7058           && addr2 >= addr1 && addr2 < addr1 + len1);
7059 }
7060
7061 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7062    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7063    matches the breakpoint's address space.  On targets that have global
7064    breakpoints, the address space doesn't really matter.  */
7065
7066 static int
7067 breakpoint_location_address_match (struct bp_location *bl,
7068                                    struct address_space *aspace,
7069                                    CORE_ADDR addr)
7070 {
7071   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7072                                     aspace, addr)
7073           || (bl->length
7074               && breakpoint_address_match_range (bl->pspace->aspace,
7075                                                  bl->address, bl->length,
7076                                                  aspace, addr)));
7077 }
7078
7079 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7080    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7081    true, otherwise returns false.  */
7082
7083 static int
7084 tracepoint_locations_match (struct bp_location *loc1,
7085                             struct bp_location *loc2)
7086 {
7087   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7088     /* Since tracepoint locations are never duplicated with others', tracepoint
7089        locations at the same address of different tracepoints are regarded as
7090        different locations.  */
7091     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7092   else
7093     return 0;
7094 }
7095
7096 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7097    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7098    represent the same location.  */
7099
7100 static int
7101 breakpoint_locations_match (struct bp_location *loc1, 
7102                             struct bp_location *loc2)
7103 {
7104   int hw_point1, hw_point2;
7105
7106   /* Both of them must not be in moribund_locations.  */
7107   gdb_assert (loc1->owner != NULL);
7108   gdb_assert (loc2->owner != NULL);
7109
7110   hw_point1 = is_hardware_watchpoint (loc1->owner);
7111   hw_point2 = is_hardware_watchpoint (loc2->owner);
7112
7113   if (hw_point1 != hw_point2)
7114     return 0;
7115   else if (hw_point1)
7116     return watchpoint_locations_match (loc1, loc2);
7117   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7118     return tracepoint_locations_match (loc1, loc2);
7119   else
7120     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7121     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7122                                      loc2->pspace->aspace, loc2->address)
7123             && loc1->length == loc2->length);
7124 }
7125
7126 static void
7127 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7128                                int bnum, int have_bnum)
7129 {
7130   /* The longest string possibly returned by hex_string_custom
7131      is 50 chars.  These must be at least that big for safety.  */
7132   char astr1[64];
7133   char astr2[64];
7134
7135   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7136   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7137   if (have_bnum)
7138     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7139              bnum, astr1, astr2);
7140   else
7141     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7142 }
7143
7144 /* Adjust a breakpoint's address to account for architectural
7145    constraints on breakpoint placement.  Return the adjusted address.
7146    Note: Very few targets require this kind of adjustment.  For most
7147    targets, this function is simply the identity function.  */
7148
7149 static CORE_ADDR
7150 adjust_breakpoint_address (struct gdbarch *gdbarch,
7151                            CORE_ADDR bpaddr, enum bptype bptype)
7152 {
7153   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7154     {
7155       /* Very few targets need any kind of breakpoint adjustment.  */
7156       return bpaddr;
7157     }
7158   else if (bptype == bp_watchpoint
7159            || bptype == bp_hardware_watchpoint
7160            || bptype == bp_read_watchpoint
7161            || bptype == bp_access_watchpoint
7162            || bptype == bp_catchpoint)
7163     {
7164       /* Watchpoints and the various bp_catch_* eventpoints should not
7165          have their addresses modified.  */
7166       return bpaddr;
7167     }
7168   else
7169     {
7170       CORE_ADDR adjusted_bpaddr;
7171
7172       /* Some targets have architectural constraints on the placement
7173          of breakpoint instructions.  Obtain the adjusted address.  */
7174       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7175
7176       /* An adjusted breakpoint address can significantly alter
7177          a user's expectations.  Print a warning if an adjustment
7178          is required.  */
7179       if (adjusted_bpaddr != bpaddr)
7180         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7181
7182       return adjusted_bpaddr;
7183     }
7184 }
7185
7186 void
7187 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7188                   struct breakpoint *owner)
7189 {
7190   memset (loc, 0, sizeof (*loc));
7191
7192   gdb_assert (ops != NULL);
7193
7194   loc->ops = ops;
7195   loc->owner = owner;
7196   loc->cond = NULL;
7197   loc->cond_bytecode = NULL;
7198   loc->shlib_disabled = 0;
7199   loc->enabled = 1;
7200
7201   switch (owner->type)
7202     {
7203     case bp_breakpoint:
7204     case bp_until:
7205     case bp_finish:
7206     case bp_longjmp:
7207     case bp_longjmp_resume:
7208     case bp_longjmp_call_dummy:
7209     case bp_exception:
7210     case bp_exception_resume:
7211     case bp_step_resume:
7212     case bp_hp_step_resume:
7213     case bp_watchpoint_scope:
7214     case bp_call_dummy:
7215     case bp_std_terminate:
7216     case bp_shlib_event:
7217     case bp_thread_event:
7218     case bp_overlay_event:
7219     case bp_jit_event:
7220     case bp_longjmp_master:
7221     case bp_std_terminate_master:
7222     case bp_exception_master:
7223     case bp_gnu_ifunc_resolver:
7224     case bp_gnu_ifunc_resolver_return:
7225     case bp_dprintf:
7226       loc->loc_type = bp_loc_software_breakpoint;
7227       mark_breakpoint_location_modified (loc);
7228       break;
7229     case bp_hardware_breakpoint:
7230       loc->loc_type = bp_loc_hardware_breakpoint;
7231       mark_breakpoint_location_modified (loc);
7232       break;
7233     case bp_hardware_watchpoint:
7234     case bp_read_watchpoint:
7235     case bp_access_watchpoint:
7236       loc->loc_type = bp_loc_hardware_watchpoint;
7237       break;
7238     case bp_watchpoint:
7239     case bp_catchpoint:
7240     case bp_tracepoint:
7241     case bp_fast_tracepoint:
7242     case bp_static_tracepoint:
7243       loc->loc_type = bp_loc_other;
7244       break;
7245     default:
7246       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7247     }
7248
7249   loc->refc = 1;
7250 }
7251
7252 /* Allocate a struct bp_location.  */
7253
7254 static struct bp_location *
7255 allocate_bp_location (struct breakpoint *bpt)
7256 {
7257   return bpt->ops->allocate_location (bpt);
7258 }
7259
7260 static void
7261 free_bp_location (struct bp_location *loc)
7262 {
7263   loc->ops->dtor (loc);
7264   xfree (loc);
7265 }
7266
7267 /* Increment reference count.  */
7268
7269 static void
7270 incref_bp_location (struct bp_location *bl)
7271 {
7272   ++bl->refc;
7273 }
7274
7275 /* Decrement reference count.  If the reference count reaches 0,
7276    destroy the bp_location.  Sets *BLP to NULL.  */
7277
7278 static void
7279 decref_bp_location (struct bp_location **blp)
7280 {
7281   gdb_assert ((*blp)->refc > 0);
7282
7283   if (--(*blp)->refc == 0)
7284     free_bp_location (*blp);
7285   *blp = NULL;
7286 }
7287
7288 /* Add breakpoint B at the end of the global breakpoint chain.  */
7289
7290 static void
7291 add_to_breakpoint_chain (struct breakpoint *b)
7292 {
7293   struct breakpoint *b1;
7294
7295   /* Add this breakpoint to the end of the chain so that a list of
7296      breakpoints will come out in order of increasing numbers.  */
7297
7298   b1 = breakpoint_chain;
7299   if (b1 == 0)
7300     breakpoint_chain = b;
7301   else
7302     {
7303       while (b1->next)
7304         b1 = b1->next;
7305       b1->next = b;
7306     }
7307 }
7308
7309 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7310
7311 static void
7312 init_raw_breakpoint_without_location (struct breakpoint *b,
7313                                       struct gdbarch *gdbarch,
7314                                       enum bptype bptype,
7315                                       const struct breakpoint_ops *ops)
7316 {
7317   memset (b, 0, sizeof (*b));
7318
7319   gdb_assert (ops != NULL);
7320
7321   b->ops = ops;
7322   b->type = bptype;
7323   b->gdbarch = gdbarch;
7324   b->language = current_language->la_language;
7325   b->input_radix = input_radix;
7326   b->thread = -1;
7327   b->enable_state = bp_enabled;
7328   b->next = 0;
7329   b->silent = 0;
7330   b->ignore_count = 0;
7331   b->commands = NULL;
7332   b->frame_id = null_frame_id;
7333   b->condition_not_parsed = 0;
7334   b->py_bp_object = NULL;
7335   b->related_breakpoint = b;
7336 }
7337
7338 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7339    that has type BPTYPE and has no locations as yet.  */
7340
7341 static struct breakpoint *
7342 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7343                                      enum bptype bptype,
7344                                      const struct breakpoint_ops *ops)
7345 {
7346   struct breakpoint *b = XNEW (struct breakpoint);
7347
7348   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7349   add_to_breakpoint_chain (b);
7350   return b;
7351 }
7352
7353 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7354    resolutions should be made as the user specified the location explicitly
7355    enough.  */
7356
7357 static void
7358 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7359 {
7360   gdb_assert (loc->owner != NULL);
7361
7362   if (loc->owner->type == bp_breakpoint
7363       || loc->owner->type == bp_hardware_breakpoint
7364       || is_tracepoint (loc->owner))
7365     {
7366       int is_gnu_ifunc;
7367       const char *function_name;
7368       CORE_ADDR func_addr;
7369
7370       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7371                                           &func_addr, NULL, &is_gnu_ifunc);
7372
7373       if (is_gnu_ifunc && !explicit_loc)
7374         {
7375           struct breakpoint *b = loc->owner;
7376
7377           gdb_assert (loc->pspace == current_program_space);
7378           if (gnu_ifunc_resolve_name (function_name,
7379                                       &loc->requested_address))
7380             {
7381               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7382               loc->address = adjust_breakpoint_address (loc->gdbarch,
7383                                                         loc->requested_address,
7384                                                         b->type);
7385             }
7386           else if (b->type == bp_breakpoint && b->loc == loc
7387                    && loc->next == NULL && b->related_breakpoint == b)
7388             {
7389               /* Create only the whole new breakpoint of this type but do not
7390                  mess more complicated breakpoints with multiple locations.  */
7391               b->type = bp_gnu_ifunc_resolver;
7392               /* Remember the resolver's address for use by the return
7393                  breakpoint.  */
7394               loc->related_address = func_addr;
7395             }
7396         }
7397
7398       if (function_name)
7399         loc->function_name = xstrdup (function_name);
7400     }
7401 }
7402
7403 /* Attempt to determine architecture of location identified by SAL.  */
7404 struct gdbarch *
7405 get_sal_arch (struct symtab_and_line sal)
7406 {
7407   if (sal.section)
7408     return get_objfile_arch (sal.section->objfile);
7409   if (sal.symtab)
7410     return get_objfile_arch (sal.symtab->objfile);
7411
7412   return NULL;
7413 }
7414
7415 /* Low level routine for partially initializing a breakpoint of type
7416    BPTYPE.  The newly created breakpoint's address, section, source
7417    file name, and line number are provided by SAL.
7418
7419    It is expected that the caller will complete the initialization of
7420    the newly created breakpoint struct as well as output any status
7421    information regarding the creation of a new breakpoint.  */
7422
7423 static void
7424 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7425                      struct symtab_and_line sal, enum bptype bptype,
7426                      const struct breakpoint_ops *ops)
7427 {
7428   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7429
7430   add_location_to_breakpoint (b, &sal);
7431
7432   if (bptype != bp_catchpoint)
7433     gdb_assert (sal.pspace != NULL);
7434
7435   /* Store the program space that was used to set the breakpoint,
7436      except for ordinary breakpoints, which are independent of the
7437      program space.  */
7438   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7439     b->pspace = sal.pspace;
7440 }
7441
7442 /* set_raw_breakpoint is a low level routine for allocating and
7443    partially initializing a breakpoint of type BPTYPE.  The newly
7444    created breakpoint's address, section, source file name, and line
7445    number are provided by SAL.  The newly created and partially
7446    initialized breakpoint is added to the breakpoint chain and
7447    is also returned as the value of this function.
7448
7449    It is expected that the caller will complete the initialization of
7450    the newly created breakpoint struct as well as output any status
7451    information regarding the creation of a new breakpoint.  In
7452    particular, set_raw_breakpoint does NOT set the breakpoint
7453    number!  Care should be taken to not allow an error to occur
7454    prior to completing the initialization of the breakpoint.  If this
7455    should happen, a bogus breakpoint will be left on the chain.  */
7456
7457 struct breakpoint *
7458 set_raw_breakpoint (struct gdbarch *gdbarch,
7459                     struct symtab_and_line sal, enum bptype bptype,
7460                     const struct breakpoint_ops *ops)
7461 {
7462   struct breakpoint *b = XNEW (struct breakpoint);
7463
7464   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7465   add_to_breakpoint_chain (b);
7466   return b;
7467 }
7468
7469
7470 /* Note that the breakpoint object B describes a permanent breakpoint
7471    instruction, hard-wired into the inferior's code.  */
7472 void
7473 make_breakpoint_permanent (struct breakpoint *b)
7474 {
7475   struct bp_location *bl;
7476
7477   b->enable_state = bp_permanent;
7478
7479   /* By definition, permanent breakpoints are already present in the
7480      code.  Mark all locations as inserted.  For now,
7481      make_breakpoint_permanent is called in just one place, so it's
7482      hard to say if it's reasonable to have permanent breakpoint with
7483      multiple locations or not, but it's easy to implement.  */
7484   for (bl = b->loc; bl; bl = bl->next)
7485     bl->inserted = 1;
7486 }
7487
7488 /* Call this routine when stepping and nexting to enable a breakpoint
7489    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7490    initiated the operation.  */
7491
7492 void
7493 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7494 {
7495   struct breakpoint *b, *b_tmp;
7496   int thread = tp->num;
7497
7498   /* To avoid having to rescan all objfile symbols at every step,
7499      we maintain a list of continually-inserted but always disabled
7500      longjmp "master" breakpoints.  Here, we simply create momentary
7501      clones of those and enable them for the requested thread.  */
7502   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7503     if (b->pspace == current_program_space
7504         && (b->type == bp_longjmp_master
7505             || b->type == bp_exception_master))
7506       {
7507         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7508         struct breakpoint *clone;
7509
7510         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7511            after their removal.  */
7512         clone = momentary_breakpoint_from_master (b, type,
7513                                                   &longjmp_breakpoint_ops, 1);
7514         clone->thread = thread;
7515       }
7516
7517   tp->initiating_frame = frame;
7518 }
7519
7520 /* Delete all longjmp breakpoints from THREAD.  */
7521 void
7522 delete_longjmp_breakpoint (int thread)
7523 {
7524   struct breakpoint *b, *b_tmp;
7525
7526   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7527     if (b->type == bp_longjmp || b->type == bp_exception)
7528       {
7529         if (b->thread == thread)
7530           delete_breakpoint (b);
7531       }
7532 }
7533
7534 void
7535 delete_longjmp_breakpoint_at_next_stop (int thread)
7536 {
7537   struct breakpoint *b, *b_tmp;
7538
7539   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7540     if (b->type == bp_longjmp || b->type == bp_exception)
7541       {
7542         if (b->thread == thread)
7543           b->disposition = disp_del_at_next_stop;
7544       }
7545 }
7546
7547 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7548    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7549    pointer to any of them.  Return NULL if this system cannot place longjmp
7550    breakpoints.  */
7551
7552 struct breakpoint *
7553 set_longjmp_breakpoint_for_call_dummy (void)
7554 {
7555   struct breakpoint *b, *retval = NULL;
7556
7557   ALL_BREAKPOINTS (b)
7558     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7559       {
7560         struct breakpoint *new_b;
7561
7562         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7563                                                   &momentary_breakpoint_ops,
7564                                                   1);
7565         new_b->thread = pid_to_thread_id (inferior_ptid);
7566
7567         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7568
7569         gdb_assert (new_b->related_breakpoint == new_b);
7570         if (retval == NULL)
7571           retval = new_b;
7572         new_b->related_breakpoint = retval;
7573         while (retval->related_breakpoint != new_b->related_breakpoint)
7574           retval = retval->related_breakpoint;
7575         retval->related_breakpoint = new_b;
7576       }
7577
7578   return retval;
7579 }
7580
7581 /* Verify all existing dummy frames and their associated breakpoints for
7582    TP.  Remove those which can no longer be found in the current frame
7583    stack.
7584
7585    You should call this function only at places where it is safe to currently
7586    unwind the whole stack.  Failed stack unwind would discard live dummy
7587    frames.  */
7588
7589 void
7590 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7591 {
7592   struct breakpoint *b, *b_tmp;
7593
7594   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7595     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7596       {
7597         struct breakpoint *dummy_b = b->related_breakpoint;
7598
7599         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7600           dummy_b = dummy_b->related_breakpoint;
7601         if (dummy_b->type != bp_call_dummy
7602             || frame_find_by_id (dummy_b->frame_id) != NULL)
7603           continue;
7604         
7605         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7606
7607         while (b->related_breakpoint != b)
7608           {
7609             if (b_tmp == b->related_breakpoint)
7610               b_tmp = b->related_breakpoint->next;
7611             delete_breakpoint (b->related_breakpoint);
7612           }
7613         delete_breakpoint (b);
7614       }
7615 }
7616
7617 void
7618 enable_overlay_breakpoints (void)
7619 {
7620   struct breakpoint *b;
7621
7622   ALL_BREAKPOINTS (b)
7623     if (b->type == bp_overlay_event)
7624     {
7625       b->enable_state = bp_enabled;
7626       update_global_location_list (UGLL_MAY_INSERT);
7627       overlay_events_enabled = 1;
7628     }
7629 }
7630
7631 void
7632 disable_overlay_breakpoints (void)
7633 {
7634   struct breakpoint *b;
7635
7636   ALL_BREAKPOINTS (b)
7637     if (b->type == bp_overlay_event)
7638     {
7639       b->enable_state = bp_disabled;
7640       update_global_location_list (UGLL_DONT_INSERT);
7641       overlay_events_enabled = 0;
7642     }
7643 }
7644
7645 /* Set an active std::terminate breakpoint for each std::terminate
7646    master breakpoint.  */
7647 void
7648 set_std_terminate_breakpoint (void)
7649 {
7650   struct breakpoint *b, *b_tmp;
7651
7652   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7653     if (b->pspace == current_program_space
7654         && b->type == bp_std_terminate_master)
7655       {
7656         momentary_breakpoint_from_master (b, bp_std_terminate,
7657                                           &momentary_breakpoint_ops, 1);
7658       }
7659 }
7660
7661 /* Delete all the std::terminate breakpoints.  */
7662 void
7663 delete_std_terminate_breakpoint (void)
7664 {
7665   struct breakpoint *b, *b_tmp;
7666
7667   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7668     if (b->type == bp_std_terminate)
7669       delete_breakpoint (b);
7670 }
7671
7672 struct breakpoint *
7673 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7674 {
7675   struct breakpoint *b;
7676
7677   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7678                                   &internal_breakpoint_ops);
7679
7680   b->enable_state = bp_enabled;
7681   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7682   b->addr_string
7683     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7684
7685   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7686
7687   return b;
7688 }
7689
7690 void
7691 remove_thread_event_breakpoints (void)
7692 {
7693   struct breakpoint *b, *b_tmp;
7694
7695   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7696     if (b->type == bp_thread_event
7697         && b->loc->pspace == current_program_space)
7698       delete_breakpoint (b);
7699 }
7700
7701 struct lang_and_radix
7702   {
7703     enum language lang;
7704     int radix;
7705   };
7706
7707 /* Create a breakpoint for JIT code registration and unregistration.  */
7708
7709 struct breakpoint *
7710 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7711 {
7712   struct breakpoint *b;
7713
7714   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7715                                   &internal_breakpoint_ops);
7716   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7717   return b;
7718 }
7719
7720 /* Remove JIT code registration and unregistration breakpoint(s).  */
7721
7722 void
7723 remove_jit_event_breakpoints (void)
7724 {
7725   struct breakpoint *b, *b_tmp;
7726
7727   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7728     if (b->type == bp_jit_event
7729         && b->loc->pspace == current_program_space)
7730       delete_breakpoint (b);
7731 }
7732
7733 void
7734 remove_solib_event_breakpoints (void)
7735 {
7736   struct breakpoint *b, *b_tmp;
7737
7738   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7739     if (b->type == bp_shlib_event
7740         && b->loc->pspace == current_program_space)
7741       delete_breakpoint (b);
7742 }
7743
7744 /* See breakpoint.h.  */
7745
7746 void
7747 remove_solib_event_breakpoints_at_next_stop (void)
7748 {
7749   struct breakpoint *b, *b_tmp;
7750
7751   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7752     if (b->type == bp_shlib_event
7753         && b->loc->pspace == current_program_space)
7754       b->disposition = disp_del_at_next_stop;
7755 }
7756
7757 /* Helper for create_solib_event_breakpoint /
7758    create_and_insert_solib_event_breakpoint.  Allows specifying which
7759    INSERT_MODE to pass through to update_global_location_list.  */
7760
7761 static struct breakpoint *
7762 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7763                                  enum ugll_insert_mode insert_mode)
7764 {
7765   struct breakpoint *b;
7766
7767   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7768                                   &internal_breakpoint_ops);
7769   update_global_location_list_nothrow (insert_mode);
7770   return b;
7771 }
7772
7773 struct breakpoint *
7774 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7775 {
7776   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7777 }
7778
7779 /* See breakpoint.h.  */
7780
7781 struct breakpoint *
7782 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7783 {
7784   struct breakpoint *b;
7785
7786   /* Explicitly tell update_global_location_list to insert
7787      locations.  */
7788   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7789   if (!b->loc->inserted)
7790     {
7791       delete_breakpoint (b);
7792       return NULL;
7793     }
7794   return b;
7795 }
7796
7797 /* Disable any breakpoints that are on code in shared libraries.  Only
7798    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7799
7800 void
7801 disable_breakpoints_in_shlibs (void)
7802 {
7803   struct bp_location *loc, **locp_tmp;
7804
7805   ALL_BP_LOCATIONS (loc, locp_tmp)
7806   {
7807     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7808     struct breakpoint *b = loc->owner;
7809
7810     /* We apply the check to all breakpoints, including disabled for
7811        those with loc->duplicate set.  This is so that when breakpoint
7812        becomes enabled, or the duplicate is removed, gdb will try to
7813        insert all breakpoints.  If we don't set shlib_disabled here,
7814        we'll try to insert those breakpoints and fail.  */
7815     if (((b->type == bp_breakpoint)
7816          || (b->type == bp_jit_event)
7817          || (b->type == bp_hardware_breakpoint)
7818          || (is_tracepoint (b)))
7819         && loc->pspace == current_program_space
7820         && !loc->shlib_disabled
7821         && solib_name_from_address (loc->pspace, loc->address)
7822         )
7823       {
7824         loc->shlib_disabled = 1;
7825       }
7826   }
7827 }
7828
7829 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7830    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7831    disabled ones can just stay disabled.  */
7832
7833 static void
7834 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7835 {
7836   struct bp_location *loc, **locp_tmp;
7837   int disabled_shlib_breaks = 0;
7838
7839   /* SunOS a.out shared libraries are always mapped, so do not
7840      disable breakpoints; they will only be reported as unloaded
7841      through clear_solib when GDB discards its shared library
7842      list.  See clear_solib for more information.  */
7843   if (exec_bfd != NULL
7844       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7845     return;
7846
7847   ALL_BP_LOCATIONS (loc, locp_tmp)
7848   {
7849     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7850     struct breakpoint *b = loc->owner;
7851
7852     if (solib->pspace == loc->pspace
7853         && !loc->shlib_disabled
7854         && (((b->type == bp_breakpoint
7855               || b->type == bp_jit_event
7856               || b->type == bp_hardware_breakpoint)
7857              && (loc->loc_type == bp_loc_hardware_breakpoint
7858                  || loc->loc_type == bp_loc_software_breakpoint))
7859             || is_tracepoint (b))
7860         && solib_contains_address_p (solib, loc->address))
7861       {
7862         loc->shlib_disabled = 1;
7863         /* At this point, we cannot rely on remove_breakpoint
7864            succeeding so we must mark the breakpoint as not inserted
7865            to prevent future errors occurring in remove_breakpoints.  */
7866         loc->inserted = 0;
7867
7868         /* This may cause duplicate notifications for the same breakpoint.  */
7869         observer_notify_breakpoint_modified (b);
7870
7871         if (!disabled_shlib_breaks)
7872           {
7873             target_terminal_ours_for_output ();
7874             warning (_("Temporarily disabling breakpoints "
7875                        "for unloaded shared library \"%s\""),
7876                      solib->so_name);
7877           }
7878         disabled_shlib_breaks = 1;
7879       }
7880   }
7881 }
7882
7883 /* Disable any breakpoints and tracepoints in OBJFILE upon
7884    notification of free_objfile.  Only apply to enabled breakpoints,
7885    disabled ones can just stay disabled.  */
7886
7887 static void
7888 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7889 {
7890   struct breakpoint *b;
7891
7892   if (objfile == NULL)
7893     return;
7894
7895   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7896      managed by the user with add-symbol-file/remove-symbol-file.
7897      Similarly to how breakpoints in shared libraries are handled in
7898      response to "nosharedlibrary", mark breakpoints in such modules
7899      shlib_disabled so they end up uninserted on the next global
7900      location list update.  Shared libraries not loaded by the user
7901      aren't handled here -- they're already handled in
7902      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7903      solib_unloaded observer.  We skip objfiles that are not
7904      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7905      main objfile).  */
7906   if ((objfile->flags & OBJF_SHARED) == 0
7907       || (objfile->flags & OBJF_USERLOADED) == 0)
7908     return;
7909
7910   ALL_BREAKPOINTS (b)
7911     {
7912       struct bp_location *loc;
7913       int bp_modified = 0;
7914
7915       if (!is_breakpoint (b) && !is_tracepoint (b))
7916         continue;
7917
7918       for (loc = b->loc; loc != NULL; loc = loc->next)
7919         {
7920           CORE_ADDR loc_addr = loc->address;
7921
7922           if (loc->loc_type != bp_loc_hardware_breakpoint
7923               && loc->loc_type != bp_loc_software_breakpoint)
7924             continue;
7925
7926           if (loc->shlib_disabled != 0)
7927             continue;
7928
7929           if (objfile->pspace != loc->pspace)
7930             continue;
7931
7932           if (loc->loc_type != bp_loc_hardware_breakpoint
7933               && loc->loc_type != bp_loc_software_breakpoint)
7934             continue;
7935
7936           if (is_addr_in_objfile (loc_addr, objfile))
7937             {
7938               loc->shlib_disabled = 1;
7939               /* At this point, we don't know whether the object was
7940                  unmapped from the inferior or not, so leave the
7941                  inserted flag alone.  We'll handle failure to
7942                  uninsert quietly, in case the object was indeed
7943                  unmapped.  */
7944
7945               mark_breakpoint_location_modified (loc);
7946
7947               bp_modified = 1;
7948             }
7949         }
7950
7951       if (bp_modified)
7952         observer_notify_breakpoint_modified (b);
7953     }
7954 }
7955
7956 /* FORK & VFORK catchpoints.  */
7957
7958 /* An instance of this type is used to represent a fork or vfork
7959    catchpoint.  It includes a "struct breakpoint" as a kind of base
7960    class; users downcast to "struct breakpoint *" when needed.  A
7961    breakpoint is really of this type iff its ops pointer points to
7962    CATCH_FORK_BREAKPOINT_OPS.  */
7963
7964 struct fork_catchpoint
7965 {
7966   /* The base class.  */
7967   struct breakpoint base;
7968
7969   /* Process id of a child process whose forking triggered this
7970      catchpoint.  This field is only valid immediately after this
7971      catchpoint has triggered.  */
7972   ptid_t forked_inferior_pid;
7973 };
7974
7975 /* Implement the "insert" breakpoint_ops method for fork
7976    catchpoints.  */
7977
7978 static int
7979 insert_catch_fork (struct bp_location *bl)
7980 {
7981   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7982 }
7983
7984 /* Implement the "remove" breakpoint_ops method for fork
7985    catchpoints.  */
7986
7987 static int
7988 remove_catch_fork (struct bp_location *bl)
7989 {
7990   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7991 }
7992
7993 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7994    catchpoints.  */
7995
7996 static int
7997 breakpoint_hit_catch_fork (const struct bp_location *bl,
7998                            struct address_space *aspace, CORE_ADDR bp_addr,
7999                            const struct target_waitstatus *ws)
8000 {
8001   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8002
8003   if (ws->kind != TARGET_WAITKIND_FORKED)
8004     return 0;
8005
8006   c->forked_inferior_pid = ws->value.related_pid;
8007   return 1;
8008 }
8009
8010 /* Implement the "print_it" breakpoint_ops method for fork
8011    catchpoints.  */
8012
8013 static enum print_stop_action
8014 print_it_catch_fork (bpstat bs)
8015 {
8016   struct ui_out *uiout = current_uiout;
8017   struct breakpoint *b = bs->breakpoint_at;
8018   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
8019
8020   annotate_catchpoint (b->number);
8021   if (b->disposition == disp_del)
8022     ui_out_text (uiout, "\nTemporary catchpoint ");
8023   else
8024     ui_out_text (uiout, "\nCatchpoint ");
8025   if (ui_out_is_mi_like_p (uiout))
8026     {
8027       ui_out_field_string (uiout, "reason",
8028                            async_reason_lookup (EXEC_ASYNC_FORK));
8029       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8030     }
8031   ui_out_field_int (uiout, "bkptno", b->number);
8032   ui_out_text (uiout, " (forked process ");
8033   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8034   ui_out_text (uiout, "), ");
8035   return PRINT_SRC_AND_LOC;
8036 }
8037
8038 /* Implement the "print_one" breakpoint_ops method for fork
8039    catchpoints.  */
8040
8041 static void
8042 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8043 {
8044   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8045   struct value_print_options opts;
8046   struct ui_out *uiout = current_uiout;
8047
8048   get_user_print_options (&opts);
8049
8050   /* Field 4, the address, is omitted (which makes the columns not
8051      line up too nicely with the headers, but the effect is relatively
8052      readable).  */
8053   if (opts.addressprint)
8054     ui_out_field_skip (uiout, "addr");
8055   annotate_field (5);
8056   ui_out_text (uiout, "fork");
8057   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8058     {
8059       ui_out_text (uiout, ", process ");
8060       ui_out_field_int (uiout, "what",
8061                         ptid_get_pid (c->forked_inferior_pid));
8062       ui_out_spaces (uiout, 1);
8063     }
8064
8065   if (ui_out_is_mi_like_p (uiout))
8066     ui_out_field_string (uiout, "catch-type", "fork");
8067 }
8068
8069 /* Implement the "print_mention" breakpoint_ops method for fork
8070    catchpoints.  */
8071
8072 static void
8073 print_mention_catch_fork (struct breakpoint *b)
8074 {
8075   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8076 }
8077
8078 /* Implement the "print_recreate" breakpoint_ops method for fork
8079    catchpoints.  */
8080
8081 static void
8082 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8083 {
8084   fprintf_unfiltered (fp, "catch fork");
8085   print_recreate_thread (b, fp);
8086 }
8087
8088 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8089
8090 static struct breakpoint_ops catch_fork_breakpoint_ops;
8091
8092 /* Implement the "insert" breakpoint_ops method for vfork
8093    catchpoints.  */
8094
8095 static int
8096 insert_catch_vfork (struct bp_location *bl)
8097 {
8098   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8099 }
8100
8101 /* Implement the "remove" breakpoint_ops method for vfork
8102    catchpoints.  */
8103
8104 static int
8105 remove_catch_vfork (struct bp_location *bl)
8106 {
8107   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8108 }
8109
8110 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8111    catchpoints.  */
8112
8113 static int
8114 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8115                             struct address_space *aspace, CORE_ADDR bp_addr,
8116                             const struct target_waitstatus *ws)
8117 {
8118   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8119
8120   if (ws->kind != TARGET_WAITKIND_VFORKED)
8121     return 0;
8122
8123   c->forked_inferior_pid = ws->value.related_pid;
8124   return 1;
8125 }
8126
8127 /* Implement the "print_it" breakpoint_ops method for vfork
8128    catchpoints.  */
8129
8130 static enum print_stop_action
8131 print_it_catch_vfork (bpstat bs)
8132 {
8133   struct ui_out *uiout = current_uiout;
8134   struct breakpoint *b = bs->breakpoint_at;
8135   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8136
8137   annotate_catchpoint (b->number);
8138   if (b->disposition == disp_del)
8139     ui_out_text (uiout, "\nTemporary catchpoint ");
8140   else
8141     ui_out_text (uiout, "\nCatchpoint ");
8142   if (ui_out_is_mi_like_p (uiout))
8143     {
8144       ui_out_field_string (uiout, "reason",
8145                            async_reason_lookup (EXEC_ASYNC_VFORK));
8146       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8147     }
8148   ui_out_field_int (uiout, "bkptno", b->number);
8149   ui_out_text (uiout, " (vforked process ");
8150   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8151   ui_out_text (uiout, "), ");
8152   return PRINT_SRC_AND_LOC;
8153 }
8154
8155 /* Implement the "print_one" breakpoint_ops method for vfork
8156    catchpoints.  */
8157
8158 static void
8159 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8160 {
8161   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8162   struct value_print_options opts;
8163   struct ui_out *uiout = current_uiout;
8164
8165   get_user_print_options (&opts);
8166   /* Field 4, the address, is omitted (which makes the columns not
8167      line up too nicely with the headers, but the effect is relatively
8168      readable).  */
8169   if (opts.addressprint)
8170     ui_out_field_skip (uiout, "addr");
8171   annotate_field (5);
8172   ui_out_text (uiout, "vfork");
8173   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8174     {
8175       ui_out_text (uiout, ", process ");
8176       ui_out_field_int (uiout, "what",
8177                         ptid_get_pid (c->forked_inferior_pid));
8178       ui_out_spaces (uiout, 1);
8179     }
8180
8181   if (ui_out_is_mi_like_p (uiout))
8182     ui_out_field_string (uiout, "catch-type", "vfork");
8183 }
8184
8185 /* Implement the "print_mention" breakpoint_ops method for vfork
8186    catchpoints.  */
8187
8188 static void
8189 print_mention_catch_vfork (struct breakpoint *b)
8190 {
8191   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8192 }
8193
8194 /* Implement the "print_recreate" breakpoint_ops method for vfork
8195    catchpoints.  */
8196
8197 static void
8198 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8199 {
8200   fprintf_unfiltered (fp, "catch vfork");
8201   print_recreate_thread (b, fp);
8202 }
8203
8204 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8205
8206 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8207
8208 /* An instance of this type is used to represent an solib catchpoint.
8209    It includes a "struct breakpoint" as a kind of base class; users
8210    downcast to "struct breakpoint *" when needed.  A breakpoint is
8211    really of this type iff its ops pointer points to
8212    CATCH_SOLIB_BREAKPOINT_OPS.  */
8213
8214 struct solib_catchpoint
8215 {
8216   /* The base class.  */
8217   struct breakpoint base;
8218
8219   /* True for "catch load", false for "catch unload".  */
8220   unsigned char is_load;
8221
8222   /* Regular expression to match, if any.  COMPILED is only valid when
8223      REGEX is non-NULL.  */
8224   char *regex;
8225   regex_t compiled;
8226 };
8227
8228 static void
8229 dtor_catch_solib (struct breakpoint *b)
8230 {
8231   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8232
8233   if (self->regex)
8234     regfree (&self->compiled);
8235   xfree (self->regex);
8236
8237   base_breakpoint_ops.dtor (b);
8238 }
8239
8240 static int
8241 insert_catch_solib (struct bp_location *ignore)
8242 {
8243   return 0;
8244 }
8245
8246 static int
8247 remove_catch_solib (struct bp_location *ignore)
8248 {
8249   return 0;
8250 }
8251
8252 static int
8253 breakpoint_hit_catch_solib (const struct bp_location *bl,
8254                             struct address_space *aspace,
8255                             CORE_ADDR bp_addr,
8256                             const struct target_waitstatus *ws)
8257 {
8258   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8259   struct breakpoint *other;
8260
8261   if (ws->kind == TARGET_WAITKIND_LOADED)
8262     return 1;
8263
8264   ALL_BREAKPOINTS (other)
8265   {
8266     struct bp_location *other_bl;
8267
8268     if (other == bl->owner)
8269       continue;
8270
8271     if (other->type != bp_shlib_event)
8272       continue;
8273
8274     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8275       continue;
8276
8277     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8278       {
8279         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8280           return 1;
8281       }
8282   }
8283
8284   return 0;
8285 }
8286
8287 static void
8288 check_status_catch_solib (struct bpstats *bs)
8289 {
8290   struct solib_catchpoint *self
8291     = (struct solib_catchpoint *) bs->breakpoint_at;
8292   int ix;
8293
8294   if (self->is_load)
8295     {
8296       struct so_list *iter;
8297
8298       for (ix = 0;
8299            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8300                         ix, iter);
8301            ++ix)
8302         {
8303           if (!self->regex
8304               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8305             return;
8306         }
8307     }
8308   else
8309     {
8310       char *iter;
8311
8312       for (ix = 0;
8313            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8314                         ix, iter);
8315            ++ix)
8316         {
8317           if (!self->regex
8318               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8319             return;
8320         }
8321     }
8322
8323   bs->stop = 0;
8324   bs->print_it = print_it_noop;
8325 }
8326
8327 static enum print_stop_action
8328 print_it_catch_solib (bpstat bs)
8329 {
8330   struct breakpoint *b = bs->breakpoint_at;
8331   struct ui_out *uiout = current_uiout;
8332
8333   annotate_catchpoint (b->number);
8334   if (b->disposition == disp_del)
8335     ui_out_text (uiout, "\nTemporary catchpoint ");
8336   else
8337     ui_out_text (uiout, "\nCatchpoint ");
8338   ui_out_field_int (uiout, "bkptno", b->number);
8339   ui_out_text (uiout, "\n");
8340   if (ui_out_is_mi_like_p (uiout))
8341     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8342   print_solib_event (1);
8343   return PRINT_SRC_AND_LOC;
8344 }
8345
8346 static void
8347 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8348 {
8349   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8350   struct value_print_options opts;
8351   struct ui_out *uiout = current_uiout;
8352   char *msg;
8353
8354   get_user_print_options (&opts);
8355   /* Field 4, the address, is omitted (which makes the columns not
8356      line up too nicely with the headers, but the effect is relatively
8357      readable).  */
8358   if (opts.addressprint)
8359     {
8360       annotate_field (4);
8361       ui_out_field_skip (uiout, "addr");
8362     }
8363
8364   annotate_field (5);
8365   if (self->is_load)
8366     {
8367       if (self->regex)
8368         msg = xstrprintf (_("load of library matching %s"), self->regex);
8369       else
8370         msg = xstrdup (_("load of library"));
8371     }
8372   else
8373     {
8374       if (self->regex)
8375         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8376       else
8377         msg = xstrdup (_("unload of library"));
8378     }
8379   ui_out_field_string (uiout, "what", msg);
8380   xfree (msg);
8381
8382   if (ui_out_is_mi_like_p (uiout))
8383     ui_out_field_string (uiout, "catch-type",
8384                          self->is_load ? "load" : "unload");
8385 }
8386
8387 static void
8388 print_mention_catch_solib (struct breakpoint *b)
8389 {
8390   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8391
8392   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8393                    self->is_load ? "load" : "unload");
8394 }
8395
8396 static void
8397 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8398 {
8399   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8400
8401   fprintf_unfiltered (fp, "%s %s",
8402                       b->disposition == disp_del ? "tcatch" : "catch",
8403                       self->is_load ? "load" : "unload");
8404   if (self->regex)
8405     fprintf_unfiltered (fp, " %s", self->regex);
8406   fprintf_unfiltered (fp, "\n");
8407 }
8408
8409 static struct breakpoint_ops catch_solib_breakpoint_ops;
8410
8411 /* Shared helper function (MI and CLI) for creating and installing
8412    a shared object event catchpoint.  If IS_LOAD is non-zero then
8413    the events to be caught are load events, otherwise they are
8414    unload events.  If IS_TEMP is non-zero the catchpoint is a
8415    temporary one.  If ENABLED is non-zero the catchpoint is
8416    created in an enabled state.  */
8417
8418 void
8419 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8420 {
8421   struct solib_catchpoint *c;
8422   struct gdbarch *gdbarch = get_current_arch ();
8423   struct cleanup *cleanup;
8424
8425   if (!arg)
8426     arg = "";
8427   arg = skip_spaces (arg);
8428
8429   c = XCNEW (struct solib_catchpoint);
8430   cleanup = make_cleanup (xfree, c);
8431
8432   if (*arg != '\0')
8433     {
8434       int errcode;
8435
8436       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8437       if (errcode != 0)
8438         {
8439           char *err = get_regcomp_error (errcode, &c->compiled);
8440
8441           make_cleanup (xfree, err);
8442           error (_("Invalid regexp (%s): %s"), err, arg);
8443         }
8444       c->regex = xstrdup (arg);
8445     }
8446
8447   c->is_load = is_load;
8448   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8449                    &catch_solib_breakpoint_ops);
8450
8451   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8452
8453   discard_cleanups (cleanup);
8454   install_breakpoint (0, &c->base, 1);
8455 }
8456
8457 /* A helper function that does all the work for "catch load" and
8458    "catch unload".  */
8459
8460 static void
8461 catch_load_or_unload (char *arg, int from_tty, int is_load,
8462                       struct cmd_list_element *command)
8463 {
8464   int tempflag;
8465   const int enabled = 1;
8466
8467   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8468
8469   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8470 }
8471
8472 static void
8473 catch_load_command_1 (char *arg, int from_tty,
8474                       struct cmd_list_element *command)
8475 {
8476   catch_load_or_unload (arg, from_tty, 1, command);
8477 }
8478
8479 static void
8480 catch_unload_command_1 (char *arg, int from_tty,
8481                         struct cmd_list_element *command)
8482 {
8483   catch_load_or_unload (arg, from_tty, 0, command);
8484 }
8485
8486 /* An instance of this type is used to represent a syscall catchpoint.
8487    It includes a "struct breakpoint" as a kind of base class; users
8488    downcast to "struct breakpoint *" when needed.  A breakpoint is
8489    really of this type iff its ops pointer points to
8490    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8491
8492 struct syscall_catchpoint
8493 {
8494   /* The base class.  */
8495   struct breakpoint base;
8496
8497   /* Syscall numbers used for the 'catch syscall' feature.  If no
8498      syscall has been specified for filtering, its value is NULL.
8499      Otherwise, it holds a list of all syscalls to be caught.  The
8500      list elements are allocated with xmalloc.  */
8501   VEC(int) *syscalls_to_be_caught;
8502 };
8503
8504 /* Implement the "dtor" breakpoint_ops method for syscall
8505    catchpoints.  */
8506
8507 static void
8508 dtor_catch_syscall (struct breakpoint *b)
8509 {
8510   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8511
8512   VEC_free (int, c->syscalls_to_be_caught);
8513
8514   base_breakpoint_ops.dtor (b);
8515 }
8516
8517 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8518
8519 struct catch_syscall_inferior_data
8520 {
8521   /* We keep a count of the number of times the user has requested a
8522      particular syscall to be tracked, and pass this information to the
8523      target.  This lets capable targets implement filtering directly.  */
8524
8525   /* Number of times that "any" syscall is requested.  */
8526   int any_syscall_count;
8527
8528   /* Count of each system call.  */
8529   VEC(int) *syscalls_counts;
8530
8531   /* This counts all syscall catch requests, so we can readily determine
8532      if any catching is necessary.  */
8533   int total_syscalls_count;
8534 };
8535
8536 static struct catch_syscall_inferior_data*
8537 get_catch_syscall_inferior_data (struct inferior *inf)
8538 {
8539   struct catch_syscall_inferior_data *inf_data;
8540
8541   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8542   if (inf_data == NULL)
8543     {
8544       inf_data = XCNEW (struct catch_syscall_inferior_data);
8545       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8546     }
8547
8548   return inf_data;
8549 }
8550
8551 static void
8552 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8553 {
8554   xfree (arg);
8555 }
8556
8557
8558 /* Implement the "insert" breakpoint_ops method for syscall
8559    catchpoints.  */
8560
8561 static int
8562 insert_catch_syscall (struct bp_location *bl)
8563 {
8564   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8565   struct inferior *inf = current_inferior ();
8566   struct catch_syscall_inferior_data *inf_data
8567     = get_catch_syscall_inferior_data (inf);
8568
8569   ++inf_data->total_syscalls_count;
8570   if (!c->syscalls_to_be_caught)
8571     ++inf_data->any_syscall_count;
8572   else
8573     {
8574       int i, iter;
8575
8576       for (i = 0;
8577            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8578            i++)
8579         {
8580           int elem;
8581
8582           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8583             {
8584               int old_size = VEC_length (int, inf_data->syscalls_counts);
8585               uintptr_t vec_addr_offset
8586                 = old_size * ((uintptr_t) sizeof (int));
8587               uintptr_t vec_addr;
8588               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8589               vec_addr = ((uintptr_t) VEC_address (int,
8590                                                   inf_data->syscalls_counts)
8591                           + vec_addr_offset);
8592               memset ((void *) vec_addr, 0,
8593                       (iter + 1 - old_size) * sizeof (int));
8594             }
8595           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8596           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8597         }
8598     }
8599
8600   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8601                                         inf_data->total_syscalls_count != 0,
8602                                         inf_data->any_syscall_count,
8603                                         VEC_length (int,
8604                                                     inf_data->syscalls_counts),
8605                                         VEC_address (int,
8606                                                      inf_data->syscalls_counts));
8607 }
8608
8609 /* Implement the "remove" breakpoint_ops method for syscall
8610    catchpoints.  */
8611
8612 static int
8613 remove_catch_syscall (struct bp_location *bl)
8614 {
8615   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8616   struct inferior *inf = current_inferior ();
8617   struct catch_syscall_inferior_data *inf_data
8618     = get_catch_syscall_inferior_data (inf);
8619
8620   --inf_data->total_syscalls_count;
8621   if (!c->syscalls_to_be_caught)
8622     --inf_data->any_syscall_count;
8623   else
8624     {
8625       int i, iter;
8626
8627       for (i = 0;
8628            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8629            i++)
8630         {
8631           int elem;
8632           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8633             /* Shouldn't happen.  */
8634             continue;
8635           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8636           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8637         }
8638     }
8639
8640   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8641                                         inf_data->total_syscalls_count != 0,
8642                                         inf_data->any_syscall_count,
8643                                         VEC_length (int,
8644                                                     inf_data->syscalls_counts),
8645                                         VEC_address (int,
8646                                                      inf_data->syscalls_counts));
8647 }
8648
8649 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8650    catchpoints.  */
8651
8652 static int
8653 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8654                               struct address_space *aspace, CORE_ADDR bp_addr,
8655                               const struct target_waitstatus *ws)
8656 {
8657   /* We must check if we are catching specific syscalls in this
8658      breakpoint.  If we are, then we must guarantee that the called
8659      syscall is the same syscall we are catching.  */
8660   int syscall_number = 0;
8661   const struct syscall_catchpoint *c
8662     = (const struct syscall_catchpoint *) bl->owner;
8663
8664   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8665       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8666     return 0;
8667
8668   syscall_number = ws->value.syscall_number;
8669
8670   /* Now, checking if the syscall is the same.  */
8671   if (c->syscalls_to_be_caught)
8672     {
8673       int i, iter;
8674
8675       for (i = 0;
8676            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8677            i++)
8678         if (syscall_number == iter)
8679           return 1;
8680
8681       return 0;
8682     }
8683
8684   return 1;
8685 }
8686
8687 /* Implement the "print_it" breakpoint_ops method for syscall
8688    catchpoints.  */
8689
8690 static enum print_stop_action
8691 print_it_catch_syscall (bpstat bs)
8692 {
8693   struct ui_out *uiout = current_uiout;
8694   struct breakpoint *b = bs->breakpoint_at;
8695   /* These are needed because we want to know in which state a
8696      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8697      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8698      must print "called syscall" or "returned from syscall".  */
8699   ptid_t ptid;
8700   struct target_waitstatus last;
8701   struct syscall s;
8702
8703   get_last_target_status (&ptid, &last);
8704
8705   get_syscall_by_number (last.value.syscall_number, &s);
8706
8707   annotate_catchpoint (b->number);
8708
8709   if (b->disposition == disp_del)
8710     ui_out_text (uiout, "\nTemporary catchpoint ");
8711   else
8712     ui_out_text (uiout, "\nCatchpoint ");
8713   if (ui_out_is_mi_like_p (uiout))
8714     {
8715       ui_out_field_string (uiout, "reason",
8716                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8717                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8718                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8719       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8720     }
8721   ui_out_field_int (uiout, "bkptno", b->number);
8722
8723   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8724     ui_out_text (uiout, " (call to syscall ");
8725   else
8726     ui_out_text (uiout, " (returned from syscall ");
8727
8728   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8729     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8730   if (s.name != NULL)
8731     ui_out_field_string (uiout, "syscall-name", s.name);
8732
8733   ui_out_text (uiout, "), ");
8734
8735   return PRINT_SRC_AND_LOC;
8736 }
8737
8738 /* Implement the "print_one" breakpoint_ops method for syscall
8739    catchpoints.  */
8740
8741 static void
8742 print_one_catch_syscall (struct breakpoint *b,
8743                          struct bp_location **last_loc)
8744 {
8745   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8746   struct value_print_options opts;
8747   struct ui_out *uiout = current_uiout;
8748
8749   get_user_print_options (&opts);
8750   /* Field 4, the address, is omitted (which makes the columns not
8751      line up too nicely with the headers, but the effect is relatively
8752      readable).  */
8753   if (opts.addressprint)
8754     ui_out_field_skip (uiout, "addr");
8755   annotate_field (5);
8756
8757   if (c->syscalls_to_be_caught
8758       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8759     ui_out_text (uiout, "syscalls \"");
8760   else
8761     ui_out_text (uiout, "syscall \"");
8762
8763   if (c->syscalls_to_be_caught)
8764     {
8765       int i, iter;
8766       char *text = xstrprintf ("%s", "");
8767
8768       for (i = 0;
8769            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8770            i++)
8771         {
8772           char *x = text;
8773           struct syscall s;
8774           get_syscall_by_number (iter, &s);
8775
8776           if (s.name != NULL)
8777             text = xstrprintf ("%s%s, ", text, s.name);
8778           else
8779             text = xstrprintf ("%s%d, ", text, iter);
8780
8781           /* We have to xfree the last 'text' (now stored at 'x')
8782              because xstrprintf dynamically allocates new space for it
8783              on every call.  */
8784           xfree (x);
8785         }
8786       /* Remove the last comma.  */
8787       text[strlen (text) - 2] = '\0';
8788       ui_out_field_string (uiout, "what", text);
8789     }
8790   else
8791     ui_out_field_string (uiout, "what", "<any syscall>");
8792   ui_out_text (uiout, "\" ");
8793
8794   if (ui_out_is_mi_like_p (uiout))
8795     ui_out_field_string (uiout, "catch-type", "syscall");
8796 }
8797
8798 /* Implement the "print_mention" breakpoint_ops method for syscall
8799    catchpoints.  */
8800
8801 static void
8802 print_mention_catch_syscall (struct breakpoint *b)
8803 {
8804   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8805
8806   if (c->syscalls_to_be_caught)
8807     {
8808       int i, iter;
8809
8810       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8811         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8812       else
8813         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8814
8815       for (i = 0;
8816            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8817            i++)
8818         {
8819           struct syscall s;
8820           get_syscall_by_number (iter, &s);
8821
8822           if (s.name)
8823             printf_filtered (" '%s' [%d]", s.name, s.number);
8824           else
8825             printf_filtered (" %d", s.number);
8826         }
8827       printf_filtered (")");
8828     }
8829   else
8830     printf_filtered (_("Catchpoint %d (any syscall)"),
8831                      b->number);
8832 }
8833
8834 /* Implement the "print_recreate" breakpoint_ops method for syscall
8835    catchpoints.  */
8836
8837 static void
8838 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8839 {
8840   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8841
8842   fprintf_unfiltered (fp, "catch syscall");
8843
8844   if (c->syscalls_to_be_caught)
8845     {
8846       int i, iter;
8847
8848       for (i = 0;
8849            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8850            i++)
8851         {
8852           struct syscall s;
8853
8854           get_syscall_by_number (iter, &s);
8855           if (s.name)
8856             fprintf_unfiltered (fp, " %s", s.name);
8857           else
8858             fprintf_unfiltered (fp, " %d", s.number);
8859         }
8860     }
8861   print_recreate_thread (b, fp);
8862 }
8863
8864 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8865
8866 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8867
8868 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8869
8870 static int
8871 syscall_catchpoint_p (struct breakpoint *b)
8872 {
8873   return (b->ops == &catch_syscall_breakpoint_ops);
8874 }
8875
8876 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8877    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8878    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8879    the breakpoint_ops structure associated to the catchpoint.  */
8880
8881 void
8882 init_catchpoint (struct breakpoint *b,
8883                  struct gdbarch *gdbarch, int tempflag,
8884                  char *cond_string,
8885                  const struct breakpoint_ops *ops)
8886 {
8887   struct symtab_and_line sal;
8888
8889   init_sal (&sal);
8890   sal.pspace = current_program_space;
8891
8892   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8893
8894   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8895   b->disposition = tempflag ? disp_del : disp_donttouch;
8896 }
8897
8898 void
8899 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8900 {
8901   add_to_breakpoint_chain (b);
8902   set_breakpoint_number (internal, b);
8903   if (is_tracepoint (b))
8904     set_tracepoint_count (breakpoint_count);
8905   if (!internal)
8906     mention (b);
8907   observer_notify_breakpoint_created (b);
8908
8909   if (update_gll)
8910     update_global_location_list (UGLL_MAY_INSERT);
8911 }
8912
8913 static void
8914 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8915                                     int tempflag, char *cond_string,
8916                                     const struct breakpoint_ops *ops)
8917 {
8918   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8919
8920   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8921
8922   c->forked_inferior_pid = null_ptid;
8923
8924   install_breakpoint (0, &c->base, 1);
8925 }
8926
8927 /* Exec catchpoints.  */
8928
8929 /* An instance of this type is used to represent an exec catchpoint.
8930    It includes a "struct breakpoint" as a kind of base class; users
8931    downcast to "struct breakpoint *" when needed.  A breakpoint is
8932    really of this type iff its ops pointer points to
8933    CATCH_EXEC_BREAKPOINT_OPS.  */
8934
8935 struct exec_catchpoint
8936 {
8937   /* The base class.  */
8938   struct breakpoint base;
8939
8940   /* Filename of a program whose exec triggered this catchpoint.
8941      This field is only valid immediately after this catchpoint has
8942      triggered.  */
8943   char *exec_pathname;
8944 };
8945
8946 /* Implement the "dtor" breakpoint_ops method for exec
8947    catchpoints.  */
8948
8949 static void
8950 dtor_catch_exec (struct breakpoint *b)
8951 {
8952   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8953
8954   xfree (c->exec_pathname);
8955
8956   base_breakpoint_ops.dtor (b);
8957 }
8958
8959 static int
8960 insert_catch_exec (struct bp_location *bl)
8961 {
8962   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8963 }
8964
8965 static int
8966 remove_catch_exec (struct bp_location *bl)
8967 {
8968   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8969 }
8970
8971 static int
8972 breakpoint_hit_catch_exec (const struct bp_location *bl,
8973                            struct address_space *aspace, CORE_ADDR bp_addr,
8974                            const struct target_waitstatus *ws)
8975 {
8976   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8977
8978   if (ws->kind != TARGET_WAITKIND_EXECD)
8979     return 0;
8980
8981   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8982   return 1;
8983 }
8984
8985 static enum print_stop_action
8986 print_it_catch_exec (bpstat bs)
8987 {
8988   struct ui_out *uiout = current_uiout;
8989   struct breakpoint *b = bs->breakpoint_at;
8990   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8991
8992   annotate_catchpoint (b->number);
8993   if (b->disposition == disp_del)
8994     ui_out_text (uiout, "\nTemporary catchpoint ");
8995   else
8996     ui_out_text (uiout, "\nCatchpoint ");
8997   if (ui_out_is_mi_like_p (uiout))
8998     {
8999       ui_out_field_string (uiout, "reason",
9000                            async_reason_lookup (EXEC_ASYNC_EXEC));
9001       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9002     }
9003   ui_out_field_int (uiout, "bkptno", b->number);
9004   ui_out_text (uiout, " (exec'd ");
9005   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
9006   ui_out_text (uiout, "), ");
9007
9008   return PRINT_SRC_AND_LOC;
9009 }
9010
9011 static void
9012 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
9013 {
9014   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
9015   struct value_print_options opts;
9016   struct ui_out *uiout = current_uiout;
9017
9018   get_user_print_options (&opts);
9019
9020   /* Field 4, the address, is omitted (which makes the columns
9021      not line up too nicely with the headers, but the effect
9022      is relatively readable).  */
9023   if (opts.addressprint)
9024     ui_out_field_skip (uiout, "addr");
9025   annotate_field (5);
9026   ui_out_text (uiout, "exec");
9027   if (c->exec_pathname != NULL)
9028     {
9029       ui_out_text (uiout, ", program \"");
9030       ui_out_field_string (uiout, "what", c->exec_pathname);
9031       ui_out_text (uiout, "\" ");
9032     }
9033
9034   if (ui_out_is_mi_like_p (uiout))
9035     ui_out_field_string (uiout, "catch-type", "exec");
9036 }
9037
9038 static void
9039 print_mention_catch_exec (struct breakpoint *b)
9040 {
9041   printf_filtered (_("Catchpoint %d (exec)"), b->number);
9042 }
9043
9044 /* Implement the "print_recreate" breakpoint_ops method for exec
9045    catchpoints.  */
9046
9047 static void
9048 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
9049 {
9050   fprintf_unfiltered (fp, "catch exec");
9051   print_recreate_thread (b, fp);
9052 }
9053
9054 static struct breakpoint_ops catch_exec_breakpoint_ops;
9055
9056 static void
9057 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
9058                                  const struct breakpoint_ops *ops)
9059 {
9060   struct syscall_catchpoint *c;
9061   struct gdbarch *gdbarch = get_current_arch ();
9062
9063   c = XNEW (struct syscall_catchpoint);
9064   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
9065   c->syscalls_to_be_caught = filter;
9066
9067   install_breakpoint (0, &c->base, 1);
9068 }
9069
9070 static int
9071 hw_breakpoint_used_count (void)
9072 {
9073   int i = 0;
9074   struct breakpoint *b;
9075   struct bp_location *bl;
9076
9077   ALL_BREAKPOINTS (b)
9078   {
9079     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
9080       for (bl = b->loc; bl; bl = bl->next)
9081         {
9082           /* Special types of hardware breakpoints may use more than
9083              one register.  */
9084           i += b->ops->resources_needed (bl);
9085         }
9086   }
9087
9088   return i;
9089 }
9090
9091 /* Returns the resources B would use if it were a hardware
9092    watchpoint.  */
9093
9094 static int
9095 hw_watchpoint_use_count (struct breakpoint *b)
9096 {
9097   int i = 0;
9098   struct bp_location *bl;
9099
9100   if (!breakpoint_enabled (b))
9101     return 0;
9102
9103   for (bl = b->loc; bl; bl = bl->next)
9104     {
9105       /* Special types of hardware watchpoints may use more than
9106          one register.  */
9107       i += b->ops->resources_needed (bl);
9108     }
9109
9110   return i;
9111 }
9112
9113 /* Returns the sum the used resources of all hardware watchpoints of
9114    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
9115    the sum of the used resources of all hardware watchpoints of other
9116    types _not_ TYPE.  */
9117
9118 static int
9119 hw_watchpoint_used_count_others (struct breakpoint *except,
9120                                  enum bptype type, int *other_type_used)
9121 {
9122   int i = 0;
9123   struct breakpoint *b;
9124
9125   *other_type_used = 0;
9126   ALL_BREAKPOINTS (b)
9127     {
9128       if (b == except)
9129         continue;
9130       if (!breakpoint_enabled (b))
9131         continue;
9132
9133       if (b->type == type)
9134         i += hw_watchpoint_use_count (b);
9135       else if (is_hardware_watchpoint (b))
9136         *other_type_used = 1;
9137     }
9138
9139   return i;
9140 }
9141
9142 void
9143 disable_watchpoints_before_interactive_call_start (void)
9144 {
9145   struct breakpoint *b;
9146
9147   ALL_BREAKPOINTS (b)
9148   {
9149     if (is_watchpoint (b) && breakpoint_enabled (b))
9150       {
9151         b->enable_state = bp_call_disabled;
9152         update_global_location_list (UGLL_DONT_INSERT);
9153       }
9154   }
9155 }
9156
9157 void
9158 enable_watchpoints_after_interactive_call_stop (void)
9159 {
9160   struct breakpoint *b;
9161
9162   ALL_BREAKPOINTS (b)
9163   {
9164     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9165       {
9166         b->enable_state = bp_enabled;
9167         update_global_location_list (UGLL_MAY_INSERT);
9168       }
9169   }
9170 }
9171
9172 void
9173 disable_breakpoints_before_startup (void)
9174 {
9175   current_program_space->executing_startup = 1;
9176   update_global_location_list (UGLL_DONT_INSERT);
9177 }
9178
9179 void
9180 enable_breakpoints_after_startup (void)
9181 {
9182   current_program_space->executing_startup = 0;
9183   breakpoint_re_set ();
9184 }
9185
9186
9187 /* Set a breakpoint that will evaporate an end of command
9188    at address specified by SAL.
9189    Restrict it to frame FRAME if FRAME is nonzero.  */
9190
9191 struct breakpoint *
9192 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9193                           struct frame_id frame_id, enum bptype type)
9194 {
9195   struct breakpoint *b;
9196
9197   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9198      tail-called one.  */
9199   gdb_assert (!frame_id_artificial_p (frame_id));
9200
9201   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9202   b->enable_state = bp_enabled;
9203   b->disposition = disp_donttouch;
9204   b->frame_id = frame_id;
9205
9206   /* If we're debugging a multi-threaded program, then we want
9207      momentary breakpoints to be active in only a single thread of
9208      control.  */
9209   if (in_thread_list (inferior_ptid))
9210     b->thread = pid_to_thread_id (inferior_ptid);
9211
9212   update_global_location_list_nothrow (UGLL_MAY_INSERT);
9213
9214   return b;
9215 }
9216
9217 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9218    The new breakpoint will have type TYPE, use OPS as its
9219    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9220
9221 static struct breakpoint *
9222 momentary_breakpoint_from_master (struct breakpoint *orig,
9223                                   enum bptype type,
9224                                   const struct breakpoint_ops *ops,
9225                                   int loc_enabled)
9226 {
9227   struct breakpoint *copy;
9228
9229   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9230   copy->loc = allocate_bp_location (copy);
9231   set_breakpoint_location_function (copy->loc, 1);
9232
9233   copy->loc->gdbarch = orig->loc->gdbarch;
9234   copy->loc->requested_address = orig->loc->requested_address;
9235   copy->loc->address = orig->loc->address;
9236   copy->loc->section = orig->loc->section;
9237   copy->loc->pspace = orig->loc->pspace;
9238   copy->loc->probe = orig->loc->probe;
9239   copy->loc->line_number = orig->loc->line_number;
9240   copy->loc->symtab = orig->loc->symtab;
9241   copy->loc->enabled = loc_enabled;
9242   copy->frame_id = orig->frame_id;
9243   copy->thread = orig->thread;
9244   copy->pspace = orig->pspace;
9245
9246   copy->enable_state = bp_enabled;
9247   copy->disposition = disp_donttouch;
9248   copy->number = internal_breakpoint_number--;
9249
9250   update_global_location_list_nothrow (UGLL_DONT_INSERT);
9251   return copy;
9252 }
9253
9254 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9255    ORIG is NULL.  */
9256
9257 struct breakpoint *
9258 clone_momentary_breakpoint (struct breakpoint *orig)
9259 {
9260   /* If there's nothing to clone, then return nothing.  */
9261   if (orig == NULL)
9262     return NULL;
9263
9264   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9265 }
9266
9267 struct breakpoint *
9268 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9269                                 enum bptype type)
9270 {
9271   struct symtab_and_line sal;
9272
9273   sal = find_pc_line (pc, 0);
9274   sal.pc = pc;
9275   sal.section = find_pc_overlay (pc);
9276   sal.explicit_pc = 1;
9277
9278   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9279 }
9280 \f
9281
9282 /* Tell the user we have just set a breakpoint B.  */
9283
9284 static void
9285 mention (struct breakpoint *b)
9286 {
9287   b->ops->print_mention (b);
9288   if (ui_out_is_mi_like_p (current_uiout))
9289     return;
9290   printf_filtered ("\n");
9291 }
9292 \f
9293
9294 static struct bp_location *
9295 add_location_to_breakpoint (struct breakpoint *b,
9296                             const struct symtab_and_line *sal)
9297 {
9298   struct bp_location *loc, **tmp;
9299   CORE_ADDR adjusted_address;
9300   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9301
9302   if (loc_gdbarch == NULL)
9303     loc_gdbarch = b->gdbarch;
9304
9305   /* Adjust the breakpoint's address prior to allocating a location.
9306      Once we call allocate_bp_location(), that mostly uninitialized
9307      location will be placed on the location chain.  Adjustment of the
9308      breakpoint may cause target_read_memory() to be called and we do
9309      not want its scan of the location chain to find a breakpoint and
9310      location that's only been partially initialized.  */
9311   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9312                                                 sal->pc, b->type);
9313
9314   /* Sort the locations by their ADDRESS.  */
9315   loc = allocate_bp_location (b);
9316   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9317        tmp = &((*tmp)->next))
9318     ;
9319   loc->next = *tmp;
9320   *tmp = loc;
9321
9322   loc->requested_address = sal->pc;
9323   loc->address = adjusted_address;
9324   loc->pspace = sal->pspace;
9325   loc->probe.probe = sal->probe;
9326   loc->probe.objfile = sal->objfile;
9327   gdb_assert (loc->pspace != NULL);
9328   loc->section = sal->section;
9329   loc->gdbarch = loc_gdbarch;
9330   loc->line_number = sal->line;
9331   loc->symtab = sal->symtab;
9332
9333   set_breakpoint_location_function (loc,
9334                                     sal->explicit_pc || sal->explicit_line);
9335   return loc;
9336 }
9337 \f
9338
9339 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9340    return 0 otherwise.  */
9341
9342 static int
9343 bp_loc_is_permanent (struct bp_location *loc)
9344 {
9345   int len;
9346   CORE_ADDR addr;
9347   const gdb_byte *bpoint;
9348   gdb_byte *target_mem;
9349   struct cleanup *cleanup;
9350   int retval = 0;
9351
9352   gdb_assert (loc != NULL);
9353
9354   addr = loc->address;
9355   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9356
9357   /* Software breakpoints unsupported?  */
9358   if (bpoint == NULL)
9359     return 0;
9360
9361   target_mem = alloca (len);
9362
9363   /* Enable the automatic memory restoration from breakpoints while
9364      we read the memory.  Otherwise we could say about our temporary
9365      breakpoints they are permanent.  */
9366   cleanup = save_current_space_and_thread ();
9367
9368   switch_to_program_space_and_thread (loc->pspace);
9369   make_show_memory_breakpoints_cleanup (0);
9370
9371   if (target_read_memory (loc->address, target_mem, len) == 0
9372       && memcmp (target_mem, bpoint, len) == 0)
9373     retval = 1;
9374
9375   do_cleanups (cleanup);
9376
9377   return retval;
9378 }
9379
9380 /* Build a command list for the dprintf corresponding to the current
9381    settings of the dprintf style options.  */
9382
9383 static void
9384 update_dprintf_command_list (struct breakpoint *b)
9385 {
9386   char *dprintf_args = b->extra_string;
9387   char *printf_line = NULL;
9388
9389   if (!dprintf_args)
9390     return;
9391
9392   dprintf_args = skip_spaces (dprintf_args);
9393
9394   /* Allow a comma, as it may have terminated a location, but don't
9395      insist on it.  */
9396   if (*dprintf_args == ',')
9397     ++dprintf_args;
9398   dprintf_args = skip_spaces (dprintf_args);
9399
9400   if (*dprintf_args != '"')
9401     error (_("Bad format string, missing '\"'."));
9402
9403   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9404     printf_line = xstrprintf ("printf %s", dprintf_args);
9405   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9406     {
9407       if (!dprintf_function)
9408         error (_("No function supplied for dprintf call"));
9409
9410       if (dprintf_channel && strlen (dprintf_channel) > 0)
9411         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9412                                   dprintf_function,
9413                                   dprintf_channel,
9414                                   dprintf_args);
9415       else
9416         printf_line = xstrprintf ("call (void) %s (%s)",
9417                                   dprintf_function,
9418                                   dprintf_args);
9419     }
9420   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9421     {
9422       if (target_can_run_breakpoint_commands ())
9423         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9424       else
9425         {
9426           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9427           printf_line = xstrprintf ("printf %s", dprintf_args);
9428         }
9429     }
9430   else
9431     internal_error (__FILE__, __LINE__,
9432                     _("Invalid dprintf style."));
9433
9434   gdb_assert (printf_line != NULL);
9435   /* Manufacture a printf sequence.  */
9436   {
9437     struct command_line *printf_cmd_line
9438       = xmalloc (sizeof (struct command_line));
9439
9440     printf_cmd_line = xmalloc (sizeof (struct command_line));
9441     printf_cmd_line->control_type = simple_control;
9442     printf_cmd_line->body_count = 0;
9443     printf_cmd_line->body_list = NULL;
9444     printf_cmd_line->next = NULL;
9445     printf_cmd_line->line = printf_line;
9446
9447     breakpoint_set_commands (b, printf_cmd_line);
9448   }
9449 }
9450
9451 /* Update all dprintf commands, making their command lists reflect
9452    current style settings.  */
9453
9454 static void
9455 update_dprintf_commands (char *args, int from_tty,
9456                          struct cmd_list_element *c)
9457 {
9458   struct breakpoint *b;
9459
9460   ALL_BREAKPOINTS (b)
9461     {
9462       if (b->type == bp_dprintf)
9463         update_dprintf_command_list (b);
9464     }
9465 }
9466
9467 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9468    as textual description of the location, and COND_STRING
9469    as condition expression.  */
9470
9471 static void
9472 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9473                      struct symtabs_and_lines sals, char *addr_string,
9474                      char *filter, char *cond_string,
9475                      char *extra_string,
9476                      enum bptype type, enum bpdisp disposition,
9477                      int thread, int task, int ignore_count,
9478                      const struct breakpoint_ops *ops, int from_tty,
9479                      int enabled, int internal, unsigned flags,
9480                      int display_canonical)
9481 {
9482   int i;
9483
9484   if (type == bp_hardware_breakpoint)
9485     {
9486       int target_resources_ok;
9487
9488       i = hw_breakpoint_used_count ();
9489       target_resources_ok =
9490         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9491                                             i + 1, 0);
9492       if (target_resources_ok == 0)
9493         error (_("No hardware breakpoint support in the target."));
9494       else if (target_resources_ok < 0)
9495         error (_("Hardware breakpoints used exceeds limit."));
9496     }
9497
9498   gdb_assert (sals.nelts > 0);
9499
9500   for (i = 0; i < sals.nelts; ++i)
9501     {
9502       struct symtab_and_line sal = sals.sals[i];
9503       struct bp_location *loc;
9504
9505       if (from_tty)
9506         {
9507           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9508           if (!loc_gdbarch)
9509             loc_gdbarch = gdbarch;
9510
9511           describe_other_breakpoints (loc_gdbarch,
9512                                       sal.pspace, sal.pc, sal.section, thread);
9513         }
9514
9515       if (i == 0)
9516         {
9517           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9518           b->thread = thread;
9519           b->task = task;
9520
9521           b->cond_string = cond_string;
9522           b->extra_string = extra_string;
9523           b->ignore_count = ignore_count;
9524           b->enable_state = enabled ? bp_enabled : bp_disabled;
9525           b->disposition = disposition;
9526
9527           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9528             b->loc->inserted = 1;
9529
9530           if (type == bp_static_tracepoint)
9531             {
9532               struct tracepoint *t = (struct tracepoint *) b;
9533               struct static_tracepoint_marker marker;
9534
9535               if (strace_marker_p (b))
9536                 {
9537                   /* We already know the marker exists, otherwise, we
9538                      wouldn't see a sal for it.  */
9539                   char *p = &addr_string[3];
9540                   char *endp;
9541                   char *marker_str;
9542
9543                   p = skip_spaces (p);
9544
9545                   endp = skip_to_space (p);
9546
9547                   marker_str = savestring (p, endp - p);
9548                   t->static_trace_marker_id = marker_str;
9549
9550                   printf_filtered (_("Probed static tracepoint "
9551                                      "marker \"%s\"\n"),
9552                                    t->static_trace_marker_id);
9553                 }
9554               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9555                 {
9556                   t->static_trace_marker_id = xstrdup (marker.str_id);
9557                   release_static_tracepoint_marker (&marker);
9558
9559                   printf_filtered (_("Probed static tracepoint "
9560                                      "marker \"%s\"\n"),
9561                                    t->static_trace_marker_id);
9562                 }
9563               else
9564                 warning (_("Couldn't determine the static "
9565                            "tracepoint marker to probe"));
9566             }
9567
9568           loc = b->loc;
9569         }
9570       else
9571         {
9572           loc = add_location_to_breakpoint (b, &sal);
9573           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9574             loc->inserted = 1;
9575         }
9576
9577       if (bp_loc_is_permanent (loc))
9578         make_breakpoint_permanent (b);
9579
9580       if (b->cond_string)
9581         {
9582           const char *arg = b->cond_string;
9583
9584           loc->cond = parse_exp_1 (&arg, loc->address,
9585                                    block_for_pc (loc->address), 0);
9586           if (*arg)
9587               error (_("Garbage '%s' follows condition"), arg);
9588         }
9589
9590       /* Dynamic printf requires and uses additional arguments on the
9591          command line, otherwise it's an error.  */
9592       if (type == bp_dprintf)
9593         {
9594           if (b->extra_string)
9595             update_dprintf_command_list (b);
9596           else
9597             error (_("Format string required"));
9598         }
9599       else if (b->extra_string)
9600         error (_("Garbage '%s' at end of command"), b->extra_string);
9601     }
9602
9603   b->display_canonical = display_canonical;
9604   if (addr_string)
9605     b->addr_string = addr_string;
9606   else
9607     /* addr_string has to be used or breakpoint_re_set will delete
9608        me.  */
9609     b->addr_string
9610       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9611   b->filter = filter;
9612 }
9613
9614 static void
9615 create_breakpoint_sal (struct gdbarch *gdbarch,
9616                        struct symtabs_and_lines sals, char *addr_string,
9617                        char *filter, char *cond_string,
9618                        char *extra_string,
9619                        enum bptype type, enum bpdisp disposition,
9620                        int thread, int task, int ignore_count,
9621                        const struct breakpoint_ops *ops, int from_tty,
9622                        int enabled, int internal, unsigned flags,
9623                        int display_canonical)
9624 {
9625   struct breakpoint *b;
9626   struct cleanup *old_chain;
9627
9628   if (is_tracepoint_type (type))
9629     {
9630       struct tracepoint *t;
9631
9632       t = XCNEW (struct tracepoint);
9633       b = &t->base;
9634     }
9635   else
9636     b = XNEW (struct breakpoint);
9637
9638   old_chain = make_cleanup (xfree, b);
9639
9640   init_breakpoint_sal (b, gdbarch,
9641                        sals, addr_string,
9642                        filter, cond_string, extra_string,
9643                        type, disposition,
9644                        thread, task, ignore_count,
9645                        ops, from_tty,
9646                        enabled, internal, flags,
9647                        display_canonical);
9648   discard_cleanups (old_chain);
9649
9650   install_breakpoint (internal, b, 0);
9651 }
9652
9653 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9654    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9655    value.  COND_STRING, if not NULL, specified the condition to be
9656    used for all breakpoints.  Essentially the only case where
9657    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9658    function.  In that case, it's still not possible to specify
9659    separate conditions for different overloaded functions, so
9660    we take just a single condition string.
9661    
9662    NOTE: If the function succeeds, the caller is expected to cleanup
9663    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9664    array contents).  If the function fails (error() is called), the
9665    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9666    COND and SALS arrays and each of those arrays contents.  */
9667
9668 static void
9669 create_breakpoints_sal (struct gdbarch *gdbarch,
9670                         struct linespec_result *canonical,
9671                         char *cond_string, char *extra_string,
9672                         enum bptype type, enum bpdisp disposition,
9673                         int thread, int task, int ignore_count,
9674                         const struct breakpoint_ops *ops, int from_tty,
9675                         int enabled, int internal, unsigned flags)
9676 {
9677   int i;
9678   struct linespec_sals *lsal;
9679
9680   if (canonical->pre_expanded)
9681     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9682
9683   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9684     {
9685       /* Note that 'addr_string' can be NULL in the case of a plain
9686          'break', without arguments.  */
9687       char *addr_string = (canonical->addr_string
9688                            ? xstrdup (canonical->addr_string)
9689                            : NULL);
9690       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9691       struct cleanup *inner = make_cleanup (xfree, addr_string);
9692
9693       make_cleanup (xfree, filter_string);
9694       create_breakpoint_sal (gdbarch, lsal->sals,
9695                              addr_string,
9696                              filter_string,
9697                              cond_string, extra_string,
9698                              type, disposition,
9699                              thread, task, ignore_count, ops,
9700                              from_tty, enabled, internal, flags,
9701                              canonical->special_display);
9702       discard_cleanups (inner);
9703     }
9704 }
9705
9706 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9707    followed by conditionals.  On return, SALS contains an array of SAL
9708    addresses found.  ADDR_STRING contains a vector of (canonical)
9709    address strings.  ADDRESS points to the end of the SAL.
9710
9711    The array and the line spec strings are allocated on the heap, it is
9712    the caller's responsibility to free them.  */
9713
9714 static void
9715 parse_breakpoint_sals (char **address,
9716                        struct linespec_result *canonical)
9717 {
9718   /* If no arg given, or if first arg is 'if ', use the default
9719      breakpoint.  */
9720   if ((*address) == NULL
9721       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9722     {
9723       /* The last displayed codepoint, if it's valid, is our default breakpoint
9724          address.  */
9725       if (last_displayed_sal_is_valid ())
9726         {
9727           struct linespec_sals lsal;
9728           struct symtab_and_line sal;
9729           CORE_ADDR pc;
9730
9731           init_sal (&sal);              /* Initialize to zeroes.  */
9732           lsal.sals.sals = (struct symtab_and_line *)
9733             xmalloc (sizeof (struct symtab_and_line));
9734
9735           /* Set sal's pspace, pc, symtab, and line to the values
9736              corresponding to the last call to print_frame_info.
9737              Be sure to reinitialize LINE with NOTCURRENT == 0
9738              as the breakpoint line number is inappropriate otherwise.
9739              find_pc_line would adjust PC, re-set it back.  */
9740           get_last_displayed_sal (&sal);
9741           pc = sal.pc;
9742           sal = find_pc_line (pc, 0);
9743
9744           /* "break" without arguments is equivalent to "break *PC"
9745              where PC is the last displayed codepoint's address.  So
9746              make sure to set sal.explicit_pc to prevent GDB from
9747              trying to expand the list of sals to include all other
9748              instances with the same symtab and line.  */
9749           sal.pc = pc;
9750           sal.explicit_pc = 1;
9751
9752           lsal.sals.sals[0] = sal;
9753           lsal.sals.nelts = 1;
9754           lsal.canonical = NULL;
9755
9756           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9757         }
9758       else
9759         error (_("No default breakpoint address now."));
9760     }
9761   else
9762     {
9763       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9764
9765       /* Force almost all breakpoints to be in terms of the
9766          current_source_symtab (which is decode_line_1's default).
9767          This should produce the results we want almost all of the
9768          time while leaving default_breakpoint_* alone.
9769
9770          ObjC: However, don't match an Objective-C method name which
9771          may have a '+' or '-' succeeded by a '['.  */
9772       if (last_displayed_sal_is_valid ()
9773           && (!cursal.symtab
9774               || ((strchr ("+-", (*address)[0]) != NULL)
9775                   && ((*address)[1] != '['))))
9776         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9777                           get_last_displayed_symtab (),
9778                           get_last_displayed_line (),
9779                           canonical, NULL, NULL);
9780       else
9781         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9782                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9783     }
9784 }
9785
9786
9787 /* Convert each SAL into a real PC.  Verify that the PC can be
9788    inserted as a breakpoint.  If it can't throw an error.  */
9789
9790 static void
9791 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9792 {    
9793   int i;
9794
9795   for (i = 0; i < sals->nelts; i++)
9796     resolve_sal_pc (&sals->sals[i]);
9797 }
9798
9799 /* Fast tracepoints may have restrictions on valid locations.  For
9800    instance, a fast tracepoint using a jump instead of a trap will
9801    likely have to overwrite more bytes than a trap would, and so can
9802    only be placed where the instruction is longer than the jump, or a
9803    multi-instruction sequence does not have a jump into the middle of
9804    it, etc.  */
9805
9806 static void
9807 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9808                             struct symtabs_and_lines *sals)
9809 {
9810   int i, rslt;
9811   struct symtab_and_line *sal;
9812   char *msg;
9813   struct cleanup *old_chain;
9814
9815   for (i = 0; i < sals->nelts; i++)
9816     {
9817       struct gdbarch *sarch;
9818
9819       sal = &sals->sals[i];
9820
9821       sarch = get_sal_arch (*sal);
9822       /* We fall back to GDBARCH if there is no architecture
9823          associated with SAL.  */
9824       if (sarch == NULL)
9825         sarch = gdbarch;
9826       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9827                                                NULL, &msg);
9828       old_chain = make_cleanup (xfree, msg);
9829
9830       if (!rslt)
9831         error (_("May not have a fast tracepoint at 0x%s%s"),
9832                paddress (sarch, sal->pc), (msg ? msg : ""));
9833
9834       do_cleanups (old_chain);
9835     }
9836 }
9837
9838 /* Issue an invalid thread ID error.  */
9839
9840 static void ATTRIBUTE_NORETURN
9841 invalid_thread_id_error (int id)
9842 {
9843   error (_("Unknown thread %d."), id);
9844 }
9845
9846 /* Given TOK, a string specification of condition and thread, as
9847    accepted by the 'break' command, extract the condition
9848    string and thread number and set *COND_STRING and *THREAD.
9849    PC identifies the context at which the condition should be parsed.
9850    If no condition is found, *COND_STRING is set to NULL.
9851    If no thread is found, *THREAD is set to -1.  */
9852
9853 static void
9854 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9855                            char **cond_string, int *thread, int *task,
9856                            char **rest)
9857 {
9858   *cond_string = NULL;
9859   *thread = -1;
9860   *task = 0;
9861   *rest = NULL;
9862
9863   while (tok && *tok)
9864     {
9865       const char *end_tok;
9866       int toklen;
9867       const char *cond_start = NULL;
9868       const char *cond_end = NULL;
9869
9870       tok = skip_spaces_const (tok);
9871
9872       if ((*tok == '"' || *tok == ',') && rest)
9873         {
9874           *rest = savestring (tok, strlen (tok));
9875           return;
9876         }
9877
9878       end_tok = skip_to_space_const (tok);
9879
9880       toklen = end_tok - tok;
9881
9882       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9883         {
9884           struct expression *expr;
9885
9886           tok = cond_start = end_tok + 1;
9887           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9888           xfree (expr);
9889           cond_end = tok;
9890           *cond_string = savestring (cond_start, cond_end - cond_start);
9891         }
9892       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9893         {
9894           char *tmptok;
9895
9896           tok = end_tok + 1;
9897           *thread = strtol (tok, &tmptok, 0);
9898           if (tok == tmptok)
9899             error (_("Junk after thread keyword."));
9900           if (!valid_thread_id (*thread))
9901             invalid_thread_id_error (*thread);
9902           tok = tmptok;
9903         }
9904       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9905         {
9906           char *tmptok;
9907
9908           tok = end_tok + 1;
9909           *task = strtol (tok, &tmptok, 0);
9910           if (tok == tmptok)
9911             error (_("Junk after task keyword."));
9912           if (!valid_task_id (*task))
9913             error (_("Unknown task %d."), *task);
9914           tok = tmptok;
9915         }
9916       else if (rest)
9917         {
9918           *rest = savestring (tok, strlen (tok));
9919           return;
9920         }
9921       else
9922         error (_("Junk at end of arguments."));
9923     }
9924 }
9925
9926 /* Decode a static tracepoint marker spec.  */
9927
9928 static struct symtabs_and_lines
9929 decode_static_tracepoint_spec (char **arg_p)
9930 {
9931   VEC(static_tracepoint_marker_p) *markers = NULL;
9932   struct symtabs_and_lines sals;
9933   struct cleanup *old_chain;
9934   char *p = &(*arg_p)[3];
9935   char *endp;
9936   char *marker_str;
9937   int i;
9938
9939   p = skip_spaces (p);
9940
9941   endp = skip_to_space (p);
9942
9943   marker_str = savestring (p, endp - p);
9944   old_chain = make_cleanup (xfree, marker_str);
9945
9946   markers = target_static_tracepoint_markers_by_strid (marker_str);
9947   if (VEC_empty(static_tracepoint_marker_p, markers))
9948     error (_("No known static tracepoint marker named %s"), marker_str);
9949
9950   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9951   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9952
9953   for (i = 0; i < sals.nelts; i++)
9954     {
9955       struct static_tracepoint_marker *marker;
9956
9957       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9958
9959       init_sal (&sals.sals[i]);
9960
9961       sals.sals[i] = find_pc_line (marker->address, 0);
9962       sals.sals[i].pc = marker->address;
9963
9964       release_static_tracepoint_marker (marker);
9965     }
9966
9967   do_cleanups (old_chain);
9968
9969   *arg_p = endp;
9970   return sals;
9971 }
9972
9973 /* Set a breakpoint.  This function is shared between CLI and MI
9974    functions for setting a breakpoint.  This function has two major
9975    modes of operations, selected by the PARSE_ARG parameter.  If
9976    non-zero, the function will parse ARG, extracting location,
9977    condition, thread and extra string.  Otherwise, ARG is just the
9978    breakpoint's location, with condition, thread, and extra string
9979    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9980    If INTERNAL is non-zero, the breakpoint number will be allocated
9981    from the internal breakpoint count.  Returns true if any breakpoint
9982    was created; false otherwise.  */
9983
9984 int
9985 create_breakpoint (struct gdbarch *gdbarch,
9986                    char *arg, char *cond_string,
9987                    int thread, char *extra_string,
9988                    int parse_arg,
9989                    int tempflag, enum bptype type_wanted,
9990                    int ignore_count,
9991                    enum auto_boolean pending_break_support,
9992                    const struct breakpoint_ops *ops,
9993                    int from_tty, int enabled, int internal,
9994                    unsigned flags)
9995 {
9996   volatile struct gdb_exception e;
9997   char *copy_arg = NULL;
9998   char *addr_start = arg;
9999   struct linespec_result canonical;
10000   struct cleanup *old_chain;
10001   struct cleanup *bkpt_chain = NULL;
10002   int pending = 0;
10003   int task = 0;
10004   int prev_bkpt_count = breakpoint_count;
10005
10006   gdb_assert (ops != NULL);
10007
10008   init_linespec_result (&canonical);
10009
10010   TRY_CATCH (e, RETURN_MASK_ALL)
10011     {
10012       ops->create_sals_from_address (&arg, &canonical, type_wanted,
10013                                      addr_start, &copy_arg);
10014     }
10015
10016   /* If caller is interested in rc value from parse, set value.  */
10017   switch (e.reason)
10018     {
10019     case GDB_NO_ERROR:
10020       if (VEC_empty (linespec_sals, canonical.sals))
10021         return 0;
10022       break;
10023     case RETURN_ERROR:
10024       switch (e.error)
10025         {
10026         case NOT_FOUND_ERROR:
10027
10028           /* If pending breakpoint support is turned off, throw
10029              error.  */
10030
10031           if (pending_break_support == AUTO_BOOLEAN_FALSE)
10032             throw_exception (e);
10033
10034           exception_print (gdb_stderr, e);
10035
10036           /* If pending breakpoint support is auto query and the user
10037              selects no, then simply return the error code.  */
10038           if (pending_break_support == AUTO_BOOLEAN_AUTO
10039               && !nquery (_("Make %s pending on future shared library load? "),
10040                           bptype_string (type_wanted)))
10041             return 0;
10042
10043           /* At this point, either the user was queried about setting
10044              a pending breakpoint and selected yes, or pending
10045              breakpoint behavior is on and thus a pending breakpoint
10046              is defaulted on behalf of the user.  */
10047           {
10048             struct linespec_sals lsal;
10049
10050             copy_arg = xstrdup (addr_start);
10051             lsal.canonical = xstrdup (copy_arg);
10052             lsal.sals.nelts = 1;
10053             lsal.sals.sals = XNEW (struct symtab_and_line);
10054             init_sal (&lsal.sals.sals[0]);
10055             pending = 1;
10056             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
10057           }
10058           break;
10059         default:
10060           throw_exception (e);
10061         }
10062       break;
10063     default:
10064       throw_exception (e);
10065     }
10066
10067   /* Create a chain of things that always need to be cleaned up.  */
10068   old_chain = make_cleanup_destroy_linespec_result (&canonical);
10069
10070   /* ----------------------------- SNIP -----------------------------
10071      Anything added to the cleanup chain beyond this point is assumed
10072      to be part of a breakpoint.  If the breakpoint create succeeds
10073      then the memory is not reclaimed.  */
10074   bkpt_chain = make_cleanup (null_cleanup, 0);
10075
10076   /* Resolve all line numbers to PC's and verify that the addresses
10077      are ok for the target.  */
10078   if (!pending)
10079     {
10080       int ix;
10081       struct linespec_sals *iter;
10082
10083       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10084         breakpoint_sals_to_pc (&iter->sals);
10085     }
10086
10087   /* Fast tracepoints may have additional restrictions on location.  */
10088   if (!pending && type_wanted == bp_fast_tracepoint)
10089     {
10090       int ix;
10091       struct linespec_sals *iter;
10092
10093       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10094         check_fast_tracepoint_sals (gdbarch, &iter->sals);
10095     }
10096
10097   /* Verify that condition can be parsed, before setting any
10098      breakpoints.  Allocate a separate condition expression for each
10099      breakpoint.  */
10100   if (!pending)
10101     {
10102       if (parse_arg)
10103         {
10104           char *rest;
10105           struct linespec_sals *lsal;
10106
10107           lsal = VEC_index (linespec_sals, canonical.sals, 0);
10108
10109           /* Here we only parse 'arg' to separate condition
10110              from thread number, so parsing in context of first
10111              sal is OK.  When setting the breakpoint we'll
10112              re-parse it in context of each sal.  */
10113
10114           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
10115                                      &thread, &task, &rest);
10116           if (cond_string)
10117             make_cleanup (xfree, cond_string);
10118           if (rest)
10119             make_cleanup (xfree, rest);
10120           if (rest)
10121             extra_string = rest;
10122         }
10123       else
10124         {
10125           if (*arg != '\0')
10126             error (_("Garbage '%s' at end of location"), arg);
10127
10128           /* Create a private copy of condition string.  */
10129           if (cond_string)
10130             {
10131               cond_string = xstrdup (cond_string);
10132               make_cleanup (xfree, cond_string);
10133             }
10134           /* Create a private copy of any extra string.  */
10135           if (extra_string)
10136             {
10137               extra_string = xstrdup (extra_string);
10138               make_cleanup (xfree, extra_string);
10139             }
10140         }
10141
10142       ops->create_breakpoints_sal (gdbarch, &canonical,
10143                                    cond_string, extra_string, type_wanted,
10144                                    tempflag ? disp_del : disp_donttouch,
10145                                    thread, task, ignore_count, ops,
10146                                    from_tty, enabled, internal, flags);
10147     }
10148   else
10149     {
10150       struct breakpoint *b;
10151
10152       make_cleanup (xfree, copy_arg);
10153
10154       if (is_tracepoint_type (type_wanted))
10155         {
10156           struct tracepoint *t;
10157
10158           t = XCNEW (struct tracepoint);
10159           b = &t->base;
10160         }
10161       else
10162         b = XNEW (struct breakpoint);
10163
10164       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10165
10166       b->addr_string = copy_arg;
10167       if (parse_arg)
10168         b->cond_string = NULL;
10169       else
10170         {
10171           /* Create a private copy of condition string.  */
10172           if (cond_string)
10173             {
10174               cond_string = xstrdup (cond_string);
10175               make_cleanup (xfree, cond_string);
10176             }
10177           b->cond_string = cond_string;
10178         }
10179       b->extra_string = NULL;
10180       b->ignore_count = ignore_count;
10181       b->disposition = tempflag ? disp_del : disp_donttouch;
10182       b->condition_not_parsed = 1;
10183       b->enable_state = enabled ? bp_enabled : bp_disabled;
10184       if ((type_wanted != bp_breakpoint
10185            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10186         b->pspace = current_program_space;
10187
10188       install_breakpoint (internal, b, 0);
10189     }
10190   
10191   if (VEC_length (linespec_sals, canonical.sals) > 1)
10192     {
10193       warning (_("Multiple breakpoints were set.\nUse the "
10194                  "\"delete\" command to delete unwanted breakpoints."));
10195       prev_breakpoint_count = prev_bkpt_count;
10196     }
10197
10198   /* That's it.  Discard the cleanups for data inserted into the
10199      breakpoint.  */
10200   discard_cleanups (bkpt_chain);
10201   /* But cleanup everything else.  */
10202   do_cleanups (old_chain);
10203
10204   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10205   update_global_location_list (UGLL_MAY_INSERT);
10206
10207   return 1;
10208 }
10209
10210 /* Set a breakpoint.
10211    ARG is a string describing breakpoint address,
10212    condition, and thread.
10213    FLAG specifies if a breakpoint is hardware on,
10214    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10215    and BP_TEMPFLAG.  */
10216
10217 static void
10218 break_command_1 (char *arg, int flag, int from_tty)
10219 {
10220   int tempflag = flag & BP_TEMPFLAG;
10221   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10222                              ? bp_hardware_breakpoint
10223                              : bp_breakpoint);
10224   struct breakpoint_ops *ops;
10225   const char *arg_cp = arg;
10226
10227   /* Matching breakpoints on probes.  */
10228   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10229     ops = &bkpt_probe_breakpoint_ops;
10230   else
10231     ops = &bkpt_breakpoint_ops;
10232
10233   create_breakpoint (get_current_arch (),
10234                      arg,
10235                      NULL, 0, NULL, 1 /* parse arg */,
10236                      tempflag, type_wanted,
10237                      0 /* Ignore count */,
10238                      pending_break_support,
10239                      ops,
10240                      from_tty,
10241                      1 /* enabled */,
10242                      0 /* internal */,
10243                      0);
10244 }
10245
10246 /* Helper function for break_command_1 and disassemble_command.  */
10247
10248 void
10249 resolve_sal_pc (struct symtab_and_line *sal)
10250 {
10251   CORE_ADDR pc;
10252
10253   if (sal->pc == 0 && sal->symtab != NULL)
10254     {
10255       if (!find_line_pc (sal->symtab, sal->line, &pc))
10256         error (_("No line %d in file \"%s\"."),
10257                sal->line, symtab_to_filename_for_display (sal->symtab));
10258       sal->pc = pc;
10259
10260       /* If this SAL corresponds to a breakpoint inserted using a line
10261          number, then skip the function prologue if necessary.  */
10262       if (sal->explicit_line)
10263         skip_prologue_sal (sal);
10264     }
10265
10266   if (sal->section == 0 && sal->symtab != NULL)
10267     {
10268       const struct blockvector *bv;
10269       const struct block *b;
10270       struct symbol *sym;
10271
10272       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10273       if (bv != NULL)
10274         {
10275           sym = block_linkage_function (b);
10276           if (sym != NULL)
10277             {
10278               fixup_symbol_section (sym, sal->symtab->objfile);
10279               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10280             }
10281           else
10282             {
10283               /* It really is worthwhile to have the section, so we'll
10284                  just have to look harder. This case can be executed
10285                  if we have line numbers but no functions (as can
10286                  happen in assembly source).  */
10287
10288               struct bound_minimal_symbol msym;
10289               struct cleanup *old_chain = save_current_space_and_thread ();
10290
10291               switch_to_program_space_and_thread (sal->pspace);
10292
10293               msym = lookup_minimal_symbol_by_pc (sal->pc);
10294               if (msym.minsym)
10295                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10296
10297               do_cleanups (old_chain);
10298             }
10299         }
10300     }
10301 }
10302
10303 void
10304 break_command (char *arg, int from_tty)
10305 {
10306   break_command_1 (arg, 0, from_tty);
10307 }
10308
10309 void
10310 tbreak_command (char *arg, int from_tty)
10311 {
10312   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10313 }
10314
10315 static void
10316 hbreak_command (char *arg, int from_tty)
10317 {
10318   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10319 }
10320
10321 static void
10322 thbreak_command (char *arg, int from_tty)
10323 {
10324   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10325 }
10326
10327 static void
10328 stop_command (char *arg, int from_tty)
10329 {
10330   printf_filtered (_("Specify the type of breakpoint to set.\n\
10331 Usage: stop in <function | address>\n\
10332        stop at <line>\n"));
10333 }
10334
10335 static void
10336 stopin_command (char *arg, int from_tty)
10337 {
10338   int badInput = 0;
10339
10340   if (arg == (char *) NULL)
10341     badInput = 1;
10342   else if (*arg != '*')
10343     {
10344       char *argptr = arg;
10345       int hasColon = 0;
10346
10347       /* Look for a ':'.  If this is a line number specification, then
10348          say it is bad, otherwise, it should be an address or
10349          function/method name.  */
10350       while (*argptr && !hasColon)
10351         {
10352           hasColon = (*argptr == ':');
10353           argptr++;
10354         }
10355
10356       if (hasColon)
10357         badInput = (*argptr != ':');    /* Not a class::method */
10358       else
10359         badInput = isdigit (*arg);      /* a simple line number */
10360     }
10361
10362   if (badInput)
10363     printf_filtered (_("Usage: stop in <function | address>\n"));
10364   else
10365     break_command_1 (arg, 0, from_tty);
10366 }
10367
10368 static void
10369 stopat_command (char *arg, int from_tty)
10370 {
10371   int badInput = 0;
10372
10373   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10374     badInput = 1;
10375   else
10376     {
10377       char *argptr = arg;
10378       int hasColon = 0;
10379
10380       /* Look for a ':'.  If there is a '::' then get out, otherwise
10381          it is probably a line number.  */
10382       while (*argptr && !hasColon)
10383         {
10384           hasColon = (*argptr == ':');
10385           argptr++;
10386         }
10387
10388       if (hasColon)
10389         badInput = (*argptr == ':');    /* we have class::method */
10390       else
10391         badInput = !isdigit (*arg);     /* not a line number */
10392     }
10393
10394   if (badInput)
10395     printf_filtered (_("Usage: stop at <line>\n"));
10396   else
10397     break_command_1 (arg, 0, from_tty);
10398 }
10399
10400 /* The dynamic printf command is mostly like a regular breakpoint, but
10401    with a prewired command list consisting of a single output command,
10402    built from extra arguments supplied on the dprintf command
10403    line.  */
10404
10405 static void
10406 dprintf_command (char *arg, int from_tty)
10407 {
10408   create_breakpoint (get_current_arch (),
10409                      arg,
10410                      NULL, 0, NULL, 1 /* parse arg */,
10411                      0, bp_dprintf,
10412                      0 /* Ignore count */,
10413                      pending_break_support,
10414                      &dprintf_breakpoint_ops,
10415                      from_tty,
10416                      1 /* enabled */,
10417                      0 /* internal */,
10418                      0);
10419 }
10420
10421 static void
10422 agent_printf_command (char *arg, int from_tty)
10423 {
10424   error (_("May only run agent-printf on the target"));
10425 }
10426
10427 /* Implement the "breakpoint_hit" breakpoint_ops method for
10428    ranged breakpoints.  */
10429
10430 static int
10431 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10432                                   struct address_space *aspace,
10433                                   CORE_ADDR bp_addr,
10434                                   const struct target_waitstatus *ws)
10435 {
10436   if (ws->kind != TARGET_WAITKIND_STOPPED
10437       || ws->value.sig != GDB_SIGNAL_TRAP)
10438     return 0;
10439
10440   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10441                                          bl->length, aspace, bp_addr);
10442 }
10443
10444 /* Implement the "resources_needed" breakpoint_ops method for
10445    ranged breakpoints.  */
10446
10447 static int
10448 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10449 {
10450   return target_ranged_break_num_registers ();
10451 }
10452
10453 /* Implement the "print_it" breakpoint_ops method for
10454    ranged breakpoints.  */
10455
10456 static enum print_stop_action
10457 print_it_ranged_breakpoint (bpstat bs)
10458 {
10459   struct breakpoint *b = bs->breakpoint_at;
10460   struct bp_location *bl = b->loc;
10461   struct ui_out *uiout = current_uiout;
10462
10463   gdb_assert (b->type == bp_hardware_breakpoint);
10464
10465   /* Ranged breakpoints have only one location.  */
10466   gdb_assert (bl && bl->next == NULL);
10467
10468   annotate_breakpoint (b->number);
10469   if (b->disposition == disp_del)
10470     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10471   else
10472     ui_out_text (uiout, "\nRanged breakpoint ");
10473   if (ui_out_is_mi_like_p (uiout))
10474     {
10475       ui_out_field_string (uiout, "reason",
10476                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10477       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10478     }
10479   ui_out_field_int (uiout, "bkptno", b->number);
10480   ui_out_text (uiout, ", ");
10481
10482   return PRINT_SRC_AND_LOC;
10483 }
10484
10485 /* Implement the "print_one" breakpoint_ops method for
10486    ranged breakpoints.  */
10487
10488 static void
10489 print_one_ranged_breakpoint (struct breakpoint *b,
10490                              struct bp_location **last_loc)
10491 {
10492   struct bp_location *bl = b->loc;
10493   struct value_print_options opts;
10494   struct ui_out *uiout = current_uiout;
10495
10496   /* Ranged breakpoints have only one location.  */
10497   gdb_assert (bl && bl->next == NULL);
10498
10499   get_user_print_options (&opts);
10500
10501   if (opts.addressprint)
10502     /* We don't print the address range here, it will be printed later
10503        by print_one_detail_ranged_breakpoint.  */
10504     ui_out_field_skip (uiout, "addr");
10505   annotate_field (5);
10506   print_breakpoint_location (b, bl);
10507   *last_loc = bl;
10508 }
10509
10510 /* Implement the "print_one_detail" breakpoint_ops method for
10511    ranged breakpoints.  */
10512
10513 static void
10514 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10515                                     struct ui_out *uiout)
10516 {
10517   CORE_ADDR address_start, address_end;
10518   struct bp_location *bl = b->loc;
10519   struct ui_file *stb = mem_fileopen ();
10520   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10521
10522   gdb_assert (bl);
10523
10524   address_start = bl->address;
10525   address_end = address_start + bl->length - 1;
10526
10527   ui_out_text (uiout, "\taddress range: ");
10528   fprintf_unfiltered (stb, "[%s, %s]",
10529                       print_core_address (bl->gdbarch, address_start),
10530                       print_core_address (bl->gdbarch, address_end));
10531   ui_out_field_stream (uiout, "addr", stb);
10532   ui_out_text (uiout, "\n");
10533
10534   do_cleanups (cleanup);
10535 }
10536
10537 /* Implement the "print_mention" breakpoint_ops method for
10538    ranged breakpoints.  */
10539
10540 static void
10541 print_mention_ranged_breakpoint (struct breakpoint *b)
10542 {
10543   struct bp_location *bl = b->loc;
10544   struct ui_out *uiout = current_uiout;
10545
10546   gdb_assert (bl);
10547   gdb_assert (b->type == bp_hardware_breakpoint);
10548
10549   if (ui_out_is_mi_like_p (uiout))
10550     return;
10551
10552   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10553                    b->number, paddress (bl->gdbarch, bl->address),
10554                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10555 }
10556
10557 /* Implement the "print_recreate" breakpoint_ops method for
10558    ranged breakpoints.  */
10559
10560 static void
10561 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10562 {
10563   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10564                       b->addr_string_range_end);
10565   print_recreate_thread (b, fp);
10566 }
10567
10568 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10569
10570 static struct breakpoint_ops ranged_breakpoint_ops;
10571
10572 /* Find the address where the end of the breakpoint range should be
10573    placed, given the SAL of the end of the range.  This is so that if
10574    the user provides a line number, the end of the range is set to the
10575    last instruction of the given line.  */
10576
10577 static CORE_ADDR
10578 find_breakpoint_range_end (struct symtab_and_line sal)
10579 {
10580   CORE_ADDR end;
10581
10582   /* If the user provided a PC value, use it.  Otherwise,
10583      find the address of the end of the given location.  */
10584   if (sal.explicit_pc)
10585     end = sal.pc;
10586   else
10587     {
10588       int ret;
10589       CORE_ADDR start;
10590
10591       ret = find_line_pc_range (sal, &start, &end);
10592       if (!ret)
10593         error (_("Could not find location of the end of the range."));
10594
10595       /* find_line_pc_range returns the start of the next line.  */
10596       end--;
10597     }
10598
10599   return end;
10600 }
10601
10602 /* Implement the "break-range" CLI command.  */
10603
10604 static void
10605 break_range_command (char *arg, int from_tty)
10606 {
10607   char *arg_start, *addr_string_start, *addr_string_end;
10608   struct linespec_result canonical_start, canonical_end;
10609   int bp_count, can_use_bp, length;
10610   CORE_ADDR end;
10611   struct breakpoint *b;
10612   struct symtab_and_line sal_start, sal_end;
10613   struct cleanup *cleanup_bkpt;
10614   struct linespec_sals *lsal_start, *lsal_end;
10615
10616   /* We don't support software ranged breakpoints.  */
10617   if (target_ranged_break_num_registers () < 0)
10618     error (_("This target does not support hardware ranged breakpoints."));
10619
10620   bp_count = hw_breakpoint_used_count ();
10621   bp_count += target_ranged_break_num_registers ();
10622   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10623                                                    bp_count, 0);
10624   if (can_use_bp < 0)
10625     error (_("Hardware breakpoints used exceeds limit."));
10626
10627   arg = skip_spaces (arg);
10628   if (arg == NULL || arg[0] == '\0')
10629     error(_("No address range specified."));
10630
10631   init_linespec_result (&canonical_start);
10632
10633   arg_start = arg;
10634   parse_breakpoint_sals (&arg, &canonical_start);
10635
10636   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10637
10638   if (arg[0] != ',')
10639     error (_("Too few arguments."));
10640   else if (VEC_empty (linespec_sals, canonical_start.sals))
10641     error (_("Could not find location of the beginning of the range."));
10642
10643   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10644
10645   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10646       || lsal_start->sals.nelts != 1)
10647     error (_("Cannot create a ranged breakpoint with multiple locations."));
10648
10649   sal_start = lsal_start->sals.sals[0];
10650   addr_string_start = savestring (arg_start, arg - arg_start);
10651   make_cleanup (xfree, addr_string_start);
10652
10653   arg++;        /* Skip the comma.  */
10654   arg = skip_spaces (arg);
10655
10656   /* Parse the end location.  */
10657
10658   init_linespec_result (&canonical_end);
10659   arg_start = arg;
10660
10661   /* We call decode_line_full directly here instead of using
10662      parse_breakpoint_sals because we need to specify the start location's
10663      symtab and line as the default symtab and line for the end of the
10664      range.  This makes it possible to have ranges like "foo.c:27, +14",
10665      where +14 means 14 lines from the start location.  */
10666   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10667                     sal_start.symtab, sal_start.line,
10668                     &canonical_end, NULL, NULL);
10669
10670   make_cleanup_destroy_linespec_result (&canonical_end);
10671
10672   if (VEC_empty (linespec_sals, canonical_end.sals))
10673     error (_("Could not find location of the end of the range."));
10674
10675   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10676   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10677       || lsal_end->sals.nelts != 1)
10678     error (_("Cannot create a ranged breakpoint with multiple locations."));
10679
10680   sal_end = lsal_end->sals.sals[0];
10681   addr_string_end = savestring (arg_start, arg - arg_start);
10682   make_cleanup (xfree, addr_string_end);
10683
10684   end = find_breakpoint_range_end (sal_end);
10685   if (sal_start.pc > end)
10686     error (_("Invalid address range, end precedes start."));
10687
10688   length = end - sal_start.pc + 1;
10689   if (length < 0)
10690     /* Length overflowed.  */
10691     error (_("Address range too large."));
10692   else if (length == 1)
10693     {
10694       /* This range is simple enough to be handled by
10695          the `hbreak' command.  */
10696       hbreak_command (addr_string_start, 1);
10697
10698       do_cleanups (cleanup_bkpt);
10699
10700       return;
10701     }
10702
10703   /* Now set up the breakpoint.  */
10704   b = set_raw_breakpoint (get_current_arch (), sal_start,
10705                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10706   set_breakpoint_count (breakpoint_count + 1);
10707   b->number = breakpoint_count;
10708   b->disposition = disp_donttouch;
10709   b->addr_string = xstrdup (addr_string_start);
10710   b->addr_string_range_end = xstrdup (addr_string_end);
10711   b->loc->length = length;
10712
10713   do_cleanups (cleanup_bkpt);
10714
10715   mention (b);
10716   observer_notify_breakpoint_created (b);
10717   update_global_location_list (UGLL_MAY_INSERT);
10718 }
10719
10720 /*  Return non-zero if EXP is verified as constant.  Returned zero
10721     means EXP is variable.  Also the constant detection may fail for
10722     some constant expressions and in such case still falsely return
10723     zero.  */
10724
10725 static int
10726 watchpoint_exp_is_const (const struct expression *exp)
10727 {
10728   int i = exp->nelts;
10729
10730   while (i > 0)
10731     {
10732       int oplenp, argsp;
10733
10734       /* We are only interested in the descriptor of each element.  */
10735       operator_length (exp, i, &oplenp, &argsp);
10736       i -= oplenp;
10737
10738       switch (exp->elts[i].opcode)
10739         {
10740         case BINOP_ADD:
10741         case BINOP_SUB:
10742         case BINOP_MUL:
10743         case BINOP_DIV:
10744         case BINOP_REM:
10745         case BINOP_MOD:
10746         case BINOP_LSH:
10747         case BINOP_RSH:
10748         case BINOP_LOGICAL_AND:
10749         case BINOP_LOGICAL_OR:
10750         case BINOP_BITWISE_AND:
10751         case BINOP_BITWISE_IOR:
10752         case BINOP_BITWISE_XOR:
10753         case BINOP_EQUAL:
10754         case BINOP_NOTEQUAL:
10755         case BINOP_LESS:
10756         case BINOP_GTR:
10757         case BINOP_LEQ:
10758         case BINOP_GEQ:
10759         case BINOP_REPEAT:
10760         case BINOP_COMMA:
10761         case BINOP_EXP:
10762         case BINOP_MIN:
10763         case BINOP_MAX:
10764         case BINOP_INTDIV:
10765         case BINOP_CONCAT:
10766         case TERNOP_COND:
10767         case TERNOP_SLICE:
10768
10769         case OP_LONG:
10770         case OP_DOUBLE:
10771         case OP_DECFLOAT:
10772         case OP_LAST:
10773         case OP_COMPLEX:
10774         case OP_STRING:
10775         case OP_ARRAY:
10776         case OP_TYPE:
10777         case OP_TYPEOF:
10778         case OP_DECLTYPE:
10779         case OP_TYPEID:
10780         case OP_NAME:
10781         case OP_OBJC_NSSTRING:
10782
10783         case UNOP_NEG:
10784         case UNOP_LOGICAL_NOT:
10785         case UNOP_COMPLEMENT:
10786         case UNOP_ADDR:
10787         case UNOP_HIGH:
10788         case UNOP_CAST:
10789
10790         case UNOP_CAST_TYPE:
10791         case UNOP_REINTERPRET_CAST:
10792         case UNOP_DYNAMIC_CAST:
10793           /* Unary, binary and ternary operators: We have to check
10794              their operands.  If they are constant, then so is the
10795              result of that operation.  For instance, if A and B are
10796              determined to be constants, then so is "A + B".
10797
10798              UNOP_IND is one exception to the rule above, because the
10799              value of *ADDR is not necessarily a constant, even when
10800              ADDR is.  */
10801           break;
10802
10803         case OP_VAR_VALUE:
10804           /* Check whether the associated symbol is a constant.
10805
10806              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10807              possible that a buggy compiler could mark a variable as
10808              constant even when it is not, and TYPE_CONST would return
10809              true in this case, while SYMBOL_CLASS wouldn't.
10810
10811              We also have to check for function symbols because they
10812              are always constant.  */
10813           {
10814             struct symbol *s = exp->elts[i + 2].symbol;
10815
10816             if (SYMBOL_CLASS (s) != LOC_BLOCK
10817                 && SYMBOL_CLASS (s) != LOC_CONST
10818                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10819               return 0;
10820             break;
10821           }
10822
10823         /* The default action is to return 0 because we are using
10824            the optimistic approach here: If we don't know something,
10825            then it is not a constant.  */
10826         default:
10827           return 0;
10828         }
10829     }
10830
10831   return 1;
10832 }
10833
10834 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10835
10836 static void
10837 dtor_watchpoint (struct breakpoint *self)
10838 {
10839   struct watchpoint *w = (struct watchpoint *) self;
10840
10841   xfree (w->cond_exp);
10842   xfree (w->exp);
10843   xfree (w->exp_string);
10844   xfree (w->exp_string_reparse);
10845   value_free (w->val);
10846
10847   base_breakpoint_ops.dtor (self);
10848 }
10849
10850 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10851
10852 static void
10853 re_set_watchpoint (struct breakpoint *b)
10854 {
10855   struct watchpoint *w = (struct watchpoint *) b;
10856
10857   /* Watchpoint can be either on expression using entirely global
10858      variables, or it can be on local variables.
10859
10860      Watchpoints of the first kind are never auto-deleted, and even
10861      persist across program restarts.  Since they can use variables
10862      from shared libraries, we need to reparse expression as libraries
10863      are loaded and unloaded.
10864
10865      Watchpoints on local variables can also change meaning as result
10866      of solib event.  For example, if a watchpoint uses both a local
10867      and a global variables in expression, it's a local watchpoint,
10868      but unloading of a shared library will make the expression
10869      invalid.  This is not a very common use case, but we still
10870      re-evaluate expression, to avoid surprises to the user.
10871
10872      Note that for local watchpoints, we re-evaluate it only if
10873      watchpoints frame id is still valid.  If it's not, it means the
10874      watchpoint is out of scope and will be deleted soon.  In fact,
10875      I'm not sure we'll ever be called in this case.
10876
10877      If a local watchpoint's frame id is still valid, then
10878      w->exp_valid_block is likewise valid, and we can safely use it.
10879
10880      Don't do anything about disabled watchpoints, since they will be
10881      reevaluated again when enabled.  */
10882   update_watchpoint (w, 1 /* reparse */);
10883 }
10884
10885 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10886
10887 static int
10888 insert_watchpoint (struct bp_location *bl)
10889 {
10890   struct watchpoint *w = (struct watchpoint *) bl->owner;
10891   int length = w->exact ? 1 : bl->length;
10892
10893   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10894                                    w->cond_exp);
10895 }
10896
10897 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10898
10899 static int
10900 remove_watchpoint (struct bp_location *bl)
10901 {
10902   struct watchpoint *w = (struct watchpoint *) bl->owner;
10903   int length = w->exact ? 1 : bl->length;
10904
10905   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10906                                    w->cond_exp);
10907 }
10908
10909 static int
10910 breakpoint_hit_watchpoint (const struct bp_location *bl,
10911                            struct address_space *aspace, CORE_ADDR bp_addr,
10912                            const struct target_waitstatus *ws)
10913 {
10914   struct breakpoint *b = bl->owner;
10915   struct watchpoint *w = (struct watchpoint *) b;
10916
10917   /* Continuable hardware watchpoints are treated as non-existent if the
10918      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10919      some data address).  Otherwise gdb won't stop on a break instruction
10920      in the code (not from a breakpoint) when a hardware watchpoint has
10921      been defined.  Also skip watchpoints which we know did not trigger
10922      (did not match the data address).  */
10923   if (is_hardware_watchpoint (b)
10924       && w->watchpoint_triggered == watch_triggered_no)
10925     return 0;
10926
10927   return 1;
10928 }
10929
10930 static void
10931 check_status_watchpoint (bpstat bs)
10932 {
10933   gdb_assert (is_watchpoint (bs->breakpoint_at));
10934
10935   bpstat_check_watchpoint (bs);
10936 }
10937
10938 /* Implement the "resources_needed" breakpoint_ops method for
10939    hardware watchpoints.  */
10940
10941 static int
10942 resources_needed_watchpoint (const struct bp_location *bl)
10943 {
10944   struct watchpoint *w = (struct watchpoint *) bl->owner;
10945   int length = w->exact? 1 : bl->length;
10946
10947   return target_region_ok_for_hw_watchpoint (bl->address, length);
10948 }
10949
10950 /* Implement the "works_in_software_mode" breakpoint_ops method for
10951    hardware watchpoints.  */
10952
10953 static int
10954 works_in_software_mode_watchpoint (const struct breakpoint *b)
10955 {
10956   /* Read and access watchpoints only work with hardware support.  */
10957   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10958 }
10959
10960 static enum print_stop_action
10961 print_it_watchpoint (bpstat bs)
10962 {
10963   struct cleanup *old_chain;
10964   struct breakpoint *b;
10965   struct ui_file *stb;
10966   enum print_stop_action result;
10967   struct watchpoint *w;
10968   struct ui_out *uiout = current_uiout;
10969
10970   gdb_assert (bs->bp_location_at != NULL);
10971
10972   b = bs->breakpoint_at;
10973   w = (struct watchpoint *) b;
10974
10975   stb = mem_fileopen ();
10976   old_chain = make_cleanup_ui_file_delete (stb);
10977
10978   switch (b->type)
10979     {
10980     case bp_watchpoint:
10981     case bp_hardware_watchpoint:
10982       annotate_watchpoint (b->number);
10983       if (ui_out_is_mi_like_p (uiout))
10984         ui_out_field_string
10985           (uiout, "reason",
10986            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10987       mention (b);
10988       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10989       ui_out_text (uiout, "\nOld value = ");
10990       watchpoint_value_print (bs->old_val, stb);
10991       ui_out_field_stream (uiout, "old", stb);
10992       ui_out_text (uiout, "\nNew value = ");
10993       watchpoint_value_print (w->val, stb);
10994       ui_out_field_stream (uiout, "new", stb);
10995       ui_out_text (uiout, "\n");
10996       /* More than one watchpoint may have been triggered.  */
10997       result = PRINT_UNKNOWN;
10998       break;
10999
11000     case bp_read_watchpoint:
11001       if (ui_out_is_mi_like_p (uiout))
11002         ui_out_field_string
11003           (uiout, "reason",
11004            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11005       mention (b);
11006       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11007       ui_out_text (uiout, "\nValue = ");
11008       watchpoint_value_print (w->val, stb);
11009       ui_out_field_stream (uiout, "value", stb);
11010       ui_out_text (uiout, "\n");
11011       result = PRINT_UNKNOWN;
11012       break;
11013
11014     case bp_access_watchpoint:
11015       if (bs->old_val != NULL)
11016         {
11017           annotate_watchpoint (b->number);
11018           if (ui_out_is_mi_like_p (uiout))
11019             ui_out_field_string
11020               (uiout, "reason",
11021                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11022           mention (b);
11023           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11024           ui_out_text (uiout, "\nOld value = ");
11025           watchpoint_value_print (bs->old_val, stb);
11026           ui_out_field_stream (uiout, "old", stb);
11027           ui_out_text (uiout, "\nNew value = ");
11028         }
11029       else
11030         {
11031           mention (b);
11032           if (ui_out_is_mi_like_p (uiout))
11033             ui_out_field_string
11034               (uiout, "reason",
11035                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11036           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11037           ui_out_text (uiout, "\nValue = ");
11038         }
11039       watchpoint_value_print (w->val, stb);
11040       ui_out_field_stream (uiout, "new", stb);
11041       ui_out_text (uiout, "\n");
11042       result = PRINT_UNKNOWN;
11043       break;
11044     default:
11045       result = PRINT_UNKNOWN;
11046     }
11047
11048   do_cleanups (old_chain);
11049   return result;
11050 }
11051
11052 /* Implement the "print_mention" breakpoint_ops method for hardware
11053    watchpoints.  */
11054
11055 static void
11056 print_mention_watchpoint (struct breakpoint *b)
11057 {
11058   struct cleanup *ui_out_chain;
11059   struct watchpoint *w = (struct watchpoint *) b;
11060   struct ui_out *uiout = current_uiout;
11061
11062   switch (b->type)
11063     {
11064     case bp_watchpoint:
11065       ui_out_text (uiout, "Watchpoint ");
11066       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11067       break;
11068     case bp_hardware_watchpoint:
11069       ui_out_text (uiout, "Hardware watchpoint ");
11070       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11071       break;
11072     case bp_read_watchpoint:
11073       ui_out_text (uiout, "Hardware read watchpoint ");
11074       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11075       break;
11076     case bp_access_watchpoint:
11077       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
11078       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11079       break;
11080     default:
11081       internal_error (__FILE__, __LINE__,
11082                       _("Invalid hardware watchpoint type."));
11083     }
11084
11085   ui_out_field_int (uiout, "number", b->number);
11086   ui_out_text (uiout, ": ");
11087   ui_out_field_string (uiout, "exp", w->exp_string);
11088   do_cleanups (ui_out_chain);
11089 }
11090
11091 /* Implement the "print_recreate" breakpoint_ops method for
11092    watchpoints.  */
11093
11094 static void
11095 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
11096 {
11097   struct watchpoint *w = (struct watchpoint *) b;
11098
11099   switch (b->type)
11100     {
11101     case bp_watchpoint:
11102     case bp_hardware_watchpoint:
11103       fprintf_unfiltered (fp, "watch");
11104       break;
11105     case bp_read_watchpoint:
11106       fprintf_unfiltered (fp, "rwatch");
11107       break;
11108     case bp_access_watchpoint:
11109       fprintf_unfiltered (fp, "awatch");
11110       break;
11111     default:
11112       internal_error (__FILE__, __LINE__,
11113                       _("Invalid watchpoint type."));
11114     }
11115
11116   fprintf_unfiltered (fp, " %s", w->exp_string);
11117   print_recreate_thread (b, fp);
11118 }
11119
11120 /* Implement the "explains_signal" breakpoint_ops method for
11121    watchpoints.  */
11122
11123 static int
11124 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
11125 {
11126   /* A software watchpoint cannot cause a signal other than
11127      GDB_SIGNAL_TRAP.  */
11128   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
11129     return 0;
11130
11131   return 1;
11132 }
11133
11134 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
11135
11136 static struct breakpoint_ops watchpoint_breakpoint_ops;
11137
11138 /* Implement the "insert" breakpoint_ops method for
11139    masked hardware watchpoints.  */
11140
11141 static int
11142 insert_masked_watchpoint (struct bp_location *bl)
11143 {
11144   struct watchpoint *w = (struct watchpoint *) bl->owner;
11145
11146   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
11147                                         bl->watchpoint_type);
11148 }
11149
11150 /* Implement the "remove" breakpoint_ops method for
11151    masked hardware watchpoints.  */
11152
11153 static int
11154 remove_masked_watchpoint (struct bp_location *bl)
11155 {
11156   struct watchpoint *w = (struct watchpoint *) bl->owner;
11157
11158   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
11159                                         bl->watchpoint_type);
11160 }
11161
11162 /* Implement the "resources_needed" breakpoint_ops method for
11163    masked hardware watchpoints.  */
11164
11165 static int
11166 resources_needed_masked_watchpoint (const struct bp_location *bl)
11167 {
11168   struct watchpoint *w = (struct watchpoint *) bl->owner;
11169
11170   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11171 }
11172
11173 /* Implement the "works_in_software_mode" breakpoint_ops method for
11174    masked hardware watchpoints.  */
11175
11176 static int
11177 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11178 {
11179   return 0;
11180 }
11181
11182 /* Implement the "print_it" breakpoint_ops method for
11183    masked hardware watchpoints.  */
11184
11185 static enum print_stop_action
11186 print_it_masked_watchpoint (bpstat bs)
11187 {
11188   struct breakpoint *b = bs->breakpoint_at;
11189   struct ui_out *uiout = current_uiout;
11190
11191   /* Masked watchpoints have only one location.  */
11192   gdb_assert (b->loc && b->loc->next == NULL);
11193
11194   switch (b->type)
11195     {
11196     case bp_hardware_watchpoint:
11197       annotate_watchpoint (b->number);
11198       if (ui_out_is_mi_like_p (uiout))
11199         ui_out_field_string
11200           (uiout, "reason",
11201            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11202       break;
11203
11204     case bp_read_watchpoint:
11205       if (ui_out_is_mi_like_p (uiout))
11206         ui_out_field_string
11207           (uiout, "reason",
11208            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11209       break;
11210
11211     case bp_access_watchpoint:
11212       if (ui_out_is_mi_like_p (uiout))
11213         ui_out_field_string
11214           (uiout, "reason",
11215            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11216       break;
11217     default:
11218       internal_error (__FILE__, __LINE__,
11219                       _("Invalid hardware watchpoint type."));
11220     }
11221
11222   mention (b);
11223   ui_out_text (uiout, _("\n\
11224 Check the underlying instruction at PC for the memory\n\
11225 address and value which triggered this watchpoint.\n"));
11226   ui_out_text (uiout, "\n");
11227
11228   /* More than one watchpoint may have been triggered.  */
11229   return PRINT_UNKNOWN;
11230 }
11231
11232 /* Implement the "print_one_detail" breakpoint_ops method for
11233    masked hardware watchpoints.  */
11234
11235 static void
11236 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11237                                     struct ui_out *uiout)
11238 {
11239   struct watchpoint *w = (struct watchpoint *) b;
11240
11241   /* Masked watchpoints have only one location.  */
11242   gdb_assert (b->loc && b->loc->next == NULL);
11243
11244   ui_out_text (uiout, "\tmask ");
11245   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11246   ui_out_text (uiout, "\n");
11247 }
11248
11249 /* Implement the "print_mention" breakpoint_ops method for
11250    masked hardware watchpoints.  */
11251
11252 static void
11253 print_mention_masked_watchpoint (struct breakpoint *b)
11254 {
11255   struct watchpoint *w = (struct watchpoint *) b;
11256   struct ui_out *uiout = current_uiout;
11257   struct cleanup *ui_out_chain;
11258
11259   switch (b->type)
11260     {
11261     case bp_hardware_watchpoint:
11262       ui_out_text (uiout, "Masked hardware watchpoint ");
11263       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11264       break;
11265     case bp_read_watchpoint:
11266       ui_out_text (uiout, "Masked hardware read watchpoint ");
11267       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11268       break;
11269     case bp_access_watchpoint:
11270       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11271       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11272       break;
11273     default:
11274       internal_error (__FILE__, __LINE__,
11275                       _("Invalid hardware watchpoint type."));
11276     }
11277
11278   ui_out_field_int (uiout, "number", b->number);
11279   ui_out_text (uiout, ": ");
11280   ui_out_field_string (uiout, "exp", w->exp_string);
11281   do_cleanups (ui_out_chain);
11282 }
11283
11284 /* Implement the "print_recreate" breakpoint_ops method for
11285    masked hardware watchpoints.  */
11286
11287 static void
11288 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11289 {
11290   struct watchpoint *w = (struct watchpoint *) b;
11291   char tmp[40];
11292
11293   switch (b->type)
11294     {
11295     case bp_hardware_watchpoint:
11296       fprintf_unfiltered (fp, "watch");
11297       break;
11298     case bp_read_watchpoint:
11299       fprintf_unfiltered (fp, "rwatch");
11300       break;
11301     case bp_access_watchpoint:
11302       fprintf_unfiltered (fp, "awatch");
11303       break;
11304     default:
11305       internal_error (__FILE__, __LINE__,
11306                       _("Invalid hardware watchpoint type."));
11307     }
11308
11309   sprintf_vma (tmp, w->hw_wp_mask);
11310   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11311   print_recreate_thread (b, fp);
11312 }
11313
11314 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11315
11316 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11317
11318 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11319
11320 static int
11321 is_masked_watchpoint (const struct breakpoint *b)
11322 {
11323   return b->ops == &masked_watchpoint_breakpoint_ops;
11324 }
11325
11326 /* accessflag:  hw_write:  watch write, 
11327                 hw_read:   watch read, 
11328                 hw_access: watch access (read or write) */
11329 static void
11330 watch_command_1 (const char *arg, int accessflag, int from_tty,
11331                  int just_location, int internal)
11332 {
11333   volatile struct gdb_exception e;
11334   struct breakpoint *b, *scope_breakpoint = NULL;
11335   struct expression *exp;
11336   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11337   struct value *val, *mark, *result;
11338   int saved_bitpos = 0, saved_bitsize = 0;
11339   struct frame_info *frame;
11340   const char *exp_start = NULL;
11341   const char *exp_end = NULL;
11342   const char *tok, *end_tok;
11343   int toklen = -1;
11344   const char *cond_start = NULL;
11345   const char *cond_end = NULL;
11346   enum bptype bp_type;
11347   int thread = -1;
11348   int pc = 0;
11349   /* Flag to indicate whether we are going to use masks for
11350      the hardware watchpoint.  */
11351   int use_mask = 0;
11352   CORE_ADDR mask = 0;
11353   struct watchpoint *w;
11354   char *expression;
11355   struct cleanup *back_to;
11356
11357   /* Make sure that we actually have parameters to parse.  */
11358   if (arg != NULL && arg[0] != '\0')
11359     {
11360       const char *value_start;
11361
11362       exp_end = arg + strlen (arg);
11363
11364       /* Look for "parameter value" pairs at the end
11365          of the arguments string.  */
11366       for (tok = exp_end - 1; tok > arg; tok--)
11367         {
11368           /* Skip whitespace at the end of the argument list.  */
11369           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11370             tok--;
11371
11372           /* Find the beginning of the last token.
11373              This is the value of the parameter.  */
11374           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11375             tok--;
11376           value_start = tok + 1;
11377
11378           /* Skip whitespace.  */
11379           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11380             tok--;
11381
11382           end_tok = tok;
11383
11384           /* Find the beginning of the second to last token.
11385              This is the parameter itself.  */
11386           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11387             tok--;
11388           tok++;
11389           toklen = end_tok - tok + 1;
11390
11391           if (toklen == 6 && !strncmp (tok, "thread", 6))
11392             {
11393               /* At this point we've found a "thread" token, which means
11394                  the user is trying to set a watchpoint that triggers
11395                  only in a specific thread.  */
11396               char *endp;
11397
11398               if (thread != -1)
11399                 error(_("You can specify only one thread."));
11400
11401               /* Extract the thread ID from the next token.  */
11402               thread = strtol (value_start, &endp, 0);
11403
11404               /* Check if the user provided a valid numeric value for the
11405                  thread ID.  */
11406               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11407                 error (_("Invalid thread ID specification %s."), value_start);
11408
11409               /* Check if the thread actually exists.  */
11410               if (!valid_thread_id (thread))
11411                 invalid_thread_id_error (thread);
11412             }
11413           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11414             {
11415               /* We've found a "mask" token, which means the user wants to
11416                  create a hardware watchpoint that is going to have the mask
11417                  facility.  */
11418               struct value *mask_value, *mark;
11419
11420               if (use_mask)
11421                 error(_("You can specify only one mask."));
11422
11423               use_mask = just_location = 1;
11424
11425               mark = value_mark ();
11426               mask_value = parse_to_comma_and_eval (&value_start);
11427               mask = value_as_address (mask_value);
11428               value_free_to_mark (mark);
11429             }
11430           else
11431             /* We didn't recognize what we found.  We should stop here.  */
11432             break;
11433
11434           /* Truncate the string and get rid of the "parameter value" pair before
11435              the arguments string is parsed by the parse_exp_1 function.  */
11436           exp_end = tok;
11437         }
11438     }
11439   else
11440     exp_end = arg;
11441
11442   /* Parse the rest of the arguments.  From here on out, everything
11443      is in terms of a newly allocated string instead of the original
11444      ARG.  */
11445   innermost_block = NULL;
11446   expression = savestring (arg, exp_end - arg);
11447   back_to = make_cleanup (xfree, expression);
11448   exp_start = arg = expression;
11449   exp = parse_exp_1 (&arg, 0, 0, 0);
11450   exp_end = arg;
11451   /* Remove trailing whitespace from the expression before saving it.
11452      This makes the eventual display of the expression string a bit
11453      prettier.  */
11454   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11455     --exp_end;
11456
11457   /* Checking if the expression is not constant.  */
11458   if (watchpoint_exp_is_const (exp))
11459     {
11460       int len;
11461
11462       len = exp_end - exp_start;
11463       while (len > 0 && isspace (exp_start[len - 1]))
11464         len--;
11465       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11466     }
11467
11468   exp_valid_block = innermost_block;
11469   mark = value_mark ();
11470   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11471
11472   if (val != NULL && just_location)
11473     {
11474       saved_bitpos = value_bitpos (val);
11475       saved_bitsize = value_bitsize (val);
11476     }
11477
11478   if (just_location)
11479     {
11480       int ret;
11481
11482       exp_valid_block = NULL;
11483       val = value_addr (result);
11484       release_value (val);
11485       value_free_to_mark (mark);
11486
11487       if (use_mask)
11488         {
11489           ret = target_masked_watch_num_registers (value_as_address (val),
11490                                                    mask);
11491           if (ret == -1)
11492             error (_("This target does not support masked watchpoints."));
11493           else if (ret == -2)
11494             error (_("Invalid mask or memory region."));
11495         }
11496     }
11497   else if (val != NULL)
11498     release_value (val);
11499
11500   tok = skip_spaces_const (arg);
11501   end_tok = skip_to_space_const (tok);
11502
11503   toklen = end_tok - tok;
11504   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11505     {
11506       struct expression *cond;
11507
11508       innermost_block = NULL;
11509       tok = cond_start = end_tok + 1;
11510       cond = parse_exp_1 (&tok, 0, 0, 0);
11511
11512       /* The watchpoint expression may not be local, but the condition
11513          may still be.  E.g.: `watch global if local > 0'.  */
11514       cond_exp_valid_block = innermost_block;
11515
11516       xfree (cond);
11517       cond_end = tok;
11518     }
11519   if (*tok)
11520     error (_("Junk at end of command."));
11521
11522   frame = block_innermost_frame (exp_valid_block);
11523
11524   /* If the expression is "local", then set up a "watchpoint scope"
11525      breakpoint at the point where we've left the scope of the watchpoint
11526      expression.  Create the scope breakpoint before the watchpoint, so
11527      that we will encounter it first in bpstat_stop_status.  */
11528   if (exp_valid_block && frame)
11529     {
11530       if (frame_id_p (frame_unwind_caller_id (frame)))
11531         {
11532           scope_breakpoint
11533             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11534                                           frame_unwind_caller_pc (frame),
11535                                           bp_watchpoint_scope,
11536                                           &momentary_breakpoint_ops);
11537
11538           scope_breakpoint->enable_state = bp_enabled;
11539
11540           /* Automatically delete the breakpoint when it hits.  */
11541           scope_breakpoint->disposition = disp_del;
11542
11543           /* Only break in the proper frame (help with recursion).  */
11544           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11545
11546           /* Set the address at which we will stop.  */
11547           scope_breakpoint->loc->gdbarch
11548             = frame_unwind_caller_arch (frame);
11549           scope_breakpoint->loc->requested_address
11550             = frame_unwind_caller_pc (frame);
11551           scope_breakpoint->loc->address
11552             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11553                                          scope_breakpoint->loc->requested_address,
11554                                          scope_breakpoint->type);
11555         }
11556     }
11557
11558   /* Now set up the breakpoint.  We create all watchpoints as hardware
11559      watchpoints here even if hardware watchpoints are turned off, a call
11560      to update_watchpoint later in this function will cause the type to
11561      drop back to bp_watchpoint (software watchpoint) if required.  */
11562
11563   if (accessflag == hw_read)
11564     bp_type = bp_read_watchpoint;
11565   else if (accessflag == hw_access)
11566     bp_type = bp_access_watchpoint;
11567   else
11568     bp_type = bp_hardware_watchpoint;
11569
11570   w = XCNEW (struct watchpoint);
11571   b = &w->base;
11572   if (use_mask)
11573     init_raw_breakpoint_without_location (b, NULL, bp_type,
11574                                           &masked_watchpoint_breakpoint_ops);
11575   else
11576     init_raw_breakpoint_without_location (b, NULL, bp_type,
11577                                           &watchpoint_breakpoint_ops);
11578   b->thread = thread;
11579   b->disposition = disp_donttouch;
11580   b->pspace = current_program_space;
11581   w->exp = exp;
11582   w->exp_valid_block = exp_valid_block;
11583   w->cond_exp_valid_block = cond_exp_valid_block;
11584   if (just_location)
11585     {
11586       struct type *t = value_type (val);
11587       CORE_ADDR addr = value_as_address (val);
11588       char *name;
11589
11590       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11591       name = type_to_string (t);
11592
11593       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11594                                           core_addr_to_string (addr));
11595       xfree (name);
11596
11597       w->exp_string = xstrprintf ("-location %.*s",
11598                                   (int) (exp_end - exp_start), exp_start);
11599
11600       /* The above expression is in C.  */
11601       b->language = language_c;
11602     }
11603   else
11604     w->exp_string = savestring (exp_start, exp_end - exp_start);
11605
11606   if (use_mask)
11607     {
11608       w->hw_wp_mask = mask;
11609     }
11610   else
11611     {
11612       w->val = val;
11613       w->val_bitpos = saved_bitpos;
11614       w->val_bitsize = saved_bitsize;
11615       w->val_valid = 1;
11616     }
11617
11618   if (cond_start)
11619     b->cond_string = savestring (cond_start, cond_end - cond_start);
11620   else
11621     b->cond_string = 0;
11622
11623   if (frame)
11624     {
11625       w->watchpoint_frame = get_frame_id (frame);
11626       w->watchpoint_thread = inferior_ptid;
11627     }
11628   else
11629     {
11630       w->watchpoint_frame = null_frame_id;
11631       w->watchpoint_thread = null_ptid;
11632     }
11633
11634   if (scope_breakpoint != NULL)
11635     {
11636       /* The scope breakpoint is related to the watchpoint.  We will
11637          need to act on them together.  */
11638       b->related_breakpoint = scope_breakpoint;
11639       scope_breakpoint->related_breakpoint = b;
11640     }
11641
11642   if (!just_location)
11643     value_free_to_mark (mark);
11644
11645   TRY_CATCH (e, RETURN_MASK_ALL)
11646     {
11647       /* Finally update the new watchpoint.  This creates the locations
11648          that should be inserted.  */
11649       update_watchpoint (w, 1);
11650     }
11651   if (e.reason < 0)
11652     {
11653       delete_breakpoint (b);
11654       throw_exception (e);
11655     }
11656
11657   install_breakpoint (internal, b, 1);
11658   do_cleanups (back_to);
11659 }
11660
11661 /* Return count of debug registers needed to watch the given expression.
11662    If the watchpoint cannot be handled in hardware return zero.  */
11663
11664 static int
11665 can_use_hardware_watchpoint (struct value *v)
11666 {
11667   int found_memory_cnt = 0;
11668   struct value *head = v;
11669
11670   /* Did the user specifically forbid us to use hardware watchpoints? */
11671   if (!can_use_hw_watchpoints)
11672     return 0;
11673
11674   /* Make sure that the value of the expression depends only upon
11675      memory contents, and values computed from them within GDB.  If we
11676      find any register references or function calls, we can't use a
11677      hardware watchpoint.
11678
11679      The idea here is that evaluating an expression generates a series
11680      of values, one holding the value of every subexpression.  (The
11681      expression a*b+c has five subexpressions: a, b, a*b, c, and
11682      a*b+c.)  GDB's values hold almost enough information to establish
11683      the criteria given above --- they identify memory lvalues,
11684      register lvalues, computed values, etcetera.  So we can evaluate
11685      the expression, and then scan the chain of values that leaves
11686      behind to decide whether we can detect any possible change to the
11687      expression's final value using only hardware watchpoints.
11688
11689      However, I don't think that the values returned by inferior
11690      function calls are special in any way.  So this function may not
11691      notice that an expression involving an inferior function call
11692      can't be watched with hardware watchpoints.  FIXME.  */
11693   for (; v; v = value_next (v))
11694     {
11695       if (VALUE_LVAL (v) == lval_memory)
11696         {
11697           if (v != head && value_lazy (v))
11698             /* A lazy memory lvalue in the chain is one that GDB never
11699                needed to fetch; we either just used its address (e.g.,
11700                `a' in `a.b') or we never needed it at all (e.g., `a'
11701                in `a,b').  This doesn't apply to HEAD; if that is
11702                lazy then it was not readable, but watch it anyway.  */
11703             ;
11704           else
11705             {
11706               /* Ahh, memory we actually used!  Check if we can cover
11707                  it with hardware watchpoints.  */
11708               struct type *vtype = check_typedef (value_type (v));
11709
11710               /* We only watch structs and arrays if user asked for it
11711                  explicitly, never if they just happen to appear in a
11712                  middle of some value chain.  */
11713               if (v == head
11714                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11715                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11716                 {
11717                   CORE_ADDR vaddr = value_address (v);
11718                   int len;
11719                   int num_regs;
11720
11721                   len = (target_exact_watchpoints
11722                          && is_scalar_type_recursive (vtype))?
11723                     1 : TYPE_LENGTH (value_type (v));
11724
11725                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11726                   if (!num_regs)
11727                     return 0;
11728                   else
11729                     found_memory_cnt += num_regs;
11730                 }
11731             }
11732         }
11733       else if (VALUE_LVAL (v) != not_lval
11734                && deprecated_value_modifiable (v) == 0)
11735         return 0;       /* These are values from the history (e.g., $1).  */
11736       else if (VALUE_LVAL (v) == lval_register)
11737         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11738     }
11739
11740   /* The expression itself looks suitable for using a hardware
11741      watchpoint, but give the target machine a chance to reject it.  */
11742   return found_memory_cnt;
11743 }
11744
11745 void
11746 watch_command_wrapper (char *arg, int from_tty, int internal)
11747 {
11748   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11749 }
11750
11751 /* A helper function that looks for the "-location" argument and then
11752    calls watch_command_1.  */
11753
11754 static void
11755 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11756 {
11757   int just_location = 0;
11758
11759   if (arg
11760       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11761           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11762     {
11763       arg = skip_spaces (arg);
11764       just_location = 1;
11765     }
11766
11767   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11768 }
11769
11770 static void
11771 watch_command (char *arg, int from_tty)
11772 {
11773   watch_maybe_just_location (arg, hw_write, from_tty);
11774 }
11775
11776 void
11777 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11778 {
11779   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11780 }
11781
11782 static void
11783 rwatch_command (char *arg, int from_tty)
11784 {
11785   watch_maybe_just_location (arg, hw_read, from_tty);
11786 }
11787
11788 void
11789 awatch_command_wrapper (char *arg, int from_tty, int internal)
11790 {
11791   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11792 }
11793
11794 static void
11795 awatch_command (char *arg, int from_tty)
11796 {
11797   watch_maybe_just_location (arg, hw_access, from_tty);
11798 }
11799 \f
11800
11801 /* Helper routines for the until_command routine in infcmd.c.  Here
11802    because it uses the mechanisms of breakpoints.  */
11803
11804 struct until_break_command_continuation_args
11805 {
11806   struct breakpoint *breakpoint;
11807   struct breakpoint *breakpoint2;
11808   int thread_num;
11809 };
11810
11811 /* This function is called by fetch_inferior_event via the
11812    cmd_continuation pointer, to complete the until command.  It takes
11813    care of cleaning up the temporary breakpoints set up by the until
11814    command.  */
11815 static void
11816 until_break_command_continuation (void *arg, int err)
11817 {
11818   struct until_break_command_continuation_args *a = arg;
11819
11820   delete_breakpoint (a->breakpoint);
11821   if (a->breakpoint2)
11822     delete_breakpoint (a->breakpoint2);
11823   delete_longjmp_breakpoint (a->thread_num);
11824 }
11825
11826 void
11827 until_break_command (char *arg, int from_tty, int anywhere)
11828 {
11829   struct symtabs_and_lines sals;
11830   struct symtab_and_line sal;
11831   struct frame_info *frame;
11832   struct gdbarch *frame_gdbarch;
11833   struct frame_id stack_frame_id;
11834   struct frame_id caller_frame_id;
11835   struct breakpoint *breakpoint;
11836   struct breakpoint *breakpoint2 = NULL;
11837   struct cleanup *old_chain;
11838   int thread;
11839   struct thread_info *tp;
11840
11841   clear_proceed_status (0);
11842
11843   /* Set a breakpoint where the user wants it and at return from
11844      this function.  */
11845
11846   if (last_displayed_sal_is_valid ())
11847     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11848                           get_last_displayed_symtab (),
11849                           get_last_displayed_line ());
11850   else
11851     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11852                           (struct symtab *) NULL, 0);
11853
11854   if (sals.nelts != 1)
11855     error (_("Couldn't get information on specified line."));
11856
11857   sal = sals.sals[0];
11858   xfree (sals.sals);    /* malloc'd, so freed.  */
11859
11860   if (*arg)
11861     error (_("Junk at end of arguments."));
11862
11863   resolve_sal_pc (&sal);
11864
11865   tp = inferior_thread ();
11866   thread = tp->num;
11867
11868   old_chain = make_cleanup (null_cleanup, NULL);
11869
11870   /* Note linespec handling above invalidates the frame chain.
11871      Installing a breakpoint also invalidates the frame chain (as it
11872      may need to switch threads), so do any frame handling before
11873      that.  */
11874
11875   frame = get_selected_frame (NULL);
11876   frame_gdbarch = get_frame_arch (frame);
11877   stack_frame_id = get_stack_frame_id (frame);
11878   caller_frame_id = frame_unwind_caller_id (frame);
11879
11880   /* Keep within the current frame, or in frames called by the current
11881      one.  */
11882
11883   if (frame_id_p (caller_frame_id))
11884     {
11885       struct symtab_and_line sal2;
11886
11887       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11888       sal2.pc = frame_unwind_caller_pc (frame);
11889       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11890                                               sal2,
11891                                               caller_frame_id,
11892                                               bp_until);
11893       make_cleanup_delete_breakpoint (breakpoint2);
11894
11895       set_longjmp_breakpoint (tp, caller_frame_id);
11896       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11897     }
11898
11899   /* set_momentary_breakpoint could invalidate FRAME.  */
11900   frame = NULL;
11901
11902   if (anywhere)
11903     /* If the user told us to continue until a specified location,
11904        we don't specify a frame at which we need to stop.  */
11905     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11906                                            null_frame_id, bp_until);
11907   else
11908     /* Otherwise, specify the selected frame, because we want to stop
11909        only at the very same frame.  */
11910     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11911                                            stack_frame_id, bp_until);
11912   make_cleanup_delete_breakpoint (breakpoint);
11913
11914   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11915
11916   /* If we are running asynchronously, and proceed call above has
11917      actually managed to start the target, arrange for breakpoints to
11918      be deleted when the target stops.  Otherwise, we're already
11919      stopped and delete breakpoints via cleanup chain.  */
11920
11921   if (target_can_async_p () && is_running (inferior_ptid))
11922     {
11923       struct until_break_command_continuation_args *args;
11924       args = xmalloc (sizeof (*args));
11925
11926       args->breakpoint = breakpoint;
11927       args->breakpoint2 = breakpoint2;
11928       args->thread_num = thread;
11929
11930       discard_cleanups (old_chain);
11931       add_continuation (inferior_thread (),
11932                         until_break_command_continuation, args,
11933                         xfree);
11934     }
11935   else
11936     do_cleanups (old_chain);
11937 }
11938
11939 /* This function attempts to parse an optional "if <cond>" clause
11940    from the arg string.  If one is not found, it returns NULL.
11941
11942    Else, it returns a pointer to the condition string.  (It does not
11943    attempt to evaluate the string against a particular block.)  And,
11944    it updates arg to point to the first character following the parsed
11945    if clause in the arg string.  */
11946
11947 char *
11948 ep_parse_optional_if_clause (char **arg)
11949 {
11950   char *cond_string;
11951
11952   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11953     return NULL;
11954
11955   /* Skip the "if" keyword.  */
11956   (*arg) += 2;
11957
11958   /* Skip any extra leading whitespace, and record the start of the
11959      condition string.  */
11960   *arg = skip_spaces (*arg);
11961   cond_string = *arg;
11962
11963   /* Assume that the condition occupies the remainder of the arg
11964      string.  */
11965   (*arg) += strlen (cond_string);
11966
11967   return cond_string;
11968 }
11969
11970 /* Commands to deal with catching events, such as signals, exceptions,
11971    process start/exit, etc.  */
11972
11973 typedef enum
11974 {
11975   catch_fork_temporary, catch_vfork_temporary,
11976   catch_fork_permanent, catch_vfork_permanent
11977 }
11978 catch_fork_kind;
11979
11980 static void
11981 catch_fork_command_1 (char *arg, int from_tty, 
11982                       struct cmd_list_element *command)
11983 {
11984   struct gdbarch *gdbarch = get_current_arch ();
11985   char *cond_string = NULL;
11986   catch_fork_kind fork_kind;
11987   int tempflag;
11988
11989   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11990   tempflag = (fork_kind == catch_fork_temporary
11991               || fork_kind == catch_vfork_temporary);
11992
11993   if (!arg)
11994     arg = "";
11995   arg = skip_spaces (arg);
11996
11997   /* The allowed syntax is:
11998      catch [v]fork
11999      catch [v]fork if <cond>
12000
12001      First, check if there's an if clause.  */
12002   cond_string = ep_parse_optional_if_clause (&arg);
12003
12004   if ((*arg != '\0') && !isspace (*arg))
12005     error (_("Junk at end of arguments."));
12006
12007   /* If this target supports it, create a fork or vfork catchpoint
12008      and enable reporting of such events.  */
12009   switch (fork_kind)
12010     {
12011     case catch_fork_temporary:
12012     case catch_fork_permanent:
12013       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
12014                                           &catch_fork_breakpoint_ops);
12015       break;
12016     case catch_vfork_temporary:
12017     case catch_vfork_permanent:
12018       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
12019                                           &catch_vfork_breakpoint_ops);
12020       break;
12021     default:
12022       error (_("unsupported or unknown fork kind; cannot catch it"));
12023       break;
12024     }
12025 }
12026
12027 static void
12028 catch_exec_command_1 (char *arg, int from_tty, 
12029                       struct cmd_list_element *command)
12030 {
12031   struct exec_catchpoint *c;
12032   struct gdbarch *gdbarch = get_current_arch ();
12033   int tempflag;
12034   char *cond_string = NULL;
12035
12036   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12037
12038   if (!arg)
12039     arg = "";
12040   arg = skip_spaces (arg);
12041
12042   /* The allowed syntax is:
12043      catch exec
12044      catch exec if <cond>
12045
12046      First, check if there's an if clause.  */
12047   cond_string = ep_parse_optional_if_clause (&arg);
12048
12049   if ((*arg != '\0') && !isspace (*arg))
12050     error (_("Junk at end of arguments."));
12051
12052   c = XNEW (struct exec_catchpoint);
12053   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
12054                    &catch_exec_breakpoint_ops);
12055   c->exec_pathname = NULL;
12056
12057   install_breakpoint (0, &c->base, 1);
12058 }
12059
12060 void
12061 init_ada_exception_breakpoint (struct breakpoint *b,
12062                                struct gdbarch *gdbarch,
12063                                struct symtab_and_line sal,
12064                                char *addr_string,
12065                                const struct breakpoint_ops *ops,
12066                                int tempflag,
12067                                int enabled,
12068                                int from_tty)
12069 {
12070   if (from_tty)
12071     {
12072       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12073       if (!loc_gdbarch)
12074         loc_gdbarch = gdbarch;
12075
12076       describe_other_breakpoints (loc_gdbarch,
12077                                   sal.pspace, sal.pc, sal.section, -1);
12078       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12079          version for exception catchpoints, because two catchpoints
12080          used for different exception names will use the same address.
12081          In this case, a "breakpoint ... also set at..." warning is
12082          unproductive.  Besides, the warning phrasing is also a bit
12083          inappropriate, we should use the word catchpoint, and tell
12084          the user what type of catchpoint it is.  The above is good
12085          enough for now, though.  */
12086     }
12087
12088   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
12089
12090   b->enable_state = enabled ? bp_enabled : bp_disabled;
12091   b->disposition = tempflag ? disp_del : disp_donttouch;
12092   b->addr_string = addr_string;
12093   b->language = language_ada;
12094 }
12095
12096 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
12097    filter list, or NULL if no filtering is required.  */
12098 static VEC(int) *
12099 catch_syscall_split_args (char *arg)
12100 {
12101   VEC(int) *result = NULL;
12102   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
12103
12104   while (*arg != '\0')
12105     {
12106       int i, syscall_number;
12107       char *endptr;
12108       char cur_name[128];
12109       struct syscall s;
12110
12111       /* Skip whitespace.  */
12112       arg = skip_spaces (arg);
12113
12114       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
12115         cur_name[i] = arg[i];
12116       cur_name[i] = '\0';
12117       arg += i;
12118
12119       /* Check if the user provided a syscall name or a number.  */
12120       syscall_number = (int) strtol (cur_name, &endptr, 0);
12121       if (*endptr == '\0')
12122         get_syscall_by_number (syscall_number, &s);
12123       else
12124         {
12125           /* We have a name.  Let's check if it's valid and convert it
12126              to a number.  */
12127           get_syscall_by_name (cur_name, &s);
12128
12129           if (s.number == UNKNOWN_SYSCALL)
12130             /* Here we have to issue an error instead of a warning,
12131                because GDB cannot do anything useful if there's no
12132                syscall number to be caught.  */
12133             error (_("Unknown syscall name '%s'."), cur_name);
12134         }
12135
12136       /* Ok, it's valid.  */
12137       VEC_safe_push (int, result, s.number);
12138     }
12139
12140   discard_cleanups (cleanup);
12141   return result;
12142 }
12143
12144 /* Implement the "catch syscall" command.  */
12145
12146 static void
12147 catch_syscall_command_1 (char *arg, int from_tty, 
12148                          struct cmd_list_element *command)
12149 {
12150   int tempflag;
12151   VEC(int) *filter;
12152   struct syscall s;
12153   struct gdbarch *gdbarch = get_current_arch ();
12154
12155   /* Checking if the feature if supported.  */
12156   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
12157     error (_("The feature 'catch syscall' is not supported on \
12158 this architecture yet."));
12159
12160   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12161
12162   arg = skip_spaces (arg);
12163
12164   /* We need to do this first "dummy" translation in order
12165      to get the syscall XML file loaded or, most important,
12166      to display a warning to the user if there's no XML file
12167      for his/her architecture.  */
12168   get_syscall_by_number (0, &s);
12169
12170   /* The allowed syntax is:
12171      catch syscall
12172      catch syscall <name | number> [<name | number> ... <name | number>]
12173
12174      Let's check if there's a syscall name.  */
12175
12176   if (arg != NULL)
12177     filter = catch_syscall_split_args (arg);
12178   else
12179     filter = NULL;
12180
12181   create_syscall_event_catchpoint (tempflag, filter,
12182                                    &catch_syscall_breakpoint_ops);
12183 }
12184
12185 static void
12186 catch_command (char *arg, int from_tty)
12187 {
12188   error (_("Catch requires an event name."));
12189 }
12190 \f
12191
12192 static void
12193 tcatch_command (char *arg, int from_tty)
12194 {
12195   error (_("Catch requires an event name."));
12196 }
12197
12198 /* A qsort comparison function that sorts breakpoints in order.  */
12199
12200 static int
12201 compare_breakpoints (const void *a, const void *b)
12202 {
12203   const breakpoint_p *ba = a;
12204   uintptr_t ua = (uintptr_t) *ba;
12205   const breakpoint_p *bb = b;
12206   uintptr_t ub = (uintptr_t) *bb;
12207
12208   if ((*ba)->number < (*bb)->number)
12209     return -1;
12210   else if ((*ba)->number > (*bb)->number)
12211     return 1;
12212
12213   /* Now sort by address, in case we see, e..g, two breakpoints with
12214      the number 0.  */
12215   if (ua < ub)
12216     return -1;
12217   return ua > ub ? 1 : 0;
12218 }
12219
12220 /* Delete breakpoints by address or line.  */
12221
12222 static void
12223 clear_command (char *arg, int from_tty)
12224 {
12225   struct breakpoint *b, *prev;
12226   VEC(breakpoint_p) *found = 0;
12227   int ix;
12228   int default_match;
12229   struct symtabs_and_lines sals;
12230   struct symtab_and_line sal;
12231   int i;
12232   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12233
12234   if (arg)
12235     {
12236       sals = decode_line_with_current_source (arg,
12237                                               (DECODE_LINE_FUNFIRSTLINE
12238                                                | DECODE_LINE_LIST_MODE));
12239       make_cleanup (xfree, sals.sals);
12240       default_match = 0;
12241     }
12242   else
12243     {
12244       sals.sals = (struct symtab_and_line *)
12245         xmalloc (sizeof (struct symtab_and_line));
12246       make_cleanup (xfree, sals.sals);
12247       init_sal (&sal);          /* Initialize to zeroes.  */
12248
12249       /* Set sal's line, symtab, pc, and pspace to the values
12250          corresponding to the last call to print_frame_info.  If the
12251          codepoint is not valid, this will set all the fields to 0.  */
12252       get_last_displayed_sal (&sal);
12253       if (sal.symtab == 0)
12254         error (_("No source file specified."));
12255
12256       sals.sals[0] = sal;
12257       sals.nelts = 1;
12258
12259       default_match = 1;
12260     }
12261
12262   /* We don't call resolve_sal_pc here.  That's not as bad as it
12263      seems, because all existing breakpoints typically have both
12264      file/line and pc set.  So, if clear is given file/line, we can
12265      match this to existing breakpoint without obtaining pc at all.
12266
12267      We only support clearing given the address explicitly 
12268      present in breakpoint table.  Say, we've set breakpoint 
12269      at file:line.  There were several PC values for that file:line,
12270      due to optimization, all in one block.
12271
12272      We've picked one PC value.  If "clear" is issued with another
12273      PC corresponding to the same file:line, the breakpoint won't
12274      be cleared.  We probably can still clear the breakpoint, but 
12275      since the other PC value is never presented to user, user
12276      can only find it by guessing, and it does not seem important
12277      to support that.  */
12278
12279   /* For each line spec given, delete bps which correspond to it.  Do
12280      it in two passes, solely to preserve the current behavior that
12281      from_tty is forced true if we delete more than one
12282      breakpoint.  */
12283
12284   found = NULL;
12285   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12286   for (i = 0; i < sals.nelts; i++)
12287     {
12288       const char *sal_fullname;
12289
12290       /* If exact pc given, clear bpts at that pc.
12291          If line given (pc == 0), clear all bpts on specified line.
12292          If defaulting, clear all bpts on default line
12293          or at default pc.
12294
12295          defaulting    sal.pc != 0    tests to do
12296
12297          0              1             pc
12298          1              1             pc _and_ line
12299          0              0             line
12300          1              0             <can't happen> */
12301
12302       sal = sals.sals[i];
12303       sal_fullname = (sal.symtab == NULL
12304                       ? NULL : symtab_to_fullname (sal.symtab));
12305
12306       /* Find all matching breakpoints and add them to 'found'.  */
12307       ALL_BREAKPOINTS (b)
12308         {
12309           int match = 0;
12310           /* Are we going to delete b?  */
12311           if (b->type != bp_none && !is_watchpoint (b))
12312             {
12313               struct bp_location *loc = b->loc;
12314               for (; loc; loc = loc->next)
12315                 {
12316                   /* If the user specified file:line, don't allow a PC
12317                      match.  This matches historical gdb behavior.  */
12318                   int pc_match = (!sal.explicit_line
12319                                   && sal.pc
12320                                   && (loc->pspace == sal.pspace)
12321                                   && (loc->address == sal.pc)
12322                                   && (!section_is_overlay (loc->section)
12323                                       || loc->section == sal.section));
12324                   int line_match = 0;
12325
12326                   if ((default_match || sal.explicit_line)
12327                       && loc->symtab != NULL
12328                       && sal_fullname != NULL
12329                       && sal.pspace == loc->pspace
12330                       && loc->line_number == sal.line
12331                       && filename_cmp (symtab_to_fullname (loc->symtab),
12332                                        sal_fullname) == 0)
12333                     line_match = 1;
12334
12335                   if (pc_match || line_match)
12336                     {
12337                       match = 1;
12338                       break;
12339                     }
12340                 }
12341             }
12342
12343           if (match)
12344             VEC_safe_push(breakpoint_p, found, b);
12345         }
12346     }
12347
12348   /* Now go thru the 'found' chain and delete them.  */
12349   if (VEC_empty(breakpoint_p, found))
12350     {
12351       if (arg)
12352         error (_("No breakpoint at %s."), arg);
12353       else
12354         error (_("No breakpoint at this line."));
12355     }
12356
12357   /* Remove duplicates from the vec.  */
12358   qsort (VEC_address (breakpoint_p, found),
12359          VEC_length (breakpoint_p, found),
12360          sizeof (breakpoint_p),
12361          compare_breakpoints);
12362   prev = VEC_index (breakpoint_p, found, 0);
12363   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12364     {
12365       if (b == prev)
12366         {
12367           VEC_ordered_remove (breakpoint_p, found, ix);
12368           --ix;
12369         }
12370     }
12371
12372   if (VEC_length(breakpoint_p, found) > 1)
12373     from_tty = 1;       /* Always report if deleted more than one.  */
12374   if (from_tty)
12375     {
12376       if (VEC_length(breakpoint_p, found) == 1)
12377         printf_unfiltered (_("Deleted breakpoint "));
12378       else
12379         printf_unfiltered (_("Deleted breakpoints "));
12380     }
12381
12382   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12383     {
12384       if (from_tty)
12385         printf_unfiltered ("%d ", b->number);
12386       delete_breakpoint (b);
12387     }
12388   if (from_tty)
12389     putchar_unfiltered ('\n');
12390
12391   do_cleanups (cleanups);
12392 }
12393 \f
12394 /* Delete breakpoint in BS if they are `delete' breakpoints and
12395    all breakpoints that are marked for deletion, whether hit or not.
12396    This is called after any breakpoint is hit, or after errors.  */
12397
12398 void
12399 breakpoint_auto_delete (bpstat bs)
12400 {
12401   struct breakpoint *b, *b_tmp;
12402
12403   for (; bs; bs = bs->next)
12404     if (bs->breakpoint_at
12405         && bs->breakpoint_at->disposition == disp_del
12406         && bs->stop)
12407       delete_breakpoint (bs->breakpoint_at);
12408
12409   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12410   {
12411     if (b->disposition == disp_del_at_next_stop)
12412       delete_breakpoint (b);
12413   }
12414 }
12415
12416 /* A comparison function for bp_location AP and BP being interfaced to
12417    qsort.  Sort elements primarily by their ADDRESS (no matter what
12418    does breakpoint_address_is_meaningful say for its OWNER),
12419    secondarily by ordering first bp_permanent OWNERed elements and
12420    terciarily just ensuring the array is sorted stable way despite
12421    qsort being an unstable algorithm.  */
12422
12423 static int
12424 bp_location_compare (const void *ap, const void *bp)
12425 {
12426   struct bp_location *a = *(void **) ap;
12427   struct bp_location *b = *(void **) bp;
12428   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12429   int a_perm = a->owner->enable_state == bp_permanent;
12430   int b_perm = b->owner->enable_state == bp_permanent;
12431
12432   if (a->address != b->address)
12433     return (a->address > b->address) - (a->address < b->address);
12434
12435   /* Sort locations at the same address by their pspace number, keeping
12436      locations of the same inferior (in a multi-inferior environment)
12437      grouped.  */
12438
12439   if (a->pspace->num != b->pspace->num)
12440     return ((a->pspace->num > b->pspace->num)
12441             - (a->pspace->num < b->pspace->num));
12442
12443   /* Sort permanent breakpoints first.  */
12444   if (a_perm != b_perm)
12445     return (a_perm < b_perm) - (a_perm > b_perm);
12446
12447   /* Make the internal GDB representation stable across GDB runs
12448      where A and B memory inside GDB can differ.  Breakpoint locations of
12449      the same type at the same address can be sorted in arbitrary order.  */
12450
12451   if (a->owner->number != b->owner->number)
12452     return ((a->owner->number > b->owner->number)
12453             - (a->owner->number < b->owner->number));
12454
12455   return (a > b) - (a < b);
12456 }
12457
12458 /* Set bp_location_placed_address_before_address_max and
12459    bp_location_shadow_len_after_address_max according to the current
12460    content of the bp_location array.  */
12461
12462 static void
12463 bp_location_target_extensions_update (void)
12464 {
12465   struct bp_location *bl, **blp_tmp;
12466
12467   bp_location_placed_address_before_address_max = 0;
12468   bp_location_shadow_len_after_address_max = 0;
12469
12470   ALL_BP_LOCATIONS (bl, blp_tmp)
12471     {
12472       CORE_ADDR start, end, addr;
12473
12474       if (!bp_location_has_shadow (bl))
12475         continue;
12476
12477       start = bl->target_info.placed_address;
12478       end = start + bl->target_info.shadow_len;
12479
12480       gdb_assert (bl->address >= start);
12481       addr = bl->address - start;
12482       if (addr > bp_location_placed_address_before_address_max)
12483         bp_location_placed_address_before_address_max = addr;
12484
12485       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12486
12487       gdb_assert (bl->address < end);
12488       addr = end - bl->address;
12489       if (addr > bp_location_shadow_len_after_address_max)
12490         bp_location_shadow_len_after_address_max = addr;
12491     }
12492 }
12493
12494 /* Download tracepoint locations if they haven't been.  */
12495
12496 static void
12497 download_tracepoint_locations (void)
12498 {
12499   struct breakpoint *b;
12500   struct cleanup *old_chain;
12501
12502   if (!target_can_download_tracepoint ())
12503     return;
12504
12505   old_chain = save_current_space_and_thread ();
12506
12507   ALL_TRACEPOINTS (b)
12508     {
12509       struct bp_location *bl;
12510       struct tracepoint *t;
12511       int bp_location_downloaded = 0;
12512
12513       if ((b->type == bp_fast_tracepoint
12514            ? !may_insert_fast_tracepoints
12515            : !may_insert_tracepoints))
12516         continue;
12517
12518       for (bl = b->loc; bl; bl = bl->next)
12519         {
12520           /* In tracepoint, locations are _never_ duplicated, so
12521              should_be_inserted is equivalent to
12522              unduplicated_should_be_inserted.  */
12523           if (!should_be_inserted (bl) || bl->inserted)
12524             continue;
12525
12526           switch_to_program_space_and_thread (bl->pspace);
12527
12528           target_download_tracepoint (bl);
12529
12530           bl->inserted = 1;
12531           bp_location_downloaded = 1;
12532         }
12533       t = (struct tracepoint *) b;
12534       t->number_on_target = b->number;
12535       if (bp_location_downloaded)
12536         observer_notify_breakpoint_modified (b);
12537     }
12538
12539   do_cleanups (old_chain);
12540 }
12541
12542 /* Swap the insertion/duplication state between two locations.  */
12543
12544 static void
12545 swap_insertion (struct bp_location *left, struct bp_location *right)
12546 {
12547   const int left_inserted = left->inserted;
12548   const int left_duplicate = left->duplicate;
12549   const int left_needs_update = left->needs_update;
12550   const struct bp_target_info left_target_info = left->target_info;
12551
12552   /* Locations of tracepoints can never be duplicated.  */
12553   if (is_tracepoint (left->owner))
12554     gdb_assert (!left->duplicate);
12555   if (is_tracepoint (right->owner))
12556     gdb_assert (!right->duplicate);
12557
12558   left->inserted = right->inserted;
12559   left->duplicate = right->duplicate;
12560   left->needs_update = right->needs_update;
12561   left->target_info = right->target_info;
12562   right->inserted = left_inserted;
12563   right->duplicate = left_duplicate;
12564   right->needs_update = left_needs_update;
12565   right->target_info = left_target_info;
12566 }
12567
12568 /* Force the re-insertion of the locations at ADDRESS.  This is called
12569    once a new/deleted/modified duplicate location is found and we are evaluating
12570    conditions on the target's side.  Such conditions need to be updated on
12571    the target.  */
12572
12573 static void
12574 force_breakpoint_reinsertion (struct bp_location *bl)
12575 {
12576   struct bp_location **locp = NULL, **loc2p;
12577   struct bp_location *loc;
12578   CORE_ADDR address = 0;
12579   int pspace_num;
12580
12581   address = bl->address;
12582   pspace_num = bl->pspace->num;
12583
12584   /* This is only meaningful if the target is
12585      evaluating conditions and if the user has
12586      opted for condition evaluation on the target's
12587      side.  */
12588   if (gdb_evaluates_breakpoint_condition_p ()
12589       || !target_supports_evaluation_of_breakpoint_conditions ())
12590     return;
12591
12592   /* Flag all breakpoint locations with this address and
12593      the same program space as the location
12594      as "its condition has changed".  We need to
12595      update the conditions on the target's side.  */
12596   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12597     {
12598       loc = *loc2p;
12599
12600       if (!is_breakpoint (loc->owner)
12601           || pspace_num != loc->pspace->num)
12602         continue;
12603
12604       /* Flag the location appropriately.  We use a different state to
12605          let everyone know that we already updated the set of locations
12606          with addr bl->address and program space bl->pspace.  This is so
12607          we don't have to keep calling these functions just to mark locations
12608          that have already been marked.  */
12609       loc->condition_changed = condition_updated;
12610
12611       /* Free the agent expression bytecode as well.  We will compute
12612          it later on.  */
12613       if (loc->cond_bytecode)
12614         {
12615           free_agent_expr (loc->cond_bytecode);
12616           loc->cond_bytecode = NULL;
12617         }
12618     }
12619 }
12620 /* Called whether new breakpoints are created, or existing breakpoints
12621    deleted, to update the global location list and recompute which
12622    locations are duplicate of which.
12623
12624    The INSERT_MODE flag determines whether locations may not, may, or
12625    shall be inserted now.  See 'enum ugll_insert_mode' for more
12626    info.  */
12627
12628 static void
12629 update_global_location_list (enum ugll_insert_mode insert_mode)
12630 {
12631   struct breakpoint *b;
12632   struct bp_location **locp, *loc;
12633   struct cleanup *cleanups;
12634   /* Last breakpoint location address that was marked for update.  */
12635   CORE_ADDR last_addr = 0;
12636   /* Last breakpoint location program space that was marked for update.  */
12637   int last_pspace_num = -1;
12638
12639   /* Used in the duplicates detection below.  When iterating over all
12640      bp_locations, points to the first bp_location of a given address.
12641      Breakpoints and watchpoints of different types are never
12642      duplicates of each other.  Keep one pointer for each type of
12643      breakpoint/watchpoint, so we only need to loop over all locations
12644      once.  */
12645   struct bp_location *bp_loc_first;  /* breakpoint */
12646   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12647   struct bp_location *awp_loc_first; /* access watchpoint */
12648   struct bp_location *rwp_loc_first; /* read watchpoint */
12649
12650   /* Saved former bp_location array which we compare against the newly
12651      built bp_location from the current state of ALL_BREAKPOINTS.  */
12652   struct bp_location **old_location, **old_locp;
12653   unsigned old_location_count;
12654
12655   old_location = bp_location;
12656   old_location_count = bp_location_count;
12657   bp_location = NULL;
12658   bp_location_count = 0;
12659   cleanups = make_cleanup (xfree, old_location);
12660
12661   ALL_BREAKPOINTS (b)
12662     for (loc = b->loc; loc; loc = loc->next)
12663       bp_location_count++;
12664
12665   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12666   locp = bp_location;
12667   ALL_BREAKPOINTS (b)
12668     for (loc = b->loc; loc; loc = loc->next)
12669       *locp++ = loc;
12670   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12671          bp_location_compare);
12672
12673   bp_location_target_extensions_update ();
12674
12675   /* Identify bp_location instances that are no longer present in the
12676      new list, and therefore should be freed.  Note that it's not
12677      necessary that those locations should be removed from inferior --
12678      if there's another location at the same address (previously
12679      marked as duplicate), we don't need to remove/insert the
12680      location.
12681      
12682      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12683      and former bp_location array state respectively.  */
12684
12685   locp = bp_location;
12686   for (old_locp = old_location; old_locp < old_location + old_location_count;
12687        old_locp++)
12688     {
12689       struct bp_location *old_loc = *old_locp;
12690       struct bp_location **loc2p;
12691
12692       /* Tells if 'old_loc' is found among the new locations.  If
12693          not, we have to free it.  */
12694       int found_object = 0;
12695       /* Tells if the location should remain inserted in the target.  */
12696       int keep_in_target = 0;
12697       int removed = 0;
12698
12699       /* Skip LOCP entries which will definitely never be needed.
12700          Stop either at or being the one matching OLD_LOC.  */
12701       while (locp < bp_location + bp_location_count
12702              && (*locp)->address < old_loc->address)
12703         locp++;
12704
12705       for (loc2p = locp;
12706            (loc2p < bp_location + bp_location_count
12707             && (*loc2p)->address == old_loc->address);
12708            loc2p++)
12709         {
12710           /* Check if this is a new/duplicated location or a duplicated
12711              location that had its condition modified.  If so, we want to send
12712              its condition to the target if evaluation of conditions is taking
12713              place there.  */
12714           if ((*loc2p)->condition_changed == condition_modified
12715               && (last_addr != old_loc->address
12716                   || last_pspace_num != old_loc->pspace->num))
12717             {
12718               force_breakpoint_reinsertion (*loc2p);
12719               last_pspace_num = old_loc->pspace->num;
12720             }
12721
12722           if (*loc2p == old_loc)
12723             found_object = 1;
12724         }
12725
12726       /* We have already handled this address, update it so that we don't
12727          have to go through updates again.  */
12728       last_addr = old_loc->address;
12729
12730       /* Target-side condition evaluation: Handle deleted locations.  */
12731       if (!found_object)
12732         force_breakpoint_reinsertion (old_loc);
12733
12734       /* If this location is no longer present, and inserted, look if
12735          there's maybe a new location at the same address.  If so,
12736          mark that one inserted, and don't remove this one.  This is
12737          needed so that we don't have a time window where a breakpoint
12738          at certain location is not inserted.  */
12739
12740       if (old_loc->inserted)
12741         {
12742           /* If the location is inserted now, we might have to remove
12743              it.  */
12744
12745           if (found_object && should_be_inserted (old_loc))
12746             {
12747               /* The location is still present in the location list,
12748                  and still should be inserted.  Don't do anything.  */
12749               keep_in_target = 1;
12750             }
12751           else
12752             {
12753               /* This location still exists, but it won't be kept in the
12754                  target since it may have been disabled.  We proceed to
12755                  remove its target-side condition.  */
12756
12757               /* The location is either no longer present, or got
12758                  disabled.  See if there's another location at the
12759                  same address, in which case we don't need to remove
12760                  this one from the target.  */
12761
12762               /* OLD_LOC comes from existing struct breakpoint.  */
12763               if (breakpoint_address_is_meaningful (old_loc->owner))
12764                 {
12765                   for (loc2p = locp;
12766                        (loc2p < bp_location + bp_location_count
12767                         && (*loc2p)->address == old_loc->address);
12768                        loc2p++)
12769                     {
12770                       struct bp_location *loc2 = *loc2p;
12771
12772                       if (breakpoint_locations_match (loc2, old_loc))
12773                         {
12774                           /* Read watchpoint locations are switched to
12775                              access watchpoints, if the former are not
12776                              supported, but the latter are.  */
12777                           if (is_hardware_watchpoint (old_loc->owner))
12778                             {
12779                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12780                               loc2->watchpoint_type = old_loc->watchpoint_type;
12781                             }
12782
12783                           /* loc2 is a duplicated location. We need to check
12784                              if it should be inserted in case it will be
12785                              unduplicated.  */
12786                           if (loc2 != old_loc
12787                               && unduplicated_should_be_inserted (loc2))
12788                             {
12789                               swap_insertion (old_loc, loc2);
12790                               keep_in_target = 1;
12791                               break;
12792                             }
12793                         }
12794                     }
12795                 }
12796             }
12797
12798           if (!keep_in_target)
12799             {
12800               if (remove_breakpoint (old_loc, mark_uninserted))
12801                 {
12802                   /* This is just about all we can do.  We could keep
12803                      this location on the global list, and try to
12804                      remove it next time, but there's no particular
12805                      reason why we will succeed next time.
12806                      
12807                      Note that at this point, old_loc->owner is still
12808                      valid, as delete_breakpoint frees the breakpoint
12809                      only after calling us.  */
12810                   printf_filtered (_("warning: Error removing "
12811                                      "breakpoint %d\n"), 
12812                                    old_loc->owner->number);
12813                 }
12814               removed = 1;
12815             }
12816         }
12817
12818       if (!found_object)
12819         {
12820           if (removed && non_stop
12821               && breakpoint_address_is_meaningful (old_loc->owner)
12822               && !is_hardware_watchpoint (old_loc->owner))
12823             {
12824               /* This location was removed from the target.  In
12825                  non-stop mode, a race condition is possible where
12826                  we've removed a breakpoint, but stop events for that
12827                  breakpoint are already queued and will arrive later.
12828                  We apply an heuristic to be able to distinguish such
12829                  SIGTRAPs from other random SIGTRAPs: we keep this
12830                  breakpoint location for a bit, and will retire it
12831                  after we see some number of events.  The theory here
12832                  is that reporting of events should, "on the average",
12833                  be fair, so after a while we'll see events from all
12834                  threads that have anything of interest, and no longer
12835                  need to keep this breakpoint location around.  We
12836                  don't hold locations forever so to reduce chances of
12837                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12838                  SIGTRAP.
12839
12840                  The heuristic failing can be disastrous on
12841                  decr_pc_after_break targets.
12842
12843                  On decr_pc_after_break targets, like e.g., x86-linux,
12844                  if we fail to recognize a late breakpoint SIGTRAP,
12845                  because events_till_retirement has reached 0 too
12846                  soon, we'll fail to do the PC adjustment, and report
12847                  a random SIGTRAP to the user.  When the user resumes
12848                  the inferior, it will most likely immediately crash
12849                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12850                  corrupted, because of being resumed e.g., in the
12851                  middle of a multi-byte instruction, or skipped a
12852                  one-byte instruction.  This was actually seen happen
12853                  on native x86-linux, and should be less rare on
12854                  targets that do not support new thread events, like
12855                  remote, due to the heuristic depending on
12856                  thread_count.
12857
12858                  Mistaking a random SIGTRAP for a breakpoint trap
12859                  causes similar symptoms (PC adjustment applied when
12860                  it shouldn't), but then again, playing with SIGTRAPs
12861                  behind the debugger's back is asking for trouble.
12862
12863                  Since hardware watchpoint traps are always
12864                  distinguishable from other traps, so we don't need to
12865                  apply keep hardware watchpoint moribund locations
12866                  around.  We simply always ignore hardware watchpoint
12867                  traps we can no longer explain.  */
12868
12869               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12870               old_loc->owner = NULL;
12871
12872               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12873             }
12874           else
12875             {
12876               old_loc->owner = NULL;
12877               decref_bp_location (&old_loc);
12878             }
12879         }
12880     }
12881
12882   /* Rescan breakpoints at the same address and section, marking the
12883      first one as "first" and any others as "duplicates".  This is so
12884      that the bpt instruction is only inserted once.  If we have a
12885      permanent breakpoint at the same place as BPT, make that one the
12886      official one, and the rest as duplicates.  Permanent breakpoints
12887      are sorted first for the same address.
12888
12889      Do the same for hardware watchpoints, but also considering the
12890      watchpoint's type (regular/access/read) and length.  */
12891
12892   bp_loc_first = NULL;
12893   wp_loc_first = NULL;
12894   awp_loc_first = NULL;
12895   rwp_loc_first = NULL;
12896   ALL_BP_LOCATIONS (loc, locp)
12897     {
12898       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12899          non-NULL.  */
12900       struct bp_location **loc_first_p;
12901       b = loc->owner;
12902
12903       if (!unduplicated_should_be_inserted (loc)
12904           || !breakpoint_address_is_meaningful (b)
12905           /* Don't detect duplicate for tracepoint locations because they are
12906            never duplicated.  See the comments in field `duplicate' of
12907            `struct bp_location'.  */
12908           || is_tracepoint (b))
12909         {
12910           /* Clear the condition modification flag.  */
12911           loc->condition_changed = condition_unchanged;
12912           continue;
12913         }
12914
12915       /* Permanent breakpoint should always be inserted.  */
12916       if (b->enable_state == bp_permanent && ! loc->inserted)
12917         internal_error (__FILE__, __LINE__,
12918                         _("allegedly permanent breakpoint is not "
12919                         "actually inserted"));
12920
12921       if (b->type == bp_hardware_watchpoint)
12922         loc_first_p = &wp_loc_first;
12923       else if (b->type == bp_read_watchpoint)
12924         loc_first_p = &rwp_loc_first;
12925       else if (b->type == bp_access_watchpoint)
12926         loc_first_p = &awp_loc_first;
12927       else
12928         loc_first_p = &bp_loc_first;
12929
12930       if (*loc_first_p == NULL
12931           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12932           || !breakpoint_locations_match (loc, *loc_first_p))
12933         {
12934           *loc_first_p = loc;
12935           loc->duplicate = 0;
12936
12937           if (is_breakpoint (loc->owner) && loc->condition_changed)
12938             {
12939               loc->needs_update = 1;
12940               /* Clear the condition modification flag.  */
12941               loc->condition_changed = condition_unchanged;
12942             }
12943           continue;
12944         }
12945
12946
12947       /* This and the above ensure the invariant that the first location
12948          is not duplicated, and is the inserted one.
12949          All following are marked as duplicated, and are not inserted.  */
12950       if (loc->inserted)
12951         swap_insertion (loc, *loc_first_p);
12952       loc->duplicate = 1;
12953
12954       /* Clear the condition modification flag.  */
12955       loc->condition_changed = condition_unchanged;
12956
12957       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12958           && b->enable_state != bp_permanent)
12959         internal_error (__FILE__, __LINE__,
12960                         _("another breakpoint was inserted on top of "
12961                         "a permanent breakpoint"));
12962     }
12963
12964   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12965     {
12966       if (insert_mode != UGLL_DONT_INSERT)
12967         insert_breakpoint_locations ();
12968       else
12969         {
12970           /* Even though the caller told us to not insert new
12971              locations, we may still need to update conditions on the
12972              target's side of breakpoints that were already inserted
12973              if the target is evaluating breakpoint conditions.  We
12974              only update conditions for locations that are marked
12975              "needs_update".  */
12976           update_inserted_breakpoint_locations ();
12977         }
12978     }
12979
12980   if (insert_mode != UGLL_DONT_INSERT)
12981     download_tracepoint_locations ();
12982
12983   do_cleanups (cleanups);
12984 }
12985
12986 void
12987 breakpoint_retire_moribund (void)
12988 {
12989   struct bp_location *loc;
12990   int ix;
12991
12992   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12993     if (--(loc->events_till_retirement) == 0)
12994       {
12995         decref_bp_location (&loc);
12996         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12997         --ix;
12998       }
12999 }
13000
13001 static void
13002 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
13003 {
13004   volatile struct gdb_exception e;
13005
13006   TRY_CATCH (e, RETURN_MASK_ERROR)
13007     update_global_location_list (insert_mode);
13008 }
13009
13010 /* Clear BKP from a BPS.  */
13011
13012 static void
13013 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
13014 {
13015   bpstat bs;
13016
13017   for (bs = bps; bs; bs = bs->next)
13018     if (bs->breakpoint_at == bpt)
13019       {
13020         bs->breakpoint_at = NULL;
13021         bs->old_val = NULL;
13022         /* bs->commands will be freed later.  */
13023       }
13024 }
13025
13026 /* Callback for iterate_over_threads.  */
13027 static int
13028 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
13029 {
13030   struct breakpoint *bpt = data;
13031
13032   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
13033   return 0;
13034 }
13035
13036 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
13037    callbacks.  */
13038
13039 static void
13040 say_where (struct breakpoint *b)
13041 {
13042   struct value_print_options opts;
13043
13044   get_user_print_options (&opts);
13045
13046   /* i18n: cagney/2005-02-11: Below needs to be merged into a
13047      single string.  */
13048   if (b->loc == NULL)
13049     {
13050       printf_filtered (_(" (%s) pending."), b->addr_string);
13051     }
13052   else
13053     {
13054       if (opts.addressprint || b->loc->symtab == NULL)
13055         {
13056           printf_filtered (" at ");
13057           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
13058                           gdb_stdout);
13059         }
13060       if (b->loc->symtab != NULL)
13061         {
13062           /* If there is a single location, we can print the location
13063              more nicely.  */
13064           if (b->loc->next == NULL)
13065             printf_filtered (": file %s, line %d.",
13066                              symtab_to_filename_for_display (b->loc->symtab),
13067                              b->loc->line_number);
13068           else
13069             /* This is not ideal, but each location may have a
13070                different file name, and this at least reflects the
13071                real situation somewhat.  */
13072             printf_filtered (": %s.", b->addr_string);
13073         }
13074
13075       if (b->loc->next)
13076         {
13077           struct bp_location *loc = b->loc;
13078           int n = 0;
13079           for (; loc; loc = loc->next)
13080             ++n;
13081           printf_filtered (" (%d locations)", n);
13082         }
13083     }
13084 }
13085
13086 /* Default bp_location_ops methods.  */
13087
13088 static void
13089 bp_location_dtor (struct bp_location *self)
13090 {
13091   xfree (self->cond);
13092   if (self->cond_bytecode)
13093     free_agent_expr (self->cond_bytecode);
13094   xfree (self->function_name);
13095
13096   VEC_free (agent_expr_p, self->target_info.conditions);
13097   VEC_free (agent_expr_p, self->target_info.tcommands);
13098 }
13099
13100 static const struct bp_location_ops bp_location_ops =
13101 {
13102   bp_location_dtor
13103 };
13104
13105 /* Default breakpoint_ops methods all breakpoint_ops ultimately
13106    inherit from.  */
13107
13108 static void
13109 base_breakpoint_dtor (struct breakpoint *self)
13110 {
13111   decref_counted_command_line (&self->commands);
13112   xfree (self->cond_string);
13113   xfree (self->extra_string);
13114   xfree (self->addr_string);
13115   xfree (self->filter);
13116   xfree (self->addr_string_range_end);
13117 }
13118
13119 static struct bp_location *
13120 base_breakpoint_allocate_location (struct breakpoint *self)
13121 {
13122   struct bp_location *loc;
13123
13124   loc = XNEW (struct bp_location);
13125   init_bp_location (loc, &bp_location_ops, self);
13126   return loc;
13127 }
13128
13129 static void
13130 base_breakpoint_re_set (struct breakpoint *b)
13131 {
13132   /* Nothing to re-set. */
13133 }
13134
13135 #define internal_error_pure_virtual_called() \
13136   gdb_assert_not_reached ("pure virtual function called")
13137
13138 static int
13139 base_breakpoint_insert_location (struct bp_location *bl)
13140 {
13141   internal_error_pure_virtual_called ();
13142 }
13143
13144 static int
13145 base_breakpoint_remove_location (struct bp_location *bl)
13146 {
13147   internal_error_pure_virtual_called ();
13148 }
13149
13150 static int
13151 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
13152                                 struct address_space *aspace,
13153                                 CORE_ADDR bp_addr,
13154                                 const struct target_waitstatus *ws)
13155 {
13156   internal_error_pure_virtual_called ();
13157 }
13158
13159 static void
13160 base_breakpoint_check_status (bpstat bs)
13161 {
13162   /* Always stop.   */
13163 }
13164
13165 /* A "works_in_software_mode" breakpoint_ops method that just internal
13166    errors.  */
13167
13168 static int
13169 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13170 {
13171   internal_error_pure_virtual_called ();
13172 }
13173
13174 /* A "resources_needed" breakpoint_ops method that just internal
13175    errors.  */
13176
13177 static int
13178 base_breakpoint_resources_needed (const struct bp_location *bl)
13179 {
13180   internal_error_pure_virtual_called ();
13181 }
13182
13183 static enum print_stop_action
13184 base_breakpoint_print_it (bpstat bs)
13185 {
13186   internal_error_pure_virtual_called ();
13187 }
13188
13189 static void
13190 base_breakpoint_print_one_detail (const struct breakpoint *self,
13191                                   struct ui_out *uiout)
13192 {
13193   /* nothing */
13194 }
13195
13196 static void
13197 base_breakpoint_print_mention (struct breakpoint *b)
13198 {
13199   internal_error_pure_virtual_called ();
13200 }
13201
13202 static void
13203 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13204 {
13205   internal_error_pure_virtual_called ();
13206 }
13207
13208 static void
13209 base_breakpoint_create_sals_from_address (char **arg,
13210                                           struct linespec_result *canonical,
13211                                           enum bptype type_wanted,
13212                                           char *addr_start,
13213                                           char **copy_arg)
13214 {
13215   internal_error_pure_virtual_called ();
13216 }
13217
13218 static void
13219 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13220                                         struct linespec_result *c,
13221                                         char *cond_string,
13222                                         char *extra_string,
13223                                         enum bptype type_wanted,
13224                                         enum bpdisp disposition,
13225                                         int thread,
13226                                         int task, int ignore_count,
13227                                         const struct breakpoint_ops *o,
13228                                         int from_tty, int enabled,
13229                                         int internal, unsigned flags)
13230 {
13231   internal_error_pure_virtual_called ();
13232 }
13233
13234 static void
13235 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13236                                  struct symtabs_and_lines *sals)
13237 {
13238   internal_error_pure_virtual_called ();
13239 }
13240
13241 /* The default 'explains_signal' method.  */
13242
13243 static int
13244 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13245 {
13246   return 1;
13247 }
13248
13249 /* The default "after_condition_true" method.  */
13250
13251 static void
13252 base_breakpoint_after_condition_true (struct bpstats *bs)
13253 {
13254   /* Nothing to do.   */
13255 }
13256
13257 struct breakpoint_ops base_breakpoint_ops =
13258 {
13259   base_breakpoint_dtor,
13260   base_breakpoint_allocate_location,
13261   base_breakpoint_re_set,
13262   base_breakpoint_insert_location,
13263   base_breakpoint_remove_location,
13264   base_breakpoint_breakpoint_hit,
13265   base_breakpoint_check_status,
13266   base_breakpoint_resources_needed,
13267   base_breakpoint_works_in_software_mode,
13268   base_breakpoint_print_it,
13269   NULL,
13270   base_breakpoint_print_one_detail,
13271   base_breakpoint_print_mention,
13272   base_breakpoint_print_recreate,
13273   base_breakpoint_create_sals_from_address,
13274   base_breakpoint_create_breakpoints_sal,
13275   base_breakpoint_decode_linespec,
13276   base_breakpoint_explains_signal,
13277   base_breakpoint_after_condition_true,
13278 };
13279
13280 /* Default breakpoint_ops methods.  */
13281
13282 static void
13283 bkpt_re_set (struct breakpoint *b)
13284 {
13285   /* FIXME: is this still reachable?  */
13286   if (b->addr_string == NULL)
13287     {
13288       /* Anything without a string can't be re-set.  */
13289       delete_breakpoint (b);
13290       return;
13291     }
13292
13293   breakpoint_re_set_default (b);
13294 }
13295
13296 /* Copy SRC's shadow buffer and whatever else we'd set if we actually
13297    inserted DEST, so we can remove it later, in case SRC is removed
13298    first.  */
13299
13300 static void
13301 bp_target_info_copy_insertion_state (struct bp_target_info *dest,
13302                                      const struct bp_target_info *src)
13303 {
13304   dest->shadow_len = src->shadow_len;
13305   memcpy (dest->shadow_contents, src->shadow_contents, src->shadow_len);
13306   dest->placed_size = src->placed_size;
13307 }
13308
13309 static int
13310 bkpt_insert_location (struct bp_location *bl)
13311 {
13312   if (bl->loc_type == bp_loc_hardware_breakpoint)
13313     return target_insert_hw_breakpoint (bl->gdbarch,
13314                                         &bl->target_info);
13315   else
13316     {
13317       struct bp_target_info *bp_tgt = &bl->target_info;
13318       int ret;
13319       int sss_slot;
13320
13321       /* There is no need to insert a breakpoint if an unconditional
13322          raw/sss breakpoint is already inserted at that location.  */
13323       sss_slot = find_single_step_breakpoint (bp_tgt->placed_address_space,
13324                                               bp_tgt->placed_address);
13325       if (sss_slot >= 0)
13326         {
13327           struct bp_target_info *sss_bp_tgt = single_step_breakpoints[sss_slot];
13328
13329           bp_target_info_copy_insertion_state (bp_tgt, sss_bp_tgt);
13330           return 0;
13331         }
13332
13333       return target_insert_breakpoint (bl->gdbarch, bp_tgt);
13334     }
13335 }
13336
13337 static int
13338 bkpt_remove_location (struct bp_location *bl)
13339 {
13340   if (bl->loc_type == bp_loc_hardware_breakpoint)
13341     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13342   else
13343     {
13344       struct bp_target_info *bp_tgt = &bl->target_info;
13345       struct address_space *aspace = bp_tgt->placed_address_space;
13346       CORE_ADDR address = bp_tgt->placed_address;
13347
13348       /* Only remove the breakpoint if there is no raw/sss breakpoint
13349          still inserted at this location.  Otherwise, we would be
13350          effectively disabling the raw/sss breakpoint.  */
13351       if (single_step_breakpoint_inserted_here_p (aspace, address))
13352         return 0;
13353
13354       return target_remove_breakpoint (bl->gdbarch, bp_tgt);
13355     }
13356 }
13357
13358 static int
13359 bkpt_breakpoint_hit (const struct bp_location *bl,
13360                      struct address_space *aspace, CORE_ADDR bp_addr,
13361                      const struct target_waitstatus *ws)
13362 {
13363   if (ws->kind != TARGET_WAITKIND_STOPPED
13364       || ws->value.sig != GDB_SIGNAL_TRAP)
13365     return 0;
13366
13367   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13368                                  aspace, bp_addr))
13369     return 0;
13370
13371   if (overlay_debugging         /* unmapped overlay section */
13372       && section_is_overlay (bl->section)
13373       && !section_is_mapped (bl->section))
13374     return 0;
13375
13376   return 1;
13377 }
13378
13379 static int
13380 dprintf_breakpoint_hit (const struct bp_location *bl,
13381                         struct address_space *aspace, CORE_ADDR bp_addr,
13382                         const struct target_waitstatus *ws)
13383 {
13384   if (dprintf_style == dprintf_style_agent
13385       && target_can_run_breakpoint_commands ())
13386     {
13387       /* An agent-style dprintf never causes a stop.  If we see a trap
13388          for this address it must be for a breakpoint that happens to
13389          be set at the same address.  */
13390       return 0;
13391     }
13392
13393   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13394 }
13395
13396 static int
13397 bkpt_resources_needed (const struct bp_location *bl)
13398 {
13399   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13400
13401   return 1;
13402 }
13403
13404 static enum print_stop_action
13405 bkpt_print_it (bpstat bs)
13406 {
13407   struct breakpoint *b;
13408   const struct bp_location *bl;
13409   int bp_temp;
13410   struct ui_out *uiout = current_uiout;
13411
13412   gdb_assert (bs->bp_location_at != NULL);
13413
13414   bl = bs->bp_location_at;
13415   b = bs->breakpoint_at;
13416
13417   bp_temp = b->disposition == disp_del;
13418   if (bl->address != bl->requested_address)
13419     breakpoint_adjustment_warning (bl->requested_address,
13420                                    bl->address,
13421                                    b->number, 1);
13422   annotate_breakpoint (b->number);
13423   if (bp_temp)
13424     ui_out_text (uiout, "\nTemporary breakpoint ");
13425   else
13426     ui_out_text (uiout, "\nBreakpoint ");
13427   if (ui_out_is_mi_like_p (uiout))
13428     {
13429       ui_out_field_string (uiout, "reason",
13430                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13431       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13432     }
13433   ui_out_field_int (uiout, "bkptno", b->number);
13434   ui_out_text (uiout, ", ");
13435
13436   return PRINT_SRC_AND_LOC;
13437 }
13438
13439 static void
13440 bkpt_print_mention (struct breakpoint *b)
13441 {
13442   if (ui_out_is_mi_like_p (current_uiout))
13443     return;
13444
13445   switch (b->type)
13446     {
13447     case bp_breakpoint:
13448     case bp_gnu_ifunc_resolver:
13449       if (b->disposition == disp_del)
13450         printf_filtered (_("Temporary breakpoint"));
13451       else
13452         printf_filtered (_("Breakpoint"));
13453       printf_filtered (_(" %d"), b->number);
13454       if (b->type == bp_gnu_ifunc_resolver)
13455         printf_filtered (_(" at gnu-indirect-function resolver"));
13456       break;
13457     case bp_hardware_breakpoint:
13458       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13459       break;
13460     case bp_dprintf:
13461       printf_filtered (_("Dprintf %d"), b->number);
13462       break;
13463     }
13464
13465   say_where (b);
13466 }
13467
13468 static void
13469 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13470 {
13471   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13472     fprintf_unfiltered (fp, "tbreak");
13473   else if (tp->type == bp_breakpoint)
13474     fprintf_unfiltered (fp, "break");
13475   else if (tp->type == bp_hardware_breakpoint
13476            && tp->disposition == disp_del)
13477     fprintf_unfiltered (fp, "thbreak");
13478   else if (tp->type == bp_hardware_breakpoint)
13479     fprintf_unfiltered (fp, "hbreak");
13480   else
13481     internal_error (__FILE__, __LINE__,
13482                     _("unhandled breakpoint type %d"), (int) tp->type);
13483
13484   fprintf_unfiltered (fp, " %s", tp->addr_string);
13485   print_recreate_thread (tp, fp);
13486 }
13487
13488 static void
13489 bkpt_create_sals_from_address (char **arg,
13490                                struct linespec_result *canonical,
13491                                enum bptype type_wanted,
13492                                char *addr_start, char **copy_arg)
13493 {
13494   create_sals_from_address_default (arg, canonical, type_wanted,
13495                                     addr_start, copy_arg);
13496 }
13497
13498 static void
13499 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13500                              struct linespec_result *canonical,
13501                              char *cond_string,
13502                              char *extra_string,
13503                              enum bptype type_wanted,
13504                              enum bpdisp disposition,
13505                              int thread,
13506                              int task, int ignore_count,
13507                              const struct breakpoint_ops *ops,
13508                              int from_tty, int enabled,
13509                              int internal, unsigned flags)
13510 {
13511   create_breakpoints_sal_default (gdbarch, canonical,
13512                                   cond_string, extra_string,
13513                                   type_wanted,
13514                                   disposition, thread, task,
13515                                   ignore_count, ops, from_tty,
13516                                   enabled, internal, flags);
13517 }
13518
13519 static void
13520 bkpt_decode_linespec (struct breakpoint *b, char **s,
13521                       struct symtabs_and_lines *sals)
13522 {
13523   decode_linespec_default (b, s, sals);
13524 }
13525
13526 /* Virtual table for internal breakpoints.  */
13527
13528 static void
13529 internal_bkpt_re_set (struct breakpoint *b)
13530 {
13531   switch (b->type)
13532     {
13533       /* Delete overlay event and longjmp master breakpoints; they
13534          will be reset later by breakpoint_re_set.  */
13535     case bp_overlay_event:
13536     case bp_longjmp_master:
13537     case bp_std_terminate_master:
13538     case bp_exception_master:
13539       delete_breakpoint (b);
13540       break;
13541
13542       /* This breakpoint is special, it's set up when the inferior
13543          starts and we really don't want to touch it.  */
13544     case bp_shlib_event:
13545
13546       /* Like bp_shlib_event, this breakpoint type is special.  Once
13547          it is set up, we do not want to touch it.  */
13548     case bp_thread_event:
13549       break;
13550     }
13551 }
13552
13553 static void
13554 internal_bkpt_check_status (bpstat bs)
13555 {
13556   if (bs->breakpoint_at->type == bp_shlib_event)
13557     {
13558       /* If requested, stop when the dynamic linker notifies GDB of
13559          events.  This allows the user to get control and place
13560          breakpoints in initializer routines for dynamically loaded
13561          objects (among other things).  */
13562       bs->stop = stop_on_solib_events;
13563       bs->print = stop_on_solib_events;
13564     }
13565   else
13566     bs->stop = 0;
13567 }
13568
13569 static enum print_stop_action
13570 internal_bkpt_print_it (bpstat bs)
13571 {
13572   struct breakpoint *b;
13573
13574   b = bs->breakpoint_at;
13575
13576   switch (b->type)
13577     {
13578     case bp_shlib_event:
13579       /* Did we stop because the user set the stop_on_solib_events
13580          variable?  (If so, we report this as a generic, "Stopped due
13581          to shlib event" message.) */
13582       print_solib_event (0);
13583       break;
13584
13585     case bp_thread_event:
13586       /* Not sure how we will get here.
13587          GDB should not stop for these breakpoints.  */
13588       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13589       break;
13590
13591     case bp_overlay_event:
13592       /* By analogy with the thread event, GDB should not stop for these.  */
13593       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13594       break;
13595
13596     case bp_longjmp_master:
13597       /* These should never be enabled.  */
13598       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13599       break;
13600
13601     case bp_std_terminate_master:
13602       /* These should never be enabled.  */
13603       printf_filtered (_("std::terminate Master Breakpoint: "
13604                          "gdb should not stop!\n"));
13605       break;
13606
13607     case bp_exception_master:
13608       /* These should never be enabled.  */
13609       printf_filtered (_("Exception Master Breakpoint: "
13610                          "gdb should not stop!\n"));
13611       break;
13612     }
13613
13614   return PRINT_NOTHING;
13615 }
13616
13617 static void
13618 internal_bkpt_print_mention (struct breakpoint *b)
13619 {
13620   /* Nothing to mention.  These breakpoints are internal.  */
13621 }
13622
13623 /* Virtual table for momentary breakpoints  */
13624
13625 static void
13626 momentary_bkpt_re_set (struct breakpoint *b)
13627 {
13628   /* Keep temporary breakpoints, which can be encountered when we step
13629      over a dlopen call and solib_add is resetting the breakpoints.
13630      Otherwise these should have been blown away via the cleanup chain
13631      or by breakpoint_init_inferior when we rerun the executable.  */
13632 }
13633
13634 static void
13635 momentary_bkpt_check_status (bpstat bs)
13636 {
13637   /* Nothing.  The point of these breakpoints is causing a stop.  */
13638 }
13639
13640 static enum print_stop_action
13641 momentary_bkpt_print_it (bpstat bs)
13642 {
13643   struct ui_out *uiout = current_uiout;
13644
13645   if (ui_out_is_mi_like_p (uiout))
13646     {
13647       struct breakpoint *b = bs->breakpoint_at;
13648
13649       switch (b->type)
13650         {
13651         case bp_finish:
13652           ui_out_field_string
13653             (uiout, "reason",
13654              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13655           break;
13656
13657         case bp_until:
13658           ui_out_field_string
13659             (uiout, "reason",
13660              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13661           break;
13662         }
13663     }
13664
13665   return PRINT_UNKNOWN;
13666 }
13667
13668 static void
13669 momentary_bkpt_print_mention (struct breakpoint *b)
13670 {
13671   /* Nothing to mention.  These breakpoints are internal.  */
13672 }
13673
13674 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13675
13676    It gets cleared already on the removal of the first one of such placed
13677    breakpoints.  This is OK as they get all removed altogether.  */
13678
13679 static void
13680 longjmp_bkpt_dtor (struct breakpoint *self)
13681 {
13682   struct thread_info *tp = find_thread_id (self->thread);
13683
13684   if (tp)
13685     tp->initiating_frame = null_frame_id;
13686
13687   momentary_breakpoint_ops.dtor (self);
13688 }
13689
13690 /* Specific methods for probe breakpoints.  */
13691
13692 static int
13693 bkpt_probe_insert_location (struct bp_location *bl)
13694 {
13695   int v = bkpt_insert_location (bl);
13696
13697   if (v == 0)
13698     {
13699       /* The insertion was successful, now let's set the probe's semaphore
13700          if needed.  */
13701       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13702                                             bl->probe.objfile,
13703                                             bl->gdbarch);
13704     }
13705
13706   return v;
13707 }
13708
13709 static int
13710 bkpt_probe_remove_location (struct bp_location *bl)
13711 {
13712   /* Let's clear the semaphore before removing the location.  */
13713   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13714                                           bl->probe.objfile,
13715                                           bl->gdbarch);
13716
13717   return bkpt_remove_location (bl);
13718 }
13719
13720 static void
13721 bkpt_probe_create_sals_from_address (char **arg,
13722                                      struct linespec_result *canonical,
13723                                      enum bptype type_wanted,
13724                                      char *addr_start, char **copy_arg)
13725 {
13726   struct linespec_sals lsal;
13727
13728   lsal.sals = parse_probes (arg, canonical);
13729
13730   *copy_arg = xstrdup (canonical->addr_string);
13731   lsal.canonical = xstrdup (*copy_arg);
13732
13733   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13734 }
13735
13736 static void
13737 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13738                             struct symtabs_and_lines *sals)
13739 {
13740   *sals = parse_probes (s, NULL);
13741   if (!sals->sals)
13742     error (_("probe not found"));
13743 }
13744
13745 /* The breakpoint_ops structure to be used in tracepoints.  */
13746
13747 static void
13748 tracepoint_re_set (struct breakpoint *b)
13749 {
13750   breakpoint_re_set_default (b);
13751 }
13752
13753 static int
13754 tracepoint_breakpoint_hit (const struct bp_location *bl,
13755                            struct address_space *aspace, CORE_ADDR bp_addr,
13756                            const struct target_waitstatus *ws)
13757 {
13758   /* By definition, the inferior does not report stops at
13759      tracepoints.  */
13760   return 0;
13761 }
13762
13763 static void
13764 tracepoint_print_one_detail (const struct breakpoint *self,
13765                              struct ui_out *uiout)
13766 {
13767   struct tracepoint *tp = (struct tracepoint *) self;
13768   if (tp->static_trace_marker_id)
13769     {
13770       gdb_assert (self->type == bp_static_tracepoint);
13771
13772       ui_out_text (uiout, "\tmarker id is ");
13773       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13774                            tp->static_trace_marker_id);
13775       ui_out_text (uiout, "\n");
13776     }
13777 }
13778
13779 static void
13780 tracepoint_print_mention (struct breakpoint *b)
13781 {
13782   if (ui_out_is_mi_like_p (current_uiout))
13783     return;
13784
13785   switch (b->type)
13786     {
13787     case bp_tracepoint:
13788       printf_filtered (_("Tracepoint"));
13789       printf_filtered (_(" %d"), b->number);
13790       break;
13791     case bp_fast_tracepoint:
13792       printf_filtered (_("Fast tracepoint"));
13793       printf_filtered (_(" %d"), b->number);
13794       break;
13795     case bp_static_tracepoint:
13796       printf_filtered (_("Static tracepoint"));
13797       printf_filtered (_(" %d"), b->number);
13798       break;
13799     default:
13800       internal_error (__FILE__, __LINE__,
13801                       _("unhandled tracepoint type %d"), (int) b->type);
13802     }
13803
13804   say_where (b);
13805 }
13806
13807 static void
13808 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13809 {
13810   struct tracepoint *tp = (struct tracepoint *) self;
13811
13812   if (self->type == bp_fast_tracepoint)
13813     fprintf_unfiltered (fp, "ftrace");
13814   if (self->type == bp_static_tracepoint)
13815     fprintf_unfiltered (fp, "strace");
13816   else if (self->type == bp_tracepoint)
13817     fprintf_unfiltered (fp, "trace");
13818   else
13819     internal_error (__FILE__, __LINE__,
13820                     _("unhandled tracepoint type %d"), (int) self->type);
13821
13822   fprintf_unfiltered (fp, " %s", self->addr_string);
13823   print_recreate_thread (self, fp);
13824
13825   if (tp->pass_count)
13826     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13827 }
13828
13829 static void
13830 tracepoint_create_sals_from_address (char **arg,
13831                                      struct linespec_result *canonical,
13832                                      enum bptype type_wanted,
13833                                      char *addr_start, char **copy_arg)
13834 {
13835   create_sals_from_address_default (arg, canonical, type_wanted,
13836                                     addr_start, copy_arg);
13837 }
13838
13839 static void
13840 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13841                                    struct linespec_result *canonical,
13842                                    char *cond_string,
13843                                    char *extra_string,
13844                                    enum bptype type_wanted,
13845                                    enum bpdisp disposition,
13846                                    int thread,
13847                                    int task, int ignore_count,
13848                                    const struct breakpoint_ops *ops,
13849                                    int from_tty, int enabled,
13850                                    int internal, unsigned flags)
13851 {
13852   create_breakpoints_sal_default (gdbarch, canonical,
13853                                   cond_string, extra_string,
13854                                   type_wanted,
13855                                   disposition, thread, task,
13856                                   ignore_count, ops, from_tty,
13857                                   enabled, internal, flags);
13858 }
13859
13860 static void
13861 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13862                             struct symtabs_and_lines *sals)
13863 {
13864   decode_linespec_default (b, s, sals);
13865 }
13866
13867 struct breakpoint_ops tracepoint_breakpoint_ops;
13868
13869 /* The breakpoint_ops structure to be use on tracepoints placed in a
13870    static probe.  */
13871
13872 static void
13873 tracepoint_probe_create_sals_from_address (char **arg,
13874                                            struct linespec_result *canonical,
13875                                            enum bptype type_wanted,
13876                                            char *addr_start, char **copy_arg)
13877 {
13878   /* We use the same method for breakpoint on probes.  */
13879   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13880                                        addr_start, copy_arg);
13881 }
13882
13883 static void
13884 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13885                                   struct symtabs_and_lines *sals)
13886 {
13887   /* We use the same method for breakpoint on probes.  */
13888   bkpt_probe_decode_linespec (b, s, sals);
13889 }
13890
13891 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13892
13893 /* Dprintf breakpoint_ops methods.  */
13894
13895 static void
13896 dprintf_re_set (struct breakpoint *b)
13897 {
13898   breakpoint_re_set_default (b);
13899
13900   /* This breakpoint could have been pending, and be resolved now, and
13901      if so, we should now have the extra string.  If we don't, the
13902      dprintf was malformed when created, but we couldn't tell because
13903      we can't extract the extra string until the location is
13904      resolved.  */
13905   if (b->loc != NULL && b->extra_string == NULL)
13906     error (_("Format string required"));
13907
13908   /* 1 - connect to target 1, that can run breakpoint commands.
13909      2 - create a dprintf, which resolves fine.
13910      3 - disconnect from target 1
13911      4 - connect to target 2, that can NOT run breakpoint commands.
13912
13913      After steps #3/#4, you'll want the dprintf command list to
13914      be updated, because target 1 and 2 may well return different
13915      answers for target_can_run_breakpoint_commands().
13916      Given absence of finer grained resetting, we get to do
13917      it all the time.  */
13918   if (b->extra_string != NULL)
13919     update_dprintf_command_list (b);
13920 }
13921
13922 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13923
13924 static void
13925 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13926 {
13927   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13928                       tp->extra_string);
13929   print_recreate_thread (tp, fp);
13930 }
13931
13932 /* Implement the "after_condition_true" breakpoint_ops method for
13933    dprintf.
13934
13935    dprintf's are implemented with regular commands in their command
13936    list, but we run the commands here instead of before presenting the
13937    stop to the user, as dprintf's don't actually cause a stop.  This
13938    also makes it so that the commands of multiple dprintfs at the same
13939    address are all handled.  */
13940
13941 static void
13942 dprintf_after_condition_true (struct bpstats *bs)
13943 {
13944   struct cleanup *old_chain;
13945   struct bpstats tmp_bs = { NULL };
13946   struct bpstats *tmp_bs_p = &tmp_bs;
13947
13948   /* dprintf's never cause a stop.  This wasn't set in the
13949      check_status hook instead because that would make the dprintf's
13950      condition not be evaluated.  */
13951   bs->stop = 0;
13952
13953   /* Run the command list here.  Take ownership of it instead of
13954      copying.  We never want these commands to run later in
13955      bpstat_do_actions, if a breakpoint that causes a stop happens to
13956      be set at same address as this dprintf, or even if running the
13957      commands here throws.  */
13958   tmp_bs.commands = bs->commands;
13959   bs->commands = NULL;
13960   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13961
13962   bpstat_do_actions_1 (&tmp_bs_p);
13963
13964   /* 'tmp_bs.commands' will usually be NULL by now, but
13965      bpstat_do_actions_1 may return early without processing the whole
13966      list.  */
13967   do_cleanups (old_chain);
13968 }
13969
13970 /* The breakpoint_ops structure to be used on static tracepoints with
13971    markers (`-m').  */
13972
13973 static void
13974 strace_marker_create_sals_from_address (char **arg,
13975                                         struct linespec_result *canonical,
13976                                         enum bptype type_wanted,
13977                                         char *addr_start, char **copy_arg)
13978 {
13979   struct linespec_sals lsal;
13980
13981   lsal.sals = decode_static_tracepoint_spec (arg);
13982
13983   *copy_arg = savestring (addr_start, *arg - addr_start);
13984
13985   canonical->addr_string = xstrdup (*copy_arg);
13986   lsal.canonical = xstrdup (*copy_arg);
13987   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13988 }
13989
13990 static void
13991 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13992                                       struct linespec_result *canonical,
13993                                       char *cond_string,
13994                                       char *extra_string,
13995                                       enum bptype type_wanted,
13996                                       enum bpdisp disposition,
13997                                       int thread,
13998                                       int task, int ignore_count,
13999                                       const struct breakpoint_ops *ops,
14000                                       int from_tty, int enabled,
14001                                       int internal, unsigned flags)
14002 {
14003   int i;
14004   struct linespec_sals *lsal = VEC_index (linespec_sals,
14005                                           canonical->sals, 0);
14006
14007   /* If the user is creating a static tracepoint by marker id
14008      (strace -m MARKER_ID), then store the sals index, so that
14009      breakpoint_re_set can try to match up which of the newly
14010      found markers corresponds to this one, and, don't try to
14011      expand multiple locations for each sal, given than SALS
14012      already should contain all sals for MARKER_ID.  */
14013
14014   for (i = 0; i < lsal->sals.nelts; ++i)
14015     {
14016       struct symtabs_and_lines expanded;
14017       struct tracepoint *tp;
14018       struct cleanup *old_chain;
14019       char *addr_string;
14020
14021       expanded.nelts = 1;
14022       expanded.sals = &lsal->sals.sals[i];
14023
14024       addr_string = xstrdup (canonical->addr_string);
14025       old_chain = make_cleanup (xfree, addr_string);
14026
14027       tp = XCNEW (struct tracepoint);
14028       init_breakpoint_sal (&tp->base, gdbarch, expanded,
14029                            addr_string, NULL,
14030                            cond_string, extra_string,
14031                            type_wanted, disposition,
14032                            thread, task, ignore_count, ops,
14033                            from_tty, enabled, internal, flags,
14034                            canonical->special_display);
14035       /* Given that its possible to have multiple markers with
14036          the same string id, if the user is creating a static
14037          tracepoint by marker id ("strace -m MARKER_ID"), then
14038          store the sals index, so that breakpoint_re_set can
14039          try to match up which of the newly found markers
14040          corresponds to this one  */
14041       tp->static_trace_marker_id_idx = i;
14042
14043       install_breakpoint (internal, &tp->base, 0);
14044
14045       discard_cleanups (old_chain);
14046     }
14047 }
14048
14049 static void
14050 strace_marker_decode_linespec (struct breakpoint *b, char **s,
14051                                struct symtabs_and_lines *sals)
14052 {
14053   struct tracepoint *tp = (struct tracepoint *) b;
14054
14055   *sals = decode_static_tracepoint_spec (s);
14056   if (sals->nelts > tp->static_trace_marker_id_idx)
14057     {
14058       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
14059       sals->nelts = 1;
14060     }
14061   else
14062     error (_("marker %s not found"), tp->static_trace_marker_id);
14063 }
14064
14065 static struct breakpoint_ops strace_marker_breakpoint_ops;
14066
14067 static int
14068 strace_marker_p (struct breakpoint *b)
14069 {
14070   return b->ops == &strace_marker_breakpoint_ops;
14071 }
14072
14073 /* Delete a breakpoint and clean up all traces of it in the data
14074    structures.  */
14075
14076 void
14077 delete_breakpoint (struct breakpoint *bpt)
14078 {
14079   struct breakpoint *b;
14080
14081   gdb_assert (bpt != NULL);
14082
14083   /* Has this bp already been deleted?  This can happen because
14084      multiple lists can hold pointers to bp's.  bpstat lists are
14085      especial culprits.
14086
14087      One example of this happening is a watchpoint's scope bp.  When
14088      the scope bp triggers, we notice that the watchpoint is out of
14089      scope, and delete it.  We also delete its scope bp.  But the
14090      scope bp is marked "auto-deleting", and is already on a bpstat.
14091      That bpstat is then checked for auto-deleting bp's, which are
14092      deleted.
14093
14094      A real solution to this problem might involve reference counts in
14095      bp's, and/or giving them pointers back to their referencing
14096      bpstat's, and teaching delete_breakpoint to only free a bp's
14097      storage when no more references were extent.  A cheaper bandaid
14098      was chosen.  */
14099   if (bpt->type == bp_none)
14100     return;
14101
14102   /* At least avoid this stale reference until the reference counting
14103      of breakpoints gets resolved.  */
14104   if (bpt->related_breakpoint != bpt)
14105     {
14106       struct breakpoint *related;
14107       struct watchpoint *w;
14108
14109       if (bpt->type == bp_watchpoint_scope)
14110         w = (struct watchpoint *) bpt->related_breakpoint;
14111       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
14112         w = (struct watchpoint *) bpt;
14113       else
14114         w = NULL;
14115       if (w != NULL)
14116         watchpoint_del_at_next_stop (w);
14117
14118       /* Unlink bpt from the bpt->related_breakpoint ring.  */
14119       for (related = bpt; related->related_breakpoint != bpt;
14120            related = related->related_breakpoint);
14121       related->related_breakpoint = bpt->related_breakpoint;
14122       bpt->related_breakpoint = bpt;
14123     }
14124
14125   /* watch_command_1 creates a watchpoint but only sets its number if
14126      update_watchpoint succeeds in creating its bp_locations.  If there's
14127      a problem in that process, we'll be asked to delete the half-created
14128      watchpoint.  In that case, don't announce the deletion.  */
14129   if (bpt->number)
14130     observer_notify_breakpoint_deleted (bpt);
14131
14132   if (breakpoint_chain == bpt)
14133     breakpoint_chain = bpt->next;
14134
14135   ALL_BREAKPOINTS (b)
14136     if (b->next == bpt)
14137     {
14138       b->next = bpt->next;
14139       break;
14140     }
14141
14142   /* Be sure no bpstat's are pointing at the breakpoint after it's
14143      been freed.  */
14144   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
14145      in all threads for now.  Note that we cannot just remove bpstats
14146      pointing at bpt from the stop_bpstat list entirely, as breakpoint
14147      commands are associated with the bpstat; if we remove it here,
14148      then the later call to bpstat_do_actions (&stop_bpstat); in
14149      event-top.c won't do anything, and temporary breakpoints with
14150      commands won't work.  */
14151
14152   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
14153
14154   /* Now that breakpoint is removed from breakpoint list, update the
14155      global location list.  This will remove locations that used to
14156      belong to this breakpoint.  Do this before freeing the breakpoint
14157      itself, since remove_breakpoint looks at location's owner.  It
14158      might be better design to have location completely
14159      self-contained, but it's not the case now.  */
14160   update_global_location_list (UGLL_DONT_INSERT);
14161
14162   bpt->ops->dtor (bpt);
14163   /* On the chance that someone will soon try again to delete this
14164      same bp, we mark it as deleted before freeing its storage.  */
14165   bpt->type = bp_none;
14166   xfree (bpt);
14167 }
14168
14169 static void
14170 do_delete_breakpoint_cleanup (void *b)
14171 {
14172   delete_breakpoint (b);
14173 }
14174
14175 struct cleanup *
14176 make_cleanup_delete_breakpoint (struct breakpoint *b)
14177 {
14178   return make_cleanup (do_delete_breakpoint_cleanup, b);
14179 }
14180
14181 /* Iterator function to call a user-provided callback function once
14182    for each of B and its related breakpoints.  */
14183
14184 static void
14185 iterate_over_related_breakpoints (struct breakpoint *b,
14186                                   void (*function) (struct breakpoint *,
14187                                                     void *),
14188                                   void *data)
14189 {
14190   struct breakpoint *related;
14191
14192   related = b;
14193   do
14194     {
14195       struct breakpoint *next;
14196
14197       /* FUNCTION may delete RELATED.  */
14198       next = related->related_breakpoint;
14199
14200       if (next == related)
14201         {
14202           /* RELATED is the last ring entry.  */
14203           function (related, data);
14204
14205           /* FUNCTION may have deleted it, so we'd never reach back to
14206              B.  There's nothing left to do anyway, so just break
14207              out.  */
14208           break;
14209         }
14210       else
14211         function (related, data);
14212
14213       related = next;
14214     }
14215   while (related != b);
14216 }
14217
14218 static void
14219 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14220 {
14221   delete_breakpoint (b);
14222 }
14223
14224 /* A callback for map_breakpoint_numbers that calls
14225    delete_breakpoint.  */
14226
14227 static void
14228 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14229 {
14230   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14231 }
14232
14233 void
14234 delete_command (char *arg, int from_tty)
14235 {
14236   struct breakpoint *b, *b_tmp;
14237
14238   dont_repeat ();
14239
14240   if (arg == 0)
14241     {
14242       int breaks_to_delete = 0;
14243
14244       /* Delete all breakpoints if no argument.  Do not delete
14245          internal breakpoints, these have to be deleted with an
14246          explicit breakpoint number argument.  */
14247       ALL_BREAKPOINTS (b)
14248         if (user_breakpoint_p (b))
14249           {
14250             breaks_to_delete = 1;
14251             break;
14252           }
14253
14254       /* Ask user only if there are some breakpoints to delete.  */
14255       if (!from_tty
14256           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14257         {
14258           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14259             if (user_breakpoint_p (b))
14260               delete_breakpoint (b);
14261         }
14262     }
14263   else
14264     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14265 }
14266
14267 static int
14268 all_locations_are_pending (struct bp_location *loc)
14269 {
14270   for (; loc; loc = loc->next)
14271     if (!loc->shlib_disabled
14272         && !loc->pspace->executing_startup)
14273       return 0;
14274   return 1;
14275 }
14276
14277 /* Subroutine of update_breakpoint_locations to simplify it.
14278    Return non-zero if multiple fns in list LOC have the same name.
14279    Null names are ignored.  */
14280
14281 static int
14282 ambiguous_names_p (struct bp_location *loc)
14283 {
14284   struct bp_location *l;
14285   htab_t htab = htab_create_alloc (13, htab_hash_string,
14286                                    (int (*) (const void *, 
14287                                              const void *)) streq,
14288                                    NULL, xcalloc, xfree);
14289
14290   for (l = loc; l != NULL; l = l->next)
14291     {
14292       const char **slot;
14293       const char *name = l->function_name;
14294
14295       /* Allow for some names to be NULL, ignore them.  */
14296       if (name == NULL)
14297         continue;
14298
14299       slot = (const char **) htab_find_slot (htab, (const void *) name,
14300                                              INSERT);
14301       /* NOTE: We can assume slot != NULL here because xcalloc never
14302          returns NULL.  */
14303       if (*slot != NULL)
14304         {
14305           htab_delete (htab);
14306           return 1;
14307         }
14308       *slot = name;
14309     }
14310
14311   htab_delete (htab);
14312   return 0;
14313 }
14314
14315 /* When symbols change, it probably means the sources changed as well,
14316    and it might mean the static tracepoint markers are no longer at
14317    the same address or line numbers they used to be at last we
14318    checked.  Losing your static tracepoints whenever you rebuild is
14319    undesirable.  This function tries to resync/rematch gdb static
14320    tracepoints with the markers on the target, for static tracepoints
14321    that have not been set by marker id.  Static tracepoint that have
14322    been set by marker id are reset by marker id in breakpoint_re_set.
14323    The heuristic is:
14324
14325    1) For a tracepoint set at a specific address, look for a marker at
14326    the old PC.  If one is found there, assume to be the same marker.
14327    If the name / string id of the marker found is different from the
14328    previous known name, assume that means the user renamed the marker
14329    in the sources, and output a warning.
14330
14331    2) For a tracepoint set at a given line number, look for a marker
14332    at the new address of the old line number.  If one is found there,
14333    assume to be the same marker.  If the name / string id of the
14334    marker found is different from the previous known name, assume that
14335    means the user renamed the marker in the sources, and output a
14336    warning.
14337
14338    3) If a marker is no longer found at the same address or line, it
14339    may mean the marker no longer exists.  But it may also just mean
14340    the code changed a bit.  Maybe the user added a few lines of code
14341    that made the marker move up or down (in line number terms).  Ask
14342    the target for info about the marker with the string id as we knew
14343    it.  If found, update line number and address in the matching
14344    static tracepoint.  This will get confused if there's more than one
14345    marker with the same ID (possible in UST, although unadvised
14346    precisely because it confuses tools).  */
14347
14348 static struct symtab_and_line
14349 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14350 {
14351   struct tracepoint *tp = (struct tracepoint *) b;
14352   struct static_tracepoint_marker marker;
14353   CORE_ADDR pc;
14354
14355   pc = sal.pc;
14356   if (sal.line)
14357     find_line_pc (sal.symtab, sal.line, &pc);
14358
14359   if (target_static_tracepoint_marker_at (pc, &marker))
14360     {
14361       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14362         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14363                  b->number,
14364                  tp->static_trace_marker_id, marker.str_id);
14365
14366       xfree (tp->static_trace_marker_id);
14367       tp->static_trace_marker_id = xstrdup (marker.str_id);
14368       release_static_tracepoint_marker (&marker);
14369
14370       return sal;
14371     }
14372
14373   /* Old marker wasn't found on target at lineno.  Try looking it up
14374      by string ID.  */
14375   if (!sal.explicit_pc
14376       && sal.line != 0
14377       && sal.symtab != NULL
14378       && tp->static_trace_marker_id != NULL)
14379     {
14380       VEC(static_tracepoint_marker_p) *markers;
14381
14382       markers
14383         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14384
14385       if (!VEC_empty(static_tracepoint_marker_p, markers))
14386         {
14387           struct symtab_and_line sal2;
14388           struct symbol *sym;
14389           struct static_tracepoint_marker *tpmarker;
14390           struct ui_out *uiout = current_uiout;
14391
14392           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14393
14394           xfree (tp->static_trace_marker_id);
14395           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14396
14397           warning (_("marker for static tracepoint %d (%s) not "
14398                      "found at previous line number"),
14399                    b->number, tp->static_trace_marker_id);
14400
14401           init_sal (&sal2);
14402
14403           sal2.pc = tpmarker->address;
14404
14405           sal2 = find_pc_line (tpmarker->address, 0);
14406           sym = find_pc_sect_function (tpmarker->address, NULL);
14407           ui_out_text (uiout, "Now in ");
14408           if (sym)
14409             {
14410               ui_out_field_string (uiout, "func",
14411                                    SYMBOL_PRINT_NAME (sym));
14412               ui_out_text (uiout, " at ");
14413             }
14414           ui_out_field_string (uiout, "file",
14415                                symtab_to_filename_for_display (sal2.symtab));
14416           ui_out_text (uiout, ":");
14417
14418           if (ui_out_is_mi_like_p (uiout))
14419             {
14420               const char *fullname = symtab_to_fullname (sal2.symtab);
14421
14422               ui_out_field_string (uiout, "fullname", fullname);
14423             }
14424
14425           ui_out_field_int (uiout, "line", sal2.line);
14426           ui_out_text (uiout, "\n");
14427
14428           b->loc->line_number = sal2.line;
14429           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14430
14431           xfree (b->addr_string);
14432           b->addr_string = xstrprintf ("%s:%d",
14433                                    symtab_to_filename_for_display (sal2.symtab),
14434                                        b->loc->line_number);
14435
14436           /* Might be nice to check if function changed, and warn if
14437              so.  */
14438
14439           release_static_tracepoint_marker (tpmarker);
14440         }
14441     }
14442   return sal;
14443 }
14444
14445 /* Returns 1 iff locations A and B are sufficiently same that
14446    we don't need to report breakpoint as changed.  */
14447
14448 static int
14449 locations_are_equal (struct bp_location *a, struct bp_location *b)
14450 {
14451   while (a && b)
14452     {
14453       if (a->address != b->address)
14454         return 0;
14455
14456       if (a->shlib_disabled != b->shlib_disabled)
14457         return 0;
14458
14459       if (a->enabled != b->enabled)
14460         return 0;
14461
14462       a = a->next;
14463       b = b->next;
14464     }
14465
14466   if ((a == NULL) != (b == NULL))
14467     return 0;
14468
14469   return 1;
14470 }
14471
14472 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14473    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14474    a ranged breakpoint.  */
14475
14476 void
14477 update_breakpoint_locations (struct breakpoint *b,
14478                              struct symtabs_and_lines sals,
14479                              struct symtabs_and_lines sals_end)
14480 {
14481   int i;
14482   struct bp_location *existing_locations = b->loc;
14483
14484   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14485     {
14486       /* Ranged breakpoints have only one start location and one end
14487          location.  */
14488       b->enable_state = bp_disabled;
14489       update_global_location_list (UGLL_MAY_INSERT);
14490       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14491                            "multiple locations found\n"),
14492                          b->number);
14493       return;
14494     }
14495
14496   /* If there's no new locations, and all existing locations are
14497      pending, don't do anything.  This optimizes the common case where
14498      all locations are in the same shared library, that was unloaded.
14499      We'd like to retain the location, so that when the library is
14500      loaded again, we don't loose the enabled/disabled status of the
14501      individual locations.  */
14502   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14503     return;
14504
14505   b->loc = NULL;
14506
14507   for (i = 0; i < sals.nelts; ++i)
14508     {
14509       struct bp_location *new_loc;
14510
14511       switch_to_program_space_and_thread (sals.sals[i].pspace);
14512
14513       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14514
14515       /* Reparse conditions, they might contain references to the
14516          old symtab.  */
14517       if (b->cond_string != NULL)
14518         {
14519           const char *s;
14520           volatile struct gdb_exception e;
14521
14522           s = b->cond_string;
14523           TRY_CATCH (e, RETURN_MASK_ERROR)
14524             {
14525               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14526                                            block_for_pc (sals.sals[i].pc), 
14527                                            0);
14528             }
14529           if (e.reason < 0)
14530             {
14531               warning (_("failed to reevaluate condition "
14532                          "for breakpoint %d: %s"), 
14533                        b->number, e.message);
14534               new_loc->enabled = 0;
14535             }
14536         }
14537
14538       if (sals_end.nelts)
14539         {
14540           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14541
14542           new_loc->length = end - sals.sals[0].pc + 1;
14543         }
14544     }
14545
14546   /* Update locations of permanent breakpoints.  */
14547   if (b->enable_state == bp_permanent)
14548     make_breakpoint_permanent (b);
14549
14550   /* If possible, carry over 'disable' status from existing
14551      breakpoints.  */
14552   {
14553     struct bp_location *e = existing_locations;
14554     /* If there are multiple breakpoints with the same function name,
14555        e.g. for inline functions, comparing function names won't work.
14556        Instead compare pc addresses; this is just a heuristic as things
14557        may have moved, but in practice it gives the correct answer
14558        often enough until a better solution is found.  */
14559     int have_ambiguous_names = ambiguous_names_p (b->loc);
14560
14561     for (; e; e = e->next)
14562       {
14563         if (!e->enabled && e->function_name)
14564           {
14565             struct bp_location *l = b->loc;
14566             if (have_ambiguous_names)
14567               {
14568                 for (; l; l = l->next)
14569                   if (breakpoint_locations_match (e, l))
14570                     {
14571                       l->enabled = 0;
14572                       break;
14573                     }
14574               }
14575             else
14576               {
14577                 for (; l; l = l->next)
14578                   if (l->function_name
14579                       && strcmp (e->function_name, l->function_name) == 0)
14580                     {
14581                       l->enabled = 0;
14582                       break;
14583                     }
14584               }
14585           }
14586       }
14587   }
14588
14589   if (!locations_are_equal (existing_locations, b->loc))
14590     observer_notify_breakpoint_modified (b);
14591
14592   update_global_location_list (UGLL_MAY_INSERT);
14593 }
14594
14595 /* Find the SaL locations corresponding to the given ADDR_STRING.
14596    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14597
14598 static struct symtabs_and_lines
14599 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14600 {
14601   char *s;
14602   struct symtabs_and_lines sals = {0};
14603   volatile struct gdb_exception e;
14604
14605   gdb_assert (b->ops != NULL);
14606   s = addr_string;
14607
14608   TRY_CATCH (e, RETURN_MASK_ERROR)
14609     {
14610       b->ops->decode_linespec (b, &s, &sals);
14611     }
14612   if (e.reason < 0)
14613     {
14614       int not_found_and_ok = 0;
14615       /* For pending breakpoints, it's expected that parsing will
14616          fail until the right shared library is loaded.  User has
14617          already told to create pending breakpoints and don't need
14618          extra messages.  If breakpoint is in bp_shlib_disabled
14619          state, then user already saw the message about that
14620          breakpoint being disabled, and don't want to see more
14621          errors.  */
14622       if (e.error == NOT_FOUND_ERROR
14623           && (b->condition_not_parsed 
14624               || (b->loc && b->loc->shlib_disabled)
14625               || (b->loc && b->loc->pspace->executing_startup)
14626               || b->enable_state == bp_disabled))
14627         not_found_and_ok = 1;
14628
14629       if (!not_found_and_ok)
14630         {
14631           /* We surely don't want to warn about the same breakpoint
14632              10 times.  One solution, implemented here, is disable
14633              the breakpoint on error.  Another solution would be to
14634              have separate 'warning emitted' flag.  Since this
14635              happens only when a binary has changed, I don't know
14636              which approach is better.  */
14637           b->enable_state = bp_disabled;
14638           throw_exception (e);
14639         }
14640     }
14641
14642   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14643     {
14644       int i;
14645
14646       for (i = 0; i < sals.nelts; ++i)
14647         resolve_sal_pc (&sals.sals[i]);
14648       if (b->condition_not_parsed && s && s[0])
14649         {
14650           char *cond_string, *extra_string;
14651           int thread, task;
14652
14653           find_condition_and_thread (s, sals.sals[0].pc,
14654                                      &cond_string, &thread, &task,
14655                                      &extra_string);
14656           if (cond_string)
14657             b->cond_string = cond_string;
14658           b->thread = thread;
14659           b->task = task;
14660           if (extra_string)
14661             b->extra_string = extra_string;
14662           b->condition_not_parsed = 0;
14663         }
14664
14665       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14666         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14667
14668       *found = 1;
14669     }
14670   else
14671     *found = 0;
14672
14673   return sals;
14674 }
14675
14676 /* The default re_set method, for typical hardware or software
14677    breakpoints.  Reevaluate the breakpoint and recreate its
14678    locations.  */
14679
14680 static void
14681 breakpoint_re_set_default (struct breakpoint *b)
14682 {
14683   int found;
14684   struct symtabs_and_lines sals, sals_end;
14685   struct symtabs_and_lines expanded = {0};
14686   struct symtabs_and_lines expanded_end = {0};
14687
14688   sals = addr_string_to_sals (b, b->addr_string, &found);
14689   if (found)
14690     {
14691       make_cleanup (xfree, sals.sals);
14692       expanded = sals;
14693     }
14694
14695   if (b->addr_string_range_end)
14696     {
14697       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14698       if (found)
14699         {
14700           make_cleanup (xfree, sals_end.sals);
14701           expanded_end = sals_end;
14702         }
14703     }
14704
14705   update_breakpoint_locations (b, expanded, expanded_end);
14706 }
14707
14708 /* Default method for creating SALs from an address string.  It basically
14709    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14710
14711 static void
14712 create_sals_from_address_default (char **arg,
14713                                   struct linespec_result *canonical,
14714                                   enum bptype type_wanted,
14715                                   char *addr_start, char **copy_arg)
14716 {
14717   parse_breakpoint_sals (arg, canonical);
14718 }
14719
14720 /* Call create_breakpoints_sal for the given arguments.  This is the default
14721    function for the `create_breakpoints_sal' method of
14722    breakpoint_ops.  */
14723
14724 static void
14725 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14726                                 struct linespec_result *canonical,
14727                                 char *cond_string,
14728                                 char *extra_string,
14729                                 enum bptype type_wanted,
14730                                 enum bpdisp disposition,
14731                                 int thread,
14732                                 int task, int ignore_count,
14733                                 const struct breakpoint_ops *ops,
14734                                 int from_tty, int enabled,
14735                                 int internal, unsigned flags)
14736 {
14737   create_breakpoints_sal (gdbarch, canonical, cond_string,
14738                           extra_string,
14739                           type_wanted, disposition,
14740                           thread, task, ignore_count, ops, from_tty,
14741                           enabled, internal, flags);
14742 }
14743
14744 /* Decode the line represented by S by calling decode_line_full.  This is the
14745    default function for the `decode_linespec' method of breakpoint_ops.  */
14746
14747 static void
14748 decode_linespec_default (struct breakpoint *b, char **s,
14749                          struct symtabs_and_lines *sals)
14750 {
14751   struct linespec_result canonical;
14752
14753   init_linespec_result (&canonical);
14754   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14755                     (struct symtab *) NULL, 0,
14756                     &canonical, multiple_symbols_all,
14757                     b->filter);
14758
14759   /* We should get 0 or 1 resulting SALs.  */
14760   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14761
14762   if (VEC_length (linespec_sals, canonical.sals) > 0)
14763     {
14764       struct linespec_sals *lsal;
14765
14766       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14767       *sals = lsal->sals;
14768       /* Arrange it so the destructor does not free the
14769          contents.  */
14770       lsal->sals.sals = NULL;
14771     }
14772
14773   destroy_linespec_result (&canonical);
14774 }
14775
14776 /* Prepare the global context for a re-set of breakpoint B.  */
14777
14778 static struct cleanup *
14779 prepare_re_set_context (struct breakpoint *b)
14780 {
14781   struct cleanup *cleanups;
14782
14783   input_radix = b->input_radix;
14784   cleanups = save_current_space_and_thread ();
14785   if (b->pspace != NULL)
14786     switch_to_program_space_and_thread (b->pspace);
14787   set_language (b->language);
14788
14789   return cleanups;
14790 }
14791
14792 /* Reset a breakpoint given it's struct breakpoint * BINT.
14793    The value we return ends up being the return value from catch_errors.
14794    Unused in this case.  */
14795
14796 static int
14797 breakpoint_re_set_one (void *bint)
14798 {
14799   /* Get past catch_errs.  */
14800   struct breakpoint *b = (struct breakpoint *) bint;
14801   struct cleanup *cleanups;
14802
14803   cleanups = prepare_re_set_context (b);
14804   b->ops->re_set (b);
14805   do_cleanups (cleanups);
14806   return 0;
14807 }
14808
14809 /* Re-set all breakpoints after symbols have been re-loaded.  */
14810 void
14811 breakpoint_re_set (void)
14812 {
14813   struct breakpoint *b, *b_tmp;
14814   enum language save_language;
14815   int save_input_radix;
14816   struct cleanup *old_chain;
14817
14818   save_language = current_language->la_language;
14819   save_input_radix = input_radix;
14820   old_chain = save_current_program_space ();
14821
14822   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14823   {
14824     /* Format possible error msg.  */
14825     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14826                                 b->number);
14827     struct cleanup *cleanups = make_cleanup (xfree, message);
14828     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14829     do_cleanups (cleanups);
14830   }
14831   set_language (save_language);
14832   input_radix = save_input_radix;
14833
14834   jit_breakpoint_re_set ();
14835
14836   do_cleanups (old_chain);
14837
14838   create_overlay_event_breakpoint ();
14839   create_longjmp_master_breakpoint ();
14840   create_std_terminate_master_breakpoint ();
14841   create_exception_master_breakpoint ();
14842 }
14843 \f
14844 /* Reset the thread number of this breakpoint:
14845
14846    - If the breakpoint is for all threads, leave it as-is.
14847    - Else, reset it to the current thread for inferior_ptid.  */
14848 void
14849 breakpoint_re_set_thread (struct breakpoint *b)
14850 {
14851   if (b->thread != -1)
14852     {
14853       if (in_thread_list (inferior_ptid))
14854         b->thread = pid_to_thread_id (inferior_ptid);
14855
14856       /* We're being called after following a fork.  The new fork is
14857          selected as current, and unless this was a vfork will have a
14858          different program space from the original thread.  Reset that
14859          as well.  */
14860       b->loc->pspace = current_program_space;
14861     }
14862 }
14863
14864 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14865    If from_tty is nonzero, it prints a message to that effect,
14866    which ends with a period (no newline).  */
14867
14868 void
14869 set_ignore_count (int bptnum, int count, int from_tty)
14870 {
14871   struct breakpoint *b;
14872
14873   if (count < 0)
14874     count = 0;
14875
14876   ALL_BREAKPOINTS (b)
14877     if (b->number == bptnum)
14878     {
14879       if (is_tracepoint (b))
14880         {
14881           if (from_tty && count != 0)
14882             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14883                              bptnum);
14884           return;
14885         }
14886       
14887       b->ignore_count = count;
14888       if (from_tty)
14889         {
14890           if (count == 0)
14891             printf_filtered (_("Will stop next time "
14892                                "breakpoint %d is reached."),
14893                              bptnum);
14894           else if (count == 1)
14895             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14896                              bptnum);
14897           else
14898             printf_filtered (_("Will ignore next %d "
14899                                "crossings of breakpoint %d."),
14900                              count, bptnum);
14901         }
14902       observer_notify_breakpoint_modified (b);
14903       return;
14904     }
14905
14906   error (_("No breakpoint number %d."), bptnum);
14907 }
14908
14909 /* Command to set ignore-count of breakpoint N to COUNT.  */
14910
14911 static void
14912 ignore_command (char *args, int from_tty)
14913 {
14914   char *p = args;
14915   int num;
14916
14917   if (p == 0)
14918     error_no_arg (_("a breakpoint number"));
14919
14920   num = get_number (&p);
14921   if (num == 0)
14922     error (_("bad breakpoint number: '%s'"), args);
14923   if (*p == 0)
14924     error (_("Second argument (specified ignore-count) is missing."));
14925
14926   set_ignore_count (num,
14927                     longest_to_int (value_as_long (parse_and_eval (p))),
14928                     from_tty);
14929   if (from_tty)
14930     printf_filtered ("\n");
14931 }
14932 \f
14933 /* Call FUNCTION on each of the breakpoints
14934    whose numbers are given in ARGS.  */
14935
14936 static void
14937 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14938                                                       void *),
14939                         void *data)
14940 {
14941   int num;
14942   struct breakpoint *b, *tmp;
14943   int match;
14944   struct get_number_or_range_state state;
14945
14946   if (args == 0)
14947     error_no_arg (_("one or more breakpoint numbers"));
14948
14949   init_number_or_range (&state, args);
14950
14951   while (!state.finished)
14952     {
14953       const char *p = state.string;
14954
14955       match = 0;
14956
14957       num = get_number_or_range (&state);
14958       if (num == 0)
14959         {
14960           warning (_("bad breakpoint number at or near '%s'"), p);
14961         }
14962       else
14963         {
14964           ALL_BREAKPOINTS_SAFE (b, tmp)
14965             if (b->number == num)
14966               {
14967                 match = 1;
14968                 function (b, data);
14969                 break;
14970               }
14971           if (match == 0)
14972             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14973         }
14974     }
14975 }
14976
14977 static struct bp_location *
14978 find_location_by_number (char *number)
14979 {
14980   char *dot = strchr (number, '.');
14981   char *p1;
14982   int bp_num;
14983   int loc_num;
14984   struct breakpoint *b;
14985   struct bp_location *loc;  
14986
14987   *dot = '\0';
14988
14989   p1 = number;
14990   bp_num = get_number (&p1);
14991   if (bp_num == 0)
14992     error (_("Bad breakpoint number '%s'"), number);
14993
14994   ALL_BREAKPOINTS (b)
14995     if (b->number == bp_num)
14996       {
14997         break;
14998       }
14999
15000   if (!b || b->number != bp_num)
15001     error (_("Bad breakpoint number '%s'"), number);
15002   
15003   p1 = dot+1;
15004   loc_num = get_number (&p1);
15005   if (loc_num == 0)
15006     error (_("Bad breakpoint location number '%s'"), number);
15007
15008   --loc_num;
15009   loc = b->loc;
15010   for (;loc_num && loc; --loc_num, loc = loc->next)
15011     ;
15012   if (!loc)
15013     error (_("Bad breakpoint location number '%s'"), dot+1);
15014     
15015   return loc;  
15016 }
15017
15018
15019 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
15020    If from_tty is nonzero, it prints a message to that effect,
15021    which ends with a period (no newline).  */
15022
15023 void
15024 disable_breakpoint (struct breakpoint *bpt)
15025 {
15026   /* Never disable a watchpoint scope breakpoint; we want to
15027      hit them when we leave scope so we can delete both the
15028      watchpoint and its scope breakpoint at that time.  */
15029   if (bpt->type == bp_watchpoint_scope)
15030     return;
15031
15032   /* You can't disable permanent breakpoints.  */
15033   if (bpt->enable_state == bp_permanent)
15034     return;
15035
15036   bpt->enable_state = bp_disabled;
15037
15038   /* Mark breakpoint locations modified.  */
15039   mark_breakpoint_modified (bpt);
15040
15041   if (target_supports_enable_disable_tracepoint ()
15042       && current_trace_status ()->running && is_tracepoint (bpt))
15043     {
15044       struct bp_location *location;
15045      
15046       for (location = bpt->loc; location; location = location->next)
15047         target_disable_tracepoint (location);
15048     }
15049
15050   update_global_location_list (UGLL_DONT_INSERT);
15051
15052   observer_notify_breakpoint_modified (bpt);
15053 }
15054
15055 /* A callback for iterate_over_related_breakpoints.  */
15056
15057 static void
15058 do_disable_breakpoint (struct breakpoint *b, void *ignore)
15059 {
15060   disable_breakpoint (b);
15061 }
15062
15063 /* A callback for map_breakpoint_numbers that calls
15064    disable_breakpoint.  */
15065
15066 static void
15067 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
15068 {
15069   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
15070 }
15071
15072 static void
15073 disable_command (char *args, int from_tty)
15074 {
15075   if (args == 0)
15076     {
15077       struct breakpoint *bpt;
15078
15079       ALL_BREAKPOINTS (bpt)
15080         if (user_breakpoint_p (bpt))
15081           disable_breakpoint (bpt);
15082     }
15083   else
15084     {
15085       char *num = extract_arg (&args);
15086
15087       while (num)
15088         {
15089           if (strchr (num, '.'))
15090             {
15091               struct bp_location *loc = find_location_by_number (num);
15092
15093               if (loc)
15094                 {
15095                   if (loc->enabled)
15096                     {
15097                       loc->enabled = 0;
15098                       mark_breakpoint_location_modified (loc);
15099                     }
15100                   if (target_supports_enable_disable_tracepoint ()
15101                       && current_trace_status ()->running && loc->owner
15102                       && is_tracepoint (loc->owner))
15103                     target_disable_tracepoint (loc);
15104                 }
15105               update_global_location_list (UGLL_DONT_INSERT);
15106             }
15107           else
15108             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
15109           num = extract_arg (&args);
15110         }
15111     }
15112 }
15113
15114 static void
15115 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
15116                         int count)
15117 {
15118   int target_resources_ok;
15119
15120   if (bpt->type == bp_hardware_breakpoint)
15121     {
15122       int i;
15123       i = hw_breakpoint_used_count ();
15124       target_resources_ok = 
15125         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
15126                                             i + 1, 0);
15127       if (target_resources_ok == 0)
15128         error (_("No hardware breakpoint support in the target."));
15129       else if (target_resources_ok < 0)
15130         error (_("Hardware breakpoints used exceeds limit."));
15131     }
15132
15133   if (is_watchpoint (bpt))
15134     {
15135       /* Initialize it just to avoid a GCC false warning.  */
15136       enum enable_state orig_enable_state = 0;
15137       volatile struct gdb_exception e;
15138
15139       TRY_CATCH (e, RETURN_MASK_ALL)
15140         {
15141           struct watchpoint *w = (struct watchpoint *) bpt;
15142
15143           orig_enable_state = bpt->enable_state;
15144           bpt->enable_state = bp_enabled;
15145           update_watchpoint (w, 1 /* reparse */);
15146         }
15147       if (e.reason < 0)
15148         {
15149           bpt->enable_state = orig_enable_state;
15150           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
15151                              bpt->number);
15152           return;
15153         }
15154     }
15155
15156   if (bpt->enable_state != bp_permanent)
15157     bpt->enable_state = bp_enabled;
15158
15159   bpt->enable_state = bp_enabled;
15160
15161   /* Mark breakpoint locations modified.  */
15162   mark_breakpoint_modified (bpt);
15163
15164   if (target_supports_enable_disable_tracepoint ()
15165       && current_trace_status ()->running && is_tracepoint (bpt))
15166     {
15167       struct bp_location *location;
15168
15169       for (location = bpt->loc; location; location = location->next)
15170         target_enable_tracepoint (location);
15171     }
15172
15173   bpt->disposition = disposition;
15174   bpt->enable_count = count;
15175   update_global_location_list (UGLL_MAY_INSERT);
15176
15177   observer_notify_breakpoint_modified (bpt);
15178 }
15179
15180
15181 void
15182 enable_breakpoint (struct breakpoint *bpt)
15183 {
15184   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15185 }
15186
15187 static void
15188 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15189 {
15190   enable_breakpoint (bpt);
15191 }
15192
15193 /* A callback for map_breakpoint_numbers that calls
15194    enable_breakpoint.  */
15195
15196 static void
15197 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15198 {
15199   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15200 }
15201
15202 /* The enable command enables the specified breakpoints (or all defined
15203    breakpoints) so they once again become (or continue to be) effective
15204    in stopping the inferior.  */
15205
15206 static void
15207 enable_command (char *args, int from_tty)
15208 {
15209   if (args == 0)
15210     {
15211       struct breakpoint *bpt;
15212
15213       ALL_BREAKPOINTS (bpt)
15214         if (user_breakpoint_p (bpt))
15215           enable_breakpoint (bpt);
15216     }
15217   else
15218     {
15219       char *num = extract_arg (&args);
15220
15221       while (num)
15222         {
15223           if (strchr (num, '.'))
15224             {
15225               struct bp_location *loc = find_location_by_number (num);
15226
15227               if (loc)
15228                 {
15229                   if (!loc->enabled)
15230                     {
15231                       loc->enabled = 1;
15232                       mark_breakpoint_location_modified (loc);
15233                     }
15234                   if (target_supports_enable_disable_tracepoint ()
15235                       && current_trace_status ()->running && loc->owner
15236                       && is_tracepoint (loc->owner))
15237                     target_enable_tracepoint (loc);
15238                 }
15239               update_global_location_list (UGLL_MAY_INSERT);
15240             }
15241           else
15242             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15243           num = extract_arg (&args);
15244         }
15245     }
15246 }
15247
15248 /* This struct packages up disposition data for application to multiple
15249    breakpoints.  */
15250
15251 struct disp_data
15252 {
15253   enum bpdisp disp;
15254   int count;
15255 };
15256
15257 static void
15258 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15259 {
15260   struct disp_data disp_data = *(struct disp_data *) arg;
15261
15262   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15263 }
15264
15265 static void
15266 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15267 {
15268   struct disp_data disp = { disp_disable, 1 };
15269
15270   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15271 }
15272
15273 static void
15274 enable_once_command (char *args, int from_tty)
15275 {
15276   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15277 }
15278
15279 static void
15280 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15281 {
15282   struct disp_data disp = { disp_disable, *(int *) countptr };
15283
15284   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15285 }
15286
15287 static void
15288 enable_count_command (char *args, int from_tty)
15289 {
15290   int count = get_number (&args);
15291
15292   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15293 }
15294
15295 static void
15296 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15297 {
15298   struct disp_data disp = { disp_del, 1 };
15299
15300   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15301 }
15302
15303 static void
15304 enable_delete_command (char *args, int from_tty)
15305 {
15306   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15307 }
15308 \f
15309 static void
15310 set_breakpoint_cmd (char *args, int from_tty)
15311 {
15312 }
15313
15314 static void
15315 show_breakpoint_cmd (char *args, int from_tty)
15316 {
15317 }
15318
15319 /* Invalidate last known value of any hardware watchpoint if
15320    the memory which that value represents has been written to by
15321    GDB itself.  */
15322
15323 static void
15324 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15325                                       CORE_ADDR addr, ssize_t len,
15326                                       const bfd_byte *data)
15327 {
15328   struct breakpoint *bp;
15329
15330   ALL_BREAKPOINTS (bp)
15331     if (bp->enable_state == bp_enabled
15332         && bp->type == bp_hardware_watchpoint)
15333       {
15334         struct watchpoint *wp = (struct watchpoint *) bp;
15335
15336         if (wp->val_valid && wp->val)
15337           {
15338             struct bp_location *loc;
15339
15340             for (loc = bp->loc; loc != NULL; loc = loc->next)
15341               if (loc->loc_type == bp_loc_hardware_watchpoint
15342                   && loc->address + loc->length > addr
15343                   && addr + len > loc->address)
15344                 {
15345                   value_free (wp->val);
15346                   wp->val = NULL;
15347                   wp->val_valid = 0;
15348                 }
15349           }
15350       }
15351 }
15352
15353 /* Create and insert a raw software breakpoint at PC.  Return an
15354    identifier, which should be used to remove the breakpoint later.
15355    In general, places which call this should be using something on the
15356    breakpoint chain instead; this function should be eliminated
15357    someday.  */
15358
15359 void *
15360 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15361                                   struct address_space *aspace, CORE_ADDR pc)
15362 {
15363   struct bp_target_info *bp_tgt;
15364   struct bp_location *bl;
15365
15366   bp_tgt = XCNEW (struct bp_target_info);
15367
15368   bp_tgt->placed_address_space = aspace;
15369   bp_tgt->placed_address = pc;
15370
15371   /* If an unconditional non-raw breakpoint is already inserted at
15372      that location, there's no need to insert another.  However, with
15373      target-side evaluation of breakpoint conditions, if the
15374      breakpoint that is currently inserted on the target is
15375      conditional, we need to make it unconditional.  Note that a
15376      breakpoint with target-side commands is not reported even if
15377      unconditional, so we need to remove the commands from the target
15378      as well.  */
15379   bl = find_non_raw_software_breakpoint_inserted_here (aspace, pc);
15380   if (bl != NULL
15381       && VEC_empty (agent_expr_p, bl->target_info.conditions)
15382       && VEC_empty (agent_expr_p, bl->target_info.tcommands))
15383     {
15384       bp_target_info_copy_insertion_state (bp_tgt, &bl->target_info);
15385       return bp_tgt;
15386     }
15387
15388   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15389     {
15390       /* Could not insert the breakpoint.  */
15391       xfree (bp_tgt);
15392       return NULL;
15393     }
15394
15395   return bp_tgt;
15396 }
15397
15398 /* Remove a breakpoint BP inserted by
15399    deprecated_insert_raw_breakpoint.  */
15400
15401 int
15402 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15403 {
15404   struct bp_target_info *bp_tgt = bp;
15405   struct address_space *aspace = bp_tgt->placed_address_space;
15406   CORE_ADDR address = bp_tgt->placed_address;
15407   struct bp_location *bl;
15408   int ret;
15409
15410   bl = find_non_raw_software_breakpoint_inserted_here (aspace, address);
15411
15412   /* Only remove the raw breakpoint if there are no other non-raw
15413      breakpoints still inserted at this location.  Otherwise, we would
15414      be effectively disabling those breakpoints.  */
15415   if (bl == NULL)
15416     ret = target_remove_breakpoint (gdbarch, bp_tgt);
15417   else if (!VEC_empty (agent_expr_p, bl->target_info.conditions)
15418            || !VEC_empty (agent_expr_p, bl->target_info.tcommands))
15419     {
15420       /* The target is evaluating conditions, and when we inserted the
15421          software single-step breakpoint, we had made the breakpoint
15422          unconditional and command-less on the target side.  Reinsert
15423          to restore the conditions/commands.  */
15424       ret = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
15425     }
15426   else
15427     ret = 0;
15428
15429   xfree (bp_tgt);
15430
15431   return ret;
15432 }
15433
15434 /* Create and insert a breakpoint for software single step.  */
15435
15436 void
15437 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15438                                struct address_space *aspace, 
15439                                CORE_ADDR next_pc)
15440 {
15441   void **bpt_p;
15442
15443   if (single_step_breakpoints[0] == NULL)
15444     {
15445       bpt_p = &single_step_breakpoints[0];
15446       single_step_gdbarch[0] = gdbarch;
15447     }
15448   else
15449     {
15450       gdb_assert (single_step_breakpoints[1] == NULL);
15451       bpt_p = &single_step_breakpoints[1];
15452       single_step_gdbarch[1] = gdbarch;
15453     }
15454
15455   /* NOTE drow/2006-04-11: A future improvement to this function would
15456      be to only create the breakpoints once, and actually put them on
15457      the breakpoint chain.  That would let us use set_raw_breakpoint.
15458      We could adjust the addresses each time they were needed.  Doing
15459      this requires corresponding changes elsewhere where single step
15460      breakpoints are handled, however.  So, for now, we use this.  */
15461
15462   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15463   if (*bpt_p == NULL)
15464     error (_("Could not insert single-step breakpoint at %s"),
15465              paddress (gdbarch, next_pc));
15466 }
15467
15468 /* Check if the breakpoints used for software single stepping
15469    were inserted or not.  */
15470
15471 int
15472 single_step_breakpoints_inserted (void)
15473 {
15474   return (single_step_breakpoints[0] != NULL
15475           || single_step_breakpoints[1] != NULL);
15476 }
15477
15478 /* Remove and delete any breakpoints used for software single step.  */
15479
15480 void
15481 remove_single_step_breakpoints (void)
15482 {
15483   gdb_assert (single_step_breakpoints[0] != NULL);
15484
15485   /* See insert_single_step_breakpoint for more about this deprecated
15486      call.  */
15487   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15488                                     single_step_breakpoints[0]);
15489   single_step_gdbarch[0] = NULL;
15490   single_step_breakpoints[0] = NULL;
15491
15492   if (single_step_breakpoints[1] != NULL)
15493     {
15494       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15495                                         single_step_breakpoints[1]);
15496       single_step_gdbarch[1] = NULL;
15497       single_step_breakpoints[1] = NULL;
15498     }
15499 }
15500
15501 /* Delete software single step breakpoints without removing them from
15502    the inferior.  This is intended to be used if the inferior's address
15503    space where they were inserted is already gone, e.g. after exit or
15504    exec.  */
15505
15506 void
15507 cancel_single_step_breakpoints (void)
15508 {
15509   int i;
15510
15511   for (i = 0; i < 2; i++)
15512     if (single_step_breakpoints[i])
15513       {
15514         xfree (single_step_breakpoints[i]);
15515         single_step_breakpoints[i] = NULL;
15516         single_step_gdbarch[i] = NULL;
15517       }
15518 }
15519
15520 /* Detach software single-step breakpoints from INFERIOR_PTID without
15521    removing them.  */
15522
15523 static void
15524 detach_single_step_breakpoints (void)
15525 {
15526   int i;
15527
15528   for (i = 0; i < 2; i++)
15529     if (single_step_breakpoints[i])
15530       target_remove_breakpoint (single_step_gdbarch[i],
15531                                 single_step_breakpoints[i]);
15532 }
15533
15534 /* Find the software single-step breakpoint that inserted at PC.
15535    Returns its slot if found, and -1 if not found.  */
15536
15537 static int
15538 find_single_step_breakpoint (struct address_space *aspace,
15539                              CORE_ADDR pc)
15540 {
15541   int i;
15542
15543   for (i = 0; i < 2; i++)
15544     {
15545       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15546       if (bp_tgt
15547           && breakpoint_address_match (bp_tgt->placed_address_space,
15548                                        bp_tgt->placed_address,
15549                                        aspace, pc))
15550         return i;
15551     }
15552
15553   return -1;
15554 }
15555
15556 /* Check whether a software single-step breakpoint is inserted at
15557    PC.  */
15558
15559 int
15560 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15561                                         CORE_ADDR pc)
15562 {
15563   return find_single_step_breakpoint (aspace, pc) >= 0;
15564 }
15565
15566 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15567    non-zero otherwise.  */
15568 static int
15569 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15570 {
15571   if (syscall_catchpoint_p (bp)
15572       && bp->enable_state != bp_disabled
15573       && bp->enable_state != bp_call_disabled)
15574     return 1;
15575   else
15576     return 0;
15577 }
15578
15579 int
15580 catch_syscall_enabled (void)
15581 {
15582   struct catch_syscall_inferior_data *inf_data
15583     = get_catch_syscall_inferior_data (current_inferior ());
15584
15585   return inf_data->total_syscalls_count != 0;
15586 }
15587
15588 int
15589 catching_syscall_number (int syscall_number)
15590 {
15591   struct breakpoint *bp;
15592
15593   ALL_BREAKPOINTS (bp)
15594     if (is_syscall_catchpoint_enabled (bp))
15595       {
15596         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15597
15598         if (c->syscalls_to_be_caught)
15599           {
15600             int i, iter;
15601             for (i = 0;
15602                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15603                  i++)
15604               if (syscall_number == iter)
15605                 return 1;
15606           }
15607         else
15608           return 1;
15609       }
15610
15611   return 0;
15612 }
15613
15614 /* Complete syscall names.  Used by "catch syscall".  */
15615 static VEC (char_ptr) *
15616 catch_syscall_completer (struct cmd_list_element *cmd,
15617                          const char *text, const char *word)
15618 {
15619   const char **list = get_syscall_names ();
15620   VEC (char_ptr) *retlist
15621     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15622
15623   xfree (list);
15624   return retlist;
15625 }
15626
15627 /* Tracepoint-specific operations.  */
15628
15629 /* Set tracepoint count to NUM.  */
15630 static void
15631 set_tracepoint_count (int num)
15632 {
15633   tracepoint_count = num;
15634   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15635 }
15636
15637 static void
15638 trace_command (char *arg, int from_tty)
15639 {
15640   struct breakpoint_ops *ops;
15641   const char *arg_cp = arg;
15642
15643   if (arg && probe_linespec_to_ops (&arg_cp))
15644     ops = &tracepoint_probe_breakpoint_ops;
15645   else
15646     ops = &tracepoint_breakpoint_ops;
15647
15648   create_breakpoint (get_current_arch (),
15649                      arg,
15650                      NULL, 0, NULL, 1 /* parse arg */,
15651                      0 /* tempflag */,
15652                      bp_tracepoint /* type_wanted */,
15653                      0 /* Ignore count */,
15654                      pending_break_support,
15655                      ops,
15656                      from_tty,
15657                      1 /* enabled */,
15658                      0 /* internal */, 0);
15659 }
15660
15661 static void
15662 ftrace_command (char *arg, int from_tty)
15663 {
15664   create_breakpoint (get_current_arch (),
15665                      arg,
15666                      NULL, 0, NULL, 1 /* parse arg */,
15667                      0 /* tempflag */,
15668                      bp_fast_tracepoint /* type_wanted */,
15669                      0 /* Ignore count */,
15670                      pending_break_support,
15671                      &tracepoint_breakpoint_ops,
15672                      from_tty,
15673                      1 /* enabled */,
15674                      0 /* internal */, 0);
15675 }
15676
15677 /* strace command implementation.  Creates a static tracepoint.  */
15678
15679 static void
15680 strace_command (char *arg, int from_tty)
15681 {
15682   struct breakpoint_ops *ops;
15683
15684   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15685      or with a normal static tracepoint.  */
15686   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15687     ops = &strace_marker_breakpoint_ops;
15688   else
15689     ops = &tracepoint_breakpoint_ops;
15690
15691   create_breakpoint (get_current_arch (),
15692                      arg,
15693                      NULL, 0, NULL, 1 /* parse arg */,
15694                      0 /* tempflag */,
15695                      bp_static_tracepoint /* type_wanted */,
15696                      0 /* Ignore count */,
15697                      pending_break_support,
15698                      ops,
15699                      from_tty,
15700                      1 /* enabled */,
15701                      0 /* internal */, 0);
15702 }
15703
15704 /* Set up a fake reader function that gets command lines from a linked
15705    list that was acquired during tracepoint uploading.  */
15706
15707 static struct uploaded_tp *this_utp;
15708 static int next_cmd;
15709
15710 static char *
15711 read_uploaded_action (void)
15712 {
15713   char *rslt;
15714
15715   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15716
15717   next_cmd++;
15718
15719   return rslt;
15720 }
15721
15722 /* Given information about a tracepoint as recorded on a target (which
15723    can be either a live system or a trace file), attempt to create an
15724    equivalent GDB tracepoint.  This is not a reliable process, since
15725    the target does not necessarily have all the information used when
15726    the tracepoint was originally defined.  */
15727   
15728 struct tracepoint *
15729 create_tracepoint_from_upload (struct uploaded_tp *utp)
15730 {
15731   char *addr_str, small_buf[100];
15732   struct tracepoint *tp;
15733
15734   if (utp->at_string)
15735     addr_str = utp->at_string;
15736   else
15737     {
15738       /* In the absence of a source location, fall back to raw
15739          address.  Since there is no way to confirm that the address
15740          means the same thing as when the trace was started, warn the
15741          user.  */
15742       warning (_("Uploaded tracepoint %d has no "
15743                  "source location, using raw address"),
15744                utp->number);
15745       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15746       addr_str = small_buf;
15747     }
15748
15749   /* There's not much we can do with a sequence of bytecodes.  */
15750   if (utp->cond && !utp->cond_string)
15751     warning (_("Uploaded tracepoint %d condition "
15752                "has no source form, ignoring it"),
15753              utp->number);
15754
15755   if (!create_breakpoint (get_current_arch (),
15756                           addr_str,
15757                           utp->cond_string, -1, NULL,
15758                           0 /* parse cond/thread */,
15759                           0 /* tempflag */,
15760                           utp->type /* type_wanted */,
15761                           0 /* Ignore count */,
15762                           pending_break_support,
15763                           &tracepoint_breakpoint_ops,
15764                           0 /* from_tty */,
15765                           utp->enabled /* enabled */,
15766                           0 /* internal */,
15767                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15768     return NULL;
15769
15770   /* Get the tracepoint we just created.  */
15771   tp = get_tracepoint (tracepoint_count);
15772   gdb_assert (tp != NULL);
15773
15774   if (utp->pass > 0)
15775     {
15776       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15777                  tp->base.number);
15778
15779       trace_pass_command (small_buf, 0);
15780     }
15781
15782   /* If we have uploaded versions of the original commands, set up a
15783      special-purpose "reader" function and call the usual command line
15784      reader, then pass the result to the breakpoint command-setting
15785      function.  */
15786   if (!VEC_empty (char_ptr, utp->cmd_strings))
15787     {
15788       struct command_line *cmd_list;
15789
15790       this_utp = utp;
15791       next_cmd = 0;
15792
15793       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15794
15795       breakpoint_set_commands (&tp->base, cmd_list);
15796     }
15797   else if (!VEC_empty (char_ptr, utp->actions)
15798            || !VEC_empty (char_ptr, utp->step_actions))
15799     warning (_("Uploaded tracepoint %d actions "
15800                "have no source form, ignoring them"),
15801              utp->number);
15802
15803   /* Copy any status information that might be available.  */
15804   tp->base.hit_count = utp->hit_count;
15805   tp->traceframe_usage = utp->traceframe_usage;
15806
15807   return tp;
15808 }
15809   
15810 /* Print information on tracepoint number TPNUM_EXP, or all if
15811    omitted.  */
15812
15813 static void
15814 tracepoints_info (char *args, int from_tty)
15815 {
15816   struct ui_out *uiout = current_uiout;
15817   int num_printed;
15818
15819   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15820
15821   if (num_printed == 0)
15822     {
15823       if (args == NULL || *args == '\0')
15824         ui_out_message (uiout, 0, "No tracepoints.\n");
15825       else
15826         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15827     }
15828
15829   default_collect_info ();
15830 }
15831
15832 /* The 'enable trace' command enables tracepoints.
15833    Not supported by all targets.  */
15834 static void
15835 enable_trace_command (char *args, int from_tty)
15836 {
15837   enable_command (args, from_tty);
15838 }
15839
15840 /* The 'disable trace' command disables tracepoints.
15841    Not supported by all targets.  */
15842 static void
15843 disable_trace_command (char *args, int from_tty)
15844 {
15845   disable_command (args, from_tty);
15846 }
15847
15848 /* Remove a tracepoint (or all if no argument).  */
15849 static void
15850 delete_trace_command (char *arg, int from_tty)
15851 {
15852   struct breakpoint *b, *b_tmp;
15853
15854   dont_repeat ();
15855
15856   if (arg == 0)
15857     {
15858       int breaks_to_delete = 0;
15859
15860       /* Delete all breakpoints if no argument.
15861          Do not delete internal or call-dummy breakpoints, these
15862          have to be deleted with an explicit breakpoint number 
15863          argument.  */
15864       ALL_TRACEPOINTS (b)
15865         if (is_tracepoint (b) && user_breakpoint_p (b))
15866           {
15867             breaks_to_delete = 1;
15868             break;
15869           }
15870
15871       /* Ask user only if there are some breakpoints to delete.  */
15872       if (!from_tty
15873           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15874         {
15875           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15876             if (is_tracepoint (b) && user_breakpoint_p (b))
15877               delete_breakpoint (b);
15878         }
15879     }
15880   else
15881     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15882 }
15883
15884 /* Helper function for trace_pass_command.  */
15885
15886 static void
15887 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15888 {
15889   tp->pass_count = count;
15890   observer_notify_breakpoint_modified (&tp->base);
15891   if (from_tty)
15892     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15893                      tp->base.number, count);
15894 }
15895
15896 /* Set passcount for tracepoint.
15897
15898    First command argument is passcount, second is tracepoint number.
15899    If tracepoint number omitted, apply to most recently defined.
15900    Also accepts special argument "all".  */
15901
15902 static void
15903 trace_pass_command (char *args, int from_tty)
15904 {
15905   struct tracepoint *t1;
15906   unsigned int count;
15907
15908   if (args == 0 || *args == 0)
15909     error (_("passcount command requires an "
15910              "argument (count + optional TP num)"));
15911
15912   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15913
15914   args = skip_spaces (args);
15915   if (*args && strncasecmp (args, "all", 3) == 0)
15916     {
15917       struct breakpoint *b;
15918
15919       args += 3;                        /* Skip special argument "all".  */
15920       if (*args)
15921         error (_("Junk at end of arguments."));
15922
15923       ALL_TRACEPOINTS (b)
15924       {
15925         t1 = (struct tracepoint *) b;
15926         trace_pass_set_count (t1, count, from_tty);
15927       }
15928     }
15929   else if (*args == '\0')
15930     {
15931       t1 = get_tracepoint_by_number (&args, NULL);
15932       if (t1)
15933         trace_pass_set_count (t1, count, from_tty);
15934     }
15935   else
15936     {
15937       struct get_number_or_range_state state;
15938
15939       init_number_or_range (&state, args);
15940       while (!state.finished)
15941         {
15942           t1 = get_tracepoint_by_number (&args, &state);
15943           if (t1)
15944             trace_pass_set_count (t1, count, from_tty);
15945         }
15946     }
15947 }
15948
15949 struct tracepoint *
15950 get_tracepoint (int num)
15951 {
15952   struct breakpoint *t;
15953
15954   ALL_TRACEPOINTS (t)
15955     if (t->number == num)
15956       return (struct tracepoint *) t;
15957
15958   return NULL;
15959 }
15960
15961 /* Find the tracepoint with the given target-side number (which may be
15962    different from the tracepoint number after disconnecting and
15963    reconnecting).  */
15964
15965 struct tracepoint *
15966 get_tracepoint_by_number_on_target (int num)
15967 {
15968   struct breakpoint *b;
15969
15970   ALL_TRACEPOINTS (b)
15971     {
15972       struct tracepoint *t = (struct tracepoint *) b;
15973
15974       if (t->number_on_target == num)
15975         return t;
15976     }
15977
15978   return NULL;
15979 }
15980
15981 /* Utility: parse a tracepoint number and look it up in the list.
15982    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15983    If the argument is missing, the most recent tracepoint
15984    (tracepoint_count) is returned.  */
15985
15986 struct tracepoint *
15987 get_tracepoint_by_number (char **arg,
15988                           struct get_number_or_range_state *state)
15989 {
15990   struct breakpoint *t;
15991   int tpnum;
15992   char *instring = arg == NULL ? NULL : *arg;
15993
15994   if (state)
15995     {
15996       gdb_assert (!state->finished);
15997       tpnum = get_number_or_range (state);
15998     }
15999   else if (arg == NULL || *arg == NULL || ! **arg)
16000     tpnum = tracepoint_count;
16001   else
16002     tpnum = get_number (arg);
16003
16004   if (tpnum <= 0)
16005     {
16006       if (instring && *instring)
16007         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
16008                          instring);
16009       else
16010         printf_filtered (_("No previous tracepoint\n"));
16011       return NULL;
16012     }
16013
16014   ALL_TRACEPOINTS (t)
16015     if (t->number == tpnum)
16016     {
16017       return (struct tracepoint *) t;
16018     }
16019
16020   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
16021   return NULL;
16022 }
16023
16024 void
16025 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
16026 {
16027   if (b->thread != -1)
16028     fprintf_unfiltered (fp, " thread %d", b->thread);
16029
16030   if (b->task != 0)
16031     fprintf_unfiltered (fp, " task %d", b->task);
16032
16033   fprintf_unfiltered (fp, "\n");
16034 }
16035
16036 /* Save information on user settable breakpoints (watchpoints, etc) to
16037    a new script file named FILENAME.  If FILTER is non-NULL, call it
16038    on each breakpoint and only include the ones for which it returns
16039    non-zero.  */
16040
16041 static void
16042 save_breakpoints (char *filename, int from_tty,
16043                   int (*filter) (const struct breakpoint *))
16044 {
16045   struct breakpoint *tp;
16046   int any = 0;
16047   struct cleanup *cleanup;
16048   struct ui_file *fp;
16049   int extra_trace_bits = 0;
16050
16051   if (filename == 0 || *filename == 0)
16052     error (_("Argument required (file name in which to save)"));
16053
16054   /* See if we have anything to save.  */
16055   ALL_BREAKPOINTS (tp)
16056   {
16057     /* Skip internal and momentary breakpoints.  */
16058     if (!user_breakpoint_p (tp))
16059       continue;
16060
16061     /* If we have a filter, only save the breakpoints it accepts.  */
16062     if (filter && !filter (tp))
16063       continue;
16064
16065     any = 1;
16066
16067     if (is_tracepoint (tp))
16068       {
16069         extra_trace_bits = 1;
16070
16071         /* We can stop searching.  */
16072         break;
16073       }
16074   }
16075
16076   if (!any)
16077     {
16078       warning (_("Nothing to save."));
16079       return;
16080     }
16081
16082   filename = tilde_expand (filename);
16083   cleanup = make_cleanup (xfree, filename);
16084   fp = gdb_fopen (filename, "w");
16085   if (!fp)
16086     error (_("Unable to open file '%s' for saving (%s)"),
16087            filename, safe_strerror (errno));
16088   make_cleanup_ui_file_delete (fp);
16089
16090   if (extra_trace_bits)
16091     save_trace_state_variables (fp);
16092
16093   ALL_BREAKPOINTS (tp)
16094   {
16095     /* Skip internal and momentary breakpoints.  */
16096     if (!user_breakpoint_p (tp))
16097       continue;
16098
16099     /* If we have a filter, only save the breakpoints it accepts.  */
16100     if (filter && !filter (tp))
16101       continue;
16102
16103     tp->ops->print_recreate (tp, fp);
16104
16105     /* Note, we can't rely on tp->number for anything, as we can't
16106        assume the recreated breakpoint numbers will match.  Use $bpnum
16107        instead.  */
16108
16109     if (tp->cond_string)
16110       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
16111
16112     if (tp->ignore_count)
16113       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
16114
16115     if (tp->type != bp_dprintf && tp->commands)
16116       {
16117         volatile struct gdb_exception ex;       
16118
16119         fprintf_unfiltered (fp, "  commands\n");
16120         
16121         ui_out_redirect (current_uiout, fp);
16122         TRY_CATCH (ex, RETURN_MASK_ALL)
16123           {
16124             print_command_lines (current_uiout, tp->commands->commands, 2);
16125           }
16126         ui_out_redirect (current_uiout, NULL);
16127
16128         if (ex.reason < 0)
16129           throw_exception (ex);
16130
16131         fprintf_unfiltered (fp, "  end\n");
16132       }
16133
16134     if (tp->enable_state == bp_disabled)
16135       fprintf_unfiltered (fp, "disable\n");
16136
16137     /* If this is a multi-location breakpoint, check if the locations
16138        should be individually disabled.  Watchpoint locations are
16139        special, and not user visible.  */
16140     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
16141       {
16142         struct bp_location *loc;
16143         int n = 1;
16144
16145         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
16146           if (!loc->enabled)
16147             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
16148       }
16149   }
16150
16151   if (extra_trace_bits && *default_collect)
16152     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
16153
16154   if (from_tty)
16155     printf_filtered (_("Saved to file '%s'.\n"), filename);
16156   do_cleanups (cleanup);
16157 }
16158
16159 /* The `save breakpoints' command.  */
16160
16161 static void
16162 save_breakpoints_command (char *args, int from_tty)
16163 {
16164   save_breakpoints (args, from_tty, NULL);
16165 }
16166
16167 /* The `save tracepoints' command.  */
16168
16169 static void
16170 save_tracepoints_command (char *args, int from_tty)
16171 {
16172   save_breakpoints (args, from_tty, is_tracepoint);
16173 }
16174
16175 /* Create a vector of all tracepoints.  */
16176
16177 VEC(breakpoint_p) *
16178 all_tracepoints (void)
16179 {
16180   VEC(breakpoint_p) *tp_vec = 0;
16181   struct breakpoint *tp;
16182
16183   ALL_TRACEPOINTS (tp)
16184   {
16185     VEC_safe_push (breakpoint_p, tp_vec, tp);
16186   }
16187
16188   return tp_vec;
16189 }
16190
16191 \f
16192 /* This help string is used for the break, hbreak, tbreak and thbreak
16193    commands.  It is defined as a macro to prevent duplication.
16194    COMMAND should be a string constant containing the name of the
16195    command.  */
16196 #define BREAK_ARGS_HELP(command) \
16197 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
16198 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
16199 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
16200 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
16201 LOCATION may be a line number, function name, or \"*\" and an address.\n\
16202 If a line number is specified, break at start of code for that line.\n\
16203 If a function is specified, break at start of code for that function.\n\
16204 If an address is specified, break at that exact address.\n\
16205 With no LOCATION, uses current execution address of the selected\n\
16206 stack frame.  This is useful for breaking on return to a stack frame.\n\
16207 \n\
16208 THREADNUM is the number from \"info threads\".\n\
16209 CONDITION is a boolean expression.\n\
16210 \n\
16211 Multiple breakpoints at one place are permitted, and useful if their\n\
16212 conditions are different.\n\
16213 \n\
16214 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
16215
16216 /* List of subcommands for "catch".  */
16217 static struct cmd_list_element *catch_cmdlist;
16218
16219 /* List of subcommands for "tcatch".  */
16220 static struct cmd_list_element *tcatch_cmdlist;
16221
16222 void
16223 add_catch_command (char *name, char *docstring,
16224                    cmd_sfunc_ftype *sfunc,
16225                    completer_ftype *completer,
16226                    void *user_data_catch,
16227                    void *user_data_tcatch)
16228 {
16229   struct cmd_list_element *command;
16230
16231   command = add_cmd (name, class_breakpoint, NULL, docstring,
16232                      &catch_cmdlist);
16233   set_cmd_sfunc (command, sfunc);
16234   set_cmd_context (command, user_data_catch);
16235   set_cmd_completer (command, completer);
16236
16237   command = add_cmd (name, class_breakpoint, NULL, docstring,
16238                      &tcatch_cmdlist);
16239   set_cmd_sfunc (command, sfunc);
16240   set_cmd_context (command, user_data_tcatch);
16241   set_cmd_completer (command, completer);
16242 }
16243
16244 static void
16245 clear_syscall_counts (struct inferior *inf)
16246 {
16247   struct catch_syscall_inferior_data *inf_data
16248     = get_catch_syscall_inferior_data (inf);
16249
16250   inf_data->total_syscalls_count = 0;
16251   inf_data->any_syscall_count = 0;
16252   VEC_free (int, inf_data->syscalls_counts);
16253 }
16254
16255 static void
16256 save_command (char *arg, int from_tty)
16257 {
16258   printf_unfiltered (_("\"save\" must be followed by "
16259                        "the name of a save subcommand.\n"));
16260   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16261 }
16262
16263 struct breakpoint *
16264 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16265                           void *data)
16266 {
16267   struct breakpoint *b, *b_tmp;
16268
16269   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16270     {
16271       if ((*callback) (b, data))
16272         return b;
16273     }
16274
16275   return NULL;
16276 }
16277
16278 /* Zero if any of the breakpoint's locations could be a location where
16279    functions have been inlined, nonzero otherwise.  */
16280
16281 static int
16282 is_non_inline_function (struct breakpoint *b)
16283 {
16284   /* The shared library event breakpoint is set on the address of a
16285      non-inline function.  */
16286   if (b->type == bp_shlib_event)
16287     return 1;
16288
16289   return 0;
16290 }
16291
16292 /* Nonzero if the specified PC cannot be a location where functions
16293    have been inlined.  */
16294
16295 int
16296 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16297                            const struct target_waitstatus *ws)
16298 {
16299   struct breakpoint *b;
16300   struct bp_location *bl;
16301
16302   ALL_BREAKPOINTS (b)
16303     {
16304       if (!is_non_inline_function (b))
16305         continue;
16306
16307       for (bl = b->loc; bl != NULL; bl = bl->next)
16308         {
16309           if (!bl->shlib_disabled
16310               && bpstat_check_location (bl, aspace, pc, ws))
16311             return 1;
16312         }
16313     }
16314
16315   return 0;
16316 }
16317
16318 /* Remove any references to OBJFILE which is going to be freed.  */
16319
16320 void
16321 breakpoint_free_objfile (struct objfile *objfile)
16322 {
16323   struct bp_location **locp, *loc;
16324
16325   ALL_BP_LOCATIONS (loc, locp)
16326     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16327       loc->symtab = NULL;
16328 }
16329
16330 void
16331 initialize_breakpoint_ops (void)
16332 {
16333   static int initialized = 0;
16334
16335   struct breakpoint_ops *ops;
16336
16337   if (initialized)
16338     return;
16339   initialized = 1;
16340
16341   /* The breakpoint_ops structure to be inherit by all kinds of
16342      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16343      internal and momentary breakpoints, etc.).  */
16344   ops = &bkpt_base_breakpoint_ops;
16345   *ops = base_breakpoint_ops;
16346   ops->re_set = bkpt_re_set;
16347   ops->insert_location = bkpt_insert_location;
16348   ops->remove_location = bkpt_remove_location;
16349   ops->breakpoint_hit = bkpt_breakpoint_hit;
16350   ops->create_sals_from_address = bkpt_create_sals_from_address;
16351   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16352   ops->decode_linespec = bkpt_decode_linespec;
16353
16354   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16355   ops = &bkpt_breakpoint_ops;
16356   *ops = bkpt_base_breakpoint_ops;
16357   ops->re_set = bkpt_re_set;
16358   ops->resources_needed = bkpt_resources_needed;
16359   ops->print_it = bkpt_print_it;
16360   ops->print_mention = bkpt_print_mention;
16361   ops->print_recreate = bkpt_print_recreate;
16362
16363   /* Ranged breakpoints.  */
16364   ops = &ranged_breakpoint_ops;
16365   *ops = bkpt_breakpoint_ops;
16366   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16367   ops->resources_needed = resources_needed_ranged_breakpoint;
16368   ops->print_it = print_it_ranged_breakpoint;
16369   ops->print_one = print_one_ranged_breakpoint;
16370   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16371   ops->print_mention = print_mention_ranged_breakpoint;
16372   ops->print_recreate = print_recreate_ranged_breakpoint;
16373
16374   /* Internal breakpoints.  */
16375   ops = &internal_breakpoint_ops;
16376   *ops = bkpt_base_breakpoint_ops;
16377   ops->re_set = internal_bkpt_re_set;
16378   ops->check_status = internal_bkpt_check_status;
16379   ops->print_it = internal_bkpt_print_it;
16380   ops->print_mention = internal_bkpt_print_mention;
16381
16382   /* Momentary breakpoints.  */
16383   ops = &momentary_breakpoint_ops;
16384   *ops = bkpt_base_breakpoint_ops;
16385   ops->re_set = momentary_bkpt_re_set;
16386   ops->check_status = momentary_bkpt_check_status;
16387   ops->print_it = momentary_bkpt_print_it;
16388   ops->print_mention = momentary_bkpt_print_mention;
16389
16390   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16391   ops = &longjmp_breakpoint_ops;
16392   *ops = momentary_breakpoint_ops;
16393   ops->dtor = longjmp_bkpt_dtor;
16394
16395   /* Probe breakpoints.  */
16396   ops = &bkpt_probe_breakpoint_ops;
16397   *ops = bkpt_breakpoint_ops;
16398   ops->insert_location = bkpt_probe_insert_location;
16399   ops->remove_location = bkpt_probe_remove_location;
16400   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16401   ops->decode_linespec = bkpt_probe_decode_linespec;
16402
16403   /* Watchpoints.  */
16404   ops = &watchpoint_breakpoint_ops;
16405   *ops = base_breakpoint_ops;
16406   ops->dtor = dtor_watchpoint;
16407   ops->re_set = re_set_watchpoint;
16408   ops->insert_location = insert_watchpoint;
16409   ops->remove_location = remove_watchpoint;
16410   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16411   ops->check_status = check_status_watchpoint;
16412   ops->resources_needed = resources_needed_watchpoint;
16413   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16414   ops->print_it = print_it_watchpoint;
16415   ops->print_mention = print_mention_watchpoint;
16416   ops->print_recreate = print_recreate_watchpoint;
16417   ops->explains_signal = explains_signal_watchpoint;
16418
16419   /* Masked watchpoints.  */
16420   ops = &masked_watchpoint_breakpoint_ops;
16421   *ops = watchpoint_breakpoint_ops;
16422   ops->insert_location = insert_masked_watchpoint;
16423   ops->remove_location = remove_masked_watchpoint;
16424   ops->resources_needed = resources_needed_masked_watchpoint;
16425   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16426   ops->print_it = print_it_masked_watchpoint;
16427   ops->print_one_detail = print_one_detail_masked_watchpoint;
16428   ops->print_mention = print_mention_masked_watchpoint;
16429   ops->print_recreate = print_recreate_masked_watchpoint;
16430
16431   /* Tracepoints.  */
16432   ops = &tracepoint_breakpoint_ops;
16433   *ops = base_breakpoint_ops;
16434   ops->re_set = tracepoint_re_set;
16435   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16436   ops->print_one_detail = tracepoint_print_one_detail;
16437   ops->print_mention = tracepoint_print_mention;
16438   ops->print_recreate = tracepoint_print_recreate;
16439   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16440   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16441   ops->decode_linespec = tracepoint_decode_linespec;
16442
16443   /* Probe tracepoints.  */
16444   ops = &tracepoint_probe_breakpoint_ops;
16445   *ops = tracepoint_breakpoint_ops;
16446   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16447   ops->decode_linespec = tracepoint_probe_decode_linespec;
16448
16449   /* Static tracepoints with marker (`-m').  */
16450   ops = &strace_marker_breakpoint_ops;
16451   *ops = tracepoint_breakpoint_ops;
16452   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16453   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16454   ops->decode_linespec = strace_marker_decode_linespec;
16455
16456   /* Fork catchpoints.  */
16457   ops = &catch_fork_breakpoint_ops;
16458   *ops = base_breakpoint_ops;
16459   ops->insert_location = insert_catch_fork;
16460   ops->remove_location = remove_catch_fork;
16461   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16462   ops->print_it = print_it_catch_fork;
16463   ops->print_one = print_one_catch_fork;
16464   ops->print_mention = print_mention_catch_fork;
16465   ops->print_recreate = print_recreate_catch_fork;
16466
16467   /* Vfork catchpoints.  */
16468   ops = &catch_vfork_breakpoint_ops;
16469   *ops = base_breakpoint_ops;
16470   ops->insert_location = insert_catch_vfork;
16471   ops->remove_location = remove_catch_vfork;
16472   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16473   ops->print_it = print_it_catch_vfork;
16474   ops->print_one = print_one_catch_vfork;
16475   ops->print_mention = print_mention_catch_vfork;
16476   ops->print_recreate = print_recreate_catch_vfork;
16477
16478   /* Exec catchpoints.  */
16479   ops = &catch_exec_breakpoint_ops;
16480   *ops = base_breakpoint_ops;
16481   ops->dtor = dtor_catch_exec;
16482   ops->insert_location = insert_catch_exec;
16483   ops->remove_location = remove_catch_exec;
16484   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16485   ops->print_it = print_it_catch_exec;
16486   ops->print_one = print_one_catch_exec;
16487   ops->print_mention = print_mention_catch_exec;
16488   ops->print_recreate = print_recreate_catch_exec;
16489
16490   /* Syscall catchpoints.  */
16491   ops = &catch_syscall_breakpoint_ops;
16492   *ops = base_breakpoint_ops;
16493   ops->dtor = dtor_catch_syscall;
16494   ops->insert_location = insert_catch_syscall;
16495   ops->remove_location = remove_catch_syscall;
16496   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16497   ops->print_it = print_it_catch_syscall;
16498   ops->print_one = print_one_catch_syscall;
16499   ops->print_mention = print_mention_catch_syscall;
16500   ops->print_recreate = print_recreate_catch_syscall;
16501
16502   /* Solib-related catchpoints.  */
16503   ops = &catch_solib_breakpoint_ops;
16504   *ops = base_breakpoint_ops;
16505   ops->dtor = dtor_catch_solib;
16506   ops->insert_location = insert_catch_solib;
16507   ops->remove_location = remove_catch_solib;
16508   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16509   ops->check_status = check_status_catch_solib;
16510   ops->print_it = print_it_catch_solib;
16511   ops->print_one = print_one_catch_solib;
16512   ops->print_mention = print_mention_catch_solib;
16513   ops->print_recreate = print_recreate_catch_solib;
16514
16515   ops = &dprintf_breakpoint_ops;
16516   *ops = bkpt_base_breakpoint_ops;
16517   ops->re_set = dprintf_re_set;
16518   ops->resources_needed = bkpt_resources_needed;
16519   ops->print_it = bkpt_print_it;
16520   ops->print_mention = bkpt_print_mention;
16521   ops->print_recreate = dprintf_print_recreate;
16522   ops->after_condition_true = dprintf_after_condition_true;
16523   ops->breakpoint_hit = dprintf_breakpoint_hit;
16524 }
16525
16526 /* Chain containing all defined "enable breakpoint" subcommands.  */
16527
16528 static struct cmd_list_element *enablebreaklist = NULL;
16529
16530 void
16531 _initialize_breakpoint (void)
16532 {
16533   struct cmd_list_element *c;
16534
16535   initialize_breakpoint_ops ();
16536
16537   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16538   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16539   observer_attach_inferior_exit (clear_syscall_counts);
16540   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16541
16542   breakpoint_objfile_key
16543     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16544
16545   catch_syscall_inferior_data
16546     = register_inferior_data_with_cleanup (NULL,
16547                                            catch_syscall_inferior_data_cleanup);
16548
16549   breakpoint_chain = 0;
16550   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16551      before a breakpoint is set.  */
16552   breakpoint_count = 0;
16553
16554   tracepoint_count = 0;
16555
16556   add_com ("ignore", class_breakpoint, ignore_command, _("\
16557 Set ignore-count of breakpoint number N to COUNT.\n\
16558 Usage is `ignore N COUNT'."));
16559   if (xdb_commands)
16560     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16561
16562   add_com ("commands", class_breakpoint, commands_command, _("\
16563 Set commands to be executed when a breakpoint is hit.\n\
16564 Give breakpoint number as argument after \"commands\".\n\
16565 With no argument, the targeted breakpoint is the last one set.\n\
16566 The commands themselves follow starting on the next line.\n\
16567 Type a line containing \"end\" to indicate the end of them.\n\
16568 Give \"silent\" as the first line to make the breakpoint silent;\n\
16569 then no output is printed when it is hit, except what the commands print."));
16570
16571   c = add_com ("condition", class_breakpoint, condition_command, _("\
16572 Specify breakpoint number N to break only if COND is true.\n\
16573 Usage is `condition N COND', where N is an integer and COND is an\n\
16574 expression to be evaluated whenever breakpoint N is reached."));
16575   set_cmd_completer (c, condition_completer);
16576
16577   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16578 Set a temporary breakpoint.\n\
16579 Like \"break\" except the breakpoint is only temporary,\n\
16580 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16581 by using \"enable delete\" on the breakpoint number.\n\
16582 \n"
16583 BREAK_ARGS_HELP ("tbreak")));
16584   set_cmd_completer (c, location_completer);
16585
16586   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16587 Set a hardware assisted breakpoint.\n\
16588 Like \"break\" except the breakpoint requires hardware support,\n\
16589 some target hardware may not have this support.\n\
16590 \n"
16591 BREAK_ARGS_HELP ("hbreak")));
16592   set_cmd_completer (c, location_completer);
16593
16594   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16595 Set a temporary hardware assisted breakpoint.\n\
16596 Like \"hbreak\" except the breakpoint is only temporary,\n\
16597 so it will be deleted when hit.\n\
16598 \n"
16599 BREAK_ARGS_HELP ("thbreak")));
16600   set_cmd_completer (c, location_completer);
16601
16602   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16603 Enable some breakpoints.\n\
16604 Give breakpoint numbers (separated by spaces) as arguments.\n\
16605 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16606 This is used to cancel the effect of the \"disable\" command.\n\
16607 With a subcommand you can enable temporarily."),
16608                   &enablelist, "enable ", 1, &cmdlist);
16609   if (xdb_commands)
16610     add_com ("ab", class_breakpoint, enable_command, _("\
16611 Enable some breakpoints.\n\
16612 Give breakpoint numbers (separated by spaces) as arguments.\n\
16613 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16614 This is used to cancel the effect of the \"disable\" command.\n\
16615 With a subcommand you can enable temporarily."));
16616
16617   add_com_alias ("en", "enable", class_breakpoint, 1);
16618
16619   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16620 Enable some breakpoints.\n\
16621 Give breakpoint numbers (separated by spaces) as arguments.\n\
16622 This is used to cancel the effect of the \"disable\" command.\n\
16623 May be abbreviated to simply \"enable\".\n"),
16624                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16625
16626   add_cmd ("once", no_class, enable_once_command, _("\
16627 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16628 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16629            &enablebreaklist);
16630
16631   add_cmd ("delete", no_class, enable_delete_command, _("\
16632 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16633 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16634            &enablebreaklist);
16635
16636   add_cmd ("count", no_class, enable_count_command, _("\
16637 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16638 If a breakpoint is hit while enabled in this fashion,\n\
16639 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16640            &enablebreaklist);
16641
16642   add_cmd ("delete", no_class, enable_delete_command, _("\
16643 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16644 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16645            &enablelist);
16646
16647   add_cmd ("once", no_class, enable_once_command, _("\
16648 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16649 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16650            &enablelist);
16651
16652   add_cmd ("count", no_class, enable_count_command, _("\
16653 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16654 If a breakpoint is hit while enabled in this fashion,\n\
16655 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16656            &enablelist);
16657
16658   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16659 Disable some breakpoints.\n\
16660 Arguments are breakpoint numbers with spaces in between.\n\
16661 To disable all breakpoints, give no argument.\n\
16662 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16663                   &disablelist, "disable ", 1, &cmdlist);
16664   add_com_alias ("dis", "disable", class_breakpoint, 1);
16665   add_com_alias ("disa", "disable", class_breakpoint, 1);
16666   if (xdb_commands)
16667     add_com ("sb", class_breakpoint, disable_command, _("\
16668 Disable some breakpoints.\n\
16669 Arguments are breakpoint numbers with spaces in between.\n\
16670 To disable all breakpoints, give no argument.\n\
16671 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
16672
16673   add_cmd ("breakpoints", class_alias, disable_command, _("\
16674 Disable some breakpoints.\n\
16675 Arguments are breakpoint numbers with spaces in between.\n\
16676 To disable all breakpoints, give no argument.\n\
16677 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16678 This command may be abbreviated \"disable\"."),
16679            &disablelist);
16680
16681   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16682 Delete some breakpoints or auto-display expressions.\n\
16683 Arguments are breakpoint numbers with spaces in between.\n\
16684 To delete all breakpoints, give no argument.\n\
16685 \n\
16686 Also a prefix command for deletion of other GDB objects.\n\
16687 The \"unset\" command is also an alias for \"delete\"."),
16688                   &deletelist, "delete ", 1, &cmdlist);
16689   add_com_alias ("d", "delete", class_breakpoint, 1);
16690   add_com_alias ("del", "delete", class_breakpoint, 1);
16691   if (xdb_commands)
16692     add_com ("db", class_breakpoint, delete_command, _("\
16693 Delete some breakpoints.\n\
16694 Arguments are breakpoint numbers with spaces in between.\n\
16695 To delete all breakpoints, give no argument.\n"));
16696
16697   add_cmd ("breakpoints", class_alias, delete_command, _("\
16698 Delete some breakpoints or auto-display expressions.\n\
16699 Arguments are breakpoint numbers with spaces in between.\n\
16700 To delete all breakpoints, give no argument.\n\
16701 This command may be abbreviated \"delete\"."),
16702            &deletelist);
16703
16704   add_com ("clear", class_breakpoint, clear_command, _("\
16705 Clear breakpoint at specified line or function.\n\
16706 Argument may be line number, function name, or \"*\" and an address.\n\
16707 If line number is specified, all breakpoints in that line are cleared.\n\
16708 If function is specified, breakpoints at beginning of function are cleared.\n\
16709 If an address is specified, breakpoints at that address are cleared.\n\
16710 \n\
16711 With no argument, clears all breakpoints in the line that the selected frame\n\
16712 is executing in.\n\
16713 \n\
16714 See also the \"delete\" command which clears breakpoints by number."));
16715   add_com_alias ("cl", "clear", class_breakpoint, 1);
16716
16717   c = add_com ("break", class_breakpoint, break_command, _("\
16718 Set breakpoint at specified line or function.\n"
16719 BREAK_ARGS_HELP ("break")));
16720   set_cmd_completer (c, location_completer);
16721
16722   add_com_alias ("b", "break", class_run, 1);
16723   add_com_alias ("br", "break", class_run, 1);
16724   add_com_alias ("bre", "break", class_run, 1);
16725   add_com_alias ("brea", "break", class_run, 1);
16726
16727   if (xdb_commands)
16728    add_com_alias ("ba", "break", class_breakpoint, 1);
16729
16730   if (dbx_commands)
16731     {
16732       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16733 Break in function/address or break at a line in the current file."),
16734                              &stoplist, "stop ", 1, &cmdlist);
16735       add_cmd ("in", class_breakpoint, stopin_command,
16736                _("Break in function or address."), &stoplist);
16737       add_cmd ("at", class_breakpoint, stopat_command,
16738                _("Break at a line in the current file."), &stoplist);
16739       add_com ("status", class_info, breakpoints_info, _("\
16740 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16741 The \"Type\" column indicates one of:\n\
16742 \tbreakpoint     - normal breakpoint\n\
16743 \twatchpoint     - watchpoint\n\
16744 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16745 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16746 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16747 address and file/line number respectively.\n\
16748 \n\
16749 Convenience variable \"$_\" and default examine address for \"x\"\n\
16750 are set to the address of the last breakpoint listed unless the command\n\
16751 is prefixed with \"server \".\n\n\
16752 Convenience variable \"$bpnum\" contains the number of the last\n\
16753 breakpoint set."));
16754     }
16755
16756   add_info ("breakpoints", breakpoints_info, _("\
16757 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16758 The \"Type\" column indicates one of:\n\
16759 \tbreakpoint     - normal breakpoint\n\
16760 \twatchpoint     - watchpoint\n\
16761 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16762 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16763 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16764 address and file/line number respectively.\n\
16765 \n\
16766 Convenience variable \"$_\" and default examine address for \"x\"\n\
16767 are set to the address of the last breakpoint listed unless the command\n\
16768 is prefixed with \"server \".\n\n\
16769 Convenience variable \"$bpnum\" contains the number of the last\n\
16770 breakpoint set."));
16771
16772   add_info_alias ("b", "breakpoints", 1);
16773
16774   if (xdb_commands)
16775     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16776 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16777 The \"Type\" column indicates one of:\n\
16778 \tbreakpoint     - normal breakpoint\n\
16779 \twatchpoint     - watchpoint\n\
16780 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16781 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16782 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16783 address and file/line number respectively.\n\
16784 \n\
16785 Convenience variable \"$_\" and default examine address for \"x\"\n\
16786 are set to the address of the last breakpoint listed unless the command\n\
16787 is prefixed with \"server \".\n\n\
16788 Convenience variable \"$bpnum\" contains the number of the last\n\
16789 breakpoint set."));
16790
16791   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16792 Status of all breakpoints, or breakpoint number NUMBER.\n\
16793 The \"Type\" column indicates one of:\n\
16794 \tbreakpoint     - normal breakpoint\n\
16795 \twatchpoint     - watchpoint\n\
16796 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16797 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16798 \tuntil          - internal breakpoint used by the \"until\" command\n\
16799 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16800 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16801 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16802 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16803 address and file/line number respectively.\n\
16804 \n\
16805 Convenience variable \"$_\" and default examine address for \"x\"\n\
16806 are set to the address of the last breakpoint listed unless the command\n\
16807 is prefixed with \"server \".\n\n\
16808 Convenience variable \"$bpnum\" contains the number of the last\n\
16809 breakpoint set."),
16810            &maintenanceinfolist);
16811
16812   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16813 Set catchpoints to catch events."),
16814                   &catch_cmdlist, "catch ",
16815                   0/*allow-unknown*/, &cmdlist);
16816
16817   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16818 Set temporary catchpoints to catch events."),
16819                   &tcatch_cmdlist, "tcatch ",
16820                   0/*allow-unknown*/, &cmdlist);
16821
16822   add_catch_command ("fork", _("Catch calls to fork."),
16823                      catch_fork_command_1,
16824                      NULL,
16825                      (void *) (uintptr_t) catch_fork_permanent,
16826                      (void *) (uintptr_t) catch_fork_temporary);
16827   add_catch_command ("vfork", _("Catch calls to vfork."),
16828                      catch_fork_command_1,
16829                      NULL,
16830                      (void *) (uintptr_t) catch_vfork_permanent,
16831                      (void *) (uintptr_t) catch_vfork_temporary);
16832   add_catch_command ("exec", _("Catch calls to exec."),
16833                      catch_exec_command_1,
16834                      NULL,
16835                      CATCH_PERMANENT,
16836                      CATCH_TEMPORARY);
16837   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16838 Usage: catch load [REGEX]\n\
16839 If REGEX is given, only stop for libraries matching the regular expression."),
16840                      catch_load_command_1,
16841                      NULL,
16842                      CATCH_PERMANENT,
16843                      CATCH_TEMPORARY);
16844   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16845 Usage: catch unload [REGEX]\n\
16846 If REGEX is given, only stop for libraries matching the regular expression."),
16847                      catch_unload_command_1,
16848                      NULL,
16849                      CATCH_PERMANENT,
16850                      CATCH_TEMPORARY);
16851   add_catch_command ("syscall", _("\
16852 Catch system calls by their names and/or numbers.\n\
16853 Arguments say which system calls to catch.  If no arguments\n\
16854 are given, every system call will be caught.\n\
16855 Arguments, if given, should be one or more system call names\n\
16856 (if your system supports that), or system call numbers."),
16857                      catch_syscall_command_1,
16858                      catch_syscall_completer,
16859                      CATCH_PERMANENT,
16860                      CATCH_TEMPORARY);
16861
16862   c = add_com ("watch", class_breakpoint, watch_command, _("\
16863 Set a watchpoint for an expression.\n\
16864 Usage: watch [-l|-location] EXPRESSION\n\
16865 A watchpoint stops execution of your program whenever the value of\n\
16866 an expression changes.\n\
16867 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16868 the memory to which it refers."));
16869   set_cmd_completer (c, expression_completer);
16870
16871   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16872 Set a read watchpoint for an expression.\n\
16873 Usage: rwatch [-l|-location] EXPRESSION\n\
16874 A watchpoint stops execution of your program whenever the value of\n\
16875 an expression is read.\n\
16876 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16877 the memory to which it refers."));
16878   set_cmd_completer (c, expression_completer);
16879
16880   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
16881 Set a watchpoint for an expression.\n\
16882 Usage: awatch [-l|-location] EXPRESSION\n\
16883 A watchpoint stops execution of your program whenever the value of\n\
16884 an expression is either read or written.\n\
16885 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16886 the memory to which it refers."));
16887   set_cmd_completer (c, expression_completer);
16888
16889   add_info ("watchpoints", watchpoints_info, _("\
16890 Status of specified watchpoints (all watchpoints if no argument)."));
16891
16892   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16893      respond to changes - contrary to the description.  */
16894   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16895                             &can_use_hw_watchpoints, _("\
16896 Set debugger's willingness to use watchpoint hardware."), _("\
16897 Show debugger's willingness to use watchpoint hardware."), _("\
16898 If zero, gdb will not use hardware for new watchpoints, even if\n\
16899 such is available.  (However, any hardware watchpoints that were\n\
16900 created before setting this to nonzero, will continue to use watchpoint\n\
16901 hardware.)"),
16902                             NULL,
16903                             show_can_use_hw_watchpoints,
16904                             &setlist, &showlist);
16905
16906   can_use_hw_watchpoints = 1;
16907
16908   /* Tracepoint manipulation commands.  */
16909
16910   c = add_com ("trace", class_breakpoint, trace_command, _("\
16911 Set a tracepoint at specified line or function.\n\
16912 \n"
16913 BREAK_ARGS_HELP ("trace") "\n\
16914 Do \"help tracepoints\" for info on other tracepoint commands."));
16915   set_cmd_completer (c, location_completer);
16916
16917   add_com_alias ("tp", "trace", class_alias, 0);
16918   add_com_alias ("tr", "trace", class_alias, 1);
16919   add_com_alias ("tra", "trace", class_alias, 1);
16920   add_com_alias ("trac", "trace", class_alias, 1);
16921
16922   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16923 Set a fast tracepoint at specified line or function.\n\
16924 \n"
16925 BREAK_ARGS_HELP ("ftrace") "\n\
16926 Do \"help tracepoints\" for info on other tracepoint commands."));
16927   set_cmd_completer (c, location_completer);
16928
16929   c = add_com ("strace", class_breakpoint, strace_command, _("\
16930 Set a static tracepoint at specified line, function or marker.\n\
16931 \n\
16932 strace [LOCATION] [if CONDITION]\n\
16933 LOCATION may be a line number, function name, \"*\" and an address,\n\
16934 or -m MARKER_ID.\n\
16935 If a line number is specified, probe the marker at start of code\n\
16936 for that line.  If a function is specified, probe the marker at start\n\
16937 of code for that function.  If an address is specified, probe the marker\n\
16938 at that exact address.  If a marker id is specified, probe the marker\n\
16939 with that name.  With no LOCATION, uses current execution address of\n\
16940 the selected stack frame.\n\
16941 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16942 This collects arbitrary user data passed in the probe point call to the\n\
16943 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16944 by printing the $_sdata variable like any other convenience variable.\n\
16945 \n\
16946 CONDITION is a boolean expression.\n\
16947 \n\
16948 Multiple tracepoints at one place are permitted, and useful if their\n\
16949 conditions are different.\n\
16950 \n\
16951 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16952 Do \"help tracepoints\" for info on other tracepoint commands."));
16953   set_cmd_completer (c, location_completer);
16954
16955   add_info ("tracepoints", tracepoints_info, _("\
16956 Status of specified tracepoints (all tracepoints if no argument).\n\
16957 Convenience variable \"$tpnum\" contains the number of the\n\
16958 last tracepoint set."));
16959
16960   add_info_alias ("tp", "tracepoints", 1);
16961
16962   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16963 Delete specified tracepoints.\n\
16964 Arguments are tracepoint numbers, separated by spaces.\n\
16965 No argument means delete all tracepoints."),
16966            &deletelist);
16967   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16968
16969   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16970 Disable specified tracepoints.\n\
16971 Arguments are tracepoint numbers, separated by spaces.\n\
16972 No argument means disable all tracepoints."),
16973            &disablelist);
16974   deprecate_cmd (c, "disable");
16975
16976   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16977 Enable specified tracepoints.\n\
16978 Arguments are tracepoint numbers, separated by spaces.\n\
16979 No argument means enable all tracepoints."),
16980            &enablelist);
16981   deprecate_cmd (c, "enable");
16982
16983   add_com ("passcount", class_trace, trace_pass_command, _("\
16984 Set the passcount for a tracepoint.\n\
16985 The trace will end when the tracepoint has been passed 'count' times.\n\
16986 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16987 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16988
16989   add_prefix_cmd ("save", class_breakpoint, save_command,
16990                   _("Save breakpoint definitions as a script."),
16991                   &save_cmdlist, "save ",
16992                   0/*allow-unknown*/, &cmdlist);
16993
16994   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16995 Save current breakpoint definitions as a script.\n\
16996 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16997 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16998 session to restore them."),
16999                &save_cmdlist);
17000   set_cmd_completer (c, filename_completer);
17001
17002   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
17003 Save current tracepoint definitions as a script.\n\
17004 Use the 'source' command in another debug session to restore them."),
17005                &save_cmdlist);
17006   set_cmd_completer (c, filename_completer);
17007
17008   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
17009   deprecate_cmd (c, "save tracepoints");
17010
17011   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
17012 Breakpoint specific settings\n\
17013 Configure various breakpoint-specific variables such as\n\
17014 pending breakpoint behavior"),
17015                   &breakpoint_set_cmdlist, "set breakpoint ",
17016                   0/*allow-unknown*/, &setlist);
17017   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
17018 Breakpoint specific settings\n\
17019 Configure various breakpoint-specific variables such as\n\
17020 pending breakpoint behavior"),
17021                   &breakpoint_show_cmdlist, "show breakpoint ",
17022                   0/*allow-unknown*/, &showlist);
17023
17024   add_setshow_auto_boolean_cmd ("pending", no_class,
17025                                 &pending_break_support, _("\
17026 Set debugger's behavior regarding pending breakpoints."), _("\
17027 Show debugger's behavior regarding pending breakpoints."), _("\
17028 If on, an unrecognized breakpoint location will cause gdb to create a\n\
17029 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
17030 an error.  If auto, an unrecognized breakpoint location results in a\n\
17031 user-query to see if a pending breakpoint should be created."),
17032                                 NULL,
17033                                 show_pending_break_support,
17034                                 &breakpoint_set_cmdlist,
17035                                 &breakpoint_show_cmdlist);
17036
17037   pending_break_support = AUTO_BOOLEAN_AUTO;
17038
17039   add_setshow_boolean_cmd ("auto-hw", no_class,
17040                            &automatic_hardware_breakpoints, _("\
17041 Set automatic usage of hardware breakpoints."), _("\
17042 Show automatic usage of hardware breakpoints."), _("\
17043 If set, the debugger will automatically use hardware breakpoints for\n\
17044 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
17045 a warning will be emitted for such breakpoints."),
17046                            NULL,
17047                            show_automatic_hardware_breakpoints,
17048                            &breakpoint_set_cmdlist,
17049                            &breakpoint_show_cmdlist);
17050
17051   add_setshow_boolean_cmd ("always-inserted", class_support,
17052                            &always_inserted_mode, _("\
17053 Set mode for inserting breakpoints."), _("\
17054 Show mode for inserting breakpoints."), _("\
17055 When this mode is on, breakpoints are inserted immediately as soon as\n\
17056 they're created, kept inserted even when execution stops, and removed\n\
17057 only when the user deletes them.  When this mode is off (the default),\n\
17058 breakpoints are inserted only when execution continues, and removed\n\
17059 when execution stops."),
17060                                 NULL,
17061                                 &show_always_inserted_mode,
17062                                 &breakpoint_set_cmdlist,
17063                                 &breakpoint_show_cmdlist);
17064
17065   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
17066                         condition_evaluation_enums,
17067                         &condition_evaluation_mode_1, _("\
17068 Set mode of breakpoint condition evaluation."), _("\
17069 Show mode of breakpoint condition evaluation."), _("\
17070 When this is set to \"host\", breakpoint conditions will be\n\
17071 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
17072 breakpoint conditions will be downloaded to the target (if the target\n\
17073 supports such feature) and conditions will be evaluated on the target's side.\n\
17074 If this is set to \"auto\" (default), this will be automatically set to\n\
17075 \"target\" if it supports condition evaluation, otherwise it will\n\
17076 be set to \"gdb\""),
17077                            &set_condition_evaluation_mode,
17078                            &show_condition_evaluation_mode,
17079                            &breakpoint_set_cmdlist,
17080                            &breakpoint_show_cmdlist);
17081
17082   add_com ("break-range", class_breakpoint, break_range_command, _("\
17083 Set a breakpoint for an address range.\n\
17084 break-range START-LOCATION, END-LOCATION\n\
17085 where START-LOCATION and END-LOCATION can be one of the following:\n\
17086   LINENUM, for that line in the current file,\n\
17087   FILE:LINENUM, for that line in that file,\n\
17088   +OFFSET, for that number of lines after the current line\n\
17089            or the start of the range\n\
17090   FUNCTION, for the first line in that function,\n\
17091   FILE:FUNCTION, to distinguish among like-named static functions.\n\
17092   *ADDRESS, for the instruction at that address.\n\
17093 \n\
17094 The breakpoint will stop execution of the inferior whenever it executes\n\
17095 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
17096 range (including START-LOCATION and END-LOCATION)."));
17097
17098   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
17099 Set a dynamic printf at specified line or function.\n\
17100 dprintf location,format string,arg1,arg2,...\n\
17101 location may be a line number, function name, or \"*\" and an address.\n\
17102 If a line number is specified, break at start of code for that line.\n\
17103 If a function is specified, break at start of code for that function."));
17104   set_cmd_completer (c, location_completer);
17105
17106   add_setshow_enum_cmd ("dprintf-style", class_support,
17107                         dprintf_style_enums, &dprintf_style, _("\
17108 Set the style of usage for dynamic printf."), _("\
17109 Show the style of usage for dynamic printf."), _("\
17110 This setting chooses how GDB will do a dynamic printf.\n\
17111 If the value is \"gdb\", then the printing is done by GDB to its own\n\
17112 console, as with the \"printf\" command.\n\
17113 If the value is \"call\", the print is done by calling a function in your\n\
17114 program; by default printf(), but you can choose a different function or\n\
17115 output stream by setting dprintf-function and dprintf-channel."),
17116                         update_dprintf_commands, NULL,
17117                         &setlist, &showlist);
17118
17119   dprintf_function = xstrdup ("printf");
17120   add_setshow_string_cmd ("dprintf-function", class_support,
17121                           &dprintf_function, _("\
17122 Set the function to use for dynamic printf"), _("\
17123 Show the function to use for dynamic printf"), NULL,
17124                           update_dprintf_commands, NULL,
17125                           &setlist, &showlist);
17126
17127   dprintf_channel = xstrdup ("");
17128   add_setshow_string_cmd ("dprintf-channel", class_support,
17129                           &dprintf_channel, _("\
17130 Set the channel to use for dynamic printf"), _("\
17131 Show the channel to use for dynamic printf"), NULL,
17132                           update_dprintf_commands, NULL,
17133                           &setlist, &showlist);
17134
17135   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
17136                            &disconnected_dprintf, _("\
17137 Set whether dprintf continues after GDB disconnects."), _("\
17138 Show whether dprintf continues after GDB disconnects."), _("\
17139 Use this to let dprintf commands continue to hit and produce output\n\
17140 even if GDB disconnects or detaches from the target."),
17141                            NULL,
17142                            NULL,
17143                            &setlist, &showlist);
17144
17145   add_com ("agent-printf", class_vars, agent_printf_command, _("\
17146 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
17147 (target agent only) This is useful for formatted output in user-defined commands."));
17148
17149   automatic_hardware_breakpoints = 1;
17150
17151   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
17152   observer_attach_thread_exit (remove_threaded_breakpoints);
17153 }