Fix "breakpoint always-inserted off"; remove "breakpoint always-inserted auto"
[external/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     return 0;
2205
2206   return 1;
2207 }
2208
2209 /* Same as should_be_inserted but does the check assuming
2210    that the location is not duplicated.  */
2211
2212 static int
2213 unduplicated_should_be_inserted (struct bp_location *bl)
2214 {
2215   int result;
2216   const int save_duplicate = bl->duplicate;
2217
2218   bl->duplicate = 0;
2219   result = should_be_inserted (bl);
2220   bl->duplicate = save_duplicate;
2221   return result;
2222 }
2223
2224 /* Parses a conditional described by an expression COND into an
2225    agent expression bytecode suitable for evaluation
2226    by the bytecode interpreter.  Return NULL if there was
2227    any error during parsing.  */
2228
2229 static struct agent_expr *
2230 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
2231 {
2232   struct agent_expr *aexpr = NULL;
2233   volatile struct gdb_exception ex;
2234
2235   if (!cond)
2236     return NULL;
2237
2238   /* We don't want to stop processing, so catch any errors
2239      that may show up.  */
2240   TRY_CATCH (ex, RETURN_MASK_ERROR)
2241     {
2242       aexpr = gen_eval_for_expr (scope, cond);
2243     }
2244
2245   if (ex.reason < 0)
2246     {
2247       /* If we got here, it means the condition could not be parsed to a valid
2248          bytecode expression and thus can't be evaluated on the target's side.
2249          It's no use iterating through the conditions.  */
2250       return NULL;
2251     }
2252
2253   /* We have a valid agent expression.  */
2254   return aexpr;
2255 }
2256
2257 /* Based on location BL, create a list of breakpoint conditions to be
2258    passed on to the target.  If we have duplicated locations with different
2259    conditions, we will add such conditions to the list.  The idea is that the
2260    target will evaluate the list of conditions and will only notify GDB when
2261    one of them is true.  */
2262
2263 static void
2264 build_target_condition_list (struct bp_location *bl)
2265 {
2266   struct bp_location **locp = NULL, **loc2p;
2267   int null_condition_or_parse_error = 0;
2268   int modified = bl->needs_update;
2269   struct bp_location *loc;
2270
2271   /* Release conditions left over from a previous insert.  */
2272   VEC_free (agent_expr_p, bl->target_info.conditions);
2273
2274   /* This is only meaningful if the target is
2275      evaluating conditions and if the user has
2276      opted for condition evaluation on the target's
2277      side.  */
2278   if (gdb_evaluates_breakpoint_condition_p ()
2279       || !target_supports_evaluation_of_breakpoint_conditions ())
2280     return;
2281
2282   /* Do a first pass to check for locations with no assigned
2283      conditions or conditions that fail to parse to a valid agent expression
2284      bytecode.  If any of these happen, then it's no use to send conditions
2285      to the target since this location will always trigger and generate a
2286      response back to GDB.  */
2287   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2288     {
2289       loc = (*loc2p);
2290       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2291         {
2292           if (modified)
2293             {
2294               struct agent_expr *aexpr;
2295
2296               /* Re-parse the conditions since something changed.  In that
2297                  case we already freed the condition bytecodes (see
2298                  force_breakpoint_reinsertion).  We just
2299                  need to parse the condition to bytecodes again.  */
2300               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2301               loc->cond_bytecode = aexpr;
2302
2303               /* Check if we managed to parse the conditional expression
2304                  correctly.  If not, we will not send this condition
2305                  to the target.  */
2306               if (aexpr)
2307                 continue;
2308             }
2309
2310           /* If we have a NULL bytecode expression, it means something
2311              went wrong or we have a null condition expression.  */
2312           if (!loc->cond_bytecode)
2313             {
2314               null_condition_or_parse_error = 1;
2315               break;
2316             }
2317         }
2318     }
2319
2320   /* If any of these happened, it means we will have to evaluate the conditions
2321      for the location's address on gdb's side.  It is no use keeping bytecodes
2322      for all the other duplicate locations, thus we free all of them here.
2323
2324      This is so we have a finer control over which locations' conditions are
2325      being evaluated by GDB or the remote stub.  */
2326   if (null_condition_or_parse_error)
2327     {
2328       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2329         {
2330           loc = (*loc2p);
2331           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2332             {
2333               /* Only go as far as the first NULL bytecode is
2334                  located.  */
2335               if (!loc->cond_bytecode)
2336                 return;
2337
2338               free_agent_expr (loc->cond_bytecode);
2339               loc->cond_bytecode = NULL;
2340             }
2341         }
2342     }
2343
2344   /* No NULL conditions or failed bytecode generation.  Build a condition list
2345      for this location's address.  */
2346   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2347     {
2348       loc = (*loc2p);
2349       if (loc->cond
2350           && is_breakpoint (loc->owner)
2351           && loc->pspace->num == bl->pspace->num
2352           && loc->owner->enable_state == bp_enabled
2353           && loc->enabled)
2354         /* Add the condition to the vector.  This will be used later to send the
2355            conditions to the target.  */
2356         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2357                        loc->cond_bytecode);
2358     }
2359
2360   return;
2361 }
2362
2363 /* Parses a command described by string CMD into an agent expression
2364    bytecode suitable for evaluation by the bytecode interpreter.
2365    Return NULL if there was any error during parsing.  */
2366
2367 static struct agent_expr *
2368 parse_cmd_to_aexpr (CORE_ADDR scope, char *cmd)
2369 {
2370   struct cleanup *old_cleanups = 0;
2371   struct expression *expr, **argvec;
2372   struct agent_expr *aexpr = NULL;
2373   volatile struct gdb_exception ex;
2374   const char *cmdrest;
2375   const char *format_start, *format_end;
2376   struct format_piece *fpieces;
2377   int nargs;
2378   struct gdbarch *gdbarch = get_current_arch ();
2379
2380   if (!cmd)
2381     return NULL;
2382
2383   cmdrest = cmd;
2384
2385   if (*cmdrest == ',')
2386     ++cmdrest;
2387   cmdrest = skip_spaces_const (cmdrest);
2388
2389   if (*cmdrest++ != '"')
2390     error (_("No format string following the location"));
2391
2392   format_start = cmdrest;
2393
2394   fpieces = parse_format_string (&cmdrest);
2395
2396   old_cleanups = make_cleanup (free_format_pieces_cleanup, &fpieces);
2397
2398   format_end = cmdrest;
2399
2400   if (*cmdrest++ != '"')
2401     error (_("Bad format string, non-terminated '\"'."));
2402   
2403   cmdrest = skip_spaces_const (cmdrest);
2404
2405   if (!(*cmdrest == ',' || *cmdrest == '\0'))
2406     error (_("Invalid argument syntax"));
2407
2408   if (*cmdrest == ',')
2409     cmdrest++;
2410   cmdrest = skip_spaces_const (cmdrest);
2411
2412   /* For each argument, make an expression.  */
2413
2414   argvec = (struct expression **) alloca (strlen (cmd)
2415                                          * sizeof (struct expression *));
2416
2417   nargs = 0;
2418   while (*cmdrest != '\0')
2419     {
2420       const char *cmd1;
2421
2422       cmd1 = cmdrest;
2423       expr = parse_exp_1 (&cmd1, scope, block_for_pc (scope), 1);
2424       argvec[nargs++] = expr;
2425       cmdrest = cmd1;
2426       if (*cmdrest == ',')
2427         ++cmdrest;
2428     }
2429
2430   /* We don't want to stop processing, so catch any errors
2431      that may show up.  */
2432   TRY_CATCH (ex, RETURN_MASK_ERROR)
2433     {
2434       aexpr = gen_printf (scope, gdbarch, 0, 0,
2435                           format_start, format_end - format_start,
2436                           fpieces, nargs, argvec);
2437     }
2438
2439   do_cleanups (old_cleanups);
2440
2441   if (ex.reason < 0)
2442     {
2443       /* If we got here, it means the command could not be parsed to a valid
2444          bytecode expression and thus can't be evaluated on the target's side.
2445          It's no use iterating through the other commands.  */
2446       return NULL;
2447     }
2448
2449   /* We have a valid agent expression, return it.  */
2450   return aexpr;
2451 }
2452
2453 /* Based on location BL, create a list of breakpoint commands to be
2454    passed on to the target.  If we have duplicated locations with
2455    different commands, we will add any such to the list.  */
2456
2457 static void
2458 build_target_command_list (struct bp_location *bl)
2459 {
2460   struct bp_location **locp = NULL, **loc2p;
2461   int null_command_or_parse_error = 0;
2462   int modified = bl->needs_update;
2463   struct bp_location *loc;
2464
2465   /* Release commands left over from a previous insert.  */
2466   VEC_free (agent_expr_p, bl->target_info.tcommands);
2467
2468   if (!target_can_run_breakpoint_commands ())
2469     return;
2470
2471   /* For now, limit to agent-style dprintf breakpoints.  */
2472   if (dprintf_style != dprintf_style_agent)
2473     return;
2474
2475   /* For now, if we have any duplicate location that isn't a dprintf,
2476      don't install the target-side commands, as that would make the
2477      breakpoint not be reported to the core, and we'd lose
2478      control.  */
2479   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2480     {
2481       loc = (*loc2p);
2482       if (is_breakpoint (loc->owner)
2483           && loc->pspace->num == bl->pspace->num
2484           && loc->owner->type != bp_dprintf)
2485         return;
2486     }
2487
2488   /* Do a first pass to check for locations with no assigned
2489      conditions or conditions that fail to parse to a valid agent expression
2490      bytecode.  If any of these happen, then it's no use to send conditions
2491      to the target since this location will always trigger and generate a
2492      response back to GDB.  */
2493   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2494     {
2495       loc = (*loc2p);
2496       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2497         {
2498           if (modified)
2499             {
2500               struct agent_expr *aexpr;
2501
2502               /* Re-parse the commands since something changed.  In that
2503                  case we already freed the command bytecodes (see
2504                  force_breakpoint_reinsertion).  We just
2505                  need to parse the command to bytecodes again.  */
2506               aexpr = parse_cmd_to_aexpr (bl->address,
2507                                           loc->owner->extra_string);
2508               loc->cmd_bytecode = aexpr;
2509
2510               if (!aexpr)
2511                 continue;
2512             }
2513
2514           /* If we have a NULL bytecode expression, it means something
2515              went wrong or we have a null command expression.  */
2516           if (!loc->cmd_bytecode)
2517             {
2518               null_command_or_parse_error = 1;
2519               break;
2520             }
2521         }
2522     }
2523
2524   /* If anything failed, then we're not doing target-side commands,
2525      and so clean up.  */
2526   if (null_command_or_parse_error)
2527     {
2528       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2529         {
2530           loc = (*loc2p);
2531           if (is_breakpoint (loc->owner)
2532               && loc->pspace->num == bl->pspace->num)
2533             {
2534               /* Only go as far as the first NULL bytecode is
2535                  located.  */
2536               if (loc->cmd_bytecode == NULL)
2537                 return;
2538
2539               free_agent_expr (loc->cmd_bytecode);
2540               loc->cmd_bytecode = NULL;
2541             }
2542         }
2543     }
2544
2545   /* No NULL commands or failed bytecode generation.  Build a command list
2546      for this location's address.  */
2547   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2548     {
2549       loc = (*loc2p);
2550       if (loc->owner->extra_string
2551           && is_breakpoint (loc->owner)
2552           && loc->pspace->num == bl->pspace->num
2553           && loc->owner->enable_state == bp_enabled
2554           && loc->enabled)
2555         /* Add the command to the vector.  This will be used later
2556            to send the commands to the target.  */
2557         VEC_safe_push (agent_expr_p, bl->target_info.tcommands,
2558                        loc->cmd_bytecode);
2559     }
2560
2561   bl->target_info.persist = 0;
2562   /* Maybe flag this location as persistent.  */
2563   if (bl->owner->type == bp_dprintf && disconnected_dprintf)
2564     bl->target_info.persist = 1;
2565 }
2566
2567 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2568    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2569    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2570    Returns 0 for success, 1 if the bp_location type is not supported or
2571    -1 for failure.
2572
2573    NOTE drow/2003-09-09: This routine could be broken down to an
2574    object-style method for each breakpoint or catchpoint type.  */
2575 static int
2576 insert_bp_location (struct bp_location *bl,
2577                     struct ui_file *tmp_error_stream,
2578                     int *disabled_breaks,
2579                     int *hw_breakpoint_error,
2580                     int *hw_bp_error_explained_already)
2581 {
2582   enum errors bp_err = GDB_NO_ERROR;
2583   const char *bp_err_message = NULL;
2584   volatile struct gdb_exception e;
2585
2586   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2587     return 0;
2588
2589   /* Note we don't initialize bl->target_info, as that wipes out
2590      the breakpoint location's shadow_contents if the breakpoint
2591      is still inserted at that location.  This in turn breaks
2592      target_read_memory which depends on these buffers when
2593      a memory read is requested at the breakpoint location:
2594      Once the target_info has been wiped, we fail to see that
2595      we have a breakpoint inserted at that address and thus
2596      read the breakpoint instead of returning the data saved in
2597      the breakpoint location's shadow contents.  */
2598   bl->target_info.placed_address = bl->address;
2599   bl->target_info.placed_address_space = bl->pspace->aspace;
2600   bl->target_info.length = bl->length;
2601
2602   /* When working with target-side conditions, we must pass all the conditions
2603      for the same breakpoint address down to the target since GDB will not
2604      insert those locations.  With a list of breakpoint conditions, the target
2605      can decide when to stop and notify GDB.  */
2606
2607   if (is_breakpoint (bl->owner))
2608     {
2609       build_target_condition_list (bl);
2610       build_target_command_list (bl);
2611       /* Reset the modification marker.  */
2612       bl->needs_update = 0;
2613     }
2614
2615   if (bl->loc_type == bp_loc_software_breakpoint
2616       || bl->loc_type == bp_loc_hardware_breakpoint)
2617     {
2618       if (bl->owner->type != bp_hardware_breakpoint)
2619         {
2620           /* If the explicitly specified breakpoint type
2621              is not hardware breakpoint, check the memory map to see
2622              if the breakpoint address is in read only memory or not.
2623
2624              Two important cases are:
2625              - location type is not hardware breakpoint, memory
2626              is readonly.  We change the type of the location to
2627              hardware breakpoint.
2628              - location type is hardware breakpoint, memory is
2629              read-write.  This means we've previously made the
2630              location hardware one, but then the memory map changed,
2631              so we undo.
2632              
2633              When breakpoints are removed, remove_breakpoints will use
2634              location types we've just set here, the only possible
2635              problem is that memory map has changed during running
2636              program, but it's not going to work anyway with current
2637              gdb.  */
2638           struct mem_region *mr 
2639             = lookup_mem_region (bl->target_info.placed_address);
2640           
2641           if (mr)
2642             {
2643               if (automatic_hardware_breakpoints)
2644                 {
2645                   enum bp_loc_type new_type;
2646                   
2647                   if (mr->attrib.mode != MEM_RW)
2648                     new_type = bp_loc_hardware_breakpoint;
2649                   else 
2650                     new_type = bp_loc_software_breakpoint;
2651                   
2652                   if (new_type != bl->loc_type)
2653                     {
2654                       static int said = 0;
2655
2656                       bl->loc_type = new_type;
2657                       if (!said)
2658                         {
2659                           fprintf_filtered (gdb_stdout,
2660                                             _("Note: automatically using "
2661                                               "hardware breakpoints for "
2662                                               "read-only addresses.\n"));
2663                           said = 1;
2664                         }
2665                     }
2666                 }
2667               else if (bl->loc_type == bp_loc_software_breakpoint
2668                        && mr->attrib.mode != MEM_RW)        
2669                 warning (_("cannot set software breakpoint "
2670                            "at readonly address %s"),
2671                          paddress (bl->gdbarch, bl->address));
2672             }
2673         }
2674         
2675       /* First check to see if we have to handle an overlay.  */
2676       if (overlay_debugging == ovly_off
2677           || bl->section == NULL
2678           || !(section_is_overlay (bl->section)))
2679         {
2680           /* No overlay handling: just set the breakpoint.  */
2681           TRY_CATCH (e, RETURN_MASK_ALL)
2682             {
2683               int val;
2684
2685               val = bl->owner->ops->insert_location (bl);
2686               if (val)
2687                 bp_err = GENERIC_ERROR;
2688             }
2689           if (e.reason < 0)
2690             {
2691               bp_err = e.error;
2692               bp_err_message = e.message;
2693             }
2694         }
2695       else
2696         {
2697           /* This breakpoint is in an overlay section.
2698              Shall we set a breakpoint at the LMA?  */
2699           if (!overlay_events_enabled)
2700             {
2701               /* Yes -- overlay event support is not active, 
2702                  so we must try to set a breakpoint at the LMA.
2703                  This will not work for a hardware breakpoint.  */
2704               if (bl->loc_type == bp_loc_hardware_breakpoint)
2705                 warning (_("hardware breakpoint %d not supported in overlay!"),
2706                          bl->owner->number);
2707               else
2708                 {
2709                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2710                                                              bl->section);
2711                   /* Set a software (trap) breakpoint at the LMA.  */
2712                   bl->overlay_target_info = bl->target_info;
2713                   bl->overlay_target_info.placed_address = addr;
2714
2715                   /* No overlay handling: just set the breakpoint.  */
2716                   TRY_CATCH (e, RETURN_MASK_ALL)
2717                     {
2718                       int val;
2719
2720                       val = target_insert_breakpoint (bl->gdbarch,
2721                                                       &bl->overlay_target_info);
2722                       if (val)
2723                         bp_err = GENERIC_ERROR;
2724                     }
2725                   if (e.reason < 0)
2726                     {
2727                       bp_err = e.error;
2728                       bp_err_message = e.message;
2729                     }
2730
2731                   if (bp_err != GDB_NO_ERROR)
2732                     fprintf_unfiltered (tmp_error_stream,
2733                                         "Overlay breakpoint %d "
2734                                         "failed: in ROM?\n",
2735                                         bl->owner->number);
2736                 }
2737             }
2738           /* Shall we set a breakpoint at the VMA? */
2739           if (section_is_mapped (bl->section))
2740             {
2741               /* Yes.  This overlay section is mapped into memory.  */
2742               TRY_CATCH (e, RETURN_MASK_ALL)
2743                 {
2744                   int val;
2745
2746                   val = bl->owner->ops->insert_location (bl);
2747                   if (val)
2748                     bp_err = GENERIC_ERROR;
2749                 }
2750               if (e.reason < 0)
2751                 {
2752                   bp_err = e.error;
2753                   bp_err_message = e.message;
2754                 }
2755             }
2756           else
2757             {
2758               /* No.  This breakpoint will not be inserted.  
2759                  No error, but do not mark the bp as 'inserted'.  */
2760               return 0;
2761             }
2762         }
2763
2764       if (bp_err != GDB_NO_ERROR)
2765         {
2766           /* Can't set the breakpoint.  */
2767
2768           /* In some cases, we might not be able to insert a
2769              breakpoint in a shared library that has already been
2770              removed, but we have not yet processed the shlib unload
2771              event.  Unfortunately, some targets that implement
2772              breakpoint insertion themselves can't tell why the
2773              breakpoint insertion failed (e.g., the remote target
2774              doesn't define error codes), so we must treat generic
2775              errors as memory errors.  */
2776           if ((bp_err == GENERIC_ERROR || bp_err == MEMORY_ERROR)
2777               && bl->loc_type == bp_loc_software_breakpoint
2778               && (solib_name_from_address (bl->pspace, bl->address)
2779                   || shared_objfile_contains_address_p (bl->pspace,
2780                                                         bl->address)))
2781             {
2782               /* See also: disable_breakpoints_in_shlibs.  */
2783               bl->shlib_disabled = 1;
2784               observer_notify_breakpoint_modified (bl->owner);
2785               if (!*disabled_breaks)
2786                 {
2787                   fprintf_unfiltered (tmp_error_stream, 
2788                                       "Cannot insert breakpoint %d.\n", 
2789                                       bl->owner->number);
2790                   fprintf_unfiltered (tmp_error_stream, 
2791                                       "Temporarily disabling shared "
2792                                       "library breakpoints:\n");
2793                 }
2794               *disabled_breaks = 1;
2795               fprintf_unfiltered (tmp_error_stream,
2796                                   "breakpoint #%d\n", bl->owner->number);
2797               return 0;
2798             }
2799           else
2800             {
2801               if (bl->loc_type == bp_loc_hardware_breakpoint)
2802                 {
2803                   *hw_breakpoint_error = 1;
2804                   *hw_bp_error_explained_already = bp_err_message != NULL;
2805                   fprintf_unfiltered (tmp_error_stream,
2806                                       "Cannot insert hardware breakpoint %d%s",
2807                                       bl->owner->number, bp_err_message ? ":" : ".\n");
2808                   if (bp_err_message != NULL)
2809                     fprintf_unfiltered (tmp_error_stream, "%s.\n", bp_err_message);
2810                 }
2811               else
2812                 {
2813                   if (bp_err_message == NULL)
2814                     {
2815                       char *message
2816                         = memory_error_message (TARGET_XFER_E_IO,
2817                                                 bl->gdbarch, bl->address);
2818                       struct cleanup *old_chain = make_cleanup (xfree, message);
2819
2820                       fprintf_unfiltered (tmp_error_stream,
2821                                           "Cannot insert breakpoint %d.\n"
2822                                           "%s\n",
2823                                           bl->owner->number, message);
2824                       do_cleanups (old_chain);
2825                     }
2826                   else
2827                     {
2828                       fprintf_unfiltered (tmp_error_stream,
2829                                           "Cannot insert breakpoint %d: %s\n",
2830                                           bl->owner->number,
2831                                           bp_err_message);
2832                     }
2833                 }
2834               return 1;
2835
2836             }
2837         }
2838       else
2839         bl->inserted = 1;
2840
2841       return 0;
2842     }
2843
2844   else if (bl->loc_type == bp_loc_hardware_watchpoint
2845            /* NOTE drow/2003-09-08: This state only exists for removing
2846               watchpoints.  It's not clear that it's necessary...  */
2847            && bl->owner->disposition != disp_del_at_next_stop)
2848     {
2849       int val;
2850
2851       gdb_assert (bl->owner->ops != NULL
2852                   && bl->owner->ops->insert_location != NULL);
2853
2854       val = bl->owner->ops->insert_location (bl);
2855
2856       /* If trying to set a read-watchpoint, and it turns out it's not
2857          supported, try emulating one with an access watchpoint.  */
2858       if (val == 1 && bl->watchpoint_type == hw_read)
2859         {
2860           struct bp_location *loc, **loc_temp;
2861
2862           /* But don't try to insert it, if there's already another
2863              hw_access location that would be considered a duplicate
2864              of this one.  */
2865           ALL_BP_LOCATIONS (loc, loc_temp)
2866             if (loc != bl
2867                 && loc->watchpoint_type == hw_access
2868                 && watchpoint_locations_match (bl, loc))
2869               {
2870                 bl->duplicate = 1;
2871                 bl->inserted = 1;
2872                 bl->target_info = loc->target_info;
2873                 bl->watchpoint_type = hw_access;
2874                 val = 0;
2875                 break;
2876               }
2877
2878           if (val == 1)
2879             {
2880               bl->watchpoint_type = hw_access;
2881               val = bl->owner->ops->insert_location (bl);
2882
2883               if (val)
2884                 /* Back to the original value.  */
2885                 bl->watchpoint_type = hw_read;
2886             }
2887         }
2888
2889       bl->inserted = (val == 0);
2890     }
2891
2892   else if (bl->owner->type == bp_catchpoint)
2893     {
2894       int val;
2895
2896       gdb_assert (bl->owner->ops != NULL
2897                   && bl->owner->ops->insert_location != NULL);
2898
2899       val = bl->owner->ops->insert_location (bl);
2900       if (val)
2901         {
2902           bl->owner->enable_state = bp_disabled;
2903
2904           if (val == 1)
2905             warning (_("\
2906 Error inserting catchpoint %d: Your system does not support this type\n\
2907 of catchpoint."), bl->owner->number);
2908           else
2909             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2910         }
2911
2912       bl->inserted = (val == 0);
2913
2914       /* We've already printed an error message if there was a problem
2915          inserting this catchpoint, and we've disabled the catchpoint,
2916          so just return success.  */
2917       return 0;
2918     }
2919
2920   return 0;
2921 }
2922
2923 /* This function is called when program space PSPACE is about to be
2924    deleted.  It takes care of updating breakpoints to not reference
2925    PSPACE anymore.  */
2926
2927 void
2928 breakpoint_program_space_exit (struct program_space *pspace)
2929 {
2930   struct breakpoint *b, *b_temp;
2931   struct bp_location *loc, **loc_temp;
2932
2933   /* Remove any breakpoint that was set through this program space.  */
2934   ALL_BREAKPOINTS_SAFE (b, b_temp)
2935     {
2936       if (b->pspace == pspace)
2937         delete_breakpoint (b);
2938     }
2939
2940   /* Breakpoints set through other program spaces could have locations
2941      bound to PSPACE as well.  Remove those.  */
2942   ALL_BP_LOCATIONS (loc, loc_temp)
2943     {
2944       struct bp_location *tmp;
2945
2946       if (loc->pspace == pspace)
2947         {
2948           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2949           if (loc->owner->loc == loc)
2950             loc->owner->loc = loc->next;
2951           else
2952             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2953               if (tmp->next == loc)
2954                 {
2955                   tmp->next = loc->next;
2956                   break;
2957                 }
2958         }
2959     }
2960
2961   /* Now update the global location list to permanently delete the
2962      removed locations above.  */
2963   update_global_location_list (UGLL_DONT_INSERT);
2964 }
2965
2966 /* Make sure all breakpoints are inserted in inferior.
2967    Throws exception on any error.
2968    A breakpoint that is already inserted won't be inserted
2969    again, so calling this function twice is safe.  */
2970 void
2971 insert_breakpoints (void)
2972 {
2973   struct breakpoint *bpt;
2974
2975   ALL_BREAKPOINTS (bpt)
2976     if (is_hardware_watchpoint (bpt))
2977       {
2978         struct watchpoint *w = (struct watchpoint *) bpt;
2979
2980         update_watchpoint (w, 0 /* don't reparse.  */);
2981       }
2982
2983   /* Updating watchpoints creates new locations, so update the global
2984      location list.  Explicitly tell ugll to insert locations and
2985      ignore breakpoints_always_inserted_mode.  */
2986   update_global_location_list (UGLL_INSERT);
2987 }
2988
2989 /* Invoke CALLBACK for each of bp_location.  */
2990
2991 void
2992 iterate_over_bp_locations (walk_bp_location_callback callback)
2993 {
2994   struct bp_location *loc, **loc_tmp;
2995
2996   ALL_BP_LOCATIONS (loc, loc_tmp)
2997     {
2998       callback (loc, NULL);
2999     }
3000 }
3001
3002 /* This is used when we need to synch breakpoint conditions between GDB and the
3003    target.  It is the case with deleting and disabling of breakpoints when using
3004    always-inserted mode.  */
3005
3006 static void
3007 update_inserted_breakpoint_locations (void)
3008 {
3009   struct bp_location *bl, **blp_tmp;
3010   int error_flag = 0;
3011   int val = 0;
3012   int disabled_breaks = 0;
3013   int hw_breakpoint_error = 0;
3014   int hw_bp_details_reported = 0;
3015
3016   struct ui_file *tmp_error_stream = mem_fileopen ();
3017   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3018
3019   /* Explicitly mark the warning -- this will only be printed if
3020      there was an error.  */
3021   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3022
3023   save_current_space_and_thread ();
3024
3025   ALL_BP_LOCATIONS (bl, blp_tmp)
3026     {
3027       /* We only want to update software breakpoints and hardware
3028          breakpoints.  */
3029       if (!is_breakpoint (bl->owner))
3030         continue;
3031
3032       /* We only want to update locations that are already inserted
3033          and need updating.  This is to avoid unwanted insertion during
3034          deletion of breakpoints.  */
3035       if (!bl->inserted || (bl->inserted && !bl->needs_update))
3036         continue;
3037
3038       switch_to_program_space_and_thread (bl->pspace);
3039
3040       /* For targets that support global breakpoints, there's no need
3041          to select an inferior to insert breakpoint to.  In fact, even
3042          if we aren't attached to any process yet, we should still
3043          insert breakpoints.  */
3044       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3045           && ptid_equal (inferior_ptid, null_ptid))
3046         continue;
3047
3048       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3049                                     &hw_breakpoint_error, &hw_bp_details_reported);
3050       if (val)
3051         error_flag = val;
3052     }
3053
3054   if (error_flag)
3055     {
3056       target_terminal_ours_for_output ();
3057       error_stream (tmp_error_stream);
3058     }
3059
3060   do_cleanups (cleanups);
3061 }
3062
3063 /* Used when starting or continuing the program.  */
3064
3065 static void
3066 insert_breakpoint_locations (void)
3067 {
3068   struct breakpoint *bpt;
3069   struct bp_location *bl, **blp_tmp;
3070   int error_flag = 0;
3071   int val = 0;
3072   int disabled_breaks = 0;
3073   int hw_breakpoint_error = 0;
3074   int hw_bp_error_explained_already = 0;
3075
3076   struct ui_file *tmp_error_stream = mem_fileopen ();
3077   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
3078   
3079   /* Explicitly mark the warning -- this will only be printed if
3080      there was an error.  */
3081   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
3082
3083   save_current_space_and_thread ();
3084
3085   ALL_BP_LOCATIONS (bl, blp_tmp)
3086     {
3087       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
3088         continue;
3089
3090       /* There is no point inserting thread-specific breakpoints if
3091          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
3092          has BL->OWNER always non-NULL.  */
3093       if (bl->owner->thread != -1
3094           && !valid_thread_id (bl->owner->thread))
3095         continue;
3096
3097       switch_to_program_space_and_thread (bl->pspace);
3098
3099       /* For targets that support global breakpoints, there's no need
3100          to select an inferior to insert breakpoint to.  In fact, even
3101          if we aren't attached to any process yet, we should still
3102          insert breakpoints.  */
3103       if (!gdbarch_has_global_breakpoints (target_gdbarch ())
3104           && ptid_equal (inferior_ptid, null_ptid))
3105         continue;
3106
3107       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
3108                                     &hw_breakpoint_error, &hw_bp_error_explained_already);
3109       if (val)
3110         error_flag = val;
3111     }
3112
3113   /* If we failed to insert all locations of a watchpoint, remove
3114      them, as half-inserted watchpoint is of limited use.  */
3115   ALL_BREAKPOINTS (bpt)  
3116     {
3117       int some_failed = 0;
3118       struct bp_location *loc;
3119
3120       if (!is_hardware_watchpoint (bpt))
3121         continue;
3122
3123       if (!breakpoint_enabled (bpt))
3124         continue;
3125
3126       if (bpt->disposition == disp_del_at_next_stop)
3127         continue;
3128       
3129       for (loc = bpt->loc; loc; loc = loc->next)
3130         if (!loc->inserted && should_be_inserted (loc))
3131           {
3132             some_failed = 1;
3133             break;
3134           }
3135       if (some_failed)
3136         {
3137           for (loc = bpt->loc; loc; loc = loc->next)
3138             if (loc->inserted)
3139               remove_breakpoint (loc, mark_uninserted);
3140
3141           hw_breakpoint_error = 1;
3142           fprintf_unfiltered (tmp_error_stream,
3143                               "Could not insert hardware watchpoint %d.\n", 
3144                               bpt->number);
3145           error_flag = -1;
3146         }
3147     }
3148
3149   if (error_flag)
3150     {
3151       /* If a hardware breakpoint or watchpoint was inserted, add a
3152          message about possibly exhausted resources.  */
3153       if (hw_breakpoint_error && !hw_bp_error_explained_already)
3154         {
3155           fprintf_unfiltered (tmp_error_stream, 
3156                               "Could not insert hardware breakpoints:\n\
3157 You may have requested too many hardware breakpoints/watchpoints.\n");
3158         }
3159       target_terminal_ours_for_output ();
3160       error_stream (tmp_error_stream);
3161     }
3162
3163   do_cleanups (cleanups);
3164 }
3165
3166 /* Used when the program stops.
3167    Returns zero if successful, or non-zero if there was a problem
3168    removing a breakpoint location.  */
3169
3170 int
3171 remove_breakpoints (void)
3172 {
3173   struct bp_location *bl, **blp_tmp;
3174   int val = 0;
3175
3176   ALL_BP_LOCATIONS (bl, blp_tmp)
3177   {
3178     if (bl->inserted && !is_tracepoint (bl->owner))
3179       val |= remove_breakpoint (bl, mark_uninserted);
3180   }
3181   return val;
3182 }
3183
3184 /* When a thread exits, remove breakpoints that are related to
3185    that thread.  */
3186
3187 static void
3188 remove_threaded_breakpoints (struct thread_info *tp, int silent)
3189 {
3190   struct breakpoint *b, *b_tmp;
3191
3192   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3193     {
3194       if (b->thread == tp->num && user_breakpoint_p (b))
3195         {
3196           b->disposition = disp_del_at_next_stop;
3197
3198           printf_filtered (_("\
3199 Thread-specific breakpoint %d deleted - thread %d no longer in the thread list.\n"),
3200                           b->number, tp->num);
3201
3202           /* Hide it from the user.  */
3203           b->number = 0;
3204        }
3205     }
3206 }
3207
3208 /* Remove breakpoints of process PID.  */
3209
3210 int
3211 remove_breakpoints_pid (int pid)
3212 {
3213   struct bp_location *bl, **blp_tmp;
3214   int val;
3215   struct inferior *inf = find_inferior_pid (pid);
3216
3217   ALL_BP_LOCATIONS (bl, blp_tmp)
3218   {
3219     if (bl->pspace != inf->pspace)
3220       continue;
3221
3222     if (bl->owner->type == bp_dprintf)
3223       continue;
3224
3225     if (bl->inserted)
3226       {
3227         val = remove_breakpoint (bl, mark_uninserted);
3228         if (val != 0)
3229           return val;
3230       }
3231   }
3232   return 0;
3233 }
3234
3235 int
3236 reattach_breakpoints (int pid)
3237 {
3238   struct cleanup *old_chain;
3239   struct bp_location *bl, **blp_tmp;
3240   int val;
3241   struct ui_file *tmp_error_stream;
3242   int dummy1 = 0, dummy2 = 0, dummy3 = 0;
3243   struct inferior *inf;
3244   struct thread_info *tp;
3245
3246   tp = any_live_thread_of_process (pid);
3247   if (tp == NULL)
3248     return 1;
3249
3250   inf = find_inferior_pid (pid);
3251   old_chain = save_inferior_ptid ();
3252
3253   inferior_ptid = tp->ptid;
3254
3255   tmp_error_stream = mem_fileopen ();
3256   make_cleanup_ui_file_delete (tmp_error_stream);
3257
3258   ALL_BP_LOCATIONS (bl, blp_tmp)
3259   {
3260     if (bl->pspace != inf->pspace)
3261       continue;
3262
3263     if (bl->inserted)
3264       {
3265         bl->inserted = 0;
3266         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2, &dummy3);
3267         if (val != 0)
3268           {
3269             do_cleanups (old_chain);
3270             return val;
3271           }
3272       }
3273   }
3274   do_cleanups (old_chain);
3275   return 0;
3276 }
3277
3278 static int internal_breakpoint_number = -1;
3279
3280 /* Set the breakpoint number of B, depending on the value of INTERNAL.
3281    If INTERNAL is non-zero, the breakpoint number will be populated
3282    from internal_breakpoint_number and that variable decremented.
3283    Otherwise the breakpoint number will be populated from
3284    breakpoint_count and that value incremented.  Internal breakpoints
3285    do not set the internal var bpnum.  */
3286 static void
3287 set_breakpoint_number (int internal, struct breakpoint *b)
3288 {
3289   if (internal)
3290     b->number = internal_breakpoint_number--;
3291   else
3292     {
3293       set_breakpoint_count (breakpoint_count + 1);
3294       b->number = breakpoint_count;
3295     }
3296 }
3297
3298 static struct breakpoint *
3299 create_internal_breakpoint (struct gdbarch *gdbarch,
3300                             CORE_ADDR address, enum bptype type,
3301                             const struct breakpoint_ops *ops)
3302 {
3303   struct symtab_and_line sal;
3304   struct breakpoint *b;
3305
3306   init_sal (&sal);              /* Initialize to zeroes.  */
3307
3308   sal.pc = address;
3309   sal.section = find_pc_overlay (sal.pc);
3310   sal.pspace = current_program_space;
3311
3312   b = set_raw_breakpoint (gdbarch, sal, type, ops);
3313   b->number = internal_breakpoint_number--;
3314   b->disposition = disp_donttouch;
3315
3316   return b;
3317 }
3318
3319 static const char *const longjmp_names[] =
3320   {
3321     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
3322   };
3323 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
3324
3325 /* Per-objfile data private to breakpoint.c.  */
3326 struct breakpoint_objfile_data
3327 {
3328   /* Minimal symbol for "_ovly_debug_event" (if any).  */
3329   struct bound_minimal_symbol overlay_msym;
3330
3331   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
3332   struct bound_minimal_symbol longjmp_msym[NUM_LONGJMP_NAMES];
3333
3334   /* True if we have looked for longjmp probes.  */
3335   int longjmp_searched;
3336
3337   /* SystemTap probe points for longjmp (if any).  */
3338   VEC (probe_p) *longjmp_probes;
3339
3340   /* Minimal symbol for "std::terminate()" (if any).  */
3341   struct bound_minimal_symbol terminate_msym;
3342
3343   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
3344   struct bound_minimal_symbol exception_msym;
3345
3346   /* True if we have looked for exception probes.  */
3347   int exception_searched;
3348
3349   /* SystemTap probe points for unwinding (if any).  */
3350   VEC (probe_p) *exception_probes;
3351 };
3352
3353 static const struct objfile_data *breakpoint_objfile_key;
3354
3355 /* Minimal symbol not found sentinel.  */
3356 static struct minimal_symbol msym_not_found;
3357
3358 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
3359
3360 static int
3361 msym_not_found_p (const struct minimal_symbol *msym)
3362 {
3363   return msym == &msym_not_found;
3364 }
3365
3366 /* Return per-objfile data needed by breakpoint.c.
3367    Allocate the data if necessary.  */
3368
3369 static struct breakpoint_objfile_data *
3370 get_breakpoint_objfile_data (struct objfile *objfile)
3371 {
3372   struct breakpoint_objfile_data *bp_objfile_data;
3373
3374   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
3375   if (bp_objfile_data == NULL)
3376     {
3377       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
3378                                        sizeof (*bp_objfile_data));
3379
3380       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
3381       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
3382     }
3383   return bp_objfile_data;
3384 }
3385
3386 static void
3387 free_breakpoint_probes (struct objfile *obj, void *data)
3388 {
3389   struct breakpoint_objfile_data *bp_objfile_data = data;
3390
3391   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
3392   VEC_free (probe_p, bp_objfile_data->exception_probes);
3393 }
3394
3395 static void
3396 create_overlay_event_breakpoint (void)
3397 {
3398   struct objfile *objfile;
3399   const char *const func_name = "_ovly_debug_event";
3400
3401   ALL_OBJFILES (objfile)
3402     {
3403       struct breakpoint *b;
3404       struct breakpoint_objfile_data *bp_objfile_data;
3405       CORE_ADDR addr;
3406
3407       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3408
3409       if (msym_not_found_p (bp_objfile_data->overlay_msym.minsym))
3410         continue;
3411
3412       if (bp_objfile_data->overlay_msym.minsym == NULL)
3413         {
3414           struct bound_minimal_symbol m;
3415
3416           m = lookup_minimal_symbol_text (func_name, objfile);
3417           if (m.minsym == NULL)
3418             {
3419               /* Avoid future lookups in this objfile.  */
3420               bp_objfile_data->overlay_msym.minsym = &msym_not_found;
3421               continue;
3422             }
3423           bp_objfile_data->overlay_msym = m;
3424         }
3425
3426       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
3427       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3428                                       bp_overlay_event,
3429                                       &internal_breakpoint_ops);
3430       b->addr_string = xstrdup (func_name);
3431
3432       if (overlay_debugging == ovly_auto)
3433         {
3434           b->enable_state = bp_enabled;
3435           overlay_events_enabled = 1;
3436         }
3437       else
3438        {
3439          b->enable_state = bp_disabled;
3440          overlay_events_enabled = 0;
3441        }
3442     }
3443   update_global_location_list (UGLL_MAY_INSERT);
3444 }
3445
3446 static void
3447 create_longjmp_master_breakpoint (void)
3448 {
3449   struct program_space *pspace;
3450   struct cleanup *old_chain;
3451
3452   old_chain = save_current_program_space ();
3453
3454   ALL_PSPACES (pspace)
3455   {
3456     struct objfile *objfile;
3457
3458     set_current_program_space (pspace);
3459
3460     ALL_OBJFILES (objfile)
3461     {
3462       int i;
3463       struct gdbarch *gdbarch;
3464       struct breakpoint_objfile_data *bp_objfile_data;
3465
3466       gdbarch = get_objfile_arch (objfile);
3467
3468       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3469
3470       if (!bp_objfile_data->longjmp_searched)
3471         {
3472           VEC (probe_p) *ret;
3473
3474           ret = find_probes_in_objfile (objfile, "libc", "longjmp");
3475           if (ret != NULL)
3476             {
3477               /* We are only interested in checking one element.  */
3478               struct probe *p = VEC_index (probe_p, ret, 0);
3479
3480               if (!can_evaluate_probe_arguments (p))
3481                 {
3482                   /* We cannot use the probe interface here, because it does
3483                      not know how to evaluate arguments.  */
3484                   VEC_free (probe_p, ret);
3485                   ret = NULL;
3486                 }
3487             }
3488           bp_objfile_data->longjmp_probes = ret;
3489           bp_objfile_data->longjmp_searched = 1;
3490         }
3491
3492       if (bp_objfile_data->longjmp_probes != NULL)
3493         {
3494           int i;
3495           struct probe *probe;
3496           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3497
3498           for (i = 0;
3499                VEC_iterate (probe_p,
3500                             bp_objfile_data->longjmp_probes,
3501                             i, probe);
3502                ++i)
3503             {
3504               struct breakpoint *b;
3505
3506               b = create_internal_breakpoint (gdbarch,
3507                                               get_probe_address (probe,
3508                                                                  objfile),
3509                                               bp_longjmp_master,
3510                                               &internal_breakpoint_ops);
3511               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
3512               b->enable_state = bp_disabled;
3513             }
3514
3515           continue;
3516         }
3517
3518       if (!gdbarch_get_longjmp_target_p (gdbarch))
3519         continue;
3520
3521       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
3522         {
3523           struct breakpoint *b;
3524           const char *func_name;
3525           CORE_ADDR addr;
3526
3527           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i].minsym))
3528             continue;
3529
3530           func_name = longjmp_names[i];
3531           if (bp_objfile_data->longjmp_msym[i].minsym == NULL)
3532             {
3533               struct bound_minimal_symbol m;
3534
3535               m = lookup_minimal_symbol_text (func_name, objfile);
3536               if (m.minsym == NULL)
3537                 {
3538                   /* Prevent future lookups in this objfile.  */
3539                   bp_objfile_data->longjmp_msym[i].minsym = &msym_not_found;
3540                   continue;
3541                 }
3542               bp_objfile_data->longjmp_msym[i] = m;
3543             }
3544
3545           addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
3546           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
3547                                           &internal_breakpoint_ops);
3548           b->addr_string = xstrdup (func_name);
3549           b->enable_state = bp_disabled;
3550         }
3551     }
3552   }
3553   update_global_location_list (UGLL_MAY_INSERT);
3554
3555   do_cleanups (old_chain);
3556 }
3557
3558 /* Create a master std::terminate breakpoint.  */
3559 static void
3560 create_std_terminate_master_breakpoint (void)
3561 {
3562   struct program_space *pspace;
3563   struct cleanup *old_chain;
3564   const char *const func_name = "std::terminate()";
3565
3566   old_chain = save_current_program_space ();
3567
3568   ALL_PSPACES (pspace)
3569   {
3570     struct objfile *objfile;
3571     CORE_ADDR addr;
3572
3573     set_current_program_space (pspace);
3574
3575     ALL_OBJFILES (objfile)
3576     {
3577       struct breakpoint *b;
3578       struct breakpoint_objfile_data *bp_objfile_data;
3579
3580       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3581
3582       if (msym_not_found_p (bp_objfile_data->terminate_msym.minsym))
3583         continue;
3584
3585       if (bp_objfile_data->terminate_msym.minsym == NULL)
3586         {
3587           struct bound_minimal_symbol m;
3588
3589           m = lookup_minimal_symbol (func_name, NULL, objfile);
3590           if (m.minsym == NULL || (MSYMBOL_TYPE (m.minsym) != mst_text
3591                                    && MSYMBOL_TYPE (m.minsym) != mst_file_text))
3592             {
3593               /* Prevent future lookups in this objfile.  */
3594               bp_objfile_data->terminate_msym.minsym = &msym_not_found;
3595               continue;
3596             }
3597           bp_objfile_data->terminate_msym = m;
3598         }
3599
3600       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3601       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3602                                       bp_std_terminate_master,
3603                                       &internal_breakpoint_ops);
3604       b->addr_string = xstrdup (func_name);
3605       b->enable_state = bp_disabled;
3606     }
3607   }
3608
3609   update_global_location_list (UGLL_MAY_INSERT);
3610
3611   do_cleanups (old_chain);
3612 }
3613
3614 /* Install a master breakpoint on the unwinder's debug hook.  */
3615
3616 static void
3617 create_exception_master_breakpoint (void)
3618 {
3619   struct objfile *objfile;
3620   const char *const func_name = "_Unwind_DebugHook";
3621
3622   ALL_OBJFILES (objfile)
3623     {
3624       struct breakpoint *b;
3625       struct gdbarch *gdbarch;
3626       struct breakpoint_objfile_data *bp_objfile_data;
3627       CORE_ADDR addr;
3628
3629       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3630
3631       /* We prefer the SystemTap probe point if it exists.  */
3632       if (!bp_objfile_data->exception_searched)
3633         {
3634           VEC (probe_p) *ret;
3635
3636           ret = find_probes_in_objfile (objfile, "libgcc", "unwind");
3637
3638           if (ret != NULL)
3639             {
3640               /* We are only interested in checking one element.  */
3641               struct probe *p = VEC_index (probe_p, ret, 0);
3642
3643               if (!can_evaluate_probe_arguments (p))
3644                 {
3645                   /* We cannot use the probe interface here, because it does
3646                      not know how to evaluate arguments.  */
3647                   VEC_free (probe_p, ret);
3648                   ret = NULL;
3649                 }
3650             }
3651           bp_objfile_data->exception_probes = ret;
3652           bp_objfile_data->exception_searched = 1;
3653         }
3654
3655       if (bp_objfile_data->exception_probes != NULL)
3656         {
3657           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3658           int i;
3659           struct probe *probe;
3660
3661           for (i = 0;
3662                VEC_iterate (probe_p,
3663                             bp_objfile_data->exception_probes,
3664                             i, probe);
3665                ++i)
3666             {
3667               struct breakpoint *b;
3668
3669               b = create_internal_breakpoint (gdbarch,
3670                                               get_probe_address (probe,
3671                                                                  objfile),
3672                                               bp_exception_master,
3673                                               &internal_breakpoint_ops);
3674               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3675               b->enable_state = bp_disabled;
3676             }
3677
3678           continue;
3679         }
3680
3681       /* Otherwise, try the hook function.  */
3682
3683       if (msym_not_found_p (bp_objfile_data->exception_msym.minsym))
3684         continue;
3685
3686       gdbarch = get_objfile_arch (objfile);
3687
3688       if (bp_objfile_data->exception_msym.minsym == NULL)
3689         {
3690           struct bound_minimal_symbol debug_hook;
3691
3692           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3693           if (debug_hook.minsym == NULL)
3694             {
3695               bp_objfile_data->exception_msym.minsym = &msym_not_found;
3696               continue;
3697             }
3698
3699           bp_objfile_data->exception_msym = debug_hook;
3700         }
3701
3702       addr = BMSYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3703       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3704                                                  &current_target);
3705       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3706                                       &internal_breakpoint_ops);
3707       b->addr_string = xstrdup (func_name);
3708       b->enable_state = bp_disabled;
3709     }
3710
3711   update_global_location_list (UGLL_MAY_INSERT);
3712 }
3713
3714 void
3715 update_breakpoints_after_exec (void)
3716 {
3717   struct breakpoint *b, *b_tmp;
3718   struct bp_location *bploc, **bplocp_tmp;
3719
3720   /* We're about to delete breakpoints from GDB's lists.  If the
3721      INSERTED flag is true, GDB will try to lift the breakpoints by
3722      writing the breakpoints' "shadow contents" back into memory.  The
3723      "shadow contents" are NOT valid after an exec, so GDB should not
3724      do that.  Instead, the target is responsible from marking
3725      breakpoints out as soon as it detects an exec.  We don't do that
3726      here instead, because there may be other attempts to delete
3727      breakpoints after detecting an exec and before reaching here.  */
3728   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3729     if (bploc->pspace == current_program_space)
3730       gdb_assert (!bploc->inserted);
3731
3732   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3733   {
3734     if (b->pspace != current_program_space)
3735       continue;
3736
3737     /* Solib breakpoints must be explicitly reset after an exec().  */
3738     if (b->type == bp_shlib_event)
3739       {
3740         delete_breakpoint (b);
3741         continue;
3742       }
3743
3744     /* JIT breakpoints must be explicitly reset after an exec().  */
3745     if (b->type == bp_jit_event)
3746       {
3747         delete_breakpoint (b);
3748         continue;
3749       }
3750
3751     /* Thread event breakpoints must be set anew after an exec(),
3752        as must overlay event and longjmp master breakpoints.  */
3753     if (b->type == bp_thread_event || b->type == bp_overlay_event
3754         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3755         || b->type == bp_exception_master)
3756       {
3757         delete_breakpoint (b);
3758         continue;
3759       }
3760
3761     /* Step-resume breakpoints are meaningless after an exec().  */
3762     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3763       {
3764         delete_breakpoint (b);
3765         continue;
3766       }
3767
3768     /* Longjmp and longjmp-resume breakpoints are also meaningless
3769        after an exec.  */
3770     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3771         || b->type == bp_longjmp_call_dummy
3772         || b->type == bp_exception || b->type == bp_exception_resume)
3773       {
3774         delete_breakpoint (b);
3775         continue;
3776       }
3777
3778     if (b->type == bp_catchpoint)
3779       {
3780         /* For now, none of the bp_catchpoint breakpoints need to
3781            do anything at this point.  In the future, if some of
3782            the catchpoints need to something, we will need to add
3783            a new method, and call this method from here.  */
3784         continue;
3785       }
3786
3787     /* bp_finish is a special case.  The only way we ought to be able
3788        to see one of these when an exec() has happened, is if the user
3789        caught a vfork, and then said "finish".  Ordinarily a finish just
3790        carries them to the call-site of the current callee, by setting
3791        a temporary bp there and resuming.  But in this case, the finish
3792        will carry them entirely through the vfork & exec.
3793
3794        We don't want to allow a bp_finish to remain inserted now.  But
3795        we can't safely delete it, 'cause finish_command has a handle to
3796        the bp on a bpstat, and will later want to delete it.  There's a
3797        chance (and I've seen it happen) that if we delete the bp_finish
3798        here, that its storage will get reused by the time finish_command
3799        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3800        We really must allow finish_command to delete a bp_finish.
3801
3802        In the absence of a general solution for the "how do we know
3803        it's safe to delete something others may have handles to?"
3804        problem, what we'll do here is just uninsert the bp_finish, and
3805        let finish_command delete it.
3806
3807        (We know the bp_finish is "doomed" in the sense that it's
3808        momentary, and will be deleted as soon as finish_command sees
3809        the inferior stopped.  So it doesn't matter that the bp's
3810        address is probably bogus in the new a.out, unlike e.g., the
3811        solib breakpoints.)  */
3812
3813     if (b->type == bp_finish)
3814       {
3815         continue;
3816       }
3817
3818     /* Without a symbolic address, we have little hope of the
3819        pre-exec() address meaning the same thing in the post-exec()
3820        a.out.  */
3821     if (b->addr_string == NULL)
3822       {
3823         delete_breakpoint (b);
3824         continue;
3825       }
3826   }
3827   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3828   create_overlay_event_breakpoint ();
3829   create_longjmp_master_breakpoint ();
3830   create_std_terminate_master_breakpoint ();
3831   create_exception_master_breakpoint ();
3832 }
3833
3834 int
3835 detach_breakpoints (ptid_t ptid)
3836 {
3837   struct bp_location *bl, **blp_tmp;
3838   int val = 0;
3839   struct cleanup *old_chain = save_inferior_ptid ();
3840   struct inferior *inf = current_inferior ();
3841
3842   if (ptid_get_pid (ptid) == ptid_get_pid (inferior_ptid))
3843     error (_("Cannot detach breakpoints of inferior_ptid"));
3844
3845   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3846   inferior_ptid = ptid;
3847   ALL_BP_LOCATIONS (bl, blp_tmp)
3848   {
3849     if (bl->pspace != inf->pspace)
3850       continue;
3851
3852     /* This function must physically remove breakpoints locations
3853        from the specified ptid, without modifying the breakpoint
3854        package's state.  Locations of type bp_loc_other are only
3855        maintained at GDB side.  So, there is no need to remove
3856        these bp_loc_other locations.  Moreover, removing these
3857        would modify the breakpoint package's state.  */
3858     if (bl->loc_type == bp_loc_other)
3859       continue;
3860
3861     if (bl->inserted)
3862       val |= remove_breakpoint_1 (bl, mark_inserted);
3863   }
3864
3865   /* Detach single-step breakpoints as well.  */
3866   detach_single_step_breakpoints ();
3867
3868   do_cleanups (old_chain);
3869   return val;
3870 }
3871
3872 /* Remove the breakpoint location BL from the current address space.
3873    Note that this is used to detach breakpoints from a child fork.
3874    When we get here, the child isn't in the inferior list, and neither
3875    do we have objects to represent its address space --- we should
3876    *not* look at bl->pspace->aspace here.  */
3877
3878 static int
3879 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3880 {
3881   int val;
3882
3883   /* BL is never in moribund_locations by our callers.  */
3884   gdb_assert (bl->owner != NULL);
3885
3886   if (bl->owner->enable_state == bp_permanent)
3887     /* Permanent breakpoints cannot be inserted or removed.  */
3888     return 0;
3889
3890   /* The type of none suggests that owner is actually deleted.
3891      This should not ever happen.  */
3892   gdb_assert (bl->owner->type != bp_none);
3893
3894   if (bl->loc_type == bp_loc_software_breakpoint
3895       || bl->loc_type == bp_loc_hardware_breakpoint)
3896     {
3897       /* "Normal" instruction breakpoint: either the standard
3898          trap-instruction bp (bp_breakpoint), or a
3899          bp_hardware_breakpoint.  */
3900
3901       /* First check to see if we have to handle an overlay.  */
3902       if (overlay_debugging == ovly_off
3903           || bl->section == NULL
3904           || !(section_is_overlay (bl->section)))
3905         {
3906           /* No overlay handling: just remove the breakpoint.  */
3907
3908           /* If we're trying to uninsert a memory breakpoint that we
3909              know is set in a dynamic object that is marked
3910              shlib_disabled, then either the dynamic object was
3911              removed with "remove-symbol-file" or with
3912              "nosharedlibrary".  In the former case, we don't know
3913              whether another dynamic object might have loaded over the
3914              breakpoint's address -- the user might well let us know
3915              about it next with add-symbol-file (the whole point of
3916              add-symbol-file is letting the user manually maintain a
3917              list of dynamically loaded objects).  If we have the
3918              breakpoint's shadow memory, that is, this is a software
3919              breakpoint managed by GDB, check whether the breakpoint
3920              is still inserted in memory, to avoid overwriting wrong
3921              code with stale saved shadow contents.  Note that HW
3922              breakpoints don't have shadow memory, as they're
3923              implemented using a mechanism that is not dependent on
3924              being able to modify the target's memory, and as such
3925              they should always be removed.  */
3926           if (bl->shlib_disabled
3927               && bl->target_info.shadow_len != 0
3928               && !memory_validate_breakpoint (bl->gdbarch, &bl->target_info))
3929             val = 0;
3930           else
3931             val = bl->owner->ops->remove_location (bl);
3932         }
3933       else
3934         {
3935           /* This breakpoint is in an overlay section.
3936              Did we set a breakpoint at the LMA?  */
3937           if (!overlay_events_enabled)
3938               {
3939                 /* Yes -- overlay event support is not active, so we
3940                    should have set a breakpoint at the LMA.  Remove it.  
3941                 */
3942                 /* Ignore any failures: if the LMA is in ROM, we will
3943                    have already warned when we failed to insert it.  */
3944                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3945                   target_remove_hw_breakpoint (bl->gdbarch,
3946                                                &bl->overlay_target_info);
3947                 else
3948                   target_remove_breakpoint (bl->gdbarch,
3949                                             &bl->overlay_target_info);
3950               }
3951           /* Did we set a breakpoint at the VMA? 
3952              If so, we will have marked the breakpoint 'inserted'.  */
3953           if (bl->inserted)
3954             {
3955               /* Yes -- remove it.  Previously we did not bother to
3956                  remove the breakpoint if the section had been
3957                  unmapped, but let's not rely on that being safe.  We
3958                  don't know what the overlay manager might do.  */
3959
3960               /* However, we should remove *software* breakpoints only
3961                  if the section is still mapped, or else we overwrite
3962                  wrong code with the saved shadow contents.  */
3963               if (bl->loc_type == bp_loc_hardware_breakpoint
3964                   || section_is_mapped (bl->section))
3965                 val = bl->owner->ops->remove_location (bl);
3966               else
3967                 val = 0;
3968             }
3969           else
3970             {
3971               /* No -- not inserted, so no need to remove.  No error.  */
3972               val = 0;
3973             }
3974         }
3975
3976       /* In some cases, we might not be able to remove a breakpoint in
3977          a shared library that has already been removed, but we have
3978          not yet processed the shlib unload event.  Similarly for an
3979          unloaded add-symbol-file object - the user might not yet have
3980          had the chance to remove-symbol-file it.  shlib_disabled will
3981          be set if the library/object has already been removed, but
3982          the breakpoint hasn't been uninserted yet, e.g., after
3983          "nosharedlibrary" or "remove-symbol-file" with breakpoints
3984          always-inserted mode.  */
3985       if (val
3986           && (bl->loc_type == bp_loc_software_breakpoint
3987               && (bl->shlib_disabled
3988                   || solib_name_from_address (bl->pspace, bl->address)
3989                   || shared_objfile_contains_address_p (bl->pspace,
3990                                                         bl->address))))
3991         val = 0;
3992
3993       if (val)
3994         return val;
3995       bl->inserted = (is == mark_inserted);
3996     }
3997   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3998     {
3999       gdb_assert (bl->owner->ops != NULL
4000                   && bl->owner->ops->remove_location != NULL);
4001
4002       bl->inserted = (is == mark_inserted);
4003       bl->owner->ops->remove_location (bl);
4004
4005       /* Failure to remove any of the hardware watchpoints comes here.  */
4006       if ((is == mark_uninserted) && (bl->inserted))
4007         warning (_("Could not remove hardware watchpoint %d."),
4008                  bl->owner->number);
4009     }
4010   else if (bl->owner->type == bp_catchpoint
4011            && breakpoint_enabled (bl->owner)
4012            && !bl->duplicate)
4013     {
4014       gdb_assert (bl->owner->ops != NULL
4015                   && bl->owner->ops->remove_location != NULL);
4016
4017       val = bl->owner->ops->remove_location (bl);
4018       if (val)
4019         return val;
4020
4021       bl->inserted = (is == mark_inserted);
4022     }
4023
4024   return 0;
4025 }
4026
4027 static int
4028 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
4029 {
4030   int ret;
4031   struct cleanup *old_chain;
4032
4033   /* BL is never in moribund_locations by our callers.  */
4034   gdb_assert (bl->owner != NULL);
4035
4036   if (bl->owner->enable_state == bp_permanent)
4037     /* Permanent breakpoints cannot be inserted or removed.  */
4038     return 0;
4039
4040   /* The type of none suggests that owner is actually deleted.
4041      This should not ever happen.  */
4042   gdb_assert (bl->owner->type != bp_none);
4043
4044   old_chain = save_current_space_and_thread ();
4045
4046   switch_to_program_space_and_thread (bl->pspace);
4047
4048   ret = remove_breakpoint_1 (bl, is);
4049
4050   do_cleanups (old_chain);
4051   return ret;
4052 }
4053
4054 /* Clear the "inserted" flag in all breakpoints.  */
4055
4056 void
4057 mark_breakpoints_out (void)
4058 {
4059   struct bp_location *bl, **blp_tmp;
4060
4061   ALL_BP_LOCATIONS (bl, blp_tmp)
4062     if (bl->pspace == current_program_space)
4063       bl->inserted = 0;
4064 }
4065
4066 /* Clear the "inserted" flag in all breakpoints and delete any
4067    breakpoints which should go away between runs of the program.
4068
4069    Plus other such housekeeping that has to be done for breakpoints
4070    between runs.
4071
4072    Note: this function gets called at the end of a run (by
4073    generic_mourn_inferior) and when a run begins (by
4074    init_wait_for_inferior).  */
4075
4076
4077
4078 void
4079 breakpoint_init_inferior (enum inf_context context)
4080 {
4081   struct breakpoint *b, *b_tmp;
4082   struct bp_location *bl, **blp_tmp;
4083   int ix;
4084   struct program_space *pspace = current_program_space;
4085
4086   /* If breakpoint locations are shared across processes, then there's
4087      nothing to do.  */
4088   if (gdbarch_has_global_breakpoints (target_gdbarch ()))
4089     return;
4090
4091   ALL_BP_LOCATIONS (bl, blp_tmp)
4092   {
4093     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4094     if (bl->pspace == pspace
4095         && bl->owner->enable_state != bp_permanent)
4096       bl->inserted = 0;
4097   }
4098
4099   ALL_BREAKPOINTS_SAFE (b, b_tmp)
4100   {
4101     if (b->loc && b->loc->pspace != pspace)
4102       continue;
4103
4104     switch (b->type)
4105       {
4106       case bp_call_dummy:
4107       case bp_longjmp_call_dummy:
4108
4109         /* If the call dummy breakpoint is at the entry point it will
4110            cause problems when the inferior is rerun, so we better get
4111            rid of it.  */
4112
4113       case bp_watchpoint_scope:
4114
4115         /* Also get rid of scope breakpoints.  */
4116
4117       case bp_shlib_event:
4118
4119         /* Also remove solib event breakpoints.  Their addresses may
4120            have changed since the last time we ran the program.
4121            Actually we may now be debugging against different target;
4122            and so the solib backend that installed this breakpoint may
4123            not be used in by the target.  E.g.,
4124
4125            (gdb) file prog-linux
4126            (gdb) run               # native linux target
4127            ...
4128            (gdb) kill
4129            (gdb) file prog-win.exe
4130            (gdb) tar rem :9999     # remote Windows gdbserver.
4131         */
4132
4133       case bp_step_resume:
4134
4135         /* Also remove step-resume breakpoints.  */
4136
4137         delete_breakpoint (b);
4138         break;
4139
4140       case bp_watchpoint:
4141       case bp_hardware_watchpoint:
4142       case bp_read_watchpoint:
4143       case bp_access_watchpoint:
4144         {
4145           struct watchpoint *w = (struct watchpoint *) b;
4146
4147           /* Likewise for watchpoints on local expressions.  */
4148           if (w->exp_valid_block != NULL)
4149             delete_breakpoint (b);
4150           else if (context == inf_starting)
4151             {
4152               /* Reset val field to force reread of starting value in
4153                  insert_breakpoints.  */
4154               if (w->val)
4155                 value_free (w->val);
4156               w->val = NULL;
4157               w->val_valid = 0;
4158           }
4159         }
4160         break;
4161       default:
4162         break;
4163       }
4164   }
4165
4166   /* Get rid of the moribund locations.  */
4167   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
4168     decref_bp_location (&bl);
4169   VEC_free (bp_location_p, moribund_locations);
4170 }
4171
4172 /* These functions concern about actual breakpoints inserted in the
4173    target --- to e.g. check if we need to do decr_pc adjustment or if
4174    we need to hop over the bkpt --- so we check for address space
4175    match, not program space.  */
4176
4177 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
4178    exists at PC.  It returns ordinary_breakpoint_here if it's an
4179    ordinary breakpoint, or permanent_breakpoint_here if it's a
4180    permanent breakpoint.
4181    - When continuing from a location with an ordinary breakpoint, we
4182      actually single step once before calling insert_breakpoints.
4183    - When continuing from a location with a permanent breakpoint, we
4184      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
4185      the target, to advance the PC past the breakpoint.  */
4186
4187 enum breakpoint_here
4188 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4189 {
4190   struct bp_location *bl, **blp_tmp;
4191   int any_breakpoint_here = 0;
4192
4193   ALL_BP_LOCATIONS (bl, blp_tmp)
4194     {
4195       if (bl->loc_type != bp_loc_software_breakpoint
4196           && bl->loc_type != bp_loc_hardware_breakpoint)
4197         continue;
4198
4199       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
4200       if ((breakpoint_enabled (bl->owner)
4201            || bl->owner->enable_state == bp_permanent)
4202           && breakpoint_location_address_match (bl, aspace, pc))
4203         {
4204           if (overlay_debugging 
4205               && section_is_overlay (bl->section)
4206               && !section_is_mapped (bl->section))
4207             continue;           /* unmapped overlay -- can't be a match */
4208           else if (bl->owner->enable_state == bp_permanent)
4209             return permanent_breakpoint_here;
4210           else
4211             any_breakpoint_here = 1;
4212         }
4213     }
4214
4215   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
4216 }
4217
4218 /* Return true if there's a moribund breakpoint at PC.  */
4219
4220 int
4221 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
4222 {
4223   struct bp_location *loc;
4224   int ix;
4225
4226   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4227     if (breakpoint_location_address_match (loc, aspace, pc))
4228       return 1;
4229
4230   return 0;
4231 }
4232
4233 /* Returns non-zero if there's a breakpoint inserted at PC, which is
4234    inserted using regular breakpoint_chain / bp_location array
4235    mechanism.  This does not check for single-step breakpoints, which
4236    are inserted and removed using direct target manipulation.  */
4237
4238 int
4239 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
4240                                     CORE_ADDR pc)
4241 {
4242   struct bp_location *bl, **blp_tmp;
4243
4244   ALL_BP_LOCATIONS (bl, blp_tmp)
4245     {
4246       if (bl->loc_type != bp_loc_software_breakpoint
4247           && bl->loc_type != bp_loc_hardware_breakpoint)
4248         continue;
4249
4250       if (bl->inserted
4251           && breakpoint_location_address_match (bl, aspace, pc))
4252         {
4253           if (overlay_debugging 
4254               && section_is_overlay (bl->section)
4255               && !section_is_mapped (bl->section))
4256             continue;           /* unmapped overlay -- can't be a match */
4257           else
4258             return 1;
4259         }
4260     }
4261   return 0;
4262 }
4263
4264 /* Returns non-zero iff there's either regular breakpoint
4265    or a single step breakpoint inserted at PC.  */
4266
4267 int
4268 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
4269 {
4270   if (regular_breakpoint_inserted_here_p (aspace, pc))
4271     return 1;
4272
4273   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4274     return 1;
4275
4276   return 0;
4277 }
4278
4279 /* Ignoring deprecated raw breakpoints, return non-zero iff there is a
4280    software breakpoint inserted at PC.  */
4281
4282 static struct bp_location *
4283 find_non_raw_software_breakpoint_inserted_here (struct address_space *aspace,
4284                                                 CORE_ADDR pc)
4285 {
4286   struct bp_location *bl, **blp_tmp;
4287
4288   ALL_BP_LOCATIONS (bl, blp_tmp)
4289     {
4290       if (bl->loc_type != bp_loc_software_breakpoint)
4291         continue;
4292
4293       if (bl->inserted
4294           && breakpoint_address_match (bl->pspace->aspace, bl->address,
4295                                        aspace, pc))
4296         {
4297           if (overlay_debugging 
4298               && section_is_overlay (bl->section)
4299               && !section_is_mapped (bl->section))
4300             continue;           /* unmapped overlay -- can't be a match */
4301           else
4302             return bl;
4303         }
4304     }
4305
4306   return NULL;
4307 }
4308
4309 /* This function returns non-zero iff there is a software breakpoint
4310    inserted at PC.  */
4311
4312 int
4313 software_breakpoint_inserted_here_p (struct address_space *aspace,
4314                                      CORE_ADDR pc)
4315 {
4316   if (find_non_raw_software_breakpoint_inserted_here (aspace, pc) != NULL)
4317     return 1;
4318
4319   /* Also check for software single-step breakpoints.  */
4320   if (single_step_breakpoint_inserted_here_p (aspace, pc))
4321     return 1;
4322
4323   return 0;
4324 }
4325
4326 int
4327 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
4328                                        CORE_ADDR addr, ULONGEST len)
4329 {
4330   struct breakpoint *bpt;
4331
4332   ALL_BREAKPOINTS (bpt)
4333     {
4334       struct bp_location *loc;
4335
4336       if (bpt->type != bp_hardware_watchpoint
4337           && bpt->type != bp_access_watchpoint)
4338         continue;
4339
4340       if (!breakpoint_enabled (bpt))
4341         continue;
4342
4343       for (loc = bpt->loc; loc; loc = loc->next)
4344         if (loc->pspace->aspace == aspace && loc->inserted)
4345           {
4346             CORE_ADDR l, h;
4347
4348             /* Check for intersection.  */
4349             l = max (loc->address, addr);
4350             h = min (loc->address + loc->length, addr + len);
4351             if (l < h)
4352               return 1;
4353           }
4354     }
4355   return 0;
4356 }
4357
4358 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
4359    PC is valid for process/thread PTID.  */
4360
4361 int
4362 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
4363                          ptid_t ptid)
4364 {
4365   struct bp_location *bl, **blp_tmp;
4366   /* The thread and task IDs associated to PTID, computed lazily.  */
4367   int thread = -1;
4368   int task = 0;
4369   
4370   ALL_BP_LOCATIONS (bl, blp_tmp)
4371     {
4372       if (bl->loc_type != bp_loc_software_breakpoint
4373           && bl->loc_type != bp_loc_hardware_breakpoint)
4374         continue;
4375
4376       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
4377       if (!breakpoint_enabled (bl->owner)
4378           && bl->owner->enable_state != bp_permanent)
4379         continue;
4380
4381       if (!breakpoint_location_address_match (bl, aspace, pc))
4382         continue;
4383
4384       if (bl->owner->thread != -1)
4385         {
4386           /* This is a thread-specific breakpoint.  Check that ptid
4387              matches that thread.  If thread hasn't been computed yet,
4388              it is now time to do so.  */
4389           if (thread == -1)
4390             thread = pid_to_thread_id (ptid);
4391           if (bl->owner->thread != thread)
4392             continue;
4393         }
4394
4395       if (bl->owner->task != 0)
4396         {
4397           /* This is a task-specific breakpoint.  Check that ptid
4398              matches that task.  If task hasn't been computed yet,
4399              it is now time to do so.  */
4400           if (task == 0)
4401             task = ada_get_task_number (ptid);
4402           if (bl->owner->task != task)
4403             continue;
4404         }
4405
4406       if (overlay_debugging 
4407           && section_is_overlay (bl->section)
4408           && !section_is_mapped (bl->section))
4409         continue;           /* unmapped overlay -- can't be a match */
4410
4411       return 1;
4412     }
4413
4414   return 0;
4415 }
4416 \f
4417
4418 /* bpstat stuff.  External routines' interfaces are documented
4419    in breakpoint.h.  */
4420
4421 int
4422 is_catchpoint (struct breakpoint *ep)
4423 {
4424   return (ep->type == bp_catchpoint);
4425 }
4426
4427 /* Frees any storage that is part of a bpstat.  Does not walk the
4428    'next' chain.  */
4429
4430 static void
4431 bpstat_free (bpstat bs)
4432 {
4433   if (bs->old_val != NULL)
4434     value_free (bs->old_val);
4435   decref_counted_command_line (&bs->commands);
4436   decref_bp_location (&bs->bp_location_at);
4437   xfree (bs);
4438 }
4439
4440 /* Clear a bpstat so that it says we are not at any breakpoint.
4441    Also free any storage that is part of a bpstat.  */
4442
4443 void
4444 bpstat_clear (bpstat *bsp)
4445 {
4446   bpstat p;
4447   bpstat q;
4448
4449   if (bsp == 0)
4450     return;
4451   p = *bsp;
4452   while (p != NULL)
4453     {
4454       q = p->next;
4455       bpstat_free (p);
4456       p = q;
4457     }
4458   *bsp = NULL;
4459 }
4460
4461 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
4462    is part of the bpstat is copied as well.  */
4463
4464 bpstat
4465 bpstat_copy (bpstat bs)
4466 {
4467   bpstat p = NULL;
4468   bpstat tmp;
4469   bpstat retval = NULL;
4470
4471   if (bs == NULL)
4472     return bs;
4473
4474   for (; bs != NULL; bs = bs->next)
4475     {
4476       tmp = (bpstat) xmalloc (sizeof (*tmp));
4477       memcpy (tmp, bs, sizeof (*tmp));
4478       incref_counted_command_line (tmp->commands);
4479       incref_bp_location (tmp->bp_location_at);
4480       if (bs->old_val != NULL)
4481         {
4482           tmp->old_val = value_copy (bs->old_val);
4483           release_value (tmp->old_val);
4484         }
4485
4486       if (p == NULL)
4487         /* This is the first thing in the chain.  */
4488         retval = tmp;
4489       else
4490         p->next = tmp;
4491       p = tmp;
4492     }
4493   p->next = NULL;
4494   return retval;
4495 }
4496
4497 /* Find the bpstat associated with this breakpoint.  */
4498
4499 bpstat
4500 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
4501 {
4502   if (bsp == NULL)
4503     return NULL;
4504
4505   for (; bsp != NULL; bsp = bsp->next)
4506     {
4507       if (bsp->breakpoint_at == breakpoint)
4508         return bsp;
4509     }
4510   return NULL;
4511 }
4512
4513 /* See breakpoint.h.  */
4514
4515 int
4516 bpstat_explains_signal (bpstat bsp, enum gdb_signal sig)
4517 {
4518   for (; bsp != NULL; bsp = bsp->next)
4519     {
4520       if (bsp->breakpoint_at == NULL)
4521         {
4522           /* A moribund location can never explain a signal other than
4523              GDB_SIGNAL_TRAP.  */
4524           if (sig == GDB_SIGNAL_TRAP)
4525             return 1;
4526         }
4527       else
4528         {
4529           if (bsp->breakpoint_at->ops->explains_signal (bsp->breakpoint_at,
4530                                                         sig))
4531             return 1;
4532         }
4533     }
4534
4535   return 0;
4536 }
4537
4538 /* Put in *NUM the breakpoint number of the first breakpoint we are
4539    stopped at.  *BSP upon return is a bpstat which points to the
4540    remaining breakpoints stopped at (but which is not guaranteed to be
4541    good for anything but further calls to bpstat_num).
4542
4543    Return 0 if passed a bpstat which does not indicate any breakpoints.
4544    Return -1 if stopped at a breakpoint that has been deleted since
4545    we set it.
4546    Return 1 otherwise.  */
4547
4548 int
4549 bpstat_num (bpstat *bsp, int *num)
4550 {
4551   struct breakpoint *b;
4552
4553   if ((*bsp) == NULL)
4554     return 0;                   /* No more breakpoint values */
4555
4556   /* We assume we'll never have several bpstats that correspond to a
4557      single breakpoint -- otherwise, this function might return the
4558      same number more than once and this will look ugly.  */
4559   b = (*bsp)->breakpoint_at;
4560   *bsp = (*bsp)->next;
4561   if (b == NULL)
4562     return -1;                  /* breakpoint that's been deleted since */
4563
4564   *num = b->number;             /* We have its number */
4565   return 1;
4566 }
4567
4568 /* See breakpoint.h.  */
4569
4570 void
4571 bpstat_clear_actions (void)
4572 {
4573   struct thread_info *tp;
4574   bpstat bs;
4575
4576   if (ptid_equal (inferior_ptid, null_ptid))
4577     return;
4578
4579   tp = find_thread_ptid (inferior_ptid);
4580   if (tp == NULL)
4581     return;
4582
4583   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
4584     {
4585       decref_counted_command_line (&bs->commands);
4586
4587       if (bs->old_val != NULL)
4588         {
4589           value_free (bs->old_val);
4590           bs->old_val = NULL;
4591         }
4592     }
4593 }
4594
4595 /* Called when a command is about to proceed the inferior.  */
4596
4597 static void
4598 breakpoint_about_to_proceed (void)
4599 {
4600   if (!ptid_equal (inferior_ptid, null_ptid))
4601     {
4602       struct thread_info *tp = inferior_thread ();
4603
4604       /* Allow inferior function calls in breakpoint commands to not
4605          interrupt the command list.  When the call finishes
4606          successfully, the inferior will be standing at the same
4607          breakpoint as if nothing happened.  */
4608       if (tp->control.in_infcall)
4609         return;
4610     }
4611
4612   breakpoint_proceeded = 1;
4613 }
4614
4615 /* Stub for cleaning up our state if we error-out of a breakpoint
4616    command.  */
4617 static void
4618 cleanup_executing_breakpoints (void *ignore)
4619 {
4620   executing_breakpoint_commands = 0;
4621 }
4622
4623 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
4624    or its equivalent.  */
4625
4626 static int
4627 command_line_is_silent (struct command_line *cmd)
4628 {
4629   return cmd && (strcmp ("silent", cmd->line) == 0
4630                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
4631 }
4632
4633 /* Execute all the commands associated with all the breakpoints at
4634    this location.  Any of these commands could cause the process to
4635    proceed beyond this point, etc.  We look out for such changes by
4636    checking the global "breakpoint_proceeded" after each command.
4637
4638    Returns true if a breakpoint command resumed the inferior.  In that
4639    case, it is the caller's responsibility to recall it again with the
4640    bpstat of the current thread.  */
4641
4642 static int
4643 bpstat_do_actions_1 (bpstat *bsp)
4644 {
4645   bpstat bs;
4646   struct cleanup *old_chain;
4647   int again = 0;
4648
4649   /* Avoid endless recursion if a `source' command is contained
4650      in bs->commands.  */
4651   if (executing_breakpoint_commands)
4652     return 0;
4653
4654   executing_breakpoint_commands = 1;
4655   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
4656
4657   prevent_dont_repeat ();
4658
4659   /* This pointer will iterate over the list of bpstat's.  */
4660   bs = *bsp;
4661
4662   breakpoint_proceeded = 0;
4663   for (; bs != NULL; bs = bs->next)
4664     {
4665       struct counted_command_line *ccmd;
4666       struct command_line *cmd;
4667       struct cleanup *this_cmd_tree_chain;
4668
4669       /* Take ownership of the BSP's command tree, if it has one.
4670
4671          The command tree could legitimately contain commands like
4672          'step' and 'next', which call clear_proceed_status, which
4673          frees stop_bpstat's command tree.  To make sure this doesn't
4674          free the tree we're executing out from under us, we need to
4675          take ownership of the tree ourselves.  Since a given bpstat's
4676          commands are only executed once, we don't need to copy it; we
4677          can clear the pointer in the bpstat, and make sure we free
4678          the tree when we're done.  */
4679       ccmd = bs->commands;
4680       bs->commands = NULL;
4681       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
4682       cmd = ccmd ? ccmd->commands : NULL;
4683       if (command_line_is_silent (cmd))
4684         {
4685           /* The action has been already done by bpstat_stop_status.  */
4686           cmd = cmd->next;
4687         }
4688
4689       while (cmd != NULL)
4690         {
4691           execute_control_command (cmd);
4692
4693           if (breakpoint_proceeded)
4694             break;
4695           else
4696             cmd = cmd->next;
4697         }
4698
4699       /* We can free this command tree now.  */
4700       do_cleanups (this_cmd_tree_chain);
4701
4702       if (breakpoint_proceeded)
4703         {
4704           if (target_can_async_p ())
4705             /* If we are in async mode, then the target might be still
4706                running, not stopped at any breakpoint, so nothing for
4707                us to do here -- just return to the event loop.  */
4708             ;
4709           else
4710             /* In sync mode, when execute_control_command returns
4711                we're already standing on the next breakpoint.
4712                Breakpoint commands for that stop were not run, since
4713                execute_command does not run breakpoint commands --
4714                only command_line_handler does, but that one is not
4715                involved in execution of breakpoint commands.  So, we
4716                can now execute breakpoint commands.  It should be
4717                noted that making execute_command do bpstat actions is
4718                not an option -- in this case we'll have recursive
4719                invocation of bpstat for each breakpoint with a
4720                command, and can easily blow up GDB stack.  Instead, we
4721                return true, which will trigger the caller to recall us
4722                with the new stop_bpstat.  */
4723             again = 1;
4724           break;
4725         }
4726     }
4727   do_cleanups (old_chain);
4728   return again;
4729 }
4730
4731 void
4732 bpstat_do_actions (void)
4733 {
4734   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4735
4736   /* Do any commands attached to breakpoint we are stopped at.  */
4737   while (!ptid_equal (inferior_ptid, null_ptid)
4738          && target_has_execution
4739          && !is_exited (inferior_ptid)
4740          && !is_executing (inferior_ptid))
4741     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4742        and only return when it is stopped at the next breakpoint, we
4743        keep doing breakpoint actions until it returns false to
4744        indicate the inferior was not resumed.  */
4745     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4746       break;
4747
4748   discard_cleanups (cleanup_if_error);
4749 }
4750
4751 /* Print out the (old or new) value associated with a watchpoint.  */
4752
4753 static void
4754 watchpoint_value_print (struct value *val, struct ui_file *stream)
4755 {
4756   if (val == NULL)
4757     fprintf_unfiltered (stream, _("<unreadable>"));
4758   else
4759     {
4760       struct value_print_options opts;
4761       get_user_print_options (&opts);
4762       value_print (val, stream, &opts);
4763     }
4764 }
4765
4766 /* Generic routine for printing messages indicating why we
4767    stopped.  The behavior of this function depends on the value
4768    'print_it' in the bpstat structure.  Under some circumstances we
4769    may decide not to print anything here and delegate the task to
4770    normal_stop().  */
4771
4772 static enum print_stop_action
4773 print_bp_stop_message (bpstat bs)
4774 {
4775   switch (bs->print_it)
4776     {
4777     case print_it_noop:
4778       /* Nothing should be printed for this bpstat entry.  */
4779       return PRINT_UNKNOWN;
4780       break;
4781
4782     case print_it_done:
4783       /* We still want to print the frame, but we already printed the
4784          relevant messages.  */
4785       return PRINT_SRC_AND_LOC;
4786       break;
4787
4788     case print_it_normal:
4789       {
4790         struct breakpoint *b = bs->breakpoint_at;
4791
4792         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4793            which has since been deleted.  */
4794         if (b == NULL)
4795           return PRINT_UNKNOWN;
4796
4797         /* Normal case.  Call the breakpoint's print_it method.  */
4798         return b->ops->print_it (bs);
4799       }
4800       break;
4801
4802     default:
4803       internal_error (__FILE__, __LINE__,
4804                       _("print_bp_stop_message: unrecognized enum value"));
4805       break;
4806     }
4807 }
4808
4809 /* A helper function that prints a shared library stopped event.  */
4810
4811 static void
4812 print_solib_event (int is_catchpoint)
4813 {
4814   int any_deleted
4815     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4816   int any_added
4817     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4818
4819   if (!is_catchpoint)
4820     {
4821       if (any_added || any_deleted)
4822         ui_out_text (current_uiout,
4823                      _("Stopped due to shared library event:\n"));
4824       else
4825         ui_out_text (current_uiout,
4826                      _("Stopped due to shared library event (no "
4827                        "libraries added or removed)\n"));
4828     }
4829
4830   if (ui_out_is_mi_like_p (current_uiout))
4831     ui_out_field_string (current_uiout, "reason",
4832                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4833
4834   if (any_deleted)
4835     {
4836       struct cleanup *cleanup;
4837       char *name;
4838       int ix;
4839
4840       ui_out_text (current_uiout, _("  Inferior unloaded "));
4841       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4842                                                     "removed");
4843       for (ix = 0;
4844            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4845                         ix, name);
4846            ++ix)
4847         {
4848           if (ix > 0)
4849             ui_out_text (current_uiout, "    ");
4850           ui_out_field_string (current_uiout, "library", name);
4851           ui_out_text (current_uiout, "\n");
4852         }
4853
4854       do_cleanups (cleanup);
4855     }
4856
4857   if (any_added)
4858     {
4859       struct so_list *iter;
4860       int ix;
4861       struct cleanup *cleanup;
4862
4863       ui_out_text (current_uiout, _("  Inferior loaded "));
4864       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4865                                                     "added");
4866       for (ix = 0;
4867            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4868                         ix, iter);
4869            ++ix)
4870         {
4871           if (ix > 0)
4872             ui_out_text (current_uiout, "    ");
4873           ui_out_field_string (current_uiout, "library", iter->so_name);
4874           ui_out_text (current_uiout, "\n");
4875         }
4876
4877       do_cleanups (cleanup);
4878     }
4879 }
4880
4881 /* Print a message indicating what happened.  This is called from
4882    normal_stop().  The input to this routine is the head of the bpstat
4883    list - a list of the eventpoints that caused this stop.  KIND is
4884    the target_waitkind for the stopping event.  This
4885    routine calls the generic print routine for printing a message
4886    about reasons for stopping.  This will print (for example) the
4887    "Breakpoint n," part of the output.  The return value of this
4888    routine is one of:
4889
4890    PRINT_UNKNOWN: Means we printed nothing.
4891    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4892    code to print the location.  An example is 
4893    "Breakpoint 1, " which should be followed by
4894    the location.
4895    PRINT_SRC_ONLY: Means we printed something, but there is no need
4896    to also print the location part of the message.
4897    An example is the catch/throw messages, which
4898    don't require a location appended to the end.
4899    PRINT_NOTHING: We have done some printing and we don't need any 
4900    further info to be printed.  */
4901
4902 enum print_stop_action
4903 bpstat_print (bpstat bs, int kind)
4904 {
4905   int val;
4906
4907   /* Maybe another breakpoint in the chain caused us to stop.
4908      (Currently all watchpoints go on the bpstat whether hit or not.
4909      That probably could (should) be changed, provided care is taken
4910      with respect to bpstat_explains_signal).  */
4911   for (; bs; bs = bs->next)
4912     {
4913       val = print_bp_stop_message (bs);
4914       if (val == PRINT_SRC_ONLY 
4915           || val == PRINT_SRC_AND_LOC 
4916           || val == PRINT_NOTHING)
4917         return val;
4918     }
4919
4920   /* If we had hit a shared library event breakpoint,
4921      print_bp_stop_message would print out this message.  If we hit an
4922      OS-level shared library event, do the same thing.  */
4923   if (kind == TARGET_WAITKIND_LOADED)
4924     {
4925       print_solib_event (0);
4926       return PRINT_NOTHING;
4927     }
4928
4929   /* We reached the end of the chain, or we got a null BS to start
4930      with and nothing was printed.  */
4931   return PRINT_UNKNOWN;
4932 }
4933
4934 /* Evaluate the expression EXP and return 1 if value is zero.
4935    This returns the inverse of the condition because it is called
4936    from catch_errors which returns 0 if an exception happened, and if an
4937    exception happens we want execution to stop.
4938    The argument is a "struct expression *" that has been cast to a
4939    "void *" to make it pass through catch_errors.  */
4940
4941 static int
4942 breakpoint_cond_eval (void *exp)
4943 {
4944   struct value *mark = value_mark ();
4945   int i = !value_true (evaluate_expression ((struct expression *) exp));
4946
4947   value_free_to_mark (mark);
4948   return i;
4949 }
4950
4951 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4952
4953 static bpstat
4954 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4955 {
4956   bpstat bs;
4957
4958   bs = (bpstat) xmalloc (sizeof (*bs));
4959   bs->next = NULL;
4960   **bs_link_pointer = bs;
4961   *bs_link_pointer = &bs->next;
4962   bs->breakpoint_at = bl->owner;
4963   bs->bp_location_at = bl;
4964   incref_bp_location (bl);
4965   /* If the condition is false, etc., don't do the commands.  */
4966   bs->commands = NULL;
4967   bs->old_val = NULL;
4968   bs->print_it = print_it_normal;
4969   return bs;
4970 }
4971 \f
4972 /* The target has stopped with waitstatus WS.  Check if any hardware
4973    watchpoints have triggered, according to the target.  */
4974
4975 int
4976 watchpoints_triggered (struct target_waitstatus *ws)
4977 {
4978   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4979   CORE_ADDR addr;
4980   struct breakpoint *b;
4981
4982   if (!stopped_by_watchpoint)
4983     {
4984       /* We were not stopped by a watchpoint.  Mark all watchpoints
4985          as not triggered.  */
4986       ALL_BREAKPOINTS (b)
4987         if (is_hardware_watchpoint (b))
4988           {
4989             struct watchpoint *w = (struct watchpoint *) b;
4990
4991             w->watchpoint_triggered = watch_triggered_no;
4992           }
4993
4994       return 0;
4995     }
4996
4997   if (!target_stopped_data_address (&current_target, &addr))
4998     {
4999       /* We were stopped by a watchpoint, but we don't know where.
5000          Mark all watchpoints as unknown.  */
5001       ALL_BREAKPOINTS (b)
5002         if (is_hardware_watchpoint (b))
5003           {
5004             struct watchpoint *w = (struct watchpoint *) b;
5005
5006             w->watchpoint_triggered = watch_triggered_unknown;
5007           }
5008
5009       return 1;
5010     }
5011
5012   /* The target could report the data address.  Mark watchpoints
5013      affected by this data address as triggered, and all others as not
5014      triggered.  */
5015
5016   ALL_BREAKPOINTS (b)
5017     if (is_hardware_watchpoint (b))
5018       {
5019         struct watchpoint *w = (struct watchpoint *) b;
5020         struct bp_location *loc;
5021
5022         w->watchpoint_triggered = watch_triggered_no;
5023         for (loc = b->loc; loc; loc = loc->next)
5024           {
5025             if (is_masked_watchpoint (b))
5026               {
5027                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
5028                 CORE_ADDR start = loc->address & w->hw_wp_mask;
5029
5030                 if (newaddr == start)
5031                   {
5032                     w->watchpoint_triggered = watch_triggered_yes;
5033                     break;
5034                   }
5035               }
5036             /* Exact match not required.  Within range is sufficient.  */
5037             else if (target_watchpoint_addr_within_range (&current_target,
5038                                                          addr, loc->address,
5039                                                          loc->length))
5040               {
5041                 w->watchpoint_triggered = watch_triggered_yes;
5042                 break;
5043               }
5044           }
5045       }
5046
5047   return 1;
5048 }
5049
5050 /* Possible return values for watchpoint_check (this can't be an enum
5051    because of check_errors).  */
5052 /* The watchpoint has been deleted.  */
5053 #define WP_DELETED 1
5054 /* The value has changed.  */
5055 #define WP_VALUE_CHANGED 2
5056 /* The value has not changed.  */
5057 #define WP_VALUE_NOT_CHANGED 3
5058 /* Ignore this watchpoint, no matter if the value changed or not.  */
5059 #define WP_IGNORE 4
5060
5061 #define BP_TEMPFLAG 1
5062 #define BP_HARDWAREFLAG 2
5063
5064 /* Evaluate watchpoint condition expression and check if its value
5065    changed.
5066
5067    P should be a pointer to struct bpstat, but is defined as a void *
5068    in order for this function to be usable with catch_errors.  */
5069
5070 static int
5071 watchpoint_check (void *p)
5072 {
5073   bpstat bs = (bpstat) p;
5074   struct watchpoint *b;
5075   struct frame_info *fr;
5076   int within_current_scope;
5077
5078   /* BS is built from an existing struct breakpoint.  */
5079   gdb_assert (bs->breakpoint_at != NULL);
5080   b = (struct watchpoint *) bs->breakpoint_at;
5081
5082   /* If this is a local watchpoint, we only want to check if the
5083      watchpoint frame is in scope if the current thread is the thread
5084      that was used to create the watchpoint.  */
5085   if (!watchpoint_in_thread_scope (b))
5086     return WP_IGNORE;
5087
5088   if (b->exp_valid_block == NULL)
5089     within_current_scope = 1;
5090   else
5091     {
5092       struct frame_info *frame = get_current_frame ();
5093       struct gdbarch *frame_arch = get_frame_arch (frame);
5094       CORE_ADDR frame_pc = get_frame_pc (frame);
5095
5096       /* in_function_epilogue_p() returns a non-zero value if we're
5097          still in the function but the stack frame has already been
5098          invalidated.  Since we can't rely on the values of local
5099          variables after the stack has been destroyed, we are treating
5100          the watchpoint in that state as `not changed' without further
5101          checking.  Don't mark watchpoints as changed if the current
5102          frame is in an epilogue - even if they are in some other
5103          frame, our view of the stack is likely to be wrong and
5104          frame_find_by_id could error out.  */
5105       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
5106         return WP_IGNORE;
5107
5108       fr = frame_find_by_id (b->watchpoint_frame);
5109       within_current_scope = (fr != NULL);
5110
5111       /* If we've gotten confused in the unwinder, we might have
5112          returned a frame that can't describe this variable.  */
5113       if (within_current_scope)
5114         {
5115           struct symbol *function;
5116
5117           function = get_frame_function (fr);
5118           if (function == NULL
5119               || !contained_in (b->exp_valid_block,
5120                                 SYMBOL_BLOCK_VALUE (function)))
5121             within_current_scope = 0;
5122         }
5123
5124       if (within_current_scope)
5125         /* If we end up stopping, the current frame will get selected
5126            in normal_stop.  So this call to select_frame won't affect
5127            the user.  */
5128         select_frame (fr);
5129     }
5130
5131   if (within_current_scope)
5132     {
5133       /* We use value_{,free_to_}mark because it could be a *long*
5134          time before we return to the command level and call
5135          free_all_values.  We can't call free_all_values because we
5136          might be in the middle of evaluating a function call.  */
5137
5138       int pc = 0;
5139       struct value *mark;
5140       struct value *new_val;
5141
5142       if (is_masked_watchpoint (&b->base))
5143         /* Since we don't know the exact trigger address (from
5144            stopped_data_address), just tell the user we've triggered
5145            a mask watchpoint.  */
5146         return WP_VALUE_CHANGED;
5147
5148       mark = value_mark ();
5149       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL, 0);
5150
5151       if (b->val_bitsize != 0)
5152         new_val = extract_bitfield_from_watchpoint_value (b, new_val);
5153
5154       /* We use value_equal_contents instead of value_equal because
5155          the latter coerces an array to a pointer, thus comparing just
5156          the address of the array instead of its contents.  This is
5157          not what we want.  */
5158       if ((b->val != NULL) != (new_val != NULL)
5159           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
5160         {
5161           if (new_val != NULL)
5162             {
5163               release_value (new_val);
5164               value_free_to_mark (mark);
5165             }
5166           bs->old_val = b->val;
5167           b->val = new_val;
5168           b->val_valid = 1;
5169           return WP_VALUE_CHANGED;
5170         }
5171       else
5172         {
5173           /* Nothing changed.  */
5174           value_free_to_mark (mark);
5175           return WP_VALUE_NOT_CHANGED;
5176         }
5177     }
5178   else
5179     {
5180       struct ui_out *uiout = current_uiout;
5181
5182       /* This seems like the only logical thing to do because
5183          if we temporarily ignored the watchpoint, then when
5184          we reenter the block in which it is valid it contains
5185          garbage (in the case of a function, it may have two
5186          garbage values, one before and one after the prologue).
5187          So we can't even detect the first assignment to it and
5188          watch after that (since the garbage may or may not equal
5189          the first value assigned).  */
5190       /* We print all the stop information in
5191          breakpoint_ops->print_it, but in this case, by the time we
5192          call breakpoint_ops->print_it this bp will be deleted
5193          already.  So we have no choice but print the information
5194          here.  */
5195       if (ui_out_is_mi_like_p (uiout))
5196         ui_out_field_string
5197           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
5198       ui_out_text (uiout, "\nWatchpoint ");
5199       ui_out_field_int (uiout, "wpnum", b->base.number);
5200       ui_out_text (uiout,
5201                    " deleted because the program has left the block in\n\
5202 which its expression is valid.\n");     
5203
5204       /* Make sure the watchpoint's commands aren't executed.  */
5205       decref_counted_command_line (&b->base.commands);
5206       watchpoint_del_at_next_stop (b);
5207
5208       return WP_DELETED;
5209     }
5210 }
5211
5212 /* Return true if it looks like target has stopped due to hitting
5213    breakpoint location BL.  This function does not check if we should
5214    stop, only if BL explains the stop.  */
5215
5216 static int
5217 bpstat_check_location (const struct bp_location *bl,
5218                        struct address_space *aspace, CORE_ADDR bp_addr,
5219                        const struct target_waitstatus *ws)
5220 {
5221   struct breakpoint *b = bl->owner;
5222
5223   /* BL is from an existing breakpoint.  */
5224   gdb_assert (b != NULL);
5225
5226   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
5227 }
5228
5229 /* Determine if the watched values have actually changed, and we
5230    should stop.  If not, set BS->stop to 0.  */
5231
5232 static void
5233 bpstat_check_watchpoint (bpstat bs)
5234 {
5235   const struct bp_location *bl;
5236   struct watchpoint *b;
5237
5238   /* BS is built for existing struct breakpoint.  */
5239   bl = bs->bp_location_at;
5240   gdb_assert (bl != NULL);
5241   b = (struct watchpoint *) bs->breakpoint_at;
5242   gdb_assert (b != NULL);
5243
5244     {
5245       int must_check_value = 0;
5246       
5247       if (b->base.type == bp_watchpoint)
5248         /* For a software watchpoint, we must always check the
5249            watched value.  */
5250         must_check_value = 1;
5251       else if (b->watchpoint_triggered == watch_triggered_yes)
5252         /* We have a hardware watchpoint (read, write, or access)
5253            and the target earlier reported an address watched by
5254            this watchpoint.  */
5255         must_check_value = 1;
5256       else if (b->watchpoint_triggered == watch_triggered_unknown
5257                && b->base.type == bp_hardware_watchpoint)
5258         /* We were stopped by a hardware watchpoint, but the target could
5259            not report the data address.  We must check the watchpoint's
5260            value.  Access and read watchpoints are out of luck; without
5261            a data address, we can't figure it out.  */
5262         must_check_value = 1;
5263
5264       if (must_check_value)
5265         {
5266           char *message
5267             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
5268                           b->base.number);
5269           struct cleanup *cleanups = make_cleanup (xfree, message);
5270           int e = catch_errors (watchpoint_check, bs, message,
5271                                 RETURN_MASK_ALL);
5272           do_cleanups (cleanups);
5273           switch (e)
5274             {
5275             case WP_DELETED:
5276               /* We've already printed what needs to be printed.  */
5277               bs->print_it = print_it_done;
5278               /* Stop.  */
5279               break;
5280             case WP_IGNORE:
5281               bs->print_it = print_it_noop;
5282               bs->stop = 0;
5283               break;
5284             case WP_VALUE_CHANGED:
5285               if (b->base.type == bp_read_watchpoint)
5286                 {
5287                   /* There are two cases to consider here:
5288
5289                      1. We're watching the triggered memory for reads.
5290                      In that case, trust the target, and always report
5291                      the watchpoint hit to the user.  Even though
5292                      reads don't cause value changes, the value may
5293                      have changed since the last time it was read, and
5294                      since we're not trapping writes, we will not see
5295                      those, and as such we should ignore our notion of
5296                      old value.
5297
5298                      2. We're watching the triggered memory for both
5299                      reads and writes.  There are two ways this may
5300                      happen:
5301
5302                      2.1. This is a target that can't break on data
5303                      reads only, but can break on accesses (reads or
5304                      writes), such as e.g., x86.  We detect this case
5305                      at the time we try to insert read watchpoints.
5306
5307                      2.2. Otherwise, the target supports read
5308                      watchpoints, but, the user set an access or write
5309                      watchpoint watching the same memory as this read
5310                      watchpoint.
5311
5312                      If we're watching memory writes as well as reads,
5313                      ignore watchpoint hits when we find that the
5314                      value hasn't changed, as reads don't cause
5315                      changes.  This still gives false positives when
5316                      the program writes the same value to memory as
5317                      what there was already in memory (we will confuse
5318                      it for a read), but it's much better than
5319                      nothing.  */
5320
5321                   int other_write_watchpoint = 0;
5322
5323                   if (bl->watchpoint_type == hw_read)
5324                     {
5325                       struct breakpoint *other_b;
5326
5327                       ALL_BREAKPOINTS (other_b)
5328                         if (other_b->type == bp_hardware_watchpoint
5329                             || other_b->type == bp_access_watchpoint)
5330                           {
5331                             struct watchpoint *other_w =
5332                               (struct watchpoint *) other_b;
5333
5334                             if (other_w->watchpoint_triggered
5335                                 == watch_triggered_yes)
5336                               {
5337                                 other_write_watchpoint = 1;
5338                                 break;
5339                               }
5340                           }
5341                     }
5342
5343                   if (other_write_watchpoint
5344                       || bl->watchpoint_type == hw_access)
5345                     {
5346                       /* We're watching the same memory for writes,
5347                          and the value changed since the last time we
5348                          updated it, so this trap must be for a write.
5349                          Ignore it.  */
5350                       bs->print_it = print_it_noop;
5351                       bs->stop = 0;
5352                     }
5353                 }
5354               break;
5355             case WP_VALUE_NOT_CHANGED:
5356               if (b->base.type == bp_hardware_watchpoint
5357                   || b->base.type == bp_watchpoint)
5358                 {
5359                   /* Don't stop: write watchpoints shouldn't fire if
5360                      the value hasn't changed.  */
5361                   bs->print_it = print_it_noop;
5362                   bs->stop = 0;
5363                 }
5364               /* Stop.  */
5365               break;
5366             default:
5367               /* Can't happen.  */
5368             case 0:
5369               /* Error from catch_errors.  */
5370               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
5371               watchpoint_del_at_next_stop (b);
5372               /* We've already printed what needs to be printed.  */
5373               bs->print_it = print_it_done;
5374               break;
5375             }
5376         }
5377       else      /* must_check_value == 0 */
5378         {
5379           /* This is a case where some watchpoint(s) triggered, but
5380              not at the address of this watchpoint, or else no
5381              watchpoint triggered after all.  So don't print
5382              anything for this watchpoint.  */
5383           bs->print_it = print_it_noop;
5384           bs->stop = 0;
5385         }
5386     }
5387 }
5388
5389 /* For breakpoints that are currently marked as telling gdb to stop,
5390    check conditions (condition proper, frame, thread and ignore count)
5391    of breakpoint referred to by BS.  If we should not stop for this
5392    breakpoint, set BS->stop to 0.  */
5393
5394 static void
5395 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
5396 {
5397   const struct bp_location *bl;
5398   struct breakpoint *b;
5399   int value_is_zero = 0;
5400   struct expression *cond;
5401
5402   gdb_assert (bs->stop);
5403
5404   /* BS is built for existing struct breakpoint.  */
5405   bl = bs->bp_location_at;
5406   gdb_assert (bl != NULL);
5407   b = bs->breakpoint_at;
5408   gdb_assert (b != NULL);
5409
5410   /* Even if the target evaluated the condition on its end and notified GDB, we
5411      need to do so again since GDB does not know if we stopped due to a
5412      breakpoint or a single step breakpoint.  */
5413
5414   if (frame_id_p (b->frame_id)
5415       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
5416     {
5417       bs->stop = 0;
5418       return;
5419     }
5420
5421   /* If this is a thread/task-specific breakpoint, don't waste cpu
5422      evaluating the condition if this isn't the specified
5423      thread/task.  */
5424   if ((b->thread != -1 && b->thread != pid_to_thread_id (ptid))
5425       || (b->task != 0 && b->task != ada_get_task_number (ptid)))
5426
5427     {
5428       bs->stop = 0;
5429       return;
5430     }
5431
5432   /* Evaluate extension language breakpoints that have a "stop" method
5433      implemented.  */
5434   bs->stop = breakpoint_ext_lang_cond_says_stop (b);
5435
5436   if (is_watchpoint (b))
5437     {
5438       struct watchpoint *w = (struct watchpoint *) b;
5439
5440       cond = w->cond_exp;
5441     }
5442   else
5443     cond = bl->cond;
5444
5445   if (cond && b->disposition != disp_del_at_next_stop)
5446     {
5447       int within_current_scope = 1;
5448       struct watchpoint * w;
5449
5450       /* We use value_mark and value_free_to_mark because it could
5451          be a long time before we return to the command level and
5452          call free_all_values.  We can't call free_all_values
5453          because we might be in the middle of evaluating a
5454          function call.  */
5455       struct value *mark = value_mark ();
5456
5457       if (is_watchpoint (b))
5458         w = (struct watchpoint *) b;
5459       else
5460         w = NULL;
5461
5462       /* Need to select the frame, with all that implies so that
5463          the conditions will have the right context.  Because we
5464          use the frame, we will not see an inlined function's
5465          variables when we arrive at a breakpoint at the start
5466          of the inlined function; the current frame will be the
5467          call site.  */
5468       if (w == NULL || w->cond_exp_valid_block == NULL)
5469         select_frame (get_current_frame ());
5470       else
5471         {
5472           struct frame_info *frame;
5473
5474           /* For local watchpoint expressions, which particular
5475              instance of a local is being watched matters, so we
5476              keep track of the frame to evaluate the expression
5477              in.  To evaluate the condition however, it doesn't
5478              really matter which instantiation of the function
5479              where the condition makes sense triggers the
5480              watchpoint.  This allows an expression like "watch
5481              global if q > 10" set in `func', catch writes to
5482              global on all threads that call `func', or catch
5483              writes on all recursive calls of `func' by a single
5484              thread.  We simply always evaluate the condition in
5485              the innermost frame that's executing where it makes
5486              sense to evaluate the condition.  It seems
5487              intuitive.  */
5488           frame = block_innermost_frame (w->cond_exp_valid_block);
5489           if (frame != NULL)
5490             select_frame (frame);
5491           else
5492             within_current_scope = 0;
5493         }
5494       if (within_current_scope)
5495         value_is_zero
5496           = catch_errors (breakpoint_cond_eval, cond,
5497                           "Error in testing breakpoint condition:\n",
5498                           RETURN_MASK_ALL);
5499       else
5500         {
5501           warning (_("Watchpoint condition cannot be tested "
5502                      "in the current scope"));
5503           /* If we failed to set the right context for this
5504              watchpoint, unconditionally report it.  */
5505           value_is_zero = 0;
5506         }
5507       /* FIXME-someday, should give breakpoint #.  */
5508       value_free_to_mark (mark);
5509     }
5510
5511   if (cond && value_is_zero)
5512     {
5513       bs->stop = 0;
5514     }
5515   else if (b->ignore_count > 0)
5516     {
5517       b->ignore_count--;
5518       bs->stop = 0;
5519       /* Increase the hit count even though we don't stop.  */
5520       ++(b->hit_count);
5521       observer_notify_breakpoint_modified (b);
5522     }   
5523 }
5524
5525
5526 /* Get a bpstat associated with having just stopped at address
5527    BP_ADDR in thread PTID.
5528
5529    Determine whether we stopped at a breakpoint, etc, or whether we
5530    don't understand this stop.  Result is a chain of bpstat's such
5531    that:
5532
5533    if we don't understand the stop, the result is a null pointer.
5534
5535    if we understand why we stopped, the result is not null.
5536
5537    Each element of the chain refers to a particular breakpoint or
5538    watchpoint at which we have stopped.  (We may have stopped for
5539    several reasons concurrently.)
5540
5541    Each element of the chain has valid next, breakpoint_at,
5542    commands, FIXME??? fields.  */
5543
5544 bpstat
5545 bpstat_stop_status (struct address_space *aspace,
5546                     CORE_ADDR bp_addr, ptid_t ptid,
5547                     const struct target_waitstatus *ws)
5548 {
5549   struct breakpoint *b = NULL;
5550   struct bp_location *bl;
5551   struct bp_location *loc;
5552   /* First item of allocated bpstat's.  */
5553   bpstat bs_head = NULL, *bs_link = &bs_head;
5554   /* Pointer to the last thing in the chain currently.  */
5555   bpstat bs;
5556   int ix;
5557   int need_remove_insert;
5558   int removed_any;
5559
5560   /* First, build the bpstat chain with locations that explain a
5561      target stop, while being careful to not set the target running,
5562      as that may invalidate locations (in particular watchpoint
5563      locations are recreated).  Resuming will happen here with
5564      breakpoint conditions or watchpoint expressions that include
5565      inferior function calls.  */
5566
5567   ALL_BREAKPOINTS (b)
5568     {
5569       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
5570         continue;
5571
5572       for (bl = b->loc; bl != NULL; bl = bl->next)
5573         {
5574           /* For hardware watchpoints, we look only at the first
5575              location.  The watchpoint_check function will work on the
5576              entire expression, not the individual locations.  For
5577              read watchpoints, the watchpoints_triggered function has
5578              checked all locations already.  */
5579           if (b->type == bp_hardware_watchpoint && bl != b->loc)
5580             break;
5581
5582           if (!bl->enabled || bl->shlib_disabled)
5583             continue;
5584
5585           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
5586             continue;
5587
5588           /* Come here if it's a watchpoint, or if the break address
5589              matches.  */
5590
5591           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
5592                                                    explain stop.  */
5593
5594           /* Assume we stop.  Should we find a watchpoint that is not
5595              actually triggered, or if the condition of the breakpoint
5596              evaluates as false, we'll reset 'stop' to 0.  */
5597           bs->stop = 1;
5598           bs->print = 1;
5599
5600           /* If this is a scope breakpoint, mark the associated
5601              watchpoint as triggered so that we will handle the
5602              out-of-scope event.  We'll get to the watchpoint next
5603              iteration.  */
5604           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
5605             {
5606               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
5607
5608               w->watchpoint_triggered = watch_triggered_yes;
5609             }
5610         }
5611     }
5612
5613   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
5614     {
5615       if (breakpoint_location_address_match (loc, aspace, bp_addr))
5616         {
5617           bs = bpstat_alloc (loc, &bs_link);
5618           /* For hits of moribund locations, we should just proceed.  */
5619           bs->stop = 0;
5620           bs->print = 0;
5621           bs->print_it = print_it_noop;
5622         }
5623     }
5624
5625   /* A bit of special processing for shlib breakpoints.  We need to
5626      process solib loading here, so that the lists of loaded and
5627      unloaded libraries are correct before we handle "catch load" and
5628      "catch unload".  */
5629   for (bs = bs_head; bs != NULL; bs = bs->next)
5630     {
5631       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
5632         {
5633           handle_solib_event ();
5634           break;
5635         }
5636     }
5637
5638   /* Now go through the locations that caused the target to stop, and
5639      check whether we're interested in reporting this stop to higher
5640      layers, or whether we should resume the target transparently.  */
5641
5642   removed_any = 0;
5643
5644   for (bs = bs_head; bs != NULL; bs = bs->next)
5645     {
5646       if (!bs->stop)
5647         continue;
5648
5649       b = bs->breakpoint_at;
5650       b->ops->check_status (bs);
5651       if (bs->stop)
5652         {
5653           bpstat_check_breakpoint_conditions (bs, ptid);
5654
5655           if (bs->stop)
5656             {
5657               ++(b->hit_count);
5658               observer_notify_breakpoint_modified (b);
5659
5660               /* We will stop here.  */
5661               if (b->disposition == disp_disable)
5662                 {
5663                   --(b->enable_count);
5664                   if (b->enable_count <= 0
5665                       && b->enable_state != bp_permanent)
5666                     b->enable_state = bp_disabled;
5667                   removed_any = 1;
5668                 }
5669               if (b->silent)
5670                 bs->print = 0;
5671               bs->commands = b->commands;
5672               incref_counted_command_line (bs->commands);
5673               if (command_line_is_silent (bs->commands
5674                                           ? bs->commands->commands : NULL))
5675                 bs->print = 0;
5676
5677               b->ops->after_condition_true (bs);
5678             }
5679
5680         }
5681
5682       /* Print nothing for this entry if we don't stop or don't
5683          print.  */
5684       if (!bs->stop || !bs->print)
5685         bs->print_it = print_it_noop;
5686     }
5687
5688   /* If we aren't stopping, the value of some hardware watchpoint may
5689      not have changed, but the intermediate memory locations we are
5690      watching may have.  Don't bother if we're stopping; this will get
5691      done later.  */
5692   need_remove_insert = 0;
5693   if (! bpstat_causes_stop (bs_head))
5694     for (bs = bs_head; bs != NULL; bs = bs->next)
5695       if (!bs->stop
5696           && bs->breakpoint_at
5697           && is_hardware_watchpoint (bs->breakpoint_at))
5698         {
5699           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
5700
5701           update_watchpoint (w, 0 /* don't reparse.  */);
5702           need_remove_insert = 1;
5703         }
5704
5705   if (need_remove_insert)
5706     update_global_location_list (UGLL_MAY_INSERT);
5707   else if (removed_any)
5708     update_global_location_list (UGLL_DONT_INSERT);
5709
5710   return bs_head;
5711 }
5712
5713 static void
5714 handle_jit_event (void)
5715 {
5716   struct frame_info *frame;
5717   struct gdbarch *gdbarch;
5718
5719   /* Switch terminal for any messages produced by
5720      breakpoint_re_set.  */
5721   target_terminal_ours_for_output ();
5722
5723   frame = get_current_frame ();
5724   gdbarch = get_frame_arch (frame);
5725
5726   jit_event_handler (gdbarch);
5727
5728   target_terminal_inferior ();
5729 }
5730
5731 /* Prepare WHAT final decision for infrun.  */
5732
5733 /* Decide what infrun needs to do with this bpstat.  */
5734
5735 struct bpstat_what
5736 bpstat_what (bpstat bs_head)
5737 {
5738   struct bpstat_what retval;
5739   int jit_event = 0;
5740   bpstat bs;
5741
5742   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5743   retval.call_dummy = STOP_NONE;
5744   retval.is_longjmp = 0;
5745
5746   for (bs = bs_head; bs != NULL; bs = bs->next)
5747     {
5748       /* Extract this BS's action.  After processing each BS, we check
5749          if its action overrides all we've seem so far.  */
5750       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5751       enum bptype bptype;
5752
5753       if (bs->breakpoint_at == NULL)
5754         {
5755           /* I suspect this can happen if it was a momentary
5756              breakpoint which has since been deleted.  */
5757           bptype = bp_none;
5758         }
5759       else
5760         bptype = bs->breakpoint_at->type;
5761
5762       switch (bptype)
5763         {
5764         case bp_none:
5765           break;
5766         case bp_breakpoint:
5767         case bp_hardware_breakpoint:
5768         case bp_until:
5769         case bp_finish:
5770         case bp_shlib_event:
5771           if (bs->stop)
5772             {
5773               if (bs->print)
5774                 this_action = BPSTAT_WHAT_STOP_NOISY;
5775               else
5776                 this_action = BPSTAT_WHAT_STOP_SILENT;
5777             }
5778           else
5779             this_action = BPSTAT_WHAT_SINGLE;
5780           break;
5781         case bp_watchpoint:
5782         case bp_hardware_watchpoint:
5783         case bp_read_watchpoint:
5784         case bp_access_watchpoint:
5785           if (bs->stop)
5786             {
5787               if (bs->print)
5788                 this_action = BPSTAT_WHAT_STOP_NOISY;
5789               else
5790                 this_action = BPSTAT_WHAT_STOP_SILENT;
5791             }
5792           else
5793             {
5794               /* There was a watchpoint, but we're not stopping.
5795                  This requires no further action.  */
5796             }
5797           break;
5798         case bp_longjmp:
5799         case bp_longjmp_call_dummy:
5800         case bp_exception:
5801           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5802           retval.is_longjmp = bptype != bp_exception;
5803           break;
5804         case bp_longjmp_resume:
5805         case bp_exception_resume:
5806           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5807           retval.is_longjmp = bptype == bp_longjmp_resume;
5808           break;
5809         case bp_step_resume:
5810           if (bs->stop)
5811             this_action = BPSTAT_WHAT_STEP_RESUME;
5812           else
5813             {
5814               /* It is for the wrong frame.  */
5815               this_action = BPSTAT_WHAT_SINGLE;
5816             }
5817           break;
5818         case bp_hp_step_resume:
5819           if (bs->stop)
5820             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5821           else
5822             {
5823               /* It is for the wrong frame.  */
5824               this_action = BPSTAT_WHAT_SINGLE;
5825             }
5826           break;
5827         case bp_watchpoint_scope:
5828         case bp_thread_event:
5829         case bp_overlay_event:
5830         case bp_longjmp_master:
5831         case bp_std_terminate_master:
5832         case bp_exception_master:
5833           this_action = BPSTAT_WHAT_SINGLE;
5834           break;
5835         case bp_catchpoint:
5836           if (bs->stop)
5837             {
5838               if (bs->print)
5839                 this_action = BPSTAT_WHAT_STOP_NOISY;
5840               else
5841                 this_action = BPSTAT_WHAT_STOP_SILENT;
5842             }
5843           else
5844             {
5845               /* There was a catchpoint, but we're not stopping.
5846                  This requires no further action.  */
5847             }
5848           break;
5849         case bp_jit_event:
5850           jit_event = 1;
5851           this_action = BPSTAT_WHAT_SINGLE;
5852           break;
5853         case bp_call_dummy:
5854           /* Make sure the action is stop (silent or noisy),
5855              so infrun.c pops the dummy frame.  */
5856           retval.call_dummy = STOP_STACK_DUMMY;
5857           this_action = BPSTAT_WHAT_STOP_SILENT;
5858           break;
5859         case bp_std_terminate:
5860           /* Make sure the action is stop (silent or noisy),
5861              so infrun.c pops the dummy frame.  */
5862           retval.call_dummy = STOP_STD_TERMINATE;
5863           this_action = BPSTAT_WHAT_STOP_SILENT;
5864           break;
5865         case bp_tracepoint:
5866         case bp_fast_tracepoint:
5867         case bp_static_tracepoint:
5868           /* Tracepoint hits should not be reported back to GDB, and
5869              if one got through somehow, it should have been filtered
5870              out already.  */
5871           internal_error (__FILE__, __LINE__,
5872                           _("bpstat_what: tracepoint encountered"));
5873           break;
5874         case bp_gnu_ifunc_resolver:
5875           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5876           this_action = BPSTAT_WHAT_SINGLE;
5877           break;
5878         case bp_gnu_ifunc_resolver_return:
5879           /* The breakpoint will be removed, execution will restart from the
5880              PC of the former breakpoint.  */
5881           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5882           break;
5883
5884         case bp_dprintf:
5885           if (bs->stop)
5886             this_action = BPSTAT_WHAT_STOP_SILENT;
5887           else
5888             this_action = BPSTAT_WHAT_SINGLE;
5889           break;
5890
5891         default:
5892           internal_error (__FILE__, __LINE__,
5893                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5894         }
5895
5896       retval.main_action = max (retval.main_action, this_action);
5897     }
5898
5899   /* These operations may affect the bs->breakpoint_at state so they are
5900      delayed after MAIN_ACTION is decided above.  */
5901
5902   if (jit_event)
5903     {
5904       if (debug_infrun)
5905         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5906
5907       handle_jit_event ();
5908     }
5909
5910   for (bs = bs_head; bs != NULL; bs = bs->next)
5911     {
5912       struct breakpoint *b = bs->breakpoint_at;
5913
5914       if (b == NULL)
5915         continue;
5916       switch (b->type)
5917         {
5918         case bp_gnu_ifunc_resolver:
5919           gnu_ifunc_resolver_stop (b);
5920           break;
5921         case bp_gnu_ifunc_resolver_return:
5922           gnu_ifunc_resolver_return_stop (b);
5923           break;
5924         }
5925     }
5926
5927   return retval;
5928 }
5929
5930 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5931    without hardware support).  This isn't related to a specific bpstat,
5932    just to things like whether watchpoints are set.  */
5933
5934 int
5935 bpstat_should_step (void)
5936 {
5937   struct breakpoint *b;
5938
5939   ALL_BREAKPOINTS (b)
5940     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5941       return 1;
5942   return 0;
5943 }
5944
5945 int
5946 bpstat_causes_stop (bpstat bs)
5947 {
5948   for (; bs != NULL; bs = bs->next)
5949     if (bs->stop)
5950       return 1;
5951
5952   return 0;
5953 }
5954
5955 \f
5956
5957 /* Compute a string of spaces suitable to indent the next line
5958    so it starts at the position corresponding to the table column
5959    named COL_NAME in the currently active table of UIOUT.  */
5960
5961 static char *
5962 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5963 {
5964   static char wrap_indent[80];
5965   int i, total_width, width, align;
5966   char *text;
5967
5968   total_width = 0;
5969   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5970     {
5971       if (strcmp (text, col_name) == 0)
5972         {
5973           gdb_assert (total_width < sizeof wrap_indent);
5974           memset (wrap_indent, ' ', total_width);
5975           wrap_indent[total_width] = 0;
5976
5977           return wrap_indent;
5978         }
5979
5980       total_width += width + 1;
5981     }
5982
5983   return NULL;
5984 }
5985
5986 /* Determine if the locations of this breakpoint will have their conditions
5987    evaluated by the target, host or a mix of both.  Returns the following:
5988
5989     "host": Host evals condition.
5990     "host or target": Host or Target evals condition.
5991     "target": Target evals condition.
5992 */
5993
5994 static const char *
5995 bp_condition_evaluator (struct breakpoint *b)
5996 {
5997   struct bp_location *bl;
5998   char host_evals = 0;
5999   char target_evals = 0;
6000
6001   if (!b)
6002     return NULL;
6003
6004   if (!is_breakpoint (b))
6005     return NULL;
6006
6007   if (gdb_evaluates_breakpoint_condition_p ()
6008       || !target_supports_evaluation_of_breakpoint_conditions ())
6009     return condition_evaluation_host;
6010
6011   for (bl = b->loc; bl; bl = bl->next)
6012     {
6013       if (bl->cond_bytecode)
6014         target_evals++;
6015       else
6016         host_evals++;
6017     }
6018
6019   if (host_evals && target_evals)
6020     return condition_evaluation_both;
6021   else if (target_evals)
6022     return condition_evaluation_target;
6023   else
6024     return condition_evaluation_host;
6025 }
6026
6027 /* Determine the breakpoint location's condition evaluator.  This is
6028    similar to bp_condition_evaluator, but for locations.  */
6029
6030 static const char *
6031 bp_location_condition_evaluator (struct bp_location *bl)
6032 {
6033   if (bl && !is_breakpoint (bl->owner))
6034     return NULL;
6035
6036   if (gdb_evaluates_breakpoint_condition_p ()
6037       || !target_supports_evaluation_of_breakpoint_conditions ())
6038     return condition_evaluation_host;
6039
6040   if (bl && bl->cond_bytecode)
6041     return condition_evaluation_target;
6042   else
6043     return condition_evaluation_host;
6044 }
6045
6046 /* Print the LOC location out of the list of B->LOC locations.  */
6047
6048 static void
6049 print_breakpoint_location (struct breakpoint *b,
6050                            struct bp_location *loc)
6051 {
6052   struct ui_out *uiout = current_uiout;
6053   struct cleanup *old_chain = save_current_program_space ();
6054
6055   if (loc != NULL && loc->shlib_disabled)
6056     loc = NULL;
6057
6058   if (loc != NULL)
6059     set_current_program_space (loc->pspace);
6060
6061   if (b->display_canonical)
6062     ui_out_field_string (uiout, "what", b->addr_string);
6063   else if (loc && loc->symtab)
6064     {
6065       struct symbol *sym 
6066         = find_pc_sect_function (loc->address, loc->section);
6067       if (sym)
6068         {
6069           ui_out_text (uiout, "in ");
6070           ui_out_field_string (uiout, "func",
6071                                SYMBOL_PRINT_NAME (sym));
6072           ui_out_text (uiout, " ");
6073           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
6074           ui_out_text (uiout, "at ");
6075         }
6076       ui_out_field_string (uiout, "file",
6077                            symtab_to_filename_for_display (loc->symtab));
6078       ui_out_text (uiout, ":");
6079
6080       if (ui_out_is_mi_like_p (uiout))
6081         ui_out_field_string (uiout, "fullname",
6082                              symtab_to_fullname (loc->symtab));
6083       
6084       ui_out_field_int (uiout, "line", loc->line_number);
6085     }
6086   else if (loc)
6087     {
6088       struct ui_file *stb = mem_fileopen ();
6089       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
6090
6091       print_address_symbolic (loc->gdbarch, loc->address, stb,
6092                               demangle, "");
6093       ui_out_field_stream (uiout, "at", stb);
6094
6095       do_cleanups (stb_chain);
6096     }
6097   else
6098     ui_out_field_string (uiout, "pending", b->addr_string);
6099
6100   if (loc && is_breakpoint (b)
6101       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
6102       && bp_condition_evaluator (b) == condition_evaluation_both)
6103     {
6104       ui_out_text (uiout, " (");
6105       ui_out_field_string (uiout, "evaluated-by",
6106                            bp_location_condition_evaluator (loc));
6107       ui_out_text (uiout, ")");
6108     }
6109
6110   do_cleanups (old_chain);
6111 }
6112
6113 static const char *
6114 bptype_string (enum bptype type)
6115 {
6116   struct ep_type_description
6117     {
6118       enum bptype type;
6119       char *description;
6120     };
6121   static struct ep_type_description bptypes[] =
6122   {
6123     {bp_none, "?deleted?"},
6124     {bp_breakpoint, "breakpoint"},
6125     {bp_hardware_breakpoint, "hw breakpoint"},
6126     {bp_until, "until"},
6127     {bp_finish, "finish"},
6128     {bp_watchpoint, "watchpoint"},
6129     {bp_hardware_watchpoint, "hw watchpoint"},
6130     {bp_read_watchpoint, "read watchpoint"},
6131     {bp_access_watchpoint, "acc watchpoint"},
6132     {bp_longjmp, "longjmp"},
6133     {bp_longjmp_resume, "longjmp resume"},
6134     {bp_longjmp_call_dummy, "longjmp for call dummy"},
6135     {bp_exception, "exception"},
6136     {bp_exception_resume, "exception resume"},
6137     {bp_step_resume, "step resume"},
6138     {bp_hp_step_resume, "high-priority step resume"},
6139     {bp_watchpoint_scope, "watchpoint scope"},
6140     {bp_call_dummy, "call dummy"},
6141     {bp_std_terminate, "std::terminate"},
6142     {bp_shlib_event, "shlib events"},
6143     {bp_thread_event, "thread events"},
6144     {bp_overlay_event, "overlay events"},
6145     {bp_longjmp_master, "longjmp master"},
6146     {bp_std_terminate_master, "std::terminate master"},
6147     {bp_exception_master, "exception master"},
6148     {bp_catchpoint, "catchpoint"},
6149     {bp_tracepoint, "tracepoint"},
6150     {bp_fast_tracepoint, "fast tracepoint"},
6151     {bp_static_tracepoint, "static tracepoint"},
6152     {bp_dprintf, "dprintf"},
6153     {bp_jit_event, "jit events"},
6154     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
6155     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
6156   };
6157
6158   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
6159       || ((int) type != bptypes[(int) type].type))
6160     internal_error (__FILE__, __LINE__,
6161                     _("bptypes table does not describe type #%d."),
6162                     (int) type);
6163
6164   return bptypes[(int) type].description;
6165 }
6166
6167 /* For MI, output a field named 'thread-groups' with a list as the value.
6168    For CLI, prefix the list with the string 'inf'. */
6169
6170 static void
6171 output_thread_groups (struct ui_out *uiout,
6172                       const char *field_name,
6173                       VEC(int) *inf_num,
6174                       int mi_only)
6175 {
6176   struct cleanup *back_to;
6177   int is_mi = ui_out_is_mi_like_p (uiout);
6178   int inf;
6179   int i;
6180
6181   /* For backward compatibility, don't display inferiors in CLI unless
6182      there are several.  Always display them for MI. */
6183   if (!is_mi && mi_only)
6184     return;
6185
6186   back_to = make_cleanup_ui_out_list_begin_end (uiout, field_name);
6187
6188   for (i = 0; VEC_iterate (int, inf_num, i, inf); ++i)
6189     {
6190       if (is_mi)
6191         {
6192           char mi_group[10];
6193
6194           xsnprintf (mi_group, sizeof (mi_group), "i%d", inf);
6195           ui_out_field_string (uiout, NULL, mi_group);
6196         }
6197       else
6198         {
6199           if (i == 0)
6200             ui_out_text (uiout, " inf ");
6201           else
6202             ui_out_text (uiout, ", ");
6203         
6204           ui_out_text (uiout, plongest (inf));
6205         }
6206     }
6207
6208   do_cleanups (back_to);
6209 }
6210
6211 /* Print B to gdb_stdout.  */
6212
6213 static void
6214 print_one_breakpoint_location (struct breakpoint *b,
6215                                struct bp_location *loc,
6216                                int loc_number,
6217                                struct bp_location **last_loc,
6218                                int allflag)
6219 {
6220   struct command_line *l;
6221   static char bpenables[] = "nynny";
6222
6223   struct ui_out *uiout = current_uiout;
6224   int header_of_multiple = 0;
6225   int part_of_multiple = (loc != NULL);
6226   struct value_print_options opts;
6227
6228   get_user_print_options (&opts);
6229
6230   gdb_assert (!loc || loc_number != 0);
6231   /* See comment in print_one_breakpoint concerning treatment of
6232      breakpoints with single disabled location.  */
6233   if (loc == NULL 
6234       && (b->loc != NULL 
6235           && (b->loc->next != NULL || !b->loc->enabled)))
6236     header_of_multiple = 1;
6237   if (loc == NULL)
6238     loc = b->loc;
6239
6240   annotate_record ();
6241
6242   /* 1 */
6243   annotate_field (0);
6244   if (part_of_multiple)
6245     {
6246       char *formatted;
6247       formatted = xstrprintf ("%d.%d", b->number, loc_number);
6248       ui_out_field_string (uiout, "number", formatted);
6249       xfree (formatted);
6250     }
6251   else
6252     {
6253       ui_out_field_int (uiout, "number", b->number);
6254     }
6255
6256   /* 2 */
6257   annotate_field (1);
6258   if (part_of_multiple)
6259     ui_out_field_skip (uiout, "type");
6260   else
6261     ui_out_field_string (uiout, "type", bptype_string (b->type));
6262
6263   /* 3 */
6264   annotate_field (2);
6265   if (part_of_multiple)
6266     ui_out_field_skip (uiout, "disp");
6267   else
6268     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6269
6270
6271   /* 4 */
6272   annotate_field (3);
6273   if (part_of_multiple)
6274     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
6275   else
6276     ui_out_field_fmt (uiout, "enabled", "%c", 
6277                       bpenables[(int) b->enable_state]);
6278   ui_out_spaces (uiout, 2);
6279
6280   
6281   /* 5 and 6 */
6282   if (b->ops != NULL && b->ops->print_one != NULL)
6283     {
6284       /* Although the print_one can possibly print all locations,
6285          calling it here is not likely to get any nice result.  So,
6286          make sure there's just one location.  */
6287       gdb_assert (b->loc == NULL || b->loc->next == NULL);
6288       b->ops->print_one (b, last_loc);
6289     }
6290   else
6291     switch (b->type)
6292       {
6293       case bp_none:
6294         internal_error (__FILE__, __LINE__,
6295                         _("print_one_breakpoint: bp_none encountered\n"));
6296         break;
6297
6298       case bp_watchpoint:
6299       case bp_hardware_watchpoint:
6300       case bp_read_watchpoint:
6301       case bp_access_watchpoint:
6302         {
6303           struct watchpoint *w = (struct watchpoint *) b;
6304
6305           /* Field 4, the address, is omitted (which makes the columns
6306              not line up too nicely with the headers, but the effect
6307              is relatively readable).  */
6308           if (opts.addressprint)
6309             ui_out_field_skip (uiout, "addr");
6310           annotate_field (5);
6311           ui_out_field_string (uiout, "what", w->exp_string);
6312         }
6313         break;
6314
6315       case bp_breakpoint:
6316       case bp_hardware_breakpoint:
6317       case bp_until:
6318       case bp_finish:
6319       case bp_longjmp:
6320       case bp_longjmp_resume:
6321       case bp_longjmp_call_dummy:
6322       case bp_exception:
6323       case bp_exception_resume:
6324       case bp_step_resume:
6325       case bp_hp_step_resume:
6326       case bp_watchpoint_scope:
6327       case bp_call_dummy:
6328       case bp_std_terminate:
6329       case bp_shlib_event:
6330       case bp_thread_event:
6331       case bp_overlay_event:
6332       case bp_longjmp_master:
6333       case bp_std_terminate_master:
6334       case bp_exception_master:
6335       case bp_tracepoint:
6336       case bp_fast_tracepoint:
6337       case bp_static_tracepoint:
6338       case bp_dprintf:
6339       case bp_jit_event:
6340       case bp_gnu_ifunc_resolver:
6341       case bp_gnu_ifunc_resolver_return:
6342         if (opts.addressprint)
6343           {
6344             annotate_field (4);
6345             if (header_of_multiple)
6346               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
6347             else if (b->loc == NULL || loc->shlib_disabled)
6348               ui_out_field_string (uiout, "addr", "<PENDING>");
6349             else
6350               ui_out_field_core_addr (uiout, "addr",
6351                                       loc->gdbarch, loc->address);
6352           }
6353         annotate_field (5);
6354         if (!header_of_multiple)
6355           print_breakpoint_location (b, loc);
6356         if (b->loc)
6357           *last_loc = b->loc;
6358         break;
6359       }
6360
6361
6362   if (loc != NULL && !header_of_multiple)
6363     {
6364       struct inferior *inf;
6365       VEC(int) *inf_num = NULL;
6366       int mi_only = 1;
6367
6368       ALL_INFERIORS (inf)
6369         {
6370           if (inf->pspace == loc->pspace)
6371             VEC_safe_push (int, inf_num, inf->num);
6372         }
6373
6374         /* For backward compatibility, don't display inferiors in CLI unless
6375            there are several.  Always display for MI. */
6376         if (allflag
6377             || (!gdbarch_has_global_breakpoints (target_gdbarch ())
6378                 && (number_of_program_spaces () > 1
6379                     || number_of_inferiors () > 1)
6380                 /* LOC is for existing B, it cannot be in
6381                    moribund_locations and thus having NULL OWNER.  */
6382                 && loc->owner->type != bp_catchpoint))
6383         mi_only = 0;
6384       output_thread_groups (uiout, "thread-groups", inf_num, mi_only);
6385       VEC_free (int, inf_num);
6386     }
6387
6388   if (!part_of_multiple)
6389     {
6390       if (b->thread != -1)
6391         {
6392           /* FIXME: This seems to be redundant and lost here; see the
6393              "stop only in" line a little further down.  */
6394           ui_out_text (uiout, " thread ");
6395           ui_out_field_int (uiout, "thread", b->thread);
6396         }
6397       else if (b->task != 0)
6398         {
6399           ui_out_text (uiout, " task ");
6400           ui_out_field_int (uiout, "task", b->task);
6401         }
6402     }
6403
6404   ui_out_text (uiout, "\n");
6405
6406   if (!part_of_multiple)
6407     b->ops->print_one_detail (b, uiout);
6408
6409   if (part_of_multiple && frame_id_p (b->frame_id))
6410     {
6411       annotate_field (6);
6412       ui_out_text (uiout, "\tstop only in stack frame at ");
6413       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
6414          the frame ID.  */
6415       ui_out_field_core_addr (uiout, "frame",
6416                               b->gdbarch, b->frame_id.stack_addr);
6417       ui_out_text (uiout, "\n");
6418     }
6419   
6420   if (!part_of_multiple && b->cond_string)
6421     {
6422       annotate_field (7);
6423       if (is_tracepoint (b))
6424         ui_out_text (uiout, "\ttrace only if ");
6425       else
6426         ui_out_text (uiout, "\tstop only if ");
6427       ui_out_field_string (uiout, "cond", b->cond_string);
6428
6429       /* Print whether the target is doing the breakpoint's condition
6430          evaluation.  If GDB is doing the evaluation, don't print anything.  */
6431       if (is_breakpoint (b)
6432           && breakpoint_condition_evaluation_mode ()
6433           == condition_evaluation_target)
6434         {
6435           ui_out_text (uiout, " (");
6436           ui_out_field_string (uiout, "evaluated-by",
6437                                bp_condition_evaluator (b));
6438           ui_out_text (uiout, " evals)");
6439         }
6440       ui_out_text (uiout, "\n");
6441     }
6442
6443   if (!part_of_multiple && b->thread != -1)
6444     {
6445       /* FIXME should make an annotation for this.  */
6446       ui_out_text (uiout, "\tstop only in thread ");
6447       ui_out_field_int (uiout, "thread", b->thread);
6448       ui_out_text (uiout, "\n");
6449     }
6450   
6451   if (!part_of_multiple)
6452     {
6453       if (b->hit_count)
6454         {
6455           /* FIXME should make an annotation for this.  */
6456           if (is_catchpoint (b))
6457             ui_out_text (uiout, "\tcatchpoint");
6458           else if (is_tracepoint (b))
6459             ui_out_text (uiout, "\ttracepoint");
6460           else
6461             ui_out_text (uiout, "\tbreakpoint");
6462           ui_out_text (uiout, " already hit ");
6463           ui_out_field_int (uiout, "times", b->hit_count);
6464           if (b->hit_count == 1)
6465             ui_out_text (uiout, " time\n");
6466           else
6467             ui_out_text (uiout, " times\n");
6468         }
6469       else
6470         {
6471           /* Output the count also if it is zero, but only if this is mi.  */
6472           if (ui_out_is_mi_like_p (uiout))
6473             ui_out_field_int (uiout, "times", b->hit_count);
6474         }
6475     }
6476
6477   if (!part_of_multiple && b->ignore_count)
6478     {
6479       annotate_field (8);
6480       ui_out_text (uiout, "\tignore next ");
6481       ui_out_field_int (uiout, "ignore", b->ignore_count);
6482       ui_out_text (uiout, " hits\n");
6483     }
6484
6485   /* Note that an enable count of 1 corresponds to "enable once"
6486      behavior, which is reported by the combination of enablement and
6487      disposition, so we don't need to mention it here.  */
6488   if (!part_of_multiple && b->enable_count > 1)
6489     {
6490       annotate_field (8);
6491       ui_out_text (uiout, "\tdisable after ");
6492       /* Tweak the wording to clarify that ignore and enable counts
6493          are distinct, and have additive effect.  */
6494       if (b->ignore_count)
6495         ui_out_text (uiout, "additional ");
6496       else
6497         ui_out_text (uiout, "next ");
6498       ui_out_field_int (uiout, "enable", b->enable_count);
6499       ui_out_text (uiout, " hits\n");
6500     }
6501
6502   if (!part_of_multiple && is_tracepoint (b))
6503     {
6504       struct tracepoint *tp = (struct tracepoint *) b;
6505
6506       if (tp->traceframe_usage)
6507         {
6508           ui_out_text (uiout, "\ttrace buffer usage ");
6509           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
6510           ui_out_text (uiout, " bytes\n");
6511         }
6512     }
6513
6514   l = b->commands ? b->commands->commands : NULL;
6515   if (!part_of_multiple && l)
6516     {
6517       struct cleanup *script_chain;
6518
6519       annotate_field (9);
6520       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
6521       print_command_lines (uiout, l, 4);
6522       do_cleanups (script_chain);
6523     }
6524
6525   if (is_tracepoint (b))
6526     {
6527       struct tracepoint *t = (struct tracepoint *) b;
6528
6529       if (!part_of_multiple && t->pass_count)
6530         {
6531           annotate_field (10);
6532           ui_out_text (uiout, "\tpass count ");
6533           ui_out_field_int (uiout, "pass", t->pass_count);
6534           ui_out_text (uiout, " \n");
6535         }
6536
6537       /* Don't display it when tracepoint or tracepoint location is
6538          pending.   */
6539       if (!header_of_multiple && loc != NULL && !loc->shlib_disabled)
6540         {
6541           annotate_field (11);
6542
6543           if (ui_out_is_mi_like_p (uiout))
6544             ui_out_field_string (uiout, "installed",
6545                                  loc->inserted ? "y" : "n");
6546           else
6547             {
6548               if (loc->inserted)
6549                 ui_out_text (uiout, "\t");
6550               else
6551                 ui_out_text (uiout, "\tnot ");
6552               ui_out_text (uiout, "installed on target\n");
6553             }
6554         }
6555     }
6556
6557   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
6558     {
6559       if (is_watchpoint (b))
6560         {
6561           struct watchpoint *w = (struct watchpoint *) b;
6562
6563           ui_out_field_string (uiout, "original-location", w->exp_string);
6564         }
6565       else if (b->addr_string)
6566         ui_out_field_string (uiout, "original-location", b->addr_string);
6567     }
6568 }
6569
6570 static void
6571 print_one_breakpoint (struct breakpoint *b,
6572                       struct bp_location **last_loc, 
6573                       int allflag)
6574 {
6575   struct cleanup *bkpt_chain;
6576   struct ui_out *uiout = current_uiout;
6577
6578   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
6579
6580   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
6581   do_cleanups (bkpt_chain);
6582
6583   /* If this breakpoint has custom print function,
6584      it's already printed.  Otherwise, print individual
6585      locations, if any.  */
6586   if (b->ops == NULL || b->ops->print_one == NULL)
6587     {
6588       /* If breakpoint has a single location that is disabled, we
6589          print it as if it had several locations, since otherwise it's
6590          hard to represent "breakpoint enabled, location disabled"
6591          situation.
6592
6593          Note that while hardware watchpoints have several locations
6594          internally, that's not a property exposed to user.  */
6595       if (b->loc 
6596           && !is_hardware_watchpoint (b)
6597           && (b->loc->next || !b->loc->enabled))
6598         {
6599           struct bp_location *loc;
6600           int n = 1;
6601
6602           for (loc = b->loc; loc; loc = loc->next, ++n)
6603             {
6604               struct cleanup *inner2 =
6605                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
6606               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
6607               do_cleanups (inner2);
6608             }
6609         }
6610     }
6611 }
6612
6613 static int
6614 breakpoint_address_bits (struct breakpoint *b)
6615 {
6616   int print_address_bits = 0;
6617   struct bp_location *loc;
6618
6619   for (loc = b->loc; loc; loc = loc->next)
6620     {
6621       int addr_bit;
6622
6623       /* Software watchpoints that aren't watching memory don't have
6624          an address to print.  */
6625       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
6626         continue;
6627
6628       addr_bit = gdbarch_addr_bit (loc->gdbarch);
6629       if (addr_bit > print_address_bits)
6630         print_address_bits = addr_bit;
6631     }
6632
6633   return print_address_bits;
6634 }
6635
6636 struct captured_breakpoint_query_args
6637   {
6638     int bnum;
6639   };
6640
6641 static int
6642 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
6643 {
6644   struct captured_breakpoint_query_args *args = data;
6645   struct breakpoint *b;
6646   struct bp_location *dummy_loc = NULL;
6647
6648   ALL_BREAKPOINTS (b)
6649     {
6650       if (args->bnum == b->number)
6651         {
6652           print_one_breakpoint (b, &dummy_loc, 0);
6653           return GDB_RC_OK;
6654         }
6655     }
6656   return GDB_RC_NONE;
6657 }
6658
6659 enum gdb_rc
6660 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
6661                       char **error_message)
6662 {
6663   struct captured_breakpoint_query_args args;
6664
6665   args.bnum = bnum;
6666   /* For the moment we don't trust print_one_breakpoint() to not throw
6667      an error.  */
6668   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
6669                                  error_message, RETURN_MASK_ALL) < 0)
6670     return GDB_RC_FAIL;
6671   else
6672     return GDB_RC_OK;
6673 }
6674
6675 /* Return true if this breakpoint was set by the user, false if it is
6676    internal or momentary.  */
6677
6678 int
6679 user_breakpoint_p (struct breakpoint *b)
6680 {
6681   return b->number > 0;
6682 }
6683
6684 /* Print information on user settable breakpoint (watchpoint, etc)
6685    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
6686    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
6687    FILTER is non-NULL, call it on each breakpoint and only include the
6688    ones for which it returns non-zero.  Return the total number of
6689    breakpoints listed.  */
6690
6691 static int
6692 breakpoint_1 (char *args, int allflag, 
6693               int (*filter) (const struct breakpoint *))
6694 {
6695   struct breakpoint *b;
6696   struct bp_location *last_loc = NULL;
6697   int nr_printable_breakpoints;
6698   struct cleanup *bkpttbl_chain;
6699   struct value_print_options opts;
6700   int print_address_bits = 0;
6701   int print_type_col_width = 14;
6702   struct ui_out *uiout = current_uiout;
6703
6704   get_user_print_options (&opts);
6705
6706   /* Compute the number of rows in the table, as well as the size
6707      required for address fields.  */
6708   nr_printable_breakpoints = 0;
6709   ALL_BREAKPOINTS (b)
6710     {
6711       /* If we have a filter, only list the breakpoints it accepts.  */
6712       if (filter && !filter (b))
6713         continue;
6714
6715       /* If we have an "args" string, it is a list of breakpoints to 
6716          accept.  Skip the others.  */
6717       if (args != NULL && *args != '\0')
6718         {
6719           if (allflag && parse_and_eval_long (args) != b->number)
6720             continue;
6721           if (!allflag && !number_is_in_list (args, b->number))
6722             continue;
6723         }
6724
6725       if (allflag || user_breakpoint_p (b))
6726         {
6727           int addr_bit, type_len;
6728
6729           addr_bit = breakpoint_address_bits (b);
6730           if (addr_bit > print_address_bits)
6731             print_address_bits = addr_bit;
6732
6733           type_len = strlen (bptype_string (b->type));
6734           if (type_len > print_type_col_width)
6735             print_type_col_width = type_len;
6736
6737           nr_printable_breakpoints++;
6738         }
6739     }
6740
6741   if (opts.addressprint)
6742     bkpttbl_chain 
6743       = make_cleanup_ui_out_table_begin_end (uiout, 6,
6744                                              nr_printable_breakpoints,
6745                                              "BreakpointTable");
6746   else
6747     bkpttbl_chain 
6748       = make_cleanup_ui_out_table_begin_end (uiout, 5,
6749                                              nr_printable_breakpoints,
6750                                              "BreakpointTable");
6751
6752   if (nr_printable_breakpoints > 0)
6753     annotate_breakpoints_headers ();
6754   if (nr_printable_breakpoints > 0)
6755     annotate_field (0);
6756   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
6757   if (nr_printable_breakpoints > 0)
6758     annotate_field (1);
6759   ui_out_table_header (uiout, print_type_col_width, ui_left,
6760                        "type", "Type");                         /* 2 */
6761   if (nr_printable_breakpoints > 0)
6762     annotate_field (2);
6763   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6764   if (nr_printable_breakpoints > 0)
6765     annotate_field (3);
6766   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6767   if (opts.addressprint)
6768     {
6769       if (nr_printable_breakpoints > 0)
6770         annotate_field (4);
6771       if (print_address_bits <= 32)
6772         ui_out_table_header (uiout, 10, ui_left, 
6773                              "addr", "Address");                /* 5 */
6774       else
6775         ui_out_table_header (uiout, 18, ui_left, 
6776                              "addr", "Address");                /* 5 */
6777     }
6778   if (nr_printable_breakpoints > 0)
6779     annotate_field (5);
6780   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6781   ui_out_table_body (uiout);
6782   if (nr_printable_breakpoints > 0)
6783     annotate_breakpoints_table ();
6784
6785   ALL_BREAKPOINTS (b)
6786     {
6787       QUIT;
6788       /* If we have a filter, only list the breakpoints it accepts.  */
6789       if (filter && !filter (b))
6790         continue;
6791
6792       /* If we have an "args" string, it is a list of breakpoints to 
6793          accept.  Skip the others.  */
6794
6795       if (args != NULL && *args != '\0')
6796         {
6797           if (allflag)  /* maintenance info breakpoint */
6798             {
6799               if (parse_and_eval_long (args) != b->number)
6800                 continue;
6801             }
6802           else          /* all others */
6803             {
6804               if (!number_is_in_list (args, b->number))
6805                 continue;
6806             }
6807         }
6808       /* We only print out user settable breakpoints unless the
6809          allflag is set.  */
6810       if (allflag || user_breakpoint_p (b))
6811         print_one_breakpoint (b, &last_loc, allflag);
6812     }
6813
6814   do_cleanups (bkpttbl_chain);
6815
6816   if (nr_printable_breakpoints == 0)
6817     {
6818       /* If there's a filter, let the caller decide how to report
6819          empty list.  */
6820       if (!filter)
6821         {
6822           if (args == NULL || *args == '\0')
6823             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6824           else
6825             ui_out_message (uiout, 0, 
6826                             "No breakpoint or watchpoint matching '%s'.\n",
6827                             args);
6828         }
6829     }
6830   else
6831     {
6832       if (last_loc && !server_command)
6833         set_next_address (last_loc->gdbarch, last_loc->address);
6834     }
6835
6836   /* FIXME?  Should this be moved up so that it is only called when
6837      there have been breakpoints? */
6838   annotate_breakpoints_table_end ();
6839
6840   return nr_printable_breakpoints;
6841 }
6842
6843 /* Display the value of default-collect in a way that is generally
6844    compatible with the breakpoint list.  */
6845
6846 static void
6847 default_collect_info (void)
6848 {
6849   struct ui_out *uiout = current_uiout;
6850
6851   /* If it has no value (which is frequently the case), say nothing; a
6852      message like "No default-collect." gets in user's face when it's
6853      not wanted.  */
6854   if (!*default_collect)
6855     return;
6856
6857   /* The following phrase lines up nicely with per-tracepoint collect
6858      actions.  */
6859   ui_out_text (uiout, "default collect ");
6860   ui_out_field_string (uiout, "default-collect", default_collect);
6861   ui_out_text (uiout, " \n");
6862 }
6863   
6864 static void
6865 breakpoints_info (char *args, int from_tty)
6866 {
6867   breakpoint_1 (args, 0, NULL);
6868
6869   default_collect_info ();
6870 }
6871
6872 static void
6873 watchpoints_info (char *args, int from_tty)
6874 {
6875   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6876   struct ui_out *uiout = current_uiout;
6877
6878   if (num_printed == 0)
6879     {
6880       if (args == NULL || *args == '\0')
6881         ui_out_message (uiout, 0, "No watchpoints.\n");
6882       else
6883         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6884     }
6885 }
6886
6887 static void
6888 maintenance_info_breakpoints (char *args, int from_tty)
6889 {
6890   breakpoint_1 (args, 1, NULL);
6891
6892   default_collect_info ();
6893 }
6894
6895 static int
6896 breakpoint_has_pc (struct breakpoint *b,
6897                    struct program_space *pspace,
6898                    CORE_ADDR pc, struct obj_section *section)
6899 {
6900   struct bp_location *bl = b->loc;
6901
6902   for (; bl; bl = bl->next)
6903     {
6904       if (bl->pspace == pspace
6905           && bl->address == pc
6906           && (!overlay_debugging || bl->section == section))
6907         return 1;         
6908     }
6909   return 0;
6910 }
6911
6912 /* Print a message describing any user-breakpoints set at PC.  This
6913    concerns with logical breakpoints, so we match program spaces, not
6914    address spaces.  */
6915
6916 static void
6917 describe_other_breakpoints (struct gdbarch *gdbarch,
6918                             struct program_space *pspace, CORE_ADDR pc,
6919                             struct obj_section *section, int thread)
6920 {
6921   int others = 0;
6922   struct breakpoint *b;
6923
6924   ALL_BREAKPOINTS (b)
6925     others += (user_breakpoint_p (b)
6926                && breakpoint_has_pc (b, pspace, pc, section));
6927   if (others > 0)
6928     {
6929       if (others == 1)
6930         printf_filtered (_("Note: breakpoint "));
6931       else /* if (others == ???) */
6932         printf_filtered (_("Note: breakpoints "));
6933       ALL_BREAKPOINTS (b)
6934         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6935           {
6936             others--;
6937             printf_filtered ("%d", b->number);
6938             if (b->thread == -1 && thread != -1)
6939               printf_filtered (" (all threads)");
6940             else if (b->thread != -1)
6941               printf_filtered (" (thread %d)", b->thread);
6942             printf_filtered ("%s%s ",
6943                              ((b->enable_state == bp_disabled
6944                                || b->enable_state == bp_call_disabled)
6945                               ? " (disabled)"
6946                               : b->enable_state == bp_permanent 
6947                               ? " (permanent)"
6948                               : ""),
6949                              (others > 1) ? "," 
6950                              : ((others == 1) ? " and" : ""));
6951           }
6952       printf_filtered (_("also set at pc "));
6953       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6954       printf_filtered (".\n");
6955     }
6956 }
6957 \f
6958
6959 /* Return true iff it is meaningful to use the address member of
6960    BPT.  For some breakpoint types, the address member is irrelevant
6961    and it makes no sense to attempt to compare it to other addresses
6962    (or use it for any other purpose either).
6963
6964    More specifically, each of the following breakpoint types will
6965    always have a zero valued address and we don't want to mark
6966    breakpoints of any of these types to be a duplicate of an actual
6967    breakpoint at address zero:
6968
6969       bp_watchpoint
6970       bp_catchpoint
6971
6972 */
6973
6974 static int
6975 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6976 {
6977   enum bptype type = bpt->type;
6978
6979   return (type != bp_watchpoint && type != bp_catchpoint);
6980 }
6981
6982 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6983    true if LOC1 and LOC2 represent the same watchpoint location.  */
6984
6985 static int
6986 watchpoint_locations_match (struct bp_location *loc1, 
6987                             struct bp_location *loc2)
6988 {
6989   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6990   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6991
6992   /* Both of them must exist.  */
6993   gdb_assert (w1 != NULL);
6994   gdb_assert (w2 != NULL);
6995
6996   /* If the target can evaluate the condition expression in hardware,
6997      then we we need to insert both watchpoints even if they are at
6998      the same place.  Otherwise the watchpoint will only trigger when
6999      the condition of whichever watchpoint was inserted evaluates to
7000      true, not giving a chance for GDB to check the condition of the
7001      other watchpoint.  */
7002   if ((w1->cond_exp
7003        && target_can_accel_watchpoint_condition (loc1->address, 
7004                                                  loc1->length,
7005                                                  loc1->watchpoint_type,
7006                                                  w1->cond_exp))
7007       || (w2->cond_exp
7008           && target_can_accel_watchpoint_condition (loc2->address, 
7009                                                     loc2->length,
7010                                                     loc2->watchpoint_type,
7011                                                     w2->cond_exp)))
7012     return 0;
7013
7014   /* Note that this checks the owner's type, not the location's.  In
7015      case the target does not support read watchpoints, but does
7016      support access watchpoints, we'll have bp_read_watchpoint
7017      watchpoints with hw_access locations.  Those should be considered
7018      duplicates of hw_read locations.  The hw_read locations will
7019      become hw_access locations later.  */
7020   return (loc1->owner->type == loc2->owner->type
7021           && loc1->pspace->aspace == loc2->pspace->aspace
7022           && loc1->address == loc2->address
7023           && loc1->length == loc2->length);
7024 }
7025
7026 /* See breakpoint.h.  */
7027
7028 int
7029 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
7030                           struct address_space *aspace2, CORE_ADDR addr2)
7031 {
7032   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7033            || aspace1 == aspace2)
7034           && addr1 == addr2);
7035 }
7036
7037 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
7038    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
7039    matches ASPACE2.  On targets that have global breakpoints, the address
7040    space doesn't really matter.  */
7041
7042 static int
7043 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
7044                                 int len1, struct address_space *aspace2,
7045                                 CORE_ADDR addr2)
7046 {
7047   return ((gdbarch_has_global_breakpoints (target_gdbarch ())
7048            || aspace1 == aspace2)
7049           && addr2 >= addr1 && addr2 < addr1 + len1);
7050 }
7051
7052 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
7053    a ranged breakpoint.  In most targets, a match happens only if ASPACE
7054    matches the breakpoint's address space.  On targets that have global
7055    breakpoints, the address space doesn't really matter.  */
7056
7057 static int
7058 breakpoint_location_address_match (struct bp_location *bl,
7059                                    struct address_space *aspace,
7060                                    CORE_ADDR addr)
7061 {
7062   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
7063                                     aspace, addr)
7064           || (bl->length
7065               && breakpoint_address_match_range (bl->pspace->aspace,
7066                                                  bl->address, bl->length,
7067                                                  aspace, addr)));
7068 }
7069
7070 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
7071    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
7072    true, otherwise returns false.  */
7073
7074 static int
7075 tracepoint_locations_match (struct bp_location *loc1,
7076                             struct bp_location *loc2)
7077 {
7078   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
7079     /* Since tracepoint locations are never duplicated with others', tracepoint
7080        locations at the same address of different tracepoints are regarded as
7081        different locations.  */
7082     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
7083   else
7084     return 0;
7085 }
7086
7087 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
7088    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
7089    represent the same location.  */
7090
7091 static int
7092 breakpoint_locations_match (struct bp_location *loc1, 
7093                             struct bp_location *loc2)
7094 {
7095   int hw_point1, hw_point2;
7096
7097   /* Both of them must not be in moribund_locations.  */
7098   gdb_assert (loc1->owner != NULL);
7099   gdb_assert (loc2->owner != NULL);
7100
7101   hw_point1 = is_hardware_watchpoint (loc1->owner);
7102   hw_point2 = is_hardware_watchpoint (loc2->owner);
7103
7104   if (hw_point1 != hw_point2)
7105     return 0;
7106   else if (hw_point1)
7107     return watchpoint_locations_match (loc1, loc2);
7108   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
7109     return tracepoint_locations_match (loc1, loc2);
7110   else
7111     /* We compare bp_location.length in order to cover ranged breakpoints.  */
7112     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
7113                                      loc2->pspace->aspace, loc2->address)
7114             && loc1->length == loc2->length);
7115 }
7116
7117 static void
7118 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
7119                                int bnum, int have_bnum)
7120 {
7121   /* The longest string possibly returned by hex_string_custom
7122      is 50 chars.  These must be at least that big for safety.  */
7123   char astr1[64];
7124   char astr2[64];
7125
7126   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
7127   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
7128   if (have_bnum)
7129     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
7130              bnum, astr1, astr2);
7131   else
7132     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
7133 }
7134
7135 /* Adjust a breakpoint's address to account for architectural
7136    constraints on breakpoint placement.  Return the adjusted address.
7137    Note: Very few targets require this kind of adjustment.  For most
7138    targets, this function is simply the identity function.  */
7139
7140 static CORE_ADDR
7141 adjust_breakpoint_address (struct gdbarch *gdbarch,
7142                            CORE_ADDR bpaddr, enum bptype bptype)
7143 {
7144   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
7145     {
7146       /* Very few targets need any kind of breakpoint adjustment.  */
7147       return bpaddr;
7148     }
7149   else if (bptype == bp_watchpoint
7150            || bptype == bp_hardware_watchpoint
7151            || bptype == bp_read_watchpoint
7152            || bptype == bp_access_watchpoint
7153            || bptype == bp_catchpoint)
7154     {
7155       /* Watchpoints and the various bp_catch_* eventpoints should not
7156          have their addresses modified.  */
7157       return bpaddr;
7158     }
7159   else
7160     {
7161       CORE_ADDR adjusted_bpaddr;
7162
7163       /* Some targets have architectural constraints on the placement
7164          of breakpoint instructions.  Obtain the adjusted address.  */
7165       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
7166
7167       /* An adjusted breakpoint address can significantly alter
7168          a user's expectations.  Print a warning if an adjustment
7169          is required.  */
7170       if (adjusted_bpaddr != bpaddr)
7171         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
7172
7173       return adjusted_bpaddr;
7174     }
7175 }
7176
7177 void
7178 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
7179                   struct breakpoint *owner)
7180 {
7181   memset (loc, 0, sizeof (*loc));
7182
7183   gdb_assert (ops != NULL);
7184
7185   loc->ops = ops;
7186   loc->owner = owner;
7187   loc->cond = NULL;
7188   loc->cond_bytecode = NULL;
7189   loc->shlib_disabled = 0;
7190   loc->enabled = 1;
7191
7192   switch (owner->type)
7193     {
7194     case bp_breakpoint:
7195     case bp_until:
7196     case bp_finish:
7197     case bp_longjmp:
7198     case bp_longjmp_resume:
7199     case bp_longjmp_call_dummy:
7200     case bp_exception:
7201     case bp_exception_resume:
7202     case bp_step_resume:
7203     case bp_hp_step_resume:
7204     case bp_watchpoint_scope:
7205     case bp_call_dummy:
7206     case bp_std_terminate:
7207     case bp_shlib_event:
7208     case bp_thread_event:
7209     case bp_overlay_event:
7210     case bp_jit_event:
7211     case bp_longjmp_master:
7212     case bp_std_terminate_master:
7213     case bp_exception_master:
7214     case bp_gnu_ifunc_resolver:
7215     case bp_gnu_ifunc_resolver_return:
7216     case bp_dprintf:
7217       loc->loc_type = bp_loc_software_breakpoint;
7218       mark_breakpoint_location_modified (loc);
7219       break;
7220     case bp_hardware_breakpoint:
7221       loc->loc_type = bp_loc_hardware_breakpoint;
7222       mark_breakpoint_location_modified (loc);
7223       break;
7224     case bp_hardware_watchpoint:
7225     case bp_read_watchpoint:
7226     case bp_access_watchpoint:
7227       loc->loc_type = bp_loc_hardware_watchpoint;
7228       break;
7229     case bp_watchpoint:
7230     case bp_catchpoint:
7231     case bp_tracepoint:
7232     case bp_fast_tracepoint:
7233     case bp_static_tracepoint:
7234       loc->loc_type = bp_loc_other;
7235       break;
7236     default:
7237       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
7238     }
7239
7240   loc->refc = 1;
7241 }
7242
7243 /* Allocate a struct bp_location.  */
7244
7245 static struct bp_location *
7246 allocate_bp_location (struct breakpoint *bpt)
7247 {
7248   return bpt->ops->allocate_location (bpt);
7249 }
7250
7251 static void
7252 free_bp_location (struct bp_location *loc)
7253 {
7254   loc->ops->dtor (loc);
7255   xfree (loc);
7256 }
7257
7258 /* Increment reference count.  */
7259
7260 static void
7261 incref_bp_location (struct bp_location *bl)
7262 {
7263   ++bl->refc;
7264 }
7265
7266 /* Decrement reference count.  If the reference count reaches 0,
7267    destroy the bp_location.  Sets *BLP to NULL.  */
7268
7269 static void
7270 decref_bp_location (struct bp_location **blp)
7271 {
7272   gdb_assert ((*blp)->refc > 0);
7273
7274   if (--(*blp)->refc == 0)
7275     free_bp_location (*blp);
7276   *blp = NULL;
7277 }
7278
7279 /* Add breakpoint B at the end of the global breakpoint chain.  */
7280
7281 static void
7282 add_to_breakpoint_chain (struct breakpoint *b)
7283 {
7284   struct breakpoint *b1;
7285
7286   /* Add this breakpoint to the end of the chain so that a list of
7287      breakpoints will come out in order of increasing numbers.  */
7288
7289   b1 = breakpoint_chain;
7290   if (b1 == 0)
7291     breakpoint_chain = b;
7292   else
7293     {
7294       while (b1->next)
7295         b1 = b1->next;
7296       b1->next = b;
7297     }
7298 }
7299
7300 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
7301
7302 static void
7303 init_raw_breakpoint_without_location (struct breakpoint *b,
7304                                       struct gdbarch *gdbarch,
7305                                       enum bptype bptype,
7306                                       const struct breakpoint_ops *ops)
7307 {
7308   memset (b, 0, sizeof (*b));
7309
7310   gdb_assert (ops != NULL);
7311
7312   b->ops = ops;
7313   b->type = bptype;
7314   b->gdbarch = gdbarch;
7315   b->language = current_language->la_language;
7316   b->input_radix = input_radix;
7317   b->thread = -1;
7318   b->enable_state = bp_enabled;
7319   b->next = 0;
7320   b->silent = 0;
7321   b->ignore_count = 0;
7322   b->commands = NULL;
7323   b->frame_id = null_frame_id;
7324   b->condition_not_parsed = 0;
7325   b->py_bp_object = NULL;
7326   b->related_breakpoint = b;
7327 }
7328
7329 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
7330    that has type BPTYPE and has no locations as yet.  */
7331
7332 static struct breakpoint *
7333 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
7334                                      enum bptype bptype,
7335                                      const struct breakpoint_ops *ops)
7336 {
7337   struct breakpoint *b = XNEW (struct breakpoint);
7338
7339   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7340   add_to_breakpoint_chain (b);
7341   return b;
7342 }
7343
7344 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
7345    resolutions should be made as the user specified the location explicitly
7346    enough.  */
7347
7348 static void
7349 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
7350 {
7351   gdb_assert (loc->owner != NULL);
7352
7353   if (loc->owner->type == bp_breakpoint
7354       || loc->owner->type == bp_hardware_breakpoint
7355       || is_tracepoint (loc->owner))
7356     {
7357       int is_gnu_ifunc;
7358       const char *function_name;
7359       CORE_ADDR func_addr;
7360
7361       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
7362                                           &func_addr, NULL, &is_gnu_ifunc);
7363
7364       if (is_gnu_ifunc && !explicit_loc)
7365         {
7366           struct breakpoint *b = loc->owner;
7367
7368           gdb_assert (loc->pspace == current_program_space);
7369           if (gnu_ifunc_resolve_name (function_name,
7370                                       &loc->requested_address))
7371             {
7372               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
7373               loc->address = adjust_breakpoint_address (loc->gdbarch,
7374                                                         loc->requested_address,
7375                                                         b->type);
7376             }
7377           else if (b->type == bp_breakpoint && b->loc == loc
7378                    && loc->next == NULL && b->related_breakpoint == b)
7379             {
7380               /* Create only the whole new breakpoint of this type but do not
7381                  mess more complicated breakpoints with multiple locations.  */
7382               b->type = bp_gnu_ifunc_resolver;
7383               /* Remember the resolver's address for use by the return
7384                  breakpoint.  */
7385               loc->related_address = func_addr;
7386             }
7387         }
7388
7389       if (function_name)
7390         loc->function_name = xstrdup (function_name);
7391     }
7392 }
7393
7394 /* Attempt to determine architecture of location identified by SAL.  */
7395 struct gdbarch *
7396 get_sal_arch (struct symtab_and_line sal)
7397 {
7398   if (sal.section)
7399     return get_objfile_arch (sal.section->objfile);
7400   if (sal.symtab)
7401     return get_objfile_arch (sal.symtab->objfile);
7402
7403   return NULL;
7404 }
7405
7406 /* Low level routine for partially initializing a breakpoint of type
7407    BPTYPE.  The newly created breakpoint's address, section, source
7408    file name, and line number are provided by SAL.
7409
7410    It is expected that the caller will complete the initialization of
7411    the newly created breakpoint struct as well as output any status
7412    information regarding the creation of a new breakpoint.  */
7413
7414 static void
7415 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
7416                      struct symtab_and_line sal, enum bptype bptype,
7417                      const struct breakpoint_ops *ops)
7418 {
7419   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
7420
7421   add_location_to_breakpoint (b, &sal);
7422
7423   if (bptype != bp_catchpoint)
7424     gdb_assert (sal.pspace != NULL);
7425
7426   /* Store the program space that was used to set the breakpoint,
7427      except for ordinary breakpoints, which are independent of the
7428      program space.  */
7429   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
7430     b->pspace = sal.pspace;
7431 }
7432
7433 /* set_raw_breakpoint is a low level routine for allocating and
7434    partially initializing a breakpoint of type BPTYPE.  The newly
7435    created breakpoint's address, section, source file name, and line
7436    number are provided by SAL.  The newly created and partially
7437    initialized breakpoint is added to the breakpoint chain and
7438    is also returned as the value of this function.
7439
7440    It is expected that the caller will complete the initialization of
7441    the newly created breakpoint struct as well as output any status
7442    information regarding the creation of a new breakpoint.  In
7443    particular, set_raw_breakpoint does NOT set the breakpoint
7444    number!  Care should be taken to not allow an error to occur
7445    prior to completing the initialization of the breakpoint.  If this
7446    should happen, a bogus breakpoint will be left on the chain.  */
7447
7448 struct breakpoint *
7449 set_raw_breakpoint (struct gdbarch *gdbarch,
7450                     struct symtab_and_line sal, enum bptype bptype,
7451                     const struct breakpoint_ops *ops)
7452 {
7453   struct breakpoint *b = XNEW (struct breakpoint);
7454
7455   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
7456   add_to_breakpoint_chain (b);
7457   return b;
7458 }
7459
7460
7461 /* Note that the breakpoint object B describes a permanent breakpoint
7462    instruction, hard-wired into the inferior's code.  */
7463 void
7464 make_breakpoint_permanent (struct breakpoint *b)
7465 {
7466   struct bp_location *bl;
7467
7468   b->enable_state = bp_permanent;
7469
7470   /* By definition, permanent breakpoints are already present in the
7471      code.  Mark all locations as inserted.  For now,
7472      make_breakpoint_permanent is called in just one place, so it's
7473      hard to say if it's reasonable to have permanent breakpoint with
7474      multiple locations or not, but it's easy to implement.  */
7475   for (bl = b->loc; bl; bl = bl->next)
7476     bl->inserted = 1;
7477 }
7478
7479 /* Call this routine when stepping and nexting to enable a breakpoint
7480    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
7481    initiated the operation.  */
7482
7483 void
7484 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
7485 {
7486   struct breakpoint *b, *b_tmp;
7487   int thread = tp->num;
7488
7489   /* To avoid having to rescan all objfile symbols at every step,
7490      we maintain a list of continually-inserted but always disabled
7491      longjmp "master" breakpoints.  Here, we simply create momentary
7492      clones of those and enable them for the requested thread.  */
7493   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7494     if (b->pspace == current_program_space
7495         && (b->type == bp_longjmp_master
7496             || b->type == bp_exception_master))
7497       {
7498         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
7499         struct breakpoint *clone;
7500
7501         /* longjmp_breakpoint_ops ensures INITIATING_FRAME is cleared again
7502            after their removal.  */
7503         clone = momentary_breakpoint_from_master (b, type,
7504                                                   &longjmp_breakpoint_ops, 1);
7505         clone->thread = thread;
7506       }
7507
7508   tp->initiating_frame = frame;
7509 }
7510
7511 /* Delete all longjmp breakpoints from THREAD.  */
7512 void
7513 delete_longjmp_breakpoint (int thread)
7514 {
7515   struct breakpoint *b, *b_tmp;
7516
7517   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7518     if (b->type == bp_longjmp || b->type == bp_exception)
7519       {
7520         if (b->thread == thread)
7521           delete_breakpoint (b);
7522       }
7523 }
7524
7525 void
7526 delete_longjmp_breakpoint_at_next_stop (int thread)
7527 {
7528   struct breakpoint *b, *b_tmp;
7529
7530   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7531     if (b->type == bp_longjmp || b->type == bp_exception)
7532       {
7533         if (b->thread == thread)
7534           b->disposition = disp_del_at_next_stop;
7535       }
7536 }
7537
7538 /* Place breakpoints of type bp_longjmp_call_dummy to catch longjmp for
7539    INFERIOR_PTID thread.  Chain them all by RELATED_BREAKPOINT and return
7540    pointer to any of them.  Return NULL if this system cannot place longjmp
7541    breakpoints.  */
7542
7543 struct breakpoint *
7544 set_longjmp_breakpoint_for_call_dummy (void)
7545 {
7546   struct breakpoint *b, *retval = NULL;
7547
7548   ALL_BREAKPOINTS (b)
7549     if (b->pspace == current_program_space && b->type == bp_longjmp_master)
7550       {
7551         struct breakpoint *new_b;
7552
7553         new_b = momentary_breakpoint_from_master (b, bp_longjmp_call_dummy,
7554                                                   &momentary_breakpoint_ops,
7555                                                   1);
7556         new_b->thread = pid_to_thread_id (inferior_ptid);
7557
7558         /* Link NEW_B into the chain of RETVAL breakpoints.  */
7559
7560         gdb_assert (new_b->related_breakpoint == new_b);
7561         if (retval == NULL)
7562           retval = new_b;
7563         new_b->related_breakpoint = retval;
7564         while (retval->related_breakpoint != new_b->related_breakpoint)
7565           retval = retval->related_breakpoint;
7566         retval->related_breakpoint = new_b;
7567       }
7568
7569   return retval;
7570 }
7571
7572 /* Verify all existing dummy frames and their associated breakpoints for
7573    TP.  Remove those which can no longer be found in the current frame
7574    stack.
7575
7576    You should call this function only at places where it is safe to currently
7577    unwind the whole stack.  Failed stack unwind would discard live dummy
7578    frames.  */
7579
7580 void
7581 check_longjmp_breakpoint_for_call_dummy (struct thread_info *tp)
7582 {
7583   struct breakpoint *b, *b_tmp;
7584
7585   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7586     if (b->type == bp_longjmp_call_dummy && b->thread == tp->num)
7587       {
7588         struct breakpoint *dummy_b = b->related_breakpoint;
7589
7590         while (dummy_b != b && dummy_b->type != bp_call_dummy)
7591           dummy_b = dummy_b->related_breakpoint;
7592         if (dummy_b->type != bp_call_dummy
7593             || frame_find_by_id (dummy_b->frame_id) != NULL)
7594           continue;
7595         
7596         dummy_frame_discard (dummy_b->frame_id, tp->ptid);
7597
7598         while (b->related_breakpoint != b)
7599           {
7600             if (b_tmp == b->related_breakpoint)
7601               b_tmp = b->related_breakpoint->next;
7602             delete_breakpoint (b->related_breakpoint);
7603           }
7604         delete_breakpoint (b);
7605       }
7606 }
7607
7608 void
7609 enable_overlay_breakpoints (void)
7610 {
7611   struct breakpoint *b;
7612
7613   ALL_BREAKPOINTS (b)
7614     if (b->type == bp_overlay_event)
7615     {
7616       b->enable_state = bp_enabled;
7617       update_global_location_list (UGLL_MAY_INSERT);
7618       overlay_events_enabled = 1;
7619     }
7620 }
7621
7622 void
7623 disable_overlay_breakpoints (void)
7624 {
7625   struct breakpoint *b;
7626
7627   ALL_BREAKPOINTS (b)
7628     if (b->type == bp_overlay_event)
7629     {
7630       b->enable_state = bp_disabled;
7631       update_global_location_list (UGLL_DONT_INSERT);
7632       overlay_events_enabled = 0;
7633     }
7634 }
7635
7636 /* Set an active std::terminate breakpoint for each std::terminate
7637    master breakpoint.  */
7638 void
7639 set_std_terminate_breakpoint (void)
7640 {
7641   struct breakpoint *b, *b_tmp;
7642
7643   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7644     if (b->pspace == current_program_space
7645         && b->type == bp_std_terminate_master)
7646       {
7647         momentary_breakpoint_from_master (b, bp_std_terminate,
7648                                           &momentary_breakpoint_ops, 1);
7649       }
7650 }
7651
7652 /* Delete all the std::terminate breakpoints.  */
7653 void
7654 delete_std_terminate_breakpoint (void)
7655 {
7656   struct breakpoint *b, *b_tmp;
7657
7658   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7659     if (b->type == bp_std_terminate)
7660       delete_breakpoint (b);
7661 }
7662
7663 struct breakpoint *
7664 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7665 {
7666   struct breakpoint *b;
7667
7668   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
7669                                   &internal_breakpoint_ops);
7670
7671   b->enable_state = bp_enabled;
7672   /* addr_string has to be used or breakpoint_re_set will delete me.  */
7673   b->addr_string
7674     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7675
7676   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7677
7678   return b;
7679 }
7680
7681 void
7682 remove_thread_event_breakpoints (void)
7683 {
7684   struct breakpoint *b, *b_tmp;
7685
7686   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7687     if (b->type == bp_thread_event
7688         && b->loc->pspace == current_program_space)
7689       delete_breakpoint (b);
7690 }
7691
7692 struct lang_and_radix
7693   {
7694     enum language lang;
7695     int radix;
7696   };
7697
7698 /* Create a breakpoint for JIT code registration and unregistration.  */
7699
7700 struct breakpoint *
7701 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7702 {
7703   struct breakpoint *b;
7704
7705   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
7706                                   &internal_breakpoint_ops);
7707   update_global_location_list_nothrow (UGLL_MAY_INSERT);
7708   return b;
7709 }
7710
7711 /* Remove JIT code registration and unregistration breakpoint(s).  */
7712
7713 void
7714 remove_jit_event_breakpoints (void)
7715 {
7716   struct breakpoint *b, *b_tmp;
7717
7718   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7719     if (b->type == bp_jit_event
7720         && b->loc->pspace == current_program_space)
7721       delete_breakpoint (b);
7722 }
7723
7724 void
7725 remove_solib_event_breakpoints (void)
7726 {
7727   struct breakpoint *b, *b_tmp;
7728
7729   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7730     if (b->type == bp_shlib_event
7731         && b->loc->pspace == current_program_space)
7732       delete_breakpoint (b);
7733 }
7734
7735 /* See breakpoint.h.  */
7736
7737 void
7738 remove_solib_event_breakpoints_at_next_stop (void)
7739 {
7740   struct breakpoint *b, *b_tmp;
7741
7742   ALL_BREAKPOINTS_SAFE (b, b_tmp)
7743     if (b->type == bp_shlib_event
7744         && b->loc->pspace == current_program_space)
7745       b->disposition = disp_del_at_next_stop;
7746 }
7747
7748 /* Helper for create_solib_event_breakpoint /
7749    create_and_insert_solib_event_breakpoint.  Allows specifying which
7750    INSERT_MODE to pass through to update_global_location_list.  */
7751
7752 static struct breakpoint *
7753 create_solib_event_breakpoint_1 (struct gdbarch *gdbarch, CORE_ADDR address,
7754                                  enum ugll_insert_mode insert_mode)
7755 {
7756   struct breakpoint *b;
7757
7758   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
7759                                   &internal_breakpoint_ops);
7760   update_global_location_list_nothrow (insert_mode);
7761   return b;
7762 }
7763
7764 struct breakpoint *
7765 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7766 {
7767   return create_solib_event_breakpoint_1 (gdbarch, address, UGLL_MAY_INSERT);
7768 }
7769
7770 /* See breakpoint.h.  */
7771
7772 struct breakpoint *
7773 create_and_insert_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
7774 {
7775   struct breakpoint *b;
7776
7777   /* Explicitly tell update_global_location_list to insert
7778      locations.  */
7779   b = create_solib_event_breakpoint_1 (gdbarch, address, UGLL_INSERT);
7780   if (!b->loc->inserted)
7781     {
7782       delete_breakpoint (b);
7783       return NULL;
7784     }
7785   return b;
7786 }
7787
7788 /* Disable any breakpoints that are on code in shared libraries.  Only
7789    apply to enabled breakpoints, disabled ones can just stay disabled.  */
7790
7791 void
7792 disable_breakpoints_in_shlibs (void)
7793 {
7794   struct bp_location *loc, **locp_tmp;
7795
7796   ALL_BP_LOCATIONS (loc, locp_tmp)
7797   {
7798     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7799     struct breakpoint *b = loc->owner;
7800
7801     /* We apply the check to all breakpoints, including disabled for
7802        those with loc->duplicate set.  This is so that when breakpoint
7803        becomes enabled, or the duplicate is removed, gdb will try to
7804        insert all breakpoints.  If we don't set shlib_disabled here,
7805        we'll try to insert those breakpoints and fail.  */
7806     if (((b->type == bp_breakpoint)
7807          || (b->type == bp_jit_event)
7808          || (b->type == bp_hardware_breakpoint)
7809          || (is_tracepoint (b)))
7810         && loc->pspace == current_program_space
7811         && !loc->shlib_disabled
7812         && solib_name_from_address (loc->pspace, loc->address)
7813         )
7814       {
7815         loc->shlib_disabled = 1;
7816       }
7817   }
7818 }
7819
7820 /* Disable any breakpoints and tracepoints that are in SOLIB upon
7821    notification of unloaded_shlib.  Only apply to enabled breakpoints,
7822    disabled ones can just stay disabled.  */
7823
7824 static void
7825 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
7826 {
7827   struct bp_location *loc, **locp_tmp;
7828   int disabled_shlib_breaks = 0;
7829
7830   /* SunOS a.out shared libraries are always mapped, so do not
7831      disable breakpoints; they will only be reported as unloaded
7832      through clear_solib when GDB discards its shared library
7833      list.  See clear_solib for more information.  */
7834   if (exec_bfd != NULL
7835       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
7836     return;
7837
7838   ALL_BP_LOCATIONS (loc, locp_tmp)
7839   {
7840     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
7841     struct breakpoint *b = loc->owner;
7842
7843     if (solib->pspace == loc->pspace
7844         && !loc->shlib_disabled
7845         && (((b->type == bp_breakpoint
7846               || b->type == bp_jit_event
7847               || b->type == bp_hardware_breakpoint)
7848              && (loc->loc_type == bp_loc_hardware_breakpoint
7849                  || loc->loc_type == bp_loc_software_breakpoint))
7850             || is_tracepoint (b))
7851         && solib_contains_address_p (solib, loc->address))
7852       {
7853         loc->shlib_disabled = 1;
7854         /* At this point, we cannot rely on remove_breakpoint
7855            succeeding so we must mark the breakpoint as not inserted
7856            to prevent future errors occurring in remove_breakpoints.  */
7857         loc->inserted = 0;
7858
7859         /* This may cause duplicate notifications for the same breakpoint.  */
7860         observer_notify_breakpoint_modified (b);
7861
7862         if (!disabled_shlib_breaks)
7863           {
7864             target_terminal_ours_for_output ();
7865             warning (_("Temporarily disabling breakpoints "
7866                        "for unloaded shared library \"%s\""),
7867                      solib->so_name);
7868           }
7869         disabled_shlib_breaks = 1;
7870       }
7871   }
7872 }
7873
7874 /* Disable any breakpoints and tracepoints in OBJFILE upon
7875    notification of free_objfile.  Only apply to enabled breakpoints,
7876    disabled ones can just stay disabled.  */
7877
7878 static void
7879 disable_breakpoints_in_freed_objfile (struct objfile *objfile)
7880 {
7881   struct breakpoint *b;
7882
7883   if (objfile == NULL)
7884     return;
7885
7886   /* OBJF_SHARED|OBJF_USERLOADED objfiles are dynamic modules manually
7887      managed by the user with add-symbol-file/remove-symbol-file.
7888      Similarly to how breakpoints in shared libraries are handled in
7889      response to "nosharedlibrary", mark breakpoints in such modules
7890      shlib_disabled so they end up uninserted on the next global
7891      location list update.  Shared libraries not loaded by the user
7892      aren't handled here -- they're already handled in
7893      disable_breakpoints_in_unloaded_shlib, called by solib.c's
7894      solib_unloaded observer.  We skip objfiles that are not
7895      OBJF_SHARED as those aren't considered dynamic objects (e.g. the
7896      main objfile).  */
7897   if ((objfile->flags & OBJF_SHARED) == 0
7898       || (objfile->flags & OBJF_USERLOADED) == 0)
7899     return;
7900
7901   ALL_BREAKPOINTS (b)
7902     {
7903       struct bp_location *loc;
7904       int bp_modified = 0;
7905
7906       if (!is_breakpoint (b) && !is_tracepoint (b))
7907         continue;
7908
7909       for (loc = b->loc; loc != NULL; loc = loc->next)
7910         {
7911           CORE_ADDR loc_addr = loc->address;
7912
7913           if (loc->loc_type != bp_loc_hardware_breakpoint
7914               && loc->loc_type != bp_loc_software_breakpoint)
7915             continue;
7916
7917           if (loc->shlib_disabled != 0)
7918             continue;
7919
7920           if (objfile->pspace != loc->pspace)
7921             continue;
7922
7923           if (loc->loc_type != bp_loc_hardware_breakpoint
7924               && loc->loc_type != bp_loc_software_breakpoint)
7925             continue;
7926
7927           if (is_addr_in_objfile (loc_addr, objfile))
7928             {
7929               loc->shlib_disabled = 1;
7930               /* At this point, we don't know whether the object was
7931                  unmapped from the inferior or not, so leave the
7932                  inserted flag alone.  We'll handle failure to
7933                  uninsert quietly, in case the object was indeed
7934                  unmapped.  */
7935
7936               mark_breakpoint_location_modified (loc);
7937
7938               bp_modified = 1;
7939             }
7940         }
7941
7942       if (bp_modified)
7943         observer_notify_breakpoint_modified (b);
7944     }
7945 }
7946
7947 /* FORK & VFORK catchpoints.  */
7948
7949 /* An instance of this type is used to represent a fork or vfork
7950    catchpoint.  It includes a "struct breakpoint" as a kind of base
7951    class; users downcast to "struct breakpoint *" when needed.  A
7952    breakpoint is really of this type iff its ops pointer points to
7953    CATCH_FORK_BREAKPOINT_OPS.  */
7954
7955 struct fork_catchpoint
7956 {
7957   /* The base class.  */
7958   struct breakpoint base;
7959
7960   /* Process id of a child process whose forking triggered this
7961      catchpoint.  This field is only valid immediately after this
7962      catchpoint has triggered.  */
7963   ptid_t forked_inferior_pid;
7964 };
7965
7966 /* Implement the "insert" breakpoint_ops method for fork
7967    catchpoints.  */
7968
7969 static int
7970 insert_catch_fork (struct bp_location *bl)
7971 {
7972   return target_insert_fork_catchpoint (ptid_get_pid (inferior_ptid));
7973 }
7974
7975 /* Implement the "remove" breakpoint_ops method for fork
7976    catchpoints.  */
7977
7978 static int
7979 remove_catch_fork (struct bp_location *bl)
7980 {
7981   return target_remove_fork_catchpoint (ptid_get_pid (inferior_ptid));
7982 }
7983
7984 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7985    catchpoints.  */
7986
7987 static int
7988 breakpoint_hit_catch_fork (const struct bp_location *bl,
7989                            struct address_space *aspace, CORE_ADDR bp_addr,
7990                            const struct target_waitstatus *ws)
7991 {
7992   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7993
7994   if (ws->kind != TARGET_WAITKIND_FORKED)
7995     return 0;
7996
7997   c->forked_inferior_pid = ws->value.related_pid;
7998   return 1;
7999 }
8000
8001 /* Implement the "print_it" breakpoint_ops method for fork
8002    catchpoints.  */
8003
8004 static enum print_stop_action
8005 print_it_catch_fork (bpstat bs)
8006 {
8007   struct ui_out *uiout = current_uiout;
8008   struct breakpoint *b = bs->breakpoint_at;
8009   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
8010
8011   annotate_catchpoint (b->number);
8012   if (b->disposition == disp_del)
8013     ui_out_text (uiout, "\nTemporary catchpoint ");
8014   else
8015     ui_out_text (uiout, "\nCatchpoint ");
8016   if (ui_out_is_mi_like_p (uiout))
8017     {
8018       ui_out_field_string (uiout, "reason",
8019                            async_reason_lookup (EXEC_ASYNC_FORK));
8020       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8021     }
8022   ui_out_field_int (uiout, "bkptno", b->number);
8023   ui_out_text (uiout, " (forked process ");
8024   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8025   ui_out_text (uiout, "), ");
8026   return PRINT_SRC_AND_LOC;
8027 }
8028
8029 /* Implement the "print_one" breakpoint_ops method for fork
8030    catchpoints.  */
8031
8032 static void
8033 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
8034 {
8035   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8036   struct value_print_options opts;
8037   struct ui_out *uiout = current_uiout;
8038
8039   get_user_print_options (&opts);
8040
8041   /* Field 4, the address, is omitted (which makes the columns not
8042      line up too nicely with the headers, but the effect is relatively
8043      readable).  */
8044   if (opts.addressprint)
8045     ui_out_field_skip (uiout, "addr");
8046   annotate_field (5);
8047   ui_out_text (uiout, "fork");
8048   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8049     {
8050       ui_out_text (uiout, ", process ");
8051       ui_out_field_int (uiout, "what",
8052                         ptid_get_pid (c->forked_inferior_pid));
8053       ui_out_spaces (uiout, 1);
8054     }
8055
8056   if (ui_out_is_mi_like_p (uiout))
8057     ui_out_field_string (uiout, "catch-type", "fork");
8058 }
8059
8060 /* Implement the "print_mention" breakpoint_ops method for fork
8061    catchpoints.  */
8062
8063 static void
8064 print_mention_catch_fork (struct breakpoint *b)
8065 {
8066   printf_filtered (_("Catchpoint %d (fork)"), b->number);
8067 }
8068
8069 /* Implement the "print_recreate" breakpoint_ops method for fork
8070    catchpoints.  */
8071
8072 static void
8073 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
8074 {
8075   fprintf_unfiltered (fp, "catch fork");
8076   print_recreate_thread (b, fp);
8077 }
8078
8079 /* The breakpoint_ops structure to be used in fork catchpoints.  */
8080
8081 static struct breakpoint_ops catch_fork_breakpoint_ops;
8082
8083 /* Implement the "insert" breakpoint_ops method for vfork
8084    catchpoints.  */
8085
8086 static int
8087 insert_catch_vfork (struct bp_location *bl)
8088 {
8089   return target_insert_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8090 }
8091
8092 /* Implement the "remove" breakpoint_ops method for vfork
8093    catchpoints.  */
8094
8095 static int
8096 remove_catch_vfork (struct bp_location *bl)
8097 {
8098   return target_remove_vfork_catchpoint (ptid_get_pid (inferior_ptid));
8099 }
8100
8101 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
8102    catchpoints.  */
8103
8104 static int
8105 breakpoint_hit_catch_vfork (const struct bp_location *bl,
8106                             struct address_space *aspace, CORE_ADDR bp_addr,
8107                             const struct target_waitstatus *ws)
8108 {
8109   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
8110
8111   if (ws->kind != TARGET_WAITKIND_VFORKED)
8112     return 0;
8113
8114   c->forked_inferior_pid = ws->value.related_pid;
8115   return 1;
8116 }
8117
8118 /* Implement the "print_it" breakpoint_ops method for vfork
8119    catchpoints.  */
8120
8121 static enum print_stop_action
8122 print_it_catch_vfork (bpstat bs)
8123 {
8124   struct ui_out *uiout = current_uiout;
8125   struct breakpoint *b = bs->breakpoint_at;
8126   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8127
8128   annotate_catchpoint (b->number);
8129   if (b->disposition == disp_del)
8130     ui_out_text (uiout, "\nTemporary catchpoint ");
8131   else
8132     ui_out_text (uiout, "\nCatchpoint ");
8133   if (ui_out_is_mi_like_p (uiout))
8134     {
8135       ui_out_field_string (uiout, "reason",
8136                            async_reason_lookup (EXEC_ASYNC_VFORK));
8137       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8138     }
8139   ui_out_field_int (uiout, "bkptno", b->number);
8140   ui_out_text (uiout, " (vforked process ");
8141   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
8142   ui_out_text (uiout, "), ");
8143   return PRINT_SRC_AND_LOC;
8144 }
8145
8146 /* Implement the "print_one" breakpoint_ops method for vfork
8147    catchpoints.  */
8148
8149 static void
8150 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
8151 {
8152   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
8153   struct value_print_options opts;
8154   struct ui_out *uiout = current_uiout;
8155
8156   get_user_print_options (&opts);
8157   /* Field 4, the address, is omitted (which makes the columns not
8158      line up too nicely with the headers, but the effect is relatively
8159      readable).  */
8160   if (opts.addressprint)
8161     ui_out_field_skip (uiout, "addr");
8162   annotate_field (5);
8163   ui_out_text (uiout, "vfork");
8164   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
8165     {
8166       ui_out_text (uiout, ", process ");
8167       ui_out_field_int (uiout, "what",
8168                         ptid_get_pid (c->forked_inferior_pid));
8169       ui_out_spaces (uiout, 1);
8170     }
8171
8172   if (ui_out_is_mi_like_p (uiout))
8173     ui_out_field_string (uiout, "catch-type", "vfork");
8174 }
8175
8176 /* Implement the "print_mention" breakpoint_ops method for vfork
8177    catchpoints.  */
8178
8179 static void
8180 print_mention_catch_vfork (struct breakpoint *b)
8181 {
8182   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
8183 }
8184
8185 /* Implement the "print_recreate" breakpoint_ops method for vfork
8186    catchpoints.  */
8187
8188 static void
8189 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
8190 {
8191   fprintf_unfiltered (fp, "catch vfork");
8192   print_recreate_thread (b, fp);
8193 }
8194
8195 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
8196
8197 static struct breakpoint_ops catch_vfork_breakpoint_ops;
8198
8199 /* An instance of this type is used to represent an solib catchpoint.
8200    It includes a "struct breakpoint" as a kind of base class; users
8201    downcast to "struct breakpoint *" when needed.  A breakpoint is
8202    really of this type iff its ops pointer points to
8203    CATCH_SOLIB_BREAKPOINT_OPS.  */
8204
8205 struct solib_catchpoint
8206 {
8207   /* The base class.  */
8208   struct breakpoint base;
8209
8210   /* True for "catch load", false for "catch unload".  */
8211   unsigned char is_load;
8212
8213   /* Regular expression to match, if any.  COMPILED is only valid when
8214      REGEX is non-NULL.  */
8215   char *regex;
8216   regex_t compiled;
8217 };
8218
8219 static void
8220 dtor_catch_solib (struct breakpoint *b)
8221 {
8222   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8223
8224   if (self->regex)
8225     regfree (&self->compiled);
8226   xfree (self->regex);
8227
8228   base_breakpoint_ops.dtor (b);
8229 }
8230
8231 static int
8232 insert_catch_solib (struct bp_location *ignore)
8233 {
8234   return 0;
8235 }
8236
8237 static int
8238 remove_catch_solib (struct bp_location *ignore)
8239 {
8240   return 0;
8241 }
8242
8243 static int
8244 breakpoint_hit_catch_solib (const struct bp_location *bl,
8245                             struct address_space *aspace,
8246                             CORE_ADDR bp_addr,
8247                             const struct target_waitstatus *ws)
8248 {
8249   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
8250   struct breakpoint *other;
8251
8252   if (ws->kind == TARGET_WAITKIND_LOADED)
8253     return 1;
8254
8255   ALL_BREAKPOINTS (other)
8256   {
8257     struct bp_location *other_bl;
8258
8259     if (other == bl->owner)
8260       continue;
8261
8262     if (other->type != bp_shlib_event)
8263       continue;
8264
8265     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
8266       continue;
8267
8268     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
8269       {
8270         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
8271           return 1;
8272       }
8273   }
8274
8275   return 0;
8276 }
8277
8278 static void
8279 check_status_catch_solib (struct bpstats *bs)
8280 {
8281   struct solib_catchpoint *self
8282     = (struct solib_catchpoint *) bs->breakpoint_at;
8283   int ix;
8284
8285   if (self->is_load)
8286     {
8287       struct so_list *iter;
8288
8289       for (ix = 0;
8290            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
8291                         ix, iter);
8292            ++ix)
8293         {
8294           if (!self->regex
8295               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
8296             return;
8297         }
8298     }
8299   else
8300     {
8301       char *iter;
8302
8303       for (ix = 0;
8304            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
8305                         ix, iter);
8306            ++ix)
8307         {
8308           if (!self->regex
8309               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
8310             return;
8311         }
8312     }
8313
8314   bs->stop = 0;
8315   bs->print_it = print_it_noop;
8316 }
8317
8318 static enum print_stop_action
8319 print_it_catch_solib (bpstat bs)
8320 {
8321   struct breakpoint *b = bs->breakpoint_at;
8322   struct ui_out *uiout = current_uiout;
8323
8324   annotate_catchpoint (b->number);
8325   if (b->disposition == disp_del)
8326     ui_out_text (uiout, "\nTemporary catchpoint ");
8327   else
8328     ui_out_text (uiout, "\nCatchpoint ");
8329   ui_out_field_int (uiout, "bkptno", b->number);
8330   ui_out_text (uiout, "\n");
8331   if (ui_out_is_mi_like_p (uiout))
8332     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8333   print_solib_event (1);
8334   return PRINT_SRC_AND_LOC;
8335 }
8336
8337 static void
8338 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
8339 {
8340   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8341   struct value_print_options opts;
8342   struct ui_out *uiout = current_uiout;
8343   char *msg;
8344
8345   get_user_print_options (&opts);
8346   /* Field 4, the address, is omitted (which makes the columns not
8347      line up too nicely with the headers, but the effect is relatively
8348      readable).  */
8349   if (opts.addressprint)
8350     {
8351       annotate_field (4);
8352       ui_out_field_skip (uiout, "addr");
8353     }
8354
8355   annotate_field (5);
8356   if (self->is_load)
8357     {
8358       if (self->regex)
8359         msg = xstrprintf (_("load of library matching %s"), self->regex);
8360       else
8361         msg = xstrdup (_("load of library"));
8362     }
8363   else
8364     {
8365       if (self->regex)
8366         msg = xstrprintf (_("unload of library matching %s"), self->regex);
8367       else
8368         msg = xstrdup (_("unload of library"));
8369     }
8370   ui_out_field_string (uiout, "what", msg);
8371   xfree (msg);
8372
8373   if (ui_out_is_mi_like_p (uiout))
8374     ui_out_field_string (uiout, "catch-type",
8375                          self->is_load ? "load" : "unload");
8376 }
8377
8378 static void
8379 print_mention_catch_solib (struct breakpoint *b)
8380 {
8381   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8382
8383   printf_filtered (_("Catchpoint %d (%s)"), b->number,
8384                    self->is_load ? "load" : "unload");
8385 }
8386
8387 static void
8388 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
8389 {
8390   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
8391
8392   fprintf_unfiltered (fp, "%s %s",
8393                       b->disposition == disp_del ? "tcatch" : "catch",
8394                       self->is_load ? "load" : "unload");
8395   if (self->regex)
8396     fprintf_unfiltered (fp, " %s", self->regex);
8397   fprintf_unfiltered (fp, "\n");
8398 }
8399
8400 static struct breakpoint_ops catch_solib_breakpoint_ops;
8401
8402 /* Shared helper function (MI and CLI) for creating and installing
8403    a shared object event catchpoint.  If IS_LOAD is non-zero then
8404    the events to be caught are load events, otherwise they are
8405    unload events.  If IS_TEMP is non-zero the catchpoint is a
8406    temporary one.  If ENABLED is non-zero the catchpoint is
8407    created in an enabled state.  */
8408
8409 void
8410 add_solib_catchpoint (char *arg, int is_load, int is_temp, int enabled)
8411 {
8412   struct solib_catchpoint *c;
8413   struct gdbarch *gdbarch = get_current_arch ();
8414   struct cleanup *cleanup;
8415
8416   if (!arg)
8417     arg = "";
8418   arg = skip_spaces (arg);
8419
8420   c = XCNEW (struct solib_catchpoint);
8421   cleanup = make_cleanup (xfree, c);
8422
8423   if (*arg != '\0')
8424     {
8425       int errcode;
8426
8427       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
8428       if (errcode != 0)
8429         {
8430           char *err = get_regcomp_error (errcode, &c->compiled);
8431
8432           make_cleanup (xfree, err);
8433           error (_("Invalid regexp (%s): %s"), err, arg);
8434         }
8435       c->regex = xstrdup (arg);
8436     }
8437
8438   c->is_load = is_load;
8439   init_catchpoint (&c->base, gdbarch, is_temp, NULL,
8440                    &catch_solib_breakpoint_ops);
8441
8442   c->base.enable_state = enabled ? bp_enabled : bp_disabled;
8443
8444   discard_cleanups (cleanup);
8445   install_breakpoint (0, &c->base, 1);
8446 }
8447
8448 /* A helper function that does all the work for "catch load" and
8449    "catch unload".  */
8450
8451 static void
8452 catch_load_or_unload (char *arg, int from_tty, int is_load,
8453                       struct cmd_list_element *command)
8454 {
8455   int tempflag;
8456   const int enabled = 1;
8457
8458   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8459
8460   add_solib_catchpoint (arg, is_load, tempflag, enabled);
8461 }
8462
8463 static void
8464 catch_load_command_1 (char *arg, int from_tty,
8465                       struct cmd_list_element *command)
8466 {
8467   catch_load_or_unload (arg, from_tty, 1, command);
8468 }
8469
8470 static void
8471 catch_unload_command_1 (char *arg, int from_tty,
8472                         struct cmd_list_element *command)
8473 {
8474   catch_load_or_unload (arg, from_tty, 0, command);
8475 }
8476
8477 /* An instance of this type is used to represent a syscall catchpoint.
8478    It includes a "struct breakpoint" as a kind of base class; users
8479    downcast to "struct breakpoint *" when needed.  A breakpoint is
8480    really of this type iff its ops pointer points to
8481    CATCH_SYSCALL_BREAKPOINT_OPS.  */
8482
8483 struct syscall_catchpoint
8484 {
8485   /* The base class.  */
8486   struct breakpoint base;
8487
8488   /* Syscall numbers used for the 'catch syscall' feature.  If no
8489      syscall has been specified for filtering, its value is NULL.
8490      Otherwise, it holds a list of all syscalls to be caught.  The
8491      list elements are allocated with xmalloc.  */
8492   VEC(int) *syscalls_to_be_caught;
8493 };
8494
8495 /* Implement the "dtor" breakpoint_ops method for syscall
8496    catchpoints.  */
8497
8498 static void
8499 dtor_catch_syscall (struct breakpoint *b)
8500 {
8501   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8502
8503   VEC_free (int, c->syscalls_to_be_caught);
8504
8505   base_breakpoint_ops.dtor (b);
8506 }
8507
8508 static const struct inferior_data *catch_syscall_inferior_data = NULL;
8509
8510 struct catch_syscall_inferior_data
8511 {
8512   /* We keep a count of the number of times the user has requested a
8513      particular syscall to be tracked, and pass this information to the
8514      target.  This lets capable targets implement filtering directly.  */
8515
8516   /* Number of times that "any" syscall is requested.  */
8517   int any_syscall_count;
8518
8519   /* Count of each system call.  */
8520   VEC(int) *syscalls_counts;
8521
8522   /* This counts all syscall catch requests, so we can readily determine
8523      if any catching is necessary.  */
8524   int total_syscalls_count;
8525 };
8526
8527 static struct catch_syscall_inferior_data*
8528 get_catch_syscall_inferior_data (struct inferior *inf)
8529 {
8530   struct catch_syscall_inferior_data *inf_data;
8531
8532   inf_data = inferior_data (inf, catch_syscall_inferior_data);
8533   if (inf_data == NULL)
8534     {
8535       inf_data = XCNEW (struct catch_syscall_inferior_data);
8536       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
8537     }
8538
8539   return inf_data;
8540 }
8541
8542 static void
8543 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
8544 {
8545   xfree (arg);
8546 }
8547
8548
8549 /* Implement the "insert" breakpoint_ops method for syscall
8550    catchpoints.  */
8551
8552 static int
8553 insert_catch_syscall (struct bp_location *bl)
8554 {
8555   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8556   struct inferior *inf = current_inferior ();
8557   struct catch_syscall_inferior_data *inf_data
8558     = get_catch_syscall_inferior_data (inf);
8559
8560   ++inf_data->total_syscalls_count;
8561   if (!c->syscalls_to_be_caught)
8562     ++inf_data->any_syscall_count;
8563   else
8564     {
8565       int i, iter;
8566
8567       for (i = 0;
8568            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8569            i++)
8570         {
8571           int elem;
8572
8573           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8574             {
8575               int old_size = VEC_length (int, inf_data->syscalls_counts);
8576               uintptr_t vec_addr_offset
8577                 = old_size * ((uintptr_t) sizeof (int));
8578               uintptr_t vec_addr;
8579               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
8580               vec_addr = ((uintptr_t) VEC_address (int,
8581                                                   inf_data->syscalls_counts)
8582                           + vec_addr_offset);
8583               memset ((void *) vec_addr, 0,
8584                       (iter + 1 - old_size) * sizeof (int));
8585             }
8586           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8587           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
8588         }
8589     }
8590
8591   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8592                                         inf_data->total_syscalls_count != 0,
8593                                         inf_data->any_syscall_count,
8594                                         VEC_length (int,
8595                                                     inf_data->syscalls_counts),
8596                                         VEC_address (int,
8597                                                      inf_data->syscalls_counts));
8598 }
8599
8600 /* Implement the "remove" breakpoint_ops method for syscall
8601    catchpoints.  */
8602
8603 static int
8604 remove_catch_syscall (struct bp_location *bl)
8605 {
8606   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
8607   struct inferior *inf = current_inferior ();
8608   struct catch_syscall_inferior_data *inf_data
8609     = get_catch_syscall_inferior_data (inf);
8610
8611   --inf_data->total_syscalls_count;
8612   if (!c->syscalls_to_be_caught)
8613     --inf_data->any_syscall_count;
8614   else
8615     {
8616       int i, iter;
8617
8618       for (i = 0;
8619            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8620            i++)
8621         {
8622           int elem;
8623           if (iter >= VEC_length (int, inf_data->syscalls_counts))
8624             /* Shouldn't happen.  */
8625             continue;
8626           elem = VEC_index (int, inf_data->syscalls_counts, iter);
8627           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
8628         }
8629     }
8630
8631   return target_set_syscall_catchpoint (ptid_get_pid (inferior_ptid),
8632                                         inf_data->total_syscalls_count != 0,
8633                                         inf_data->any_syscall_count,
8634                                         VEC_length (int,
8635                                                     inf_data->syscalls_counts),
8636                                         VEC_address (int,
8637                                                      inf_data->syscalls_counts));
8638 }
8639
8640 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
8641    catchpoints.  */
8642
8643 static int
8644 breakpoint_hit_catch_syscall (const struct bp_location *bl,
8645                               struct address_space *aspace, CORE_ADDR bp_addr,
8646                               const struct target_waitstatus *ws)
8647 {
8648   /* We must check if we are catching specific syscalls in this
8649      breakpoint.  If we are, then we must guarantee that the called
8650      syscall is the same syscall we are catching.  */
8651   int syscall_number = 0;
8652   const struct syscall_catchpoint *c
8653     = (const struct syscall_catchpoint *) bl->owner;
8654
8655   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
8656       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
8657     return 0;
8658
8659   syscall_number = ws->value.syscall_number;
8660
8661   /* Now, checking if the syscall is the same.  */
8662   if (c->syscalls_to_be_caught)
8663     {
8664       int i, iter;
8665
8666       for (i = 0;
8667            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8668            i++)
8669         if (syscall_number == iter)
8670           return 1;
8671
8672       return 0;
8673     }
8674
8675   return 1;
8676 }
8677
8678 /* Implement the "print_it" breakpoint_ops method for syscall
8679    catchpoints.  */
8680
8681 static enum print_stop_action
8682 print_it_catch_syscall (bpstat bs)
8683 {
8684   struct ui_out *uiout = current_uiout;
8685   struct breakpoint *b = bs->breakpoint_at;
8686   /* These are needed because we want to know in which state a
8687      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
8688      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
8689      must print "called syscall" or "returned from syscall".  */
8690   ptid_t ptid;
8691   struct target_waitstatus last;
8692   struct syscall s;
8693
8694   get_last_target_status (&ptid, &last);
8695
8696   get_syscall_by_number (last.value.syscall_number, &s);
8697
8698   annotate_catchpoint (b->number);
8699
8700   if (b->disposition == disp_del)
8701     ui_out_text (uiout, "\nTemporary catchpoint ");
8702   else
8703     ui_out_text (uiout, "\nCatchpoint ");
8704   if (ui_out_is_mi_like_p (uiout))
8705     {
8706       ui_out_field_string (uiout, "reason",
8707                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
8708                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
8709                                                 : EXEC_ASYNC_SYSCALL_RETURN));
8710       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8711     }
8712   ui_out_field_int (uiout, "bkptno", b->number);
8713
8714   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
8715     ui_out_text (uiout, " (call to syscall ");
8716   else
8717     ui_out_text (uiout, " (returned from syscall ");
8718
8719   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
8720     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
8721   if (s.name != NULL)
8722     ui_out_field_string (uiout, "syscall-name", s.name);
8723
8724   ui_out_text (uiout, "), ");
8725
8726   return PRINT_SRC_AND_LOC;
8727 }
8728
8729 /* Implement the "print_one" breakpoint_ops method for syscall
8730    catchpoints.  */
8731
8732 static void
8733 print_one_catch_syscall (struct breakpoint *b,
8734                          struct bp_location **last_loc)
8735 {
8736   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8737   struct value_print_options opts;
8738   struct ui_out *uiout = current_uiout;
8739
8740   get_user_print_options (&opts);
8741   /* Field 4, the address, is omitted (which makes the columns not
8742      line up too nicely with the headers, but the effect is relatively
8743      readable).  */
8744   if (opts.addressprint)
8745     ui_out_field_skip (uiout, "addr");
8746   annotate_field (5);
8747
8748   if (c->syscalls_to_be_caught
8749       && VEC_length (int, c->syscalls_to_be_caught) > 1)
8750     ui_out_text (uiout, "syscalls \"");
8751   else
8752     ui_out_text (uiout, "syscall \"");
8753
8754   if (c->syscalls_to_be_caught)
8755     {
8756       int i, iter;
8757       char *text = xstrprintf ("%s", "");
8758
8759       for (i = 0;
8760            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8761            i++)
8762         {
8763           char *x = text;
8764           struct syscall s;
8765           get_syscall_by_number (iter, &s);
8766
8767           if (s.name != NULL)
8768             text = xstrprintf ("%s%s, ", text, s.name);
8769           else
8770             text = xstrprintf ("%s%d, ", text, iter);
8771
8772           /* We have to xfree the last 'text' (now stored at 'x')
8773              because xstrprintf dynamically allocates new space for it
8774              on every call.  */
8775           xfree (x);
8776         }
8777       /* Remove the last comma.  */
8778       text[strlen (text) - 2] = '\0';
8779       ui_out_field_string (uiout, "what", text);
8780     }
8781   else
8782     ui_out_field_string (uiout, "what", "<any syscall>");
8783   ui_out_text (uiout, "\" ");
8784
8785   if (ui_out_is_mi_like_p (uiout))
8786     ui_out_field_string (uiout, "catch-type", "syscall");
8787 }
8788
8789 /* Implement the "print_mention" breakpoint_ops method for syscall
8790    catchpoints.  */
8791
8792 static void
8793 print_mention_catch_syscall (struct breakpoint *b)
8794 {
8795   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8796
8797   if (c->syscalls_to_be_caught)
8798     {
8799       int i, iter;
8800
8801       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
8802         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
8803       else
8804         printf_filtered (_("Catchpoint %d (syscall"), b->number);
8805
8806       for (i = 0;
8807            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8808            i++)
8809         {
8810           struct syscall s;
8811           get_syscall_by_number (iter, &s);
8812
8813           if (s.name)
8814             printf_filtered (" '%s' [%d]", s.name, s.number);
8815           else
8816             printf_filtered (" %d", s.number);
8817         }
8818       printf_filtered (")");
8819     }
8820   else
8821     printf_filtered (_("Catchpoint %d (any syscall)"),
8822                      b->number);
8823 }
8824
8825 /* Implement the "print_recreate" breakpoint_ops method for syscall
8826    catchpoints.  */
8827
8828 static void
8829 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
8830 {
8831   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
8832
8833   fprintf_unfiltered (fp, "catch syscall");
8834
8835   if (c->syscalls_to_be_caught)
8836     {
8837       int i, iter;
8838
8839       for (i = 0;
8840            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
8841            i++)
8842         {
8843           struct syscall s;
8844
8845           get_syscall_by_number (iter, &s);
8846           if (s.name)
8847             fprintf_unfiltered (fp, " %s", s.name);
8848           else
8849             fprintf_unfiltered (fp, " %d", s.number);
8850         }
8851     }
8852   print_recreate_thread (b, fp);
8853 }
8854
8855 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
8856
8857 static struct breakpoint_ops catch_syscall_breakpoint_ops;
8858
8859 /* Returns non-zero if 'b' is a syscall catchpoint.  */
8860
8861 static int
8862 syscall_catchpoint_p (struct breakpoint *b)
8863 {
8864   return (b->ops == &catch_syscall_breakpoint_ops);
8865 }
8866
8867 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
8868    is non-zero, then make the breakpoint temporary.  If COND_STRING is
8869    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
8870    the breakpoint_ops structure associated to the catchpoint.  */
8871
8872 void
8873 init_catchpoint (struct breakpoint *b,
8874                  struct gdbarch *gdbarch, int tempflag,
8875                  char *cond_string,
8876                  const struct breakpoint_ops *ops)
8877 {
8878   struct symtab_and_line sal;
8879
8880   init_sal (&sal);
8881   sal.pspace = current_program_space;
8882
8883   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
8884
8885   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
8886   b->disposition = tempflag ? disp_del : disp_donttouch;
8887 }
8888
8889 void
8890 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
8891 {
8892   add_to_breakpoint_chain (b);
8893   set_breakpoint_number (internal, b);
8894   if (is_tracepoint (b))
8895     set_tracepoint_count (breakpoint_count);
8896   if (!internal)
8897     mention (b);
8898   observer_notify_breakpoint_created (b);
8899
8900   if (update_gll)
8901     update_global_location_list (UGLL_MAY_INSERT);
8902 }
8903
8904 static void
8905 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
8906                                     int tempflag, char *cond_string,
8907                                     const struct breakpoint_ops *ops)
8908 {
8909   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
8910
8911   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
8912
8913   c->forked_inferior_pid = null_ptid;
8914
8915   install_breakpoint (0, &c->base, 1);
8916 }
8917
8918 /* Exec catchpoints.  */
8919
8920 /* An instance of this type is used to represent an exec catchpoint.
8921    It includes a "struct breakpoint" as a kind of base class; users
8922    downcast to "struct breakpoint *" when needed.  A breakpoint is
8923    really of this type iff its ops pointer points to
8924    CATCH_EXEC_BREAKPOINT_OPS.  */
8925
8926 struct exec_catchpoint
8927 {
8928   /* The base class.  */
8929   struct breakpoint base;
8930
8931   /* Filename of a program whose exec triggered this catchpoint.
8932      This field is only valid immediately after this catchpoint has
8933      triggered.  */
8934   char *exec_pathname;
8935 };
8936
8937 /* Implement the "dtor" breakpoint_ops method for exec
8938    catchpoints.  */
8939
8940 static void
8941 dtor_catch_exec (struct breakpoint *b)
8942 {
8943   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8944
8945   xfree (c->exec_pathname);
8946
8947   base_breakpoint_ops.dtor (b);
8948 }
8949
8950 static int
8951 insert_catch_exec (struct bp_location *bl)
8952 {
8953   return target_insert_exec_catchpoint (ptid_get_pid (inferior_ptid));
8954 }
8955
8956 static int
8957 remove_catch_exec (struct bp_location *bl)
8958 {
8959   return target_remove_exec_catchpoint (ptid_get_pid (inferior_ptid));
8960 }
8961
8962 static int
8963 breakpoint_hit_catch_exec (const struct bp_location *bl,
8964                            struct address_space *aspace, CORE_ADDR bp_addr,
8965                            const struct target_waitstatus *ws)
8966 {
8967   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
8968
8969   if (ws->kind != TARGET_WAITKIND_EXECD)
8970     return 0;
8971
8972   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8973   return 1;
8974 }
8975
8976 static enum print_stop_action
8977 print_it_catch_exec (bpstat bs)
8978 {
8979   struct ui_out *uiout = current_uiout;
8980   struct breakpoint *b = bs->breakpoint_at;
8981   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8982
8983   annotate_catchpoint (b->number);
8984   if (b->disposition == disp_del)
8985     ui_out_text (uiout, "\nTemporary catchpoint ");
8986   else
8987     ui_out_text (uiout, "\nCatchpoint ");
8988   if (ui_out_is_mi_like_p (uiout))
8989     {
8990       ui_out_field_string (uiout, "reason",
8991                            async_reason_lookup (EXEC_ASYNC_EXEC));
8992       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8993     }
8994   ui_out_field_int (uiout, "bkptno", b->number);
8995   ui_out_text (uiout, " (exec'd ");
8996   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8997   ui_out_text (uiout, "), ");
8998
8999   return PRINT_SRC_AND_LOC;
9000 }
9001
9002 static void
9003 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
9004 {
9005   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
9006   struct value_print_options opts;
9007   struct ui_out *uiout = current_uiout;
9008
9009   get_user_print_options (&opts);
9010
9011   /* Field 4, the address, is omitted (which makes the columns
9012      not line up too nicely with the headers, but the effect
9013      is relatively readable).  */
9014   if (opts.addressprint)
9015     ui_out_field_skip (uiout, "addr");
9016   annotate_field (5);
9017   ui_out_text (uiout, "exec");
9018   if (c->exec_pathname != NULL)
9019     {
9020       ui_out_text (uiout, ", program \"");
9021       ui_out_field_string (uiout, "what", c->exec_pathname);
9022       ui_out_text (uiout, "\" ");
9023     }
9024
9025   if (ui_out_is_mi_like_p (uiout))
9026     ui_out_field_string (uiout, "catch-type", "exec");
9027 }
9028
9029 static void
9030 print_mention_catch_exec (struct breakpoint *b)
9031 {
9032   printf_filtered (_("Catchpoint %d (exec)"), b->number);
9033 }
9034
9035 /* Implement the "print_recreate" breakpoint_ops method for exec
9036    catchpoints.  */
9037
9038 static void
9039 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
9040 {
9041   fprintf_unfiltered (fp, "catch exec");
9042   print_recreate_thread (b, fp);
9043 }
9044
9045 static struct breakpoint_ops catch_exec_breakpoint_ops;
9046
9047 static void
9048 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
9049                                  const struct breakpoint_ops *ops)
9050 {
9051   struct syscall_catchpoint *c;
9052   struct gdbarch *gdbarch = get_current_arch ();
9053
9054   c = XNEW (struct syscall_catchpoint);
9055   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
9056   c->syscalls_to_be_caught = filter;
9057
9058   install_breakpoint (0, &c->base, 1);
9059 }
9060
9061 static int
9062 hw_breakpoint_used_count (void)
9063 {
9064   int i = 0;
9065   struct breakpoint *b;
9066   struct bp_location *bl;
9067
9068   ALL_BREAKPOINTS (b)
9069   {
9070     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
9071       for (bl = b->loc; bl; bl = bl->next)
9072         {
9073           /* Special types of hardware breakpoints may use more than
9074              one register.  */
9075           i += b->ops->resources_needed (bl);
9076         }
9077   }
9078
9079   return i;
9080 }
9081
9082 /* Returns the resources B would use if it were a hardware
9083    watchpoint.  */
9084
9085 static int
9086 hw_watchpoint_use_count (struct breakpoint *b)
9087 {
9088   int i = 0;
9089   struct bp_location *bl;
9090
9091   if (!breakpoint_enabled (b))
9092     return 0;
9093
9094   for (bl = b->loc; bl; bl = bl->next)
9095     {
9096       /* Special types of hardware watchpoints may use more than
9097          one register.  */
9098       i += b->ops->resources_needed (bl);
9099     }
9100
9101   return i;
9102 }
9103
9104 /* Returns the sum the used resources of all hardware watchpoints of
9105    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
9106    the sum of the used resources of all hardware watchpoints of other
9107    types _not_ TYPE.  */
9108
9109 static int
9110 hw_watchpoint_used_count_others (struct breakpoint *except,
9111                                  enum bptype type, int *other_type_used)
9112 {
9113   int i = 0;
9114   struct breakpoint *b;
9115
9116   *other_type_used = 0;
9117   ALL_BREAKPOINTS (b)
9118     {
9119       if (b == except)
9120         continue;
9121       if (!breakpoint_enabled (b))
9122         continue;
9123
9124       if (b->type == type)
9125         i += hw_watchpoint_use_count (b);
9126       else if (is_hardware_watchpoint (b))
9127         *other_type_used = 1;
9128     }
9129
9130   return i;
9131 }
9132
9133 void
9134 disable_watchpoints_before_interactive_call_start (void)
9135 {
9136   struct breakpoint *b;
9137
9138   ALL_BREAKPOINTS (b)
9139   {
9140     if (is_watchpoint (b) && breakpoint_enabled (b))
9141       {
9142         b->enable_state = bp_call_disabled;
9143         update_global_location_list (UGLL_DONT_INSERT);
9144       }
9145   }
9146 }
9147
9148 void
9149 enable_watchpoints_after_interactive_call_stop (void)
9150 {
9151   struct breakpoint *b;
9152
9153   ALL_BREAKPOINTS (b)
9154   {
9155     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
9156       {
9157         b->enable_state = bp_enabled;
9158         update_global_location_list (UGLL_MAY_INSERT);
9159       }
9160   }
9161 }
9162
9163 void
9164 disable_breakpoints_before_startup (void)
9165 {
9166   current_program_space->executing_startup = 1;
9167   update_global_location_list (UGLL_DONT_INSERT);
9168 }
9169
9170 void
9171 enable_breakpoints_after_startup (void)
9172 {
9173   current_program_space->executing_startup = 0;
9174   breakpoint_re_set ();
9175 }
9176
9177
9178 /* Set a breakpoint that will evaporate an end of command
9179    at address specified by SAL.
9180    Restrict it to frame FRAME if FRAME is nonzero.  */
9181
9182 struct breakpoint *
9183 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
9184                           struct frame_id frame_id, enum bptype type)
9185 {
9186   struct breakpoint *b;
9187
9188   /* If FRAME_ID is valid, it should be a real frame, not an inlined or
9189      tail-called one.  */
9190   gdb_assert (!frame_id_artificial_p (frame_id));
9191
9192   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
9193   b->enable_state = bp_enabled;
9194   b->disposition = disp_donttouch;
9195   b->frame_id = frame_id;
9196
9197   /* If we're debugging a multi-threaded program, then we want
9198      momentary breakpoints to be active in only a single thread of
9199      control.  */
9200   if (in_thread_list (inferior_ptid))
9201     b->thread = pid_to_thread_id (inferior_ptid);
9202
9203   update_global_location_list_nothrow (UGLL_MAY_INSERT);
9204
9205   return b;
9206 }
9207
9208 /* Make a momentary breakpoint based on the master breakpoint ORIG.
9209    The new breakpoint will have type TYPE, use OPS as its
9210    breakpoint_ops, and will set enabled to LOC_ENABLED.  */
9211
9212 static struct breakpoint *
9213 momentary_breakpoint_from_master (struct breakpoint *orig,
9214                                   enum bptype type,
9215                                   const struct breakpoint_ops *ops,
9216                                   int loc_enabled)
9217 {
9218   struct breakpoint *copy;
9219
9220   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
9221   copy->loc = allocate_bp_location (copy);
9222   set_breakpoint_location_function (copy->loc, 1);
9223
9224   copy->loc->gdbarch = orig->loc->gdbarch;
9225   copy->loc->requested_address = orig->loc->requested_address;
9226   copy->loc->address = orig->loc->address;
9227   copy->loc->section = orig->loc->section;
9228   copy->loc->pspace = orig->loc->pspace;
9229   copy->loc->probe = orig->loc->probe;
9230   copy->loc->line_number = orig->loc->line_number;
9231   copy->loc->symtab = orig->loc->symtab;
9232   copy->loc->enabled = loc_enabled;
9233   copy->frame_id = orig->frame_id;
9234   copy->thread = orig->thread;
9235   copy->pspace = orig->pspace;
9236
9237   copy->enable_state = bp_enabled;
9238   copy->disposition = disp_donttouch;
9239   copy->number = internal_breakpoint_number--;
9240
9241   update_global_location_list_nothrow (UGLL_DONT_INSERT);
9242   return copy;
9243 }
9244
9245 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
9246    ORIG is NULL.  */
9247
9248 struct breakpoint *
9249 clone_momentary_breakpoint (struct breakpoint *orig)
9250 {
9251   /* If there's nothing to clone, then return nothing.  */
9252   if (orig == NULL)
9253     return NULL;
9254
9255   return momentary_breakpoint_from_master (orig, orig->type, orig->ops, 0);
9256 }
9257
9258 struct breakpoint *
9259 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
9260                                 enum bptype type)
9261 {
9262   struct symtab_and_line sal;
9263
9264   sal = find_pc_line (pc, 0);
9265   sal.pc = pc;
9266   sal.section = find_pc_overlay (pc);
9267   sal.explicit_pc = 1;
9268
9269   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
9270 }
9271 \f
9272
9273 /* Tell the user we have just set a breakpoint B.  */
9274
9275 static void
9276 mention (struct breakpoint *b)
9277 {
9278   b->ops->print_mention (b);
9279   if (ui_out_is_mi_like_p (current_uiout))
9280     return;
9281   printf_filtered ("\n");
9282 }
9283 \f
9284
9285 static struct bp_location *
9286 add_location_to_breakpoint (struct breakpoint *b,
9287                             const struct symtab_and_line *sal)
9288 {
9289   struct bp_location *loc, **tmp;
9290   CORE_ADDR adjusted_address;
9291   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
9292
9293   if (loc_gdbarch == NULL)
9294     loc_gdbarch = b->gdbarch;
9295
9296   /* Adjust the breakpoint's address prior to allocating a location.
9297      Once we call allocate_bp_location(), that mostly uninitialized
9298      location will be placed on the location chain.  Adjustment of the
9299      breakpoint may cause target_read_memory() to be called and we do
9300      not want its scan of the location chain to find a breakpoint and
9301      location that's only been partially initialized.  */
9302   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
9303                                                 sal->pc, b->type);
9304
9305   /* Sort the locations by their ADDRESS.  */
9306   loc = allocate_bp_location (b);
9307   for (tmp = &(b->loc); *tmp != NULL && (*tmp)->address <= adjusted_address;
9308        tmp = &((*tmp)->next))
9309     ;
9310   loc->next = *tmp;
9311   *tmp = loc;
9312
9313   loc->requested_address = sal->pc;
9314   loc->address = adjusted_address;
9315   loc->pspace = sal->pspace;
9316   loc->probe.probe = sal->probe;
9317   loc->probe.objfile = sal->objfile;
9318   gdb_assert (loc->pspace != NULL);
9319   loc->section = sal->section;
9320   loc->gdbarch = loc_gdbarch;
9321   loc->line_number = sal->line;
9322   loc->symtab = sal->symtab;
9323
9324   set_breakpoint_location_function (loc,
9325                                     sal->explicit_pc || sal->explicit_line);
9326   return loc;
9327 }
9328 \f
9329
9330 /* Return 1 if LOC is pointing to a permanent breakpoint, 
9331    return 0 otherwise.  */
9332
9333 static int
9334 bp_loc_is_permanent (struct bp_location *loc)
9335 {
9336   int len;
9337   CORE_ADDR addr;
9338   const gdb_byte *bpoint;
9339   gdb_byte *target_mem;
9340   struct cleanup *cleanup;
9341   int retval = 0;
9342
9343   gdb_assert (loc != NULL);
9344
9345   addr = loc->address;
9346   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
9347
9348   /* Software breakpoints unsupported?  */
9349   if (bpoint == NULL)
9350     return 0;
9351
9352   target_mem = alloca (len);
9353
9354   /* Enable the automatic memory restoration from breakpoints while
9355      we read the memory.  Otherwise we could say about our temporary
9356      breakpoints they are permanent.  */
9357   cleanup = save_current_space_and_thread ();
9358
9359   switch_to_program_space_and_thread (loc->pspace);
9360   make_show_memory_breakpoints_cleanup (0);
9361
9362   if (target_read_memory (loc->address, target_mem, len) == 0
9363       && memcmp (target_mem, bpoint, len) == 0)
9364     retval = 1;
9365
9366   do_cleanups (cleanup);
9367
9368   return retval;
9369 }
9370
9371 /* Build a command list for the dprintf corresponding to the current
9372    settings of the dprintf style options.  */
9373
9374 static void
9375 update_dprintf_command_list (struct breakpoint *b)
9376 {
9377   char *dprintf_args = b->extra_string;
9378   char *printf_line = NULL;
9379
9380   if (!dprintf_args)
9381     return;
9382
9383   dprintf_args = skip_spaces (dprintf_args);
9384
9385   /* Allow a comma, as it may have terminated a location, but don't
9386      insist on it.  */
9387   if (*dprintf_args == ',')
9388     ++dprintf_args;
9389   dprintf_args = skip_spaces (dprintf_args);
9390
9391   if (*dprintf_args != '"')
9392     error (_("Bad format string, missing '\"'."));
9393
9394   if (strcmp (dprintf_style, dprintf_style_gdb) == 0)
9395     printf_line = xstrprintf ("printf %s", dprintf_args);
9396   else if (strcmp (dprintf_style, dprintf_style_call) == 0)
9397     {
9398       if (!dprintf_function)
9399         error (_("No function supplied for dprintf call"));
9400
9401       if (dprintf_channel && strlen (dprintf_channel) > 0)
9402         printf_line = xstrprintf ("call (void) %s (%s,%s)",
9403                                   dprintf_function,
9404                                   dprintf_channel,
9405                                   dprintf_args);
9406       else
9407         printf_line = xstrprintf ("call (void) %s (%s)",
9408                                   dprintf_function,
9409                                   dprintf_args);
9410     }
9411   else if (strcmp (dprintf_style, dprintf_style_agent) == 0)
9412     {
9413       if (target_can_run_breakpoint_commands ())
9414         printf_line = xstrprintf ("agent-printf %s", dprintf_args);
9415       else
9416         {
9417           warning (_("Target cannot run dprintf commands, falling back to GDB printf"));
9418           printf_line = xstrprintf ("printf %s", dprintf_args);
9419         }
9420     }
9421   else
9422     internal_error (__FILE__, __LINE__,
9423                     _("Invalid dprintf style."));
9424
9425   gdb_assert (printf_line != NULL);
9426   /* Manufacture a printf sequence.  */
9427   {
9428     struct command_line *printf_cmd_line
9429       = xmalloc (sizeof (struct command_line));
9430
9431     printf_cmd_line = xmalloc (sizeof (struct command_line));
9432     printf_cmd_line->control_type = simple_control;
9433     printf_cmd_line->body_count = 0;
9434     printf_cmd_line->body_list = NULL;
9435     printf_cmd_line->next = NULL;
9436     printf_cmd_line->line = printf_line;
9437
9438     breakpoint_set_commands (b, printf_cmd_line);
9439   }
9440 }
9441
9442 /* Update all dprintf commands, making their command lists reflect
9443    current style settings.  */
9444
9445 static void
9446 update_dprintf_commands (char *args, int from_tty,
9447                          struct cmd_list_element *c)
9448 {
9449   struct breakpoint *b;
9450
9451   ALL_BREAKPOINTS (b)
9452     {
9453       if (b->type == bp_dprintf)
9454         update_dprintf_command_list (b);
9455     }
9456 }
9457
9458 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
9459    as textual description of the location, and COND_STRING
9460    as condition expression.  */
9461
9462 static void
9463 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
9464                      struct symtabs_and_lines sals, char *addr_string,
9465                      char *filter, char *cond_string,
9466                      char *extra_string,
9467                      enum bptype type, enum bpdisp disposition,
9468                      int thread, int task, int ignore_count,
9469                      const struct breakpoint_ops *ops, int from_tty,
9470                      int enabled, int internal, unsigned flags,
9471                      int display_canonical)
9472 {
9473   int i;
9474
9475   if (type == bp_hardware_breakpoint)
9476     {
9477       int target_resources_ok;
9478
9479       i = hw_breakpoint_used_count ();
9480       target_resources_ok =
9481         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9482                                             i + 1, 0);
9483       if (target_resources_ok == 0)
9484         error (_("No hardware breakpoint support in the target."));
9485       else if (target_resources_ok < 0)
9486         error (_("Hardware breakpoints used exceeds limit."));
9487     }
9488
9489   gdb_assert (sals.nelts > 0);
9490
9491   for (i = 0; i < sals.nelts; ++i)
9492     {
9493       struct symtab_and_line sal = sals.sals[i];
9494       struct bp_location *loc;
9495
9496       if (from_tty)
9497         {
9498           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9499           if (!loc_gdbarch)
9500             loc_gdbarch = gdbarch;
9501
9502           describe_other_breakpoints (loc_gdbarch,
9503                                       sal.pspace, sal.pc, sal.section, thread);
9504         }
9505
9506       if (i == 0)
9507         {
9508           init_raw_breakpoint (b, gdbarch, sal, type, ops);
9509           b->thread = thread;
9510           b->task = task;
9511
9512           b->cond_string = cond_string;
9513           b->extra_string = extra_string;
9514           b->ignore_count = ignore_count;
9515           b->enable_state = enabled ? bp_enabled : bp_disabled;
9516           b->disposition = disposition;
9517
9518           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9519             b->loc->inserted = 1;
9520
9521           if (type == bp_static_tracepoint)
9522             {
9523               struct tracepoint *t = (struct tracepoint *) b;
9524               struct static_tracepoint_marker marker;
9525
9526               if (strace_marker_p (b))
9527                 {
9528                   /* We already know the marker exists, otherwise, we
9529                      wouldn't see a sal for it.  */
9530                   char *p = &addr_string[3];
9531                   char *endp;
9532                   char *marker_str;
9533
9534                   p = skip_spaces (p);
9535
9536                   endp = skip_to_space (p);
9537
9538                   marker_str = savestring (p, endp - p);
9539                   t->static_trace_marker_id = marker_str;
9540
9541                   printf_filtered (_("Probed static tracepoint "
9542                                      "marker \"%s\"\n"),
9543                                    t->static_trace_marker_id);
9544                 }
9545               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
9546                 {
9547                   t->static_trace_marker_id = xstrdup (marker.str_id);
9548                   release_static_tracepoint_marker (&marker);
9549
9550                   printf_filtered (_("Probed static tracepoint "
9551                                      "marker \"%s\"\n"),
9552                                    t->static_trace_marker_id);
9553                 }
9554               else
9555                 warning (_("Couldn't determine the static "
9556                            "tracepoint marker to probe"));
9557             }
9558
9559           loc = b->loc;
9560         }
9561       else
9562         {
9563           loc = add_location_to_breakpoint (b, &sal);
9564           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
9565             loc->inserted = 1;
9566         }
9567
9568       if (bp_loc_is_permanent (loc))
9569         make_breakpoint_permanent (b);
9570
9571       if (b->cond_string)
9572         {
9573           const char *arg = b->cond_string;
9574
9575           loc->cond = parse_exp_1 (&arg, loc->address,
9576                                    block_for_pc (loc->address), 0);
9577           if (*arg)
9578               error (_("Garbage '%s' follows condition"), arg);
9579         }
9580
9581       /* Dynamic printf requires and uses additional arguments on the
9582          command line, otherwise it's an error.  */
9583       if (type == bp_dprintf)
9584         {
9585           if (b->extra_string)
9586             update_dprintf_command_list (b);
9587           else
9588             error (_("Format string required"));
9589         }
9590       else if (b->extra_string)
9591         error (_("Garbage '%s' at end of command"), b->extra_string);
9592     }
9593
9594   b->display_canonical = display_canonical;
9595   if (addr_string)
9596     b->addr_string = addr_string;
9597   else
9598     /* addr_string has to be used or breakpoint_re_set will delete
9599        me.  */
9600     b->addr_string
9601       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
9602   b->filter = filter;
9603 }
9604
9605 static void
9606 create_breakpoint_sal (struct gdbarch *gdbarch,
9607                        struct symtabs_and_lines sals, char *addr_string,
9608                        char *filter, char *cond_string,
9609                        char *extra_string,
9610                        enum bptype type, enum bpdisp disposition,
9611                        int thread, int task, int ignore_count,
9612                        const struct breakpoint_ops *ops, int from_tty,
9613                        int enabled, int internal, unsigned flags,
9614                        int display_canonical)
9615 {
9616   struct breakpoint *b;
9617   struct cleanup *old_chain;
9618
9619   if (is_tracepoint_type (type))
9620     {
9621       struct tracepoint *t;
9622
9623       t = XCNEW (struct tracepoint);
9624       b = &t->base;
9625     }
9626   else
9627     b = XNEW (struct breakpoint);
9628
9629   old_chain = make_cleanup (xfree, b);
9630
9631   init_breakpoint_sal (b, gdbarch,
9632                        sals, addr_string,
9633                        filter, cond_string, extra_string,
9634                        type, disposition,
9635                        thread, task, ignore_count,
9636                        ops, from_tty,
9637                        enabled, internal, flags,
9638                        display_canonical);
9639   discard_cleanups (old_chain);
9640
9641   install_breakpoint (internal, b, 0);
9642 }
9643
9644 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
9645    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
9646    value.  COND_STRING, if not NULL, specified the condition to be
9647    used for all breakpoints.  Essentially the only case where
9648    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
9649    function.  In that case, it's still not possible to specify
9650    separate conditions for different overloaded functions, so
9651    we take just a single condition string.
9652    
9653    NOTE: If the function succeeds, the caller is expected to cleanup
9654    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
9655    array contents).  If the function fails (error() is called), the
9656    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
9657    COND and SALS arrays and each of those arrays contents.  */
9658
9659 static void
9660 create_breakpoints_sal (struct gdbarch *gdbarch,
9661                         struct linespec_result *canonical,
9662                         char *cond_string, char *extra_string,
9663                         enum bptype type, enum bpdisp disposition,
9664                         int thread, int task, int ignore_count,
9665                         const struct breakpoint_ops *ops, int from_tty,
9666                         int enabled, int internal, unsigned flags)
9667 {
9668   int i;
9669   struct linespec_sals *lsal;
9670
9671   if (canonical->pre_expanded)
9672     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
9673
9674   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
9675     {
9676       /* Note that 'addr_string' can be NULL in the case of a plain
9677          'break', without arguments.  */
9678       char *addr_string = (canonical->addr_string
9679                            ? xstrdup (canonical->addr_string)
9680                            : NULL);
9681       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
9682       struct cleanup *inner = make_cleanup (xfree, addr_string);
9683
9684       make_cleanup (xfree, filter_string);
9685       create_breakpoint_sal (gdbarch, lsal->sals,
9686                              addr_string,
9687                              filter_string,
9688                              cond_string, extra_string,
9689                              type, disposition,
9690                              thread, task, ignore_count, ops,
9691                              from_tty, enabled, internal, flags,
9692                              canonical->special_display);
9693       discard_cleanups (inner);
9694     }
9695 }
9696
9697 /* Parse ADDRESS which is assumed to be a SAL specification possibly
9698    followed by conditionals.  On return, SALS contains an array of SAL
9699    addresses found.  ADDR_STRING contains a vector of (canonical)
9700    address strings.  ADDRESS points to the end of the SAL.
9701
9702    The array and the line spec strings are allocated on the heap, it is
9703    the caller's responsibility to free them.  */
9704
9705 static void
9706 parse_breakpoint_sals (char **address,
9707                        struct linespec_result *canonical)
9708 {
9709   /* If no arg given, or if first arg is 'if ', use the default
9710      breakpoint.  */
9711   if ((*address) == NULL
9712       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
9713     {
9714       /* The last displayed codepoint, if it's valid, is our default breakpoint
9715          address.  */
9716       if (last_displayed_sal_is_valid ())
9717         {
9718           struct linespec_sals lsal;
9719           struct symtab_and_line sal;
9720           CORE_ADDR pc;
9721
9722           init_sal (&sal);              /* Initialize to zeroes.  */
9723           lsal.sals.sals = (struct symtab_and_line *)
9724             xmalloc (sizeof (struct symtab_and_line));
9725
9726           /* Set sal's pspace, pc, symtab, and line to the values
9727              corresponding to the last call to print_frame_info.
9728              Be sure to reinitialize LINE with NOTCURRENT == 0
9729              as the breakpoint line number is inappropriate otherwise.
9730              find_pc_line would adjust PC, re-set it back.  */
9731           get_last_displayed_sal (&sal);
9732           pc = sal.pc;
9733           sal = find_pc_line (pc, 0);
9734
9735           /* "break" without arguments is equivalent to "break *PC"
9736              where PC is the last displayed codepoint's address.  So
9737              make sure to set sal.explicit_pc to prevent GDB from
9738              trying to expand the list of sals to include all other
9739              instances with the same symtab and line.  */
9740           sal.pc = pc;
9741           sal.explicit_pc = 1;
9742
9743           lsal.sals.sals[0] = sal;
9744           lsal.sals.nelts = 1;
9745           lsal.canonical = NULL;
9746
9747           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
9748         }
9749       else
9750         error (_("No default breakpoint address now."));
9751     }
9752   else
9753     {
9754       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
9755
9756       /* Force almost all breakpoints to be in terms of the
9757          current_source_symtab (which is decode_line_1's default).
9758          This should produce the results we want almost all of the
9759          time while leaving default_breakpoint_* alone.
9760
9761          ObjC: However, don't match an Objective-C method name which
9762          may have a '+' or '-' succeeded by a '['.  */
9763       if (last_displayed_sal_is_valid ()
9764           && (!cursal.symtab
9765               || ((strchr ("+-", (*address)[0]) != NULL)
9766                   && ((*address)[1] != '['))))
9767         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9768                           get_last_displayed_symtab (),
9769                           get_last_displayed_line (),
9770                           canonical, NULL, NULL);
9771       else
9772         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
9773                           cursal.symtab, cursal.line, canonical, NULL, NULL);
9774     }
9775 }
9776
9777
9778 /* Convert each SAL into a real PC.  Verify that the PC can be
9779    inserted as a breakpoint.  If it can't throw an error.  */
9780
9781 static void
9782 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
9783 {    
9784   int i;
9785
9786   for (i = 0; i < sals->nelts; i++)
9787     resolve_sal_pc (&sals->sals[i]);
9788 }
9789
9790 /* Fast tracepoints may have restrictions on valid locations.  For
9791    instance, a fast tracepoint using a jump instead of a trap will
9792    likely have to overwrite more bytes than a trap would, and so can
9793    only be placed where the instruction is longer than the jump, or a
9794    multi-instruction sequence does not have a jump into the middle of
9795    it, etc.  */
9796
9797 static void
9798 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
9799                             struct symtabs_and_lines *sals)
9800 {
9801   int i, rslt;
9802   struct symtab_and_line *sal;
9803   char *msg;
9804   struct cleanup *old_chain;
9805
9806   for (i = 0; i < sals->nelts; i++)
9807     {
9808       struct gdbarch *sarch;
9809
9810       sal = &sals->sals[i];
9811
9812       sarch = get_sal_arch (*sal);
9813       /* We fall back to GDBARCH if there is no architecture
9814          associated with SAL.  */
9815       if (sarch == NULL)
9816         sarch = gdbarch;
9817       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
9818                                                NULL, &msg);
9819       old_chain = make_cleanup (xfree, msg);
9820
9821       if (!rslt)
9822         error (_("May not have a fast tracepoint at 0x%s%s"),
9823                paddress (sarch, sal->pc), (msg ? msg : ""));
9824
9825       do_cleanups (old_chain);
9826     }
9827 }
9828
9829 /* Issue an invalid thread ID error.  */
9830
9831 static void ATTRIBUTE_NORETURN
9832 invalid_thread_id_error (int id)
9833 {
9834   error (_("Unknown thread %d."), id);
9835 }
9836
9837 /* Given TOK, a string specification of condition and thread, as
9838    accepted by the 'break' command, extract the condition
9839    string and thread number and set *COND_STRING and *THREAD.
9840    PC identifies the context at which the condition should be parsed.
9841    If no condition is found, *COND_STRING is set to NULL.
9842    If no thread is found, *THREAD is set to -1.  */
9843
9844 static void
9845 find_condition_and_thread (const char *tok, CORE_ADDR pc,
9846                            char **cond_string, int *thread, int *task,
9847                            char **rest)
9848 {
9849   *cond_string = NULL;
9850   *thread = -1;
9851   *task = 0;
9852   *rest = NULL;
9853
9854   while (tok && *tok)
9855     {
9856       const char *end_tok;
9857       int toklen;
9858       const char *cond_start = NULL;
9859       const char *cond_end = NULL;
9860
9861       tok = skip_spaces_const (tok);
9862
9863       if ((*tok == '"' || *tok == ',') && rest)
9864         {
9865           *rest = savestring (tok, strlen (tok));
9866           return;
9867         }
9868
9869       end_tok = skip_to_space_const (tok);
9870
9871       toklen = end_tok - tok;
9872
9873       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9874         {
9875           struct expression *expr;
9876
9877           tok = cond_start = end_tok + 1;
9878           expr = parse_exp_1 (&tok, pc, block_for_pc (pc), 0);
9879           xfree (expr);
9880           cond_end = tok;
9881           *cond_string = savestring (cond_start, cond_end - cond_start);
9882         }
9883       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
9884         {
9885           char *tmptok;
9886
9887           tok = end_tok + 1;
9888           *thread = strtol (tok, &tmptok, 0);
9889           if (tok == tmptok)
9890             error (_("Junk after thread keyword."));
9891           if (!valid_thread_id (*thread))
9892             invalid_thread_id_error (*thread);
9893           tok = tmptok;
9894         }
9895       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
9896         {
9897           char *tmptok;
9898
9899           tok = end_tok + 1;
9900           *task = strtol (tok, &tmptok, 0);
9901           if (tok == tmptok)
9902             error (_("Junk after task keyword."));
9903           if (!valid_task_id (*task))
9904             error (_("Unknown task %d."), *task);
9905           tok = tmptok;
9906         }
9907       else if (rest)
9908         {
9909           *rest = savestring (tok, strlen (tok));
9910           return;
9911         }
9912       else
9913         error (_("Junk at end of arguments."));
9914     }
9915 }
9916
9917 /* Decode a static tracepoint marker spec.  */
9918
9919 static struct symtabs_and_lines
9920 decode_static_tracepoint_spec (char **arg_p)
9921 {
9922   VEC(static_tracepoint_marker_p) *markers = NULL;
9923   struct symtabs_and_lines sals;
9924   struct cleanup *old_chain;
9925   char *p = &(*arg_p)[3];
9926   char *endp;
9927   char *marker_str;
9928   int i;
9929
9930   p = skip_spaces (p);
9931
9932   endp = skip_to_space (p);
9933
9934   marker_str = savestring (p, endp - p);
9935   old_chain = make_cleanup (xfree, marker_str);
9936
9937   markers = target_static_tracepoint_markers_by_strid (marker_str);
9938   if (VEC_empty(static_tracepoint_marker_p, markers))
9939     error (_("No known static tracepoint marker named %s"), marker_str);
9940
9941   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
9942   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
9943
9944   for (i = 0; i < sals.nelts; i++)
9945     {
9946       struct static_tracepoint_marker *marker;
9947
9948       marker = VEC_index (static_tracepoint_marker_p, markers, i);
9949
9950       init_sal (&sals.sals[i]);
9951
9952       sals.sals[i] = find_pc_line (marker->address, 0);
9953       sals.sals[i].pc = marker->address;
9954
9955       release_static_tracepoint_marker (marker);
9956     }
9957
9958   do_cleanups (old_chain);
9959
9960   *arg_p = endp;
9961   return sals;
9962 }
9963
9964 /* Set a breakpoint.  This function is shared between CLI and MI
9965    functions for setting a breakpoint.  This function has two major
9966    modes of operations, selected by the PARSE_ARG parameter.  If
9967    non-zero, the function will parse ARG, extracting location,
9968    condition, thread and extra string.  Otherwise, ARG is just the
9969    breakpoint's location, with condition, thread, and extra string
9970    specified by the COND_STRING, THREAD and EXTRA_STRING parameters.
9971    If INTERNAL is non-zero, the breakpoint number will be allocated
9972    from the internal breakpoint count.  Returns true if any breakpoint
9973    was created; false otherwise.  */
9974
9975 int
9976 create_breakpoint (struct gdbarch *gdbarch,
9977                    char *arg, char *cond_string,
9978                    int thread, char *extra_string,
9979                    int parse_arg,
9980                    int tempflag, enum bptype type_wanted,
9981                    int ignore_count,
9982                    enum auto_boolean pending_break_support,
9983                    const struct breakpoint_ops *ops,
9984                    int from_tty, int enabled, int internal,
9985                    unsigned flags)
9986 {
9987   volatile struct gdb_exception e;
9988   char *copy_arg = NULL;
9989   char *addr_start = arg;
9990   struct linespec_result canonical;
9991   struct cleanup *old_chain;
9992   struct cleanup *bkpt_chain = NULL;
9993   int pending = 0;
9994   int task = 0;
9995   int prev_bkpt_count = breakpoint_count;
9996
9997   gdb_assert (ops != NULL);
9998
9999   init_linespec_result (&canonical);
10000
10001   TRY_CATCH (e, RETURN_MASK_ALL)
10002     {
10003       ops->create_sals_from_address (&arg, &canonical, type_wanted,
10004                                      addr_start, &copy_arg);
10005     }
10006
10007   /* If caller is interested in rc value from parse, set value.  */
10008   switch (e.reason)
10009     {
10010     case GDB_NO_ERROR:
10011       if (VEC_empty (linespec_sals, canonical.sals))
10012         return 0;
10013       break;
10014     case RETURN_ERROR:
10015       switch (e.error)
10016         {
10017         case NOT_FOUND_ERROR:
10018
10019           /* If pending breakpoint support is turned off, throw
10020              error.  */
10021
10022           if (pending_break_support == AUTO_BOOLEAN_FALSE)
10023             throw_exception (e);
10024
10025           exception_print (gdb_stderr, e);
10026
10027           /* If pending breakpoint support is auto query and the user
10028              selects no, then simply return the error code.  */
10029           if (pending_break_support == AUTO_BOOLEAN_AUTO
10030               && !nquery (_("Make %s pending on future shared library load? "),
10031                           bptype_string (type_wanted)))
10032             return 0;
10033
10034           /* At this point, either the user was queried about setting
10035              a pending breakpoint and selected yes, or pending
10036              breakpoint behavior is on and thus a pending breakpoint
10037              is defaulted on behalf of the user.  */
10038           {
10039             struct linespec_sals lsal;
10040
10041             copy_arg = xstrdup (addr_start);
10042             lsal.canonical = xstrdup (copy_arg);
10043             lsal.sals.nelts = 1;
10044             lsal.sals.sals = XNEW (struct symtab_and_line);
10045             init_sal (&lsal.sals.sals[0]);
10046             pending = 1;
10047             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
10048           }
10049           break;
10050         default:
10051           throw_exception (e);
10052         }
10053       break;
10054     default:
10055       throw_exception (e);
10056     }
10057
10058   /* Create a chain of things that always need to be cleaned up.  */
10059   old_chain = make_cleanup_destroy_linespec_result (&canonical);
10060
10061   /* ----------------------------- SNIP -----------------------------
10062      Anything added to the cleanup chain beyond this point is assumed
10063      to be part of a breakpoint.  If the breakpoint create succeeds
10064      then the memory is not reclaimed.  */
10065   bkpt_chain = make_cleanup (null_cleanup, 0);
10066
10067   /* Resolve all line numbers to PC's and verify that the addresses
10068      are ok for the target.  */
10069   if (!pending)
10070     {
10071       int ix;
10072       struct linespec_sals *iter;
10073
10074       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10075         breakpoint_sals_to_pc (&iter->sals);
10076     }
10077
10078   /* Fast tracepoints may have additional restrictions on location.  */
10079   if (!pending && type_wanted == bp_fast_tracepoint)
10080     {
10081       int ix;
10082       struct linespec_sals *iter;
10083
10084       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
10085         check_fast_tracepoint_sals (gdbarch, &iter->sals);
10086     }
10087
10088   /* Verify that condition can be parsed, before setting any
10089      breakpoints.  Allocate a separate condition expression for each
10090      breakpoint.  */
10091   if (!pending)
10092     {
10093       if (parse_arg)
10094         {
10095           char *rest;
10096           struct linespec_sals *lsal;
10097
10098           lsal = VEC_index (linespec_sals, canonical.sals, 0);
10099
10100           /* Here we only parse 'arg' to separate condition
10101              from thread number, so parsing in context of first
10102              sal is OK.  When setting the breakpoint we'll
10103              re-parse it in context of each sal.  */
10104
10105           find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
10106                                      &thread, &task, &rest);
10107           if (cond_string)
10108             make_cleanup (xfree, cond_string);
10109           if (rest)
10110             make_cleanup (xfree, rest);
10111           if (rest)
10112             extra_string = rest;
10113         }
10114       else
10115         {
10116           if (*arg != '\0')
10117             error (_("Garbage '%s' at end of location"), arg);
10118
10119           /* Create a private copy of condition string.  */
10120           if (cond_string)
10121             {
10122               cond_string = xstrdup (cond_string);
10123               make_cleanup (xfree, cond_string);
10124             }
10125           /* Create a private copy of any extra string.  */
10126           if (extra_string)
10127             {
10128               extra_string = xstrdup (extra_string);
10129               make_cleanup (xfree, extra_string);
10130             }
10131         }
10132
10133       ops->create_breakpoints_sal (gdbarch, &canonical,
10134                                    cond_string, extra_string, type_wanted,
10135                                    tempflag ? disp_del : disp_donttouch,
10136                                    thread, task, ignore_count, ops,
10137                                    from_tty, enabled, internal, flags);
10138     }
10139   else
10140     {
10141       struct breakpoint *b;
10142
10143       make_cleanup (xfree, copy_arg);
10144
10145       if (is_tracepoint_type (type_wanted))
10146         {
10147           struct tracepoint *t;
10148
10149           t = XCNEW (struct tracepoint);
10150           b = &t->base;
10151         }
10152       else
10153         b = XNEW (struct breakpoint);
10154
10155       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
10156
10157       b->addr_string = copy_arg;
10158       if (parse_arg)
10159         b->cond_string = NULL;
10160       else
10161         {
10162           /* Create a private copy of condition string.  */
10163           if (cond_string)
10164             {
10165               cond_string = xstrdup (cond_string);
10166               make_cleanup (xfree, cond_string);
10167             }
10168           b->cond_string = cond_string;
10169         }
10170       b->extra_string = NULL;
10171       b->ignore_count = ignore_count;
10172       b->disposition = tempflag ? disp_del : disp_donttouch;
10173       b->condition_not_parsed = 1;
10174       b->enable_state = enabled ? bp_enabled : bp_disabled;
10175       if ((type_wanted != bp_breakpoint
10176            && type_wanted != bp_hardware_breakpoint) || thread != -1)
10177         b->pspace = current_program_space;
10178
10179       install_breakpoint (internal, b, 0);
10180     }
10181   
10182   if (VEC_length (linespec_sals, canonical.sals) > 1)
10183     {
10184       warning (_("Multiple breakpoints were set.\nUse the "
10185                  "\"delete\" command to delete unwanted breakpoints."));
10186       prev_breakpoint_count = prev_bkpt_count;
10187     }
10188
10189   /* That's it.  Discard the cleanups for data inserted into the
10190      breakpoint.  */
10191   discard_cleanups (bkpt_chain);
10192   /* But cleanup everything else.  */
10193   do_cleanups (old_chain);
10194
10195   /* error call may happen here - have BKPT_CHAIN already discarded.  */
10196   update_global_location_list (UGLL_MAY_INSERT);
10197
10198   return 1;
10199 }
10200
10201 /* Set a breakpoint.
10202    ARG is a string describing breakpoint address,
10203    condition, and thread.
10204    FLAG specifies if a breakpoint is hardware on,
10205    and if breakpoint is temporary, using BP_HARDWARE_FLAG
10206    and BP_TEMPFLAG.  */
10207
10208 static void
10209 break_command_1 (char *arg, int flag, int from_tty)
10210 {
10211   int tempflag = flag & BP_TEMPFLAG;
10212   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
10213                              ? bp_hardware_breakpoint
10214                              : bp_breakpoint);
10215   struct breakpoint_ops *ops;
10216   const char *arg_cp = arg;
10217
10218   /* Matching breakpoints on probes.  */
10219   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
10220     ops = &bkpt_probe_breakpoint_ops;
10221   else
10222     ops = &bkpt_breakpoint_ops;
10223
10224   create_breakpoint (get_current_arch (),
10225                      arg,
10226                      NULL, 0, NULL, 1 /* parse arg */,
10227                      tempflag, type_wanted,
10228                      0 /* Ignore count */,
10229                      pending_break_support,
10230                      ops,
10231                      from_tty,
10232                      1 /* enabled */,
10233                      0 /* internal */,
10234                      0);
10235 }
10236
10237 /* Helper function for break_command_1 and disassemble_command.  */
10238
10239 void
10240 resolve_sal_pc (struct symtab_and_line *sal)
10241 {
10242   CORE_ADDR pc;
10243
10244   if (sal->pc == 0 && sal->symtab != NULL)
10245     {
10246       if (!find_line_pc (sal->symtab, sal->line, &pc))
10247         error (_("No line %d in file \"%s\"."),
10248                sal->line, symtab_to_filename_for_display (sal->symtab));
10249       sal->pc = pc;
10250
10251       /* If this SAL corresponds to a breakpoint inserted using a line
10252          number, then skip the function prologue if necessary.  */
10253       if (sal->explicit_line)
10254         skip_prologue_sal (sal);
10255     }
10256
10257   if (sal->section == 0 && sal->symtab != NULL)
10258     {
10259       const struct blockvector *bv;
10260       const struct block *b;
10261       struct symbol *sym;
10262
10263       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
10264       if (bv != NULL)
10265         {
10266           sym = block_linkage_function (b);
10267           if (sym != NULL)
10268             {
10269               fixup_symbol_section (sym, sal->symtab->objfile);
10270               sal->section = SYMBOL_OBJ_SECTION (sal->symtab->objfile, sym);
10271             }
10272           else
10273             {
10274               /* It really is worthwhile to have the section, so we'll
10275                  just have to look harder. This case can be executed
10276                  if we have line numbers but no functions (as can
10277                  happen in assembly source).  */
10278
10279               struct bound_minimal_symbol msym;
10280               struct cleanup *old_chain = save_current_space_and_thread ();
10281
10282               switch_to_program_space_and_thread (sal->pspace);
10283
10284               msym = lookup_minimal_symbol_by_pc (sal->pc);
10285               if (msym.minsym)
10286                 sal->section = MSYMBOL_OBJ_SECTION (msym.objfile, msym.minsym);
10287
10288               do_cleanups (old_chain);
10289             }
10290         }
10291     }
10292 }
10293
10294 void
10295 break_command (char *arg, int from_tty)
10296 {
10297   break_command_1 (arg, 0, from_tty);
10298 }
10299
10300 void
10301 tbreak_command (char *arg, int from_tty)
10302 {
10303   break_command_1 (arg, BP_TEMPFLAG, from_tty);
10304 }
10305
10306 static void
10307 hbreak_command (char *arg, int from_tty)
10308 {
10309   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
10310 }
10311
10312 static void
10313 thbreak_command (char *arg, int from_tty)
10314 {
10315   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
10316 }
10317
10318 static void
10319 stop_command (char *arg, int from_tty)
10320 {
10321   printf_filtered (_("Specify the type of breakpoint to set.\n\
10322 Usage: stop in <function | address>\n\
10323        stop at <line>\n"));
10324 }
10325
10326 static void
10327 stopin_command (char *arg, int from_tty)
10328 {
10329   int badInput = 0;
10330
10331   if (arg == (char *) NULL)
10332     badInput = 1;
10333   else if (*arg != '*')
10334     {
10335       char *argptr = arg;
10336       int hasColon = 0;
10337
10338       /* Look for a ':'.  If this is a line number specification, then
10339          say it is bad, otherwise, it should be an address or
10340          function/method name.  */
10341       while (*argptr && !hasColon)
10342         {
10343           hasColon = (*argptr == ':');
10344           argptr++;
10345         }
10346
10347       if (hasColon)
10348         badInput = (*argptr != ':');    /* Not a class::method */
10349       else
10350         badInput = isdigit (*arg);      /* a simple line number */
10351     }
10352
10353   if (badInput)
10354     printf_filtered (_("Usage: stop in <function | address>\n"));
10355   else
10356     break_command_1 (arg, 0, from_tty);
10357 }
10358
10359 static void
10360 stopat_command (char *arg, int from_tty)
10361 {
10362   int badInput = 0;
10363
10364   if (arg == (char *) NULL || *arg == '*')      /* no line number */
10365     badInput = 1;
10366   else
10367     {
10368       char *argptr = arg;
10369       int hasColon = 0;
10370
10371       /* Look for a ':'.  If there is a '::' then get out, otherwise
10372          it is probably a line number.  */
10373       while (*argptr && !hasColon)
10374         {
10375           hasColon = (*argptr == ':');
10376           argptr++;
10377         }
10378
10379       if (hasColon)
10380         badInput = (*argptr == ':');    /* we have class::method */
10381       else
10382         badInput = !isdigit (*arg);     /* not a line number */
10383     }
10384
10385   if (badInput)
10386     printf_filtered (_("Usage: stop at <line>\n"));
10387   else
10388     break_command_1 (arg, 0, from_tty);
10389 }
10390
10391 /* The dynamic printf command is mostly like a regular breakpoint, but
10392    with a prewired command list consisting of a single output command,
10393    built from extra arguments supplied on the dprintf command
10394    line.  */
10395
10396 static void
10397 dprintf_command (char *arg, int from_tty)
10398 {
10399   create_breakpoint (get_current_arch (),
10400                      arg,
10401                      NULL, 0, NULL, 1 /* parse arg */,
10402                      0, bp_dprintf,
10403                      0 /* Ignore count */,
10404                      pending_break_support,
10405                      &dprintf_breakpoint_ops,
10406                      from_tty,
10407                      1 /* enabled */,
10408                      0 /* internal */,
10409                      0);
10410 }
10411
10412 static void
10413 agent_printf_command (char *arg, int from_tty)
10414 {
10415   error (_("May only run agent-printf on the target"));
10416 }
10417
10418 /* Implement the "breakpoint_hit" breakpoint_ops method for
10419    ranged breakpoints.  */
10420
10421 static int
10422 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
10423                                   struct address_space *aspace,
10424                                   CORE_ADDR bp_addr,
10425                                   const struct target_waitstatus *ws)
10426 {
10427   if (ws->kind != TARGET_WAITKIND_STOPPED
10428       || ws->value.sig != GDB_SIGNAL_TRAP)
10429     return 0;
10430
10431   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
10432                                          bl->length, aspace, bp_addr);
10433 }
10434
10435 /* Implement the "resources_needed" breakpoint_ops method for
10436    ranged breakpoints.  */
10437
10438 static int
10439 resources_needed_ranged_breakpoint (const struct bp_location *bl)
10440 {
10441   return target_ranged_break_num_registers ();
10442 }
10443
10444 /* Implement the "print_it" breakpoint_ops method for
10445    ranged breakpoints.  */
10446
10447 static enum print_stop_action
10448 print_it_ranged_breakpoint (bpstat bs)
10449 {
10450   struct breakpoint *b = bs->breakpoint_at;
10451   struct bp_location *bl = b->loc;
10452   struct ui_out *uiout = current_uiout;
10453
10454   gdb_assert (b->type == bp_hardware_breakpoint);
10455
10456   /* Ranged breakpoints have only one location.  */
10457   gdb_assert (bl && bl->next == NULL);
10458
10459   annotate_breakpoint (b->number);
10460   if (b->disposition == disp_del)
10461     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
10462   else
10463     ui_out_text (uiout, "\nRanged breakpoint ");
10464   if (ui_out_is_mi_like_p (uiout))
10465     {
10466       ui_out_field_string (uiout, "reason",
10467                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
10468       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
10469     }
10470   ui_out_field_int (uiout, "bkptno", b->number);
10471   ui_out_text (uiout, ", ");
10472
10473   return PRINT_SRC_AND_LOC;
10474 }
10475
10476 /* Implement the "print_one" breakpoint_ops method for
10477    ranged breakpoints.  */
10478
10479 static void
10480 print_one_ranged_breakpoint (struct breakpoint *b,
10481                              struct bp_location **last_loc)
10482 {
10483   struct bp_location *bl = b->loc;
10484   struct value_print_options opts;
10485   struct ui_out *uiout = current_uiout;
10486
10487   /* Ranged breakpoints have only one location.  */
10488   gdb_assert (bl && bl->next == NULL);
10489
10490   get_user_print_options (&opts);
10491
10492   if (opts.addressprint)
10493     /* We don't print the address range here, it will be printed later
10494        by print_one_detail_ranged_breakpoint.  */
10495     ui_out_field_skip (uiout, "addr");
10496   annotate_field (5);
10497   print_breakpoint_location (b, bl);
10498   *last_loc = bl;
10499 }
10500
10501 /* Implement the "print_one_detail" breakpoint_ops method for
10502    ranged breakpoints.  */
10503
10504 static void
10505 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
10506                                     struct ui_out *uiout)
10507 {
10508   CORE_ADDR address_start, address_end;
10509   struct bp_location *bl = b->loc;
10510   struct ui_file *stb = mem_fileopen ();
10511   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
10512
10513   gdb_assert (bl);
10514
10515   address_start = bl->address;
10516   address_end = address_start + bl->length - 1;
10517
10518   ui_out_text (uiout, "\taddress range: ");
10519   fprintf_unfiltered (stb, "[%s, %s]",
10520                       print_core_address (bl->gdbarch, address_start),
10521                       print_core_address (bl->gdbarch, address_end));
10522   ui_out_field_stream (uiout, "addr", stb);
10523   ui_out_text (uiout, "\n");
10524
10525   do_cleanups (cleanup);
10526 }
10527
10528 /* Implement the "print_mention" breakpoint_ops method for
10529    ranged breakpoints.  */
10530
10531 static void
10532 print_mention_ranged_breakpoint (struct breakpoint *b)
10533 {
10534   struct bp_location *bl = b->loc;
10535   struct ui_out *uiout = current_uiout;
10536
10537   gdb_assert (bl);
10538   gdb_assert (b->type == bp_hardware_breakpoint);
10539
10540   if (ui_out_is_mi_like_p (uiout))
10541     return;
10542
10543   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
10544                    b->number, paddress (bl->gdbarch, bl->address),
10545                    paddress (bl->gdbarch, bl->address + bl->length - 1));
10546 }
10547
10548 /* Implement the "print_recreate" breakpoint_ops method for
10549    ranged breakpoints.  */
10550
10551 static void
10552 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
10553 {
10554   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
10555                       b->addr_string_range_end);
10556   print_recreate_thread (b, fp);
10557 }
10558
10559 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
10560
10561 static struct breakpoint_ops ranged_breakpoint_ops;
10562
10563 /* Find the address where the end of the breakpoint range should be
10564    placed, given the SAL of the end of the range.  This is so that if
10565    the user provides a line number, the end of the range is set to the
10566    last instruction of the given line.  */
10567
10568 static CORE_ADDR
10569 find_breakpoint_range_end (struct symtab_and_line sal)
10570 {
10571   CORE_ADDR end;
10572
10573   /* If the user provided a PC value, use it.  Otherwise,
10574      find the address of the end of the given location.  */
10575   if (sal.explicit_pc)
10576     end = sal.pc;
10577   else
10578     {
10579       int ret;
10580       CORE_ADDR start;
10581
10582       ret = find_line_pc_range (sal, &start, &end);
10583       if (!ret)
10584         error (_("Could not find location of the end of the range."));
10585
10586       /* find_line_pc_range returns the start of the next line.  */
10587       end--;
10588     }
10589
10590   return end;
10591 }
10592
10593 /* Implement the "break-range" CLI command.  */
10594
10595 static void
10596 break_range_command (char *arg, int from_tty)
10597 {
10598   char *arg_start, *addr_string_start, *addr_string_end;
10599   struct linespec_result canonical_start, canonical_end;
10600   int bp_count, can_use_bp, length;
10601   CORE_ADDR end;
10602   struct breakpoint *b;
10603   struct symtab_and_line sal_start, sal_end;
10604   struct cleanup *cleanup_bkpt;
10605   struct linespec_sals *lsal_start, *lsal_end;
10606
10607   /* We don't support software ranged breakpoints.  */
10608   if (target_ranged_break_num_registers () < 0)
10609     error (_("This target does not support hardware ranged breakpoints."));
10610
10611   bp_count = hw_breakpoint_used_count ();
10612   bp_count += target_ranged_break_num_registers ();
10613   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
10614                                                    bp_count, 0);
10615   if (can_use_bp < 0)
10616     error (_("Hardware breakpoints used exceeds limit."));
10617
10618   arg = skip_spaces (arg);
10619   if (arg == NULL || arg[0] == '\0')
10620     error(_("No address range specified."));
10621
10622   init_linespec_result (&canonical_start);
10623
10624   arg_start = arg;
10625   parse_breakpoint_sals (&arg, &canonical_start);
10626
10627   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
10628
10629   if (arg[0] != ',')
10630     error (_("Too few arguments."));
10631   else if (VEC_empty (linespec_sals, canonical_start.sals))
10632     error (_("Could not find location of the beginning of the range."));
10633
10634   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
10635
10636   if (VEC_length (linespec_sals, canonical_start.sals) > 1
10637       || lsal_start->sals.nelts != 1)
10638     error (_("Cannot create a ranged breakpoint with multiple locations."));
10639
10640   sal_start = lsal_start->sals.sals[0];
10641   addr_string_start = savestring (arg_start, arg - arg_start);
10642   make_cleanup (xfree, addr_string_start);
10643
10644   arg++;        /* Skip the comma.  */
10645   arg = skip_spaces (arg);
10646
10647   /* Parse the end location.  */
10648
10649   init_linespec_result (&canonical_end);
10650   arg_start = arg;
10651
10652   /* We call decode_line_full directly here instead of using
10653      parse_breakpoint_sals because we need to specify the start location's
10654      symtab and line as the default symtab and line for the end of the
10655      range.  This makes it possible to have ranges like "foo.c:27, +14",
10656      where +14 means 14 lines from the start location.  */
10657   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
10658                     sal_start.symtab, sal_start.line,
10659                     &canonical_end, NULL, NULL);
10660
10661   make_cleanup_destroy_linespec_result (&canonical_end);
10662
10663   if (VEC_empty (linespec_sals, canonical_end.sals))
10664     error (_("Could not find location of the end of the range."));
10665
10666   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
10667   if (VEC_length (linespec_sals, canonical_end.sals) > 1
10668       || lsal_end->sals.nelts != 1)
10669     error (_("Cannot create a ranged breakpoint with multiple locations."));
10670
10671   sal_end = lsal_end->sals.sals[0];
10672   addr_string_end = savestring (arg_start, arg - arg_start);
10673   make_cleanup (xfree, addr_string_end);
10674
10675   end = find_breakpoint_range_end (sal_end);
10676   if (sal_start.pc > end)
10677     error (_("Invalid address range, end precedes start."));
10678
10679   length = end - sal_start.pc + 1;
10680   if (length < 0)
10681     /* Length overflowed.  */
10682     error (_("Address range too large."));
10683   else if (length == 1)
10684     {
10685       /* This range is simple enough to be handled by
10686          the `hbreak' command.  */
10687       hbreak_command (addr_string_start, 1);
10688
10689       do_cleanups (cleanup_bkpt);
10690
10691       return;
10692     }
10693
10694   /* Now set up the breakpoint.  */
10695   b = set_raw_breakpoint (get_current_arch (), sal_start,
10696                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
10697   set_breakpoint_count (breakpoint_count + 1);
10698   b->number = breakpoint_count;
10699   b->disposition = disp_donttouch;
10700   b->addr_string = xstrdup (addr_string_start);
10701   b->addr_string_range_end = xstrdup (addr_string_end);
10702   b->loc->length = length;
10703
10704   do_cleanups (cleanup_bkpt);
10705
10706   mention (b);
10707   observer_notify_breakpoint_created (b);
10708   update_global_location_list (UGLL_MAY_INSERT);
10709 }
10710
10711 /*  Return non-zero if EXP is verified as constant.  Returned zero
10712     means EXP is variable.  Also the constant detection may fail for
10713     some constant expressions and in such case still falsely return
10714     zero.  */
10715
10716 static int
10717 watchpoint_exp_is_const (const struct expression *exp)
10718 {
10719   int i = exp->nelts;
10720
10721   while (i > 0)
10722     {
10723       int oplenp, argsp;
10724
10725       /* We are only interested in the descriptor of each element.  */
10726       operator_length (exp, i, &oplenp, &argsp);
10727       i -= oplenp;
10728
10729       switch (exp->elts[i].opcode)
10730         {
10731         case BINOP_ADD:
10732         case BINOP_SUB:
10733         case BINOP_MUL:
10734         case BINOP_DIV:
10735         case BINOP_REM:
10736         case BINOP_MOD:
10737         case BINOP_LSH:
10738         case BINOP_RSH:
10739         case BINOP_LOGICAL_AND:
10740         case BINOP_LOGICAL_OR:
10741         case BINOP_BITWISE_AND:
10742         case BINOP_BITWISE_IOR:
10743         case BINOP_BITWISE_XOR:
10744         case BINOP_EQUAL:
10745         case BINOP_NOTEQUAL:
10746         case BINOP_LESS:
10747         case BINOP_GTR:
10748         case BINOP_LEQ:
10749         case BINOP_GEQ:
10750         case BINOP_REPEAT:
10751         case BINOP_COMMA:
10752         case BINOP_EXP:
10753         case BINOP_MIN:
10754         case BINOP_MAX:
10755         case BINOP_INTDIV:
10756         case BINOP_CONCAT:
10757         case TERNOP_COND:
10758         case TERNOP_SLICE:
10759
10760         case OP_LONG:
10761         case OP_DOUBLE:
10762         case OP_DECFLOAT:
10763         case OP_LAST:
10764         case OP_COMPLEX:
10765         case OP_STRING:
10766         case OP_ARRAY:
10767         case OP_TYPE:
10768         case OP_TYPEOF:
10769         case OP_DECLTYPE:
10770         case OP_TYPEID:
10771         case OP_NAME:
10772         case OP_OBJC_NSSTRING:
10773
10774         case UNOP_NEG:
10775         case UNOP_LOGICAL_NOT:
10776         case UNOP_COMPLEMENT:
10777         case UNOP_ADDR:
10778         case UNOP_HIGH:
10779         case UNOP_CAST:
10780
10781         case UNOP_CAST_TYPE:
10782         case UNOP_REINTERPRET_CAST:
10783         case UNOP_DYNAMIC_CAST:
10784           /* Unary, binary and ternary operators: We have to check
10785              their operands.  If they are constant, then so is the
10786              result of that operation.  For instance, if A and B are
10787              determined to be constants, then so is "A + B".
10788
10789              UNOP_IND is one exception to the rule above, because the
10790              value of *ADDR is not necessarily a constant, even when
10791              ADDR is.  */
10792           break;
10793
10794         case OP_VAR_VALUE:
10795           /* Check whether the associated symbol is a constant.
10796
10797              We use SYMBOL_CLASS rather than TYPE_CONST because it's
10798              possible that a buggy compiler could mark a variable as
10799              constant even when it is not, and TYPE_CONST would return
10800              true in this case, while SYMBOL_CLASS wouldn't.
10801
10802              We also have to check for function symbols because they
10803              are always constant.  */
10804           {
10805             struct symbol *s = exp->elts[i + 2].symbol;
10806
10807             if (SYMBOL_CLASS (s) != LOC_BLOCK
10808                 && SYMBOL_CLASS (s) != LOC_CONST
10809                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
10810               return 0;
10811             break;
10812           }
10813
10814         /* The default action is to return 0 because we are using
10815            the optimistic approach here: If we don't know something,
10816            then it is not a constant.  */
10817         default:
10818           return 0;
10819         }
10820     }
10821
10822   return 1;
10823 }
10824
10825 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
10826
10827 static void
10828 dtor_watchpoint (struct breakpoint *self)
10829 {
10830   struct watchpoint *w = (struct watchpoint *) self;
10831
10832   xfree (w->cond_exp);
10833   xfree (w->exp);
10834   xfree (w->exp_string);
10835   xfree (w->exp_string_reparse);
10836   value_free (w->val);
10837
10838   base_breakpoint_ops.dtor (self);
10839 }
10840
10841 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
10842
10843 static void
10844 re_set_watchpoint (struct breakpoint *b)
10845 {
10846   struct watchpoint *w = (struct watchpoint *) b;
10847
10848   /* Watchpoint can be either on expression using entirely global
10849      variables, or it can be on local variables.
10850
10851      Watchpoints of the first kind are never auto-deleted, and even
10852      persist across program restarts.  Since they can use variables
10853      from shared libraries, we need to reparse expression as libraries
10854      are loaded and unloaded.
10855
10856      Watchpoints on local variables can also change meaning as result
10857      of solib event.  For example, if a watchpoint uses both a local
10858      and a global variables in expression, it's a local watchpoint,
10859      but unloading of a shared library will make the expression
10860      invalid.  This is not a very common use case, but we still
10861      re-evaluate expression, to avoid surprises to the user.
10862
10863      Note that for local watchpoints, we re-evaluate it only if
10864      watchpoints frame id is still valid.  If it's not, it means the
10865      watchpoint is out of scope and will be deleted soon.  In fact,
10866      I'm not sure we'll ever be called in this case.
10867
10868      If a local watchpoint's frame id is still valid, then
10869      w->exp_valid_block is likewise valid, and we can safely use it.
10870
10871      Don't do anything about disabled watchpoints, since they will be
10872      reevaluated again when enabled.  */
10873   update_watchpoint (w, 1 /* reparse */);
10874 }
10875
10876 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
10877
10878 static int
10879 insert_watchpoint (struct bp_location *bl)
10880 {
10881   struct watchpoint *w = (struct watchpoint *) bl->owner;
10882   int length = w->exact ? 1 : bl->length;
10883
10884   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
10885                                    w->cond_exp);
10886 }
10887
10888 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
10889
10890 static int
10891 remove_watchpoint (struct bp_location *bl)
10892 {
10893   struct watchpoint *w = (struct watchpoint *) bl->owner;
10894   int length = w->exact ? 1 : bl->length;
10895
10896   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
10897                                    w->cond_exp);
10898 }
10899
10900 static int
10901 breakpoint_hit_watchpoint (const struct bp_location *bl,
10902                            struct address_space *aspace, CORE_ADDR bp_addr,
10903                            const struct target_waitstatus *ws)
10904 {
10905   struct breakpoint *b = bl->owner;
10906   struct watchpoint *w = (struct watchpoint *) b;
10907
10908   /* Continuable hardware watchpoints are treated as non-existent if the
10909      reason we stopped wasn't a hardware watchpoint (we didn't stop on
10910      some data address).  Otherwise gdb won't stop on a break instruction
10911      in the code (not from a breakpoint) when a hardware watchpoint has
10912      been defined.  Also skip watchpoints which we know did not trigger
10913      (did not match the data address).  */
10914   if (is_hardware_watchpoint (b)
10915       && w->watchpoint_triggered == watch_triggered_no)
10916     return 0;
10917
10918   return 1;
10919 }
10920
10921 static void
10922 check_status_watchpoint (bpstat bs)
10923 {
10924   gdb_assert (is_watchpoint (bs->breakpoint_at));
10925
10926   bpstat_check_watchpoint (bs);
10927 }
10928
10929 /* Implement the "resources_needed" breakpoint_ops method for
10930    hardware watchpoints.  */
10931
10932 static int
10933 resources_needed_watchpoint (const struct bp_location *bl)
10934 {
10935   struct watchpoint *w = (struct watchpoint *) bl->owner;
10936   int length = w->exact? 1 : bl->length;
10937
10938   return target_region_ok_for_hw_watchpoint (bl->address, length);
10939 }
10940
10941 /* Implement the "works_in_software_mode" breakpoint_ops method for
10942    hardware watchpoints.  */
10943
10944 static int
10945 works_in_software_mode_watchpoint (const struct breakpoint *b)
10946 {
10947   /* Read and access watchpoints only work with hardware support.  */
10948   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
10949 }
10950
10951 static enum print_stop_action
10952 print_it_watchpoint (bpstat bs)
10953 {
10954   struct cleanup *old_chain;
10955   struct breakpoint *b;
10956   struct ui_file *stb;
10957   enum print_stop_action result;
10958   struct watchpoint *w;
10959   struct ui_out *uiout = current_uiout;
10960
10961   gdb_assert (bs->bp_location_at != NULL);
10962
10963   b = bs->breakpoint_at;
10964   w = (struct watchpoint *) b;
10965
10966   stb = mem_fileopen ();
10967   old_chain = make_cleanup_ui_file_delete (stb);
10968
10969   switch (b->type)
10970     {
10971     case bp_watchpoint:
10972     case bp_hardware_watchpoint:
10973       annotate_watchpoint (b->number);
10974       if (ui_out_is_mi_like_p (uiout))
10975         ui_out_field_string
10976           (uiout, "reason",
10977            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10978       mention (b);
10979       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10980       ui_out_text (uiout, "\nOld value = ");
10981       watchpoint_value_print (bs->old_val, stb);
10982       ui_out_field_stream (uiout, "old", stb);
10983       ui_out_text (uiout, "\nNew value = ");
10984       watchpoint_value_print (w->val, stb);
10985       ui_out_field_stream (uiout, "new", stb);
10986       ui_out_text (uiout, "\n");
10987       /* More than one watchpoint may have been triggered.  */
10988       result = PRINT_UNKNOWN;
10989       break;
10990
10991     case bp_read_watchpoint:
10992       if (ui_out_is_mi_like_p (uiout))
10993         ui_out_field_string
10994           (uiout, "reason",
10995            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10996       mention (b);
10997       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10998       ui_out_text (uiout, "\nValue = ");
10999       watchpoint_value_print (w->val, stb);
11000       ui_out_field_stream (uiout, "value", stb);
11001       ui_out_text (uiout, "\n");
11002       result = PRINT_UNKNOWN;
11003       break;
11004
11005     case bp_access_watchpoint:
11006       if (bs->old_val != NULL)
11007         {
11008           annotate_watchpoint (b->number);
11009           if (ui_out_is_mi_like_p (uiout))
11010             ui_out_field_string
11011               (uiout, "reason",
11012                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11013           mention (b);
11014           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11015           ui_out_text (uiout, "\nOld value = ");
11016           watchpoint_value_print (bs->old_val, stb);
11017           ui_out_field_stream (uiout, "old", stb);
11018           ui_out_text (uiout, "\nNew value = ");
11019         }
11020       else
11021         {
11022           mention (b);
11023           if (ui_out_is_mi_like_p (uiout))
11024             ui_out_field_string
11025               (uiout, "reason",
11026                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11027           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
11028           ui_out_text (uiout, "\nValue = ");
11029         }
11030       watchpoint_value_print (w->val, stb);
11031       ui_out_field_stream (uiout, "new", stb);
11032       ui_out_text (uiout, "\n");
11033       result = PRINT_UNKNOWN;
11034       break;
11035     default:
11036       result = PRINT_UNKNOWN;
11037     }
11038
11039   do_cleanups (old_chain);
11040   return result;
11041 }
11042
11043 /* Implement the "print_mention" breakpoint_ops method for hardware
11044    watchpoints.  */
11045
11046 static void
11047 print_mention_watchpoint (struct breakpoint *b)
11048 {
11049   struct cleanup *ui_out_chain;
11050   struct watchpoint *w = (struct watchpoint *) b;
11051   struct ui_out *uiout = current_uiout;
11052
11053   switch (b->type)
11054     {
11055     case bp_watchpoint:
11056       ui_out_text (uiout, "Watchpoint ");
11057       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11058       break;
11059     case bp_hardware_watchpoint:
11060       ui_out_text (uiout, "Hardware watchpoint ");
11061       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11062       break;
11063     case bp_read_watchpoint:
11064       ui_out_text (uiout, "Hardware read watchpoint ");
11065       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11066       break;
11067     case bp_access_watchpoint:
11068       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
11069       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11070       break;
11071     default:
11072       internal_error (__FILE__, __LINE__,
11073                       _("Invalid hardware watchpoint type."));
11074     }
11075
11076   ui_out_field_int (uiout, "number", b->number);
11077   ui_out_text (uiout, ": ");
11078   ui_out_field_string (uiout, "exp", w->exp_string);
11079   do_cleanups (ui_out_chain);
11080 }
11081
11082 /* Implement the "print_recreate" breakpoint_ops method for
11083    watchpoints.  */
11084
11085 static void
11086 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
11087 {
11088   struct watchpoint *w = (struct watchpoint *) b;
11089
11090   switch (b->type)
11091     {
11092     case bp_watchpoint:
11093     case bp_hardware_watchpoint:
11094       fprintf_unfiltered (fp, "watch");
11095       break;
11096     case bp_read_watchpoint:
11097       fprintf_unfiltered (fp, "rwatch");
11098       break;
11099     case bp_access_watchpoint:
11100       fprintf_unfiltered (fp, "awatch");
11101       break;
11102     default:
11103       internal_error (__FILE__, __LINE__,
11104                       _("Invalid watchpoint type."));
11105     }
11106
11107   fprintf_unfiltered (fp, " %s", w->exp_string);
11108   print_recreate_thread (b, fp);
11109 }
11110
11111 /* Implement the "explains_signal" breakpoint_ops method for
11112    watchpoints.  */
11113
11114 static int
11115 explains_signal_watchpoint (struct breakpoint *b, enum gdb_signal sig)
11116 {
11117   /* A software watchpoint cannot cause a signal other than
11118      GDB_SIGNAL_TRAP.  */
11119   if (b->type == bp_watchpoint && sig != GDB_SIGNAL_TRAP)
11120     return 0;
11121
11122   return 1;
11123 }
11124
11125 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
11126
11127 static struct breakpoint_ops watchpoint_breakpoint_ops;
11128
11129 /* Implement the "insert" breakpoint_ops method for
11130    masked hardware watchpoints.  */
11131
11132 static int
11133 insert_masked_watchpoint (struct bp_location *bl)
11134 {
11135   struct watchpoint *w = (struct watchpoint *) bl->owner;
11136
11137   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
11138                                         bl->watchpoint_type);
11139 }
11140
11141 /* Implement the "remove" breakpoint_ops method for
11142    masked hardware watchpoints.  */
11143
11144 static int
11145 remove_masked_watchpoint (struct bp_location *bl)
11146 {
11147   struct watchpoint *w = (struct watchpoint *) bl->owner;
11148
11149   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
11150                                         bl->watchpoint_type);
11151 }
11152
11153 /* Implement the "resources_needed" breakpoint_ops method for
11154    masked hardware watchpoints.  */
11155
11156 static int
11157 resources_needed_masked_watchpoint (const struct bp_location *bl)
11158 {
11159   struct watchpoint *w = (struct watchpoint *) bl->owner;
11160
11161   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
11162 }
11163
11164 /* Implement the "works_in_software_mode" breakpoint_ops method for
11165    masked hardware watchpoints.  */
11166
11167 static int
11168 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
11169 {
11170   return 0;
11171 }
11172
11173 /* Implement the "print_it" breakpoint_ops method for
11174    masked hardware watchpoints.  */
11175
11176 static enum print_stop_action
11177 print_it_masked_watchpoint (bpstat bs)
11178 {
11179   struct breakpoint *b = bs->breakpoint_at;
11180   struct ui_out *uiout = current_uiout;
11181
11182   /* Masked watchpoints have only one location.  */
11183   gdb_assert (b->loc && b->loc->next == NULL);
11184
11185   switch (b->type)
11186     {
11187     case bp_hardware_watchpoint:
11188       annotate_watchpoint (b->number);
11189       if (ui_out_is_mi_like_p (uiout))
11190         ui_out_field_string
11191           (uiout, "reason",
11192            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
11193       break;
11194
11195     case bp_read_watchpoint:
11196       if (ui_out_is_mi_like_p (uiout))
11197         ui_out_field_string
11198           (uiout, "reason",
11199            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
11200       break;
11201
11202     case bp_access_watchpoint:
11203       if (ui_out_is_mi_like_p (uiout))
11204         ui_out_field_string
11205           (uiout, "reason",
11206            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
11207       break;
11208     default:
11209       internal_error (__FILE__, __LINE__,
11210                       _("Invalid hardware watchpoint type."));
11211     }
11212
11213   mention (b);
11214   ui_out_text (uiout, _("\n\
11215 Check the underlying instruction at PC for the memory\n\
11216 address and value which triggered this watchpoint.\n"));
11217   ui_out_text (uiout, "\n");
11218
11219   /* More than one watchpoint may have been triggered.  */
11220   return PRINT_UNKNOWN;
11221 }
11222
11223 /* Implement the "print_one_detail" breakpoint_ops method for
11224    masked hardware watchpoints.  */
11225
11226 static void
11227 print_one_detail_masked_watchpoint (const struct breakpoint *b,
11228                                     struct ui_out *uiout)
11229 {
11230   struct watchpoint *w = (struct watchpoint *) b;
11231
11232   /* Masked watchpoints have only one location.  */
11233   gdb_assert (b->loc && b->loc->next == NULL);
11234
11235   ui_out_text (uiout, "\tmask ");
11236   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
11237   ui_out_text (uiout, "\n");
11238 }
11239
11240 /* Implement the "print_mention" breakpoint_ops method for
11241    masked hardware watchpoints.  */
11242
11243 static void
11244 print_mention_masked_watchpoint (struct breakpoint *b)
11245 {
11246   struct watchpoint *w = (struct watchpoint *) b;
11247   struct ui_out *uiout = current_uiout;
11248   struct cleanup *ui_out_chain;
11249
11250   switch (b->type)
11251     {
11252     case bp_hardware_watchpoint:
11253       ui_out_text (uiout, "Masked hardware watchpoint ");
11254       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
11255       break;
11256     case bp_read_watchpoint:
11257       ui_out_text (uiout, "Masked hardware read watchpoint ");
11258       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
11259       break;
11260     case bp_access_watchpoint:
11261       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
11262       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
11263       break;
11264     default:
11265       internal_error (__FILE__, __LINE__,
11266                       _("Invalid hardware watchpoint type."));
11267     }
11268
11269   ui_out_field_int (uiout, "number", b->number);
11270   ui_out_text (uiout, ": ");
11271   ui_out_field_string (uiout, "exp", w->exp_string);
11272   do_cleanups (ui_out_chain);
11273 }
11274
11275 /* Implement the "print_recreate" breakpoint_ops method for
11276    masked hardware watchpoints.  */
11277
11278 static void
11279 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
11280 {
11281   struct watchpoint *w = (struct watchpoint *) b;
11282   char tmp[40];
11283
11284   switch (b->type)
11285     {
11286     case bp_hardware_watchpoint:
11287       fprintf_unfiltered (fp, "watch");
11288       break;
11289     case bp_read_watchpoint:
11290       fprintf_unfiltered (fp, "rwatch");
11291       break;
11292     case bp_access_watchpoint:
11293       fprintf_unfiltered (fp, "awatch");
11294       break;
11295     default:
11296       internal_error (__FILE__, __LINE__,
11297                       _("Invalid hardware watchpoint type."));
11298     }
11299
11300   sprintf_vma (tmp, w->hw_wp_mask);
11301   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
11302   print_recreate_thread (b, fp);
11303 }
11304
11305 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
11306
11307 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
11308
11309 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
11310
11311 static int
11312 is_masked_watchpoint (const struct breakpoint *b)
11313 {
11314   return b->ops == &masked_watchpoint_breakpoint_ops;
11315 }
11316
11317 /* accessflag:  hw_write:  watch write, 
11318                 hw_read:   watch read, 
11319                 hw_access: watch access (read or write) */
11320 static void
11321 watch_command_1 (const char *arg, int accessflag, int from_tty,
11322                  int just_location, int internal)
11323 {
11324   volatile struct gdb_exception e;
11325   struct breakpoint *b, *scope_breakpoint = NULL;
11326   struct expression *exp;
11327   const struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
11328   struct value *val, *mark, *result;
11329   int saved_bitpos = 0, saved_bitsize = 0;
11330   struct frame_info *frame;
11331   const char *exp_start = NULL;
11332   const char *exp_end = NULL;
11333   const char *tok, *end_tok;
11334   int toklen = -1;
11335   const char *cond_start = NULL;
11336   const char *cond_end = NULL;
11337   enum bptype bp_type;
11338   int thread = -1;
11339   int pc = 0;
11340   /* Flag to indicate whether we are going to use masks for
11341      the hardware watchpoint.  */
11342   int use_mask = 0;
11343   CORE_ADDR mask = 0;
11344   struct watchpoint *w;
11345   char *expression;
11346   struct cleanup *back_to;
11347
11348   /* Make sure that we actually have parameters to parse.  */
11349   if (arg != NULL && arg[0] != '\0')
11350     {
11351       const char *value_start;
11352
11353       exp_end = arg + strlen (arg);
11354
11355       /* Look for "parameter value" pairs at the end
11356          of the arguments string.  */
11357       for (tok = exp_end - 1; tok > arg; tok--)
11358         {
11359           /* Skip whitespace at the end of the argument list.  */
11360           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11361             tok--;
11362
11363           /* Find the beginning of the last token.
11364              This is the value of the parameter.  */
11365           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11366             tok--;
11367           value_start = tok + 1;
11368
11369           /* Skip whitespace.  */
11370           while (tok > arg && (*tok == ' ' || *tok == '\t'))
11371             tok--;
11372
11373           end_tok = tok;
11374
11375           /* Find the beginning of the second to last token.
11376              This is the parameter itself.  */
11377           while (tok > arg && (*tok != ' ' && *tok != '\t'))
11378             tok--;
11379           tok++;
11380           toklen = end_tok - tok + 1;
11381
11382           if (toklen == 6 && !strncmp (tok, "thread", 6))
11383             {
11384               /* At this point we've found a "thread" token, which means
11385                  the user is trying to set a watchpoint that triggers
11386                  only in a specific thread.  */
11387               char *endp;
11388
11389               if (thread != -1)
11390                 error(_("You can specify only one thread."));
11391
11392               /* Extract the thread ID from the next token.  */
11393               thread = strtol (value_start, &endp, 0);
11394
11395               /* Check if the user provided a valid numeric value for the
11396                  thread ID.  */
11397               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
11398                 error (_("Invalid thread ID specification %s."), value_start);
11399
11400               /* Check if the thread actually exists.  */
11401               if (!valid_thread_id (thread))
11402                 invalid_thread_id_error (thread);
11403             }
11404           else if (toklen == 4 && !strncmp (tok, "mask", 4))
11405             {
11406               /* We've found a "mask" token, which means the user wants to
11407                  create a hardware watchpoint that is going to have the mask
11408                  facility.  */
11409               struct value *mask_value, *mark;
11410
11411               if (use_mask)
11412                 error(_("You can specify only one mask."));
11413
11414               use_mask = just_location = 1;
11415
11416               mark = value_mark ();
11417               mask_value = parse_to_comma_and_eval (&value_start);
11418               mask = value_as_address (mask_value);
11419               value_free_to_mark (mark);
11420             }
11421           else
11422             /* We didn't recognize what we found.  We should stop here.  */
11423             break;
11424
11425           /* Truncate the string and get rid of the "parameter value" pair before
11426              the arguments string is parsed by the parse_exp_1 function.  */
11427           exp_end = tok;
11428         }
11429     }
11430   else
11431     exp_end = arg;
11432
11433   /* Parse the rest of the arguments.  From here on out, everything
11434      is in terms of a newly allocated string instead of the original
11435      ARG.  */
11436   innermost_block = NULL;
11437   expression = savestring (arg, exp_end - arg);
11438   back_to = make_cleanup (xfree, expression);
11439   exp_start = arg = expression;
11440   exp = parse_exp_1 (&arg, 0, 0, 0);
11441   exp_end = arg;
11442   /* Remove trailing whitespace from the expression before saving it.
11443      This makes the eventual display of the expression string a bit
11444      prettier.  */
11445   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
11446     --exp_end;
11447
11448   /* Checking if the expression is not constant.  */
11449   if (watchpoint_exp_is_const (exp))
11450     {
11451       int len;
11452
11453       len = exp_end - exp_start;
11454       while (len > 0 && isspace (exp_start[len - 1]))
11455         len--;
11456       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
11457     }
11458
11459   exp_valid_block = innermost_block;
11460   mark = value_mark ();
11461   fetch_subexp_value (exp, &pc, &val, &result, NULL, just_location);
11462
11463   if (val != NULL && just_location)
11464     {
11465       saved_bitpos = value_bitpos (val);
11466       saved_bitsize = value_bitsize (val);
11467     }
11468
11469   if (just_location)
11470     {
11471       int ret;
11472
11473       exp_valid_block = NULL;
11474       val = value_addr (result);
11475       release_value (val);
11476       value_free_to_mark (mark);
11477
11478       if (use_mask)
11479         {
11480           ret = target_masked_watch_num_registers (value_as_address (val),
11481                                                    mask);
11482           if (ret == -1)
11483             error (_("This target does not support masked watchpoints."));
11484           else if (ret == -2)
11485             error (_("Invalid mask or memory region."));
11486         }
11487     }
11488   else if (val != NULL)
11489     release_value (val);
11490
11491   tok = skip_spaces_const (arg);
11492   end_tok = skip_to_space_const (tok);
11493
11494   toklen = end_tok - tok;
11495   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
11496     {
11497       struct expression *cond;
11498
11499       innermost_block = NULL;
11500       tok = cond_start = end_tok + 1;
11501       cond = parse_exp_1 (&tok, 0, 0, 0);
11502
11503       /* The watchpoint expression may not be local, but the condition
11504          may still be.  E.g.: `watch global if local > 0'.  */
11505       cond_exp_valid_block = innermost_block;
11506
11507       xfree (cond);
11508       cond_end = tok;
11509     }
11510   if (*tok)
11511     error (_("Junk at end of command."));
11512
11513   frame = block_innermost_frame (exp_valid_block);
11514
11515   /* If the expression is "local", then set up a "watchpoint scope"
11516      breakpoint at the point where we've left the scope of the watchpoint
11517      expression.  Create the scope breakpoint before the watchpoint, so
11518      that we will encounter it first in bpstat_stop_status.  */
11519   if (exp_valid_block && frame)
11520     {
11521       if (frame_id_p (frame_unwind_caller_id (frame)))
11522         {
11523           scope_breakpoint
11524             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
11525                                           frame_unwind_caller_pc (frame),
11526                                           bp_watchpoint_scope,
11527                                           &momentary_breakpoint_ops);
11528
11529           scope_breakpoint->enable_state = bp_enabled;
11530
11531           /* Automatically delete the breakpoint when it hits.  */
11532           scope_breakpoint->disposition = disp_del;
11533
11534           /* Only break in the proper frame (help with recursion).  */
11535           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
11536
11537           /* Set the address at which we will stop.  */
11538           scope_breakpoint->loc->gdbarch
11539             = frame_unwind_caller_arch (frame);
11540           scope_breakpoint->loc->requested_address
11541             = frame_unwind_caller_pc (frame);
11542           scope_breakpoint->loc->address
11543             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
11544                                          scope_breakpoint->loc->requested_address,
11545                                          scope_breakpoint->type);
11546         }
11547     }
11548
11549   /* Now set up the breakpoint.  We create all watchpoints as hardware
11550      watchpoints here even if hardware watchpoints are turned off, a call
11551      to update_watchpoint later in this function will cause the type to
11552      drop back to bp_watchpoint (software watchpoint) if required.  */
11553
11554   if (accessflag == hw_read)
11555     bp_type = bp_read_watchpoint;
11556   else if (accessflag == hw_access)
11557     bp_type = bp_access_watchpoint;
11558   else
11559     bp_type = bp_hardware_watchpoint;
11560
11561   w = XCNEW (struct watchpoint);
11562   b = &w->base;
11563   if (use_mask)
11564     init_raw_breakpoint_without_location (b, NULL, bp_type,
11565                                           &masked_watchpoint_breakpoint_ops);
11566   else
11567     init_raw_breakpoint_without_location (b, NULL, bp_type,
11568                                           &watchpoint_breakpoint_ops);
11569   b->thread = thread;
11570   b->disposition = disp_donttouch;
11571   b->pspace = current_program_space;
11572   w->exp = exp;
11573   w->exp_valid_block = exp_valid_block;
11574   w->cond_exp_valid_block = cond_exp_valid_block;
11575   if (just_location)
11576     {
11577       struct type *t = value_type (val);
11578       CORE_ADDR addr = value_as_address (val);
11579       char *name;
11580
11581       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
11582       name = type_to_string (t);
11583
11584       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
11585                                           core_addr_to_string (addr));
11586       xfree (name);
11587
11588       w->exp_string = xstrprintf ("-location %.*s",
11589                                   (int) (exp_end - exp_start), exp_start);
11590
11591       /* The above expression is in C.  */
11592       b->language = language_c;
11593     }
11594   else
11595     w->exp_string = savestring (exp_start, exp_end - exp_start);
11596
11597   if (use_mask)
11598     {
11599       w->hw_wp_mask = mask;
11600     }
11601   else
11602     {
11603       w->val = val;
11604       w->val_bitpos = saved_bitpos;
11605       w->val_bitsize = saved_bitsize;
11606       w->val_valid = 1;
11607     }
11608
11609   if (cond_start)
11610     b->cond_string = savestring (cond_start, cond_end - cond_start);
11611   else
11612     b->cond_string = 0;
11613
11614   if (frame)
11615     {
11616       w->watchpoint_frame = get_frame_id (frame);
11617       w->watchpoint_thread = inferior_ptid;
11618     }
11619   else
11620     {
11621       w->watchpoint_frame = null_frame_id;
11622       w->watchpoint_thread = null_ptid;
11623     }
11624
11625   if (scope_breakpoint != NULL)
11626     {
11627       /* The scope breakpoint is related to the watchpoint.  We will
11628          need to act on them together.  */
11629       b->related_breakpoint = scope_breakpoint;
11630       scope_breakpoint->related_breakpoint = b;
11631     }
11632
11633   if (!just_location)
11634     value_free_to_mark (mark);
11635
11636   TRY_CATCH (e, RETURN_MASK_ALL)
11637     {
11638       /* Finally update the new watchpoint.  This creates the locations
11639          that should be inserted.  */
11640       update_watchpoint (w, 1);
11641     }
11642   if (e.reason < 0)
11643     {
11644       delete_breakpoint (b);
11645       throw_exception (e);
11646     }
11647
11648   install_breakpoint (internal, b, 1);
11649   do_cleanups (back_to);
11650 }
11651
11652 /* Return count of debug registers needed to watch the given expression.
11653    If the watchpoint cannot be handled in hardware return zero.  */
11654
11655 static int
11656 can_use_hardware_watchpoint (struct value *v)
11657 {
11658   int found_memory_cnt = 0;
11659   struct value *head = v;
11660
11661   /* Did the user specifically forbid us to use hardware watchpoints? */
11662   if (!can_use_hw_watchpoints)
11663     return 0;
11664
11665   /* Make sure that the value of the expression depends only upon
11666      memory contents, and values computed from them within GDB.  If we
11667      find any register references or function calls, we can't use a
11668      hardware watchpoint.
11669
11670      The idea here is that evaluating an expression generates a series
11671      of values, one holding the value of every subexpression.  (The
11672      expression a*b+c has five subexpressions: a, b, a*b, c, and
11673      a*b+c.)  GDB's values hold almost enough information to establish
11674      the criteria given above --- they identify memory lvalues,
11675      register lvalues, computed values, etcetera.  So we can evaluate
11676      the expression, and then scan the chain of values that leaves
11677      behind to decide whether we can detect any possible change to the
11678      expression's final value using only hardware watchpoints.
11679
11680      However, I don't think that the values returned by inferior
11681      function calls are special in any way.  So this function may not
11682      notice that an expression involving an inferior function call
11683      can't be watched with hardware watchpoints.  FIXME.  */
11684   for (; v; v = value_next (v))
11685     {
11686       if (VALUE_LVAL (v) == lval_memory)
11687         {
11688           if (v != head && value_lazy (v))
11689             /* A lazy memory lvalue in the chain is one that GDB never
11690                needed to fetch; we either just used its address (e.g.,
11691                `a' in `a.b') or we never needed it at all (e.g., `a'
11692                in `a,b').  This doesn't apply to HEAD; if that is
11693                lazy then it was not readable, but watch it anyway.  */
11694             ;
11695           else
11696             {
11697               /* Ahh, memory we actually used!  Check if we can cover
11698                  it with hardware watchpoints.  */
11699               struct type *vtype = check_typedef (value_type (v));
11700
11701               /* We only watch structs and arrays if user asked for it
11702                  explicitly, never if they just happen to appear in a
11703                  middle of some value chain.  */
11704               if (v == head
11705                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
11706                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
11707                 {
11708                   CORE_ADDR vaddr = value_address (v);
11709                   int len;
11710                   int num_regs;
11711
11712                   len = (target_exact_watchpoints
11713                          && is_scalar_type_recursive (vtype))?
11714                     1 : TYPE_LENGTH (value_type (v));
11715
11716                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
11717                   if (!num_regs)
11718                     return 0;
11719                   else
11720                     found_memory_cnt += num_regs;
11721                 }
11722             }
11723         }
11724       else if (VALUE_LVAL (v) != not_lval
11725                && deprecated_value_modifiable (v) == 0)
11726         return 0;       /* These are values from the history (e.g., $1).  */
11727       else if (VALUE_LVAL (v) == lval_register)
11728         return 0;       /* Cannot watch a register with a HW watchpoint.  */
11729     }
11730
11731   /* The expression itself looks suitable for using a hardware
11732      watchpoint, but give the target machine a chance to reject it.  */
11733   return found_memory_cnt;
11734 }
11735
11736 void
11737 watch_command_wrapper (char *arg, int from_tty, int internal)
11738 {
11739   watch_command_1 (arg, hw_write, from_tty, 0, internal);
11740 }
11741
11742 /* A helper function that looks for the "-location" argument and then
11743    calls watch_command_1.  */
11744
11745 static void
11746 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
11747 {
11748   int just_location = 0;
11749
11750   if (arg
11751       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
11752           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
11753     {
11754       arg = skip_spaces (arg);
11755       just_location = 1;
11756     }
11757
11758   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
11759 }
11760
11761 static void
11762 watch_command (char *arg, int from_tty)
11763 {
11764   watch_maybe_just_location (arg, hw_write, from_tty);
11765 }
11766
11767 void
11768 rwatch_command_wrapper (char *arg, int from_tty, int internal)
11769 {
11770   watch_command_1 (arg, hw_read, from_tty, 0, internal);
11771 }
11772
11773 static void
11774 rwatch_command (char *arg, int from_tty)
11775 {
11776   watch_maybe_just_location (arg, hw_read, from_tty);
11777 }
11778
11779 void
11780 awatch_command_wrapper (char *arg, int from_tty, int internal)
11781 {
11782   watch_command_1 (arg, hw_access, from_tty, 0, internal);
11783 }
11784
11785 static void
11786 awatch_command (char *arg, int from_tty)
11787 {
11788   watch_maybe_just_location (arg, hw_access, from_tty);
11789 }
11790 \f
11791
11792 /* Helper routines for the until_command routine in infcmd.c.  Here
11793    because it uses the mechanisms of breakpoints.  */
11794
11795 struct until_break_command_continuation_args
11796 {
11797   struct breakpoint *breakpoint;
11798   struct breakpoint *breakpoint2;
11799   int thread_num;
11800 };
11801
11802 /* This function is called by fetch_inferior_event via the
11803    cmd_continuation pointer, to complete the until command.  It takes
11804    care of cleaning up the temporary breakpoints set up by the until
11805    command.  */
11806 static void
11807 until_break_command_continuation (void *arg, int err)
11808 {
11809   struct until_break_command_continuation_args *a = arg;
11810
11811   delete_breakpoint (a->breakpoint);
11812   if (a->breakpoint2)
11813     delete_breakpoint (a->breakpoint2);
11814   delete_longjmp_breakpoint (a->thread_num);
11815 }
11816
11817 void
11818 until_break_command (char *arg, int from_tty, int anywhere)
11819 {
11820   struct symtabs_and_lines sals;
11821   struct symtab_and_line sal;
11822   struct frame_info *frame;
11823   struct gdbarch *frame_gdbarch;
11824   struct frame_id stack_frame_id;
11825   struct frame_id caller_frame_id;
11826   struct breakpoint *breakpoint;
11827   struct breakpoint *breakpoint2 = NULL;
11828   struct cleanup *old_chain;
11829   int thread;
11830   struct thread_info *tp;
11831
11832   clear_proceed_status (0);
11833
11834   /* Set a breakpoint where the user wants it and at return from
11835      this function.  */
11836
11837   if (last_displayed_sal_is_valid ())
11838     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11839                           get_last_displayed_symtab (),
11840                           get_last_displayed_line ());
11841   else
11842     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
11843                           (struct symtab *) NULL, 0);
11844
11845   if (sals.nelts != 1)
11846     error (_("Couldn't get information on specified line."));
11847
11848   sal = sals.sals[0];
11849   xfree (sals.sals);    /* malloc'd, so freed.  */
11850
11851   if (*arg)
11852     error (_("Junk at end of arguments."));
11853
11854   resolve_sal_pc (&sal);
11855
11856   tp = inferior_thread ();
11857   thread = tp->num;
11858
11859   old_chain = make_cleanup (null_cleanup, NULL);
11860
11861   /* Note linespec handling above invalidates the frame chain.
11862      Installing a breakpoint also invalidates the frame chain (as it
11863      may need to switch threads), so do any frame handling before
11864      that.  */
11865
11866   frame = get_selected_frame (NULL);
11867   frame_gdbarch = get_frame_arch (frame);
11868   stack_frame_id = get_stack_frame_id (frame);
11869   caller_frame_id = frame_unwind_caller_id (frame);
11870
11871   /* Keep within the current frame, or in frames called by the current
11872      one.  */
11873
11874   if (frame_id_p (caller_frame_id))
11875     {
11876       struct symtab_and_line sal2;
11877
11878       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
11879       sal2.pc = frame_unwind_caller_pc (frame);
11880       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
11881                                               sal2,
11882                                               caller_frame_id,
11883                                               bp_until);
11884       make_cleanup_delete_breakpoint (breakpoint2);
11885
11886       set_longjmp_breakpoint (tp, caller_frame_id);
11887       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
11888     }
11889
11890   /* set_momentary_breakpoint could invalidate FRAME.  */
11891   frame = NULL;
11892
11893   if (anywhere)
11894     /* If the user told us to continue until a specified location,
11895        we don't specify a frame at which we need to stop.  */
11896     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11897                                            null_frame_id, bp_until);
11898   else
11899     /* Otherwise, specify the selected frame, because we want to stop
11900        only at the very same frame.  */
11901     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
11902                                            stack_frame_id, bp_until);
11903   make_cleanup_delete_breakpoint (breakpoint);
11904
11905   proceed (-1, GDB_SIGNAL_DEFAULT, 0);
11906
11907   /* If we are running asynchronously, and proceed call above has
11908      actually managed to start the target, arrange for breakpoints to
11909      be deleted when the target stops.  Otherwise, we're already
11910      stopped and delete breakpoints via cleanup chain.  */
11911
11912   if (target_can_async_p () && is_running (inferior_ptid))
11913     {
11914       struct until_break_command_continuation_args *args;
11915       args = xmalloc (sizeof (*args));
11916
11917       args->breakpoint = breakpoint;
11918       args->breakpoint2 = breakpoint2;
11919       args->thread_num = thread;
11920
11921       discard_cleanups (old_chain);
11922       add_continuation (inferior_thread (),
11923                         until_break_command_continuation, args,
11924                         xfree);
11925     }
11926   else
11927     do_cleanups (old_chain);
11928 }
11929
11930 /* This function attempts to parse an optional "if <cond>" clause
11931    from the arg string.  If one is not found, it returns NULL.
11932
11933    Else, it returns a pointer to the condition string.  (It does not
11934    attempt to evaluate the string against a particular block.)  And,
11935    it updates arg to point to the first character following the parsed
11936    if clause in the arg string.  */
11937
11938 char *
11939 ep_parse_optional_if_clause (char **arg)
11940 {
11941   char *cond_string;
11942
11943   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
11944     return NULL;
11945
11946   /* Skip the "if" keyword.  */
11947   (*arg) += 2;
11948
11949   /* Skip any extra leading whitespace, and record the start of the
11950      condition string.  */
11951   *arg = skip_spaces (*arg);
11952   cond_string = *arg;
11953
11954   /* Assume that the condition occupies the remainder of the arg
11955      string.  */
11956   (*arg) += strlen (cond_string);
11957
11958   return cond_string;
11959 }
11960
11961 /* Commands to deal with catching events, such as signals, exceptions,
11962    process start/exit, etc.  */
11963
11964 typedef enum
11965 {
11966   catch_fork_temporary, catch_vfork_temporary,
11967   catch_fork_permanent, catch_vfork_permanent
11968 }
11969 catch_fork_kind;
11970
11971 static void
11972 catch_fork_command_1 (char *arg, int from_tty, 
11973                       struct cmd_list_element *command)
11974 {
11975   struct gdbarch *gdbarch = get_current_arch ();
11976   char *cond_string = NULL;
11977   catch_fork_kind fork_kind;
11978   int tempflag;
11979
11980   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
11981   tempflag = (fork_kind == catch_fork_temporary
11982               || fork_kind == catch_vfork_temporary);
11983
11984   if (!arg)
11985     arg = "";
11986   arg = skip_spaces (arg);
11987
11988   /* The allowed syntax is:
11989      catch [v]fork
11990      catch [v]fork if <cond>
11991
11992      First, check if there's an if clause.  */
11993   cond_string = ep_parse_optional_if_clause (&arg);
11994
11995   if ((*arg != '\0') && !isspace (*arg))
11996     error (_("Junk at end of arguments."));
11997
11998   /* If this target supports it, create a fork or vfork catchpoint
11999      and enable reporting of such events.  */
12000   switch (fork_kind)
12001     {
12002     case catch_fork_temporary:
12003     case catch_fork_permanent:
12004       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
12005                                           &catch_fork_breakpoint_ops);
12006       break;
12007     case catch_vfork_temporary:
12008     case catch_vfork_permanent:
12009       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
12010                                           &catch_vfork_breakpoint_ops);
12011       break;
12012     default:
12013       error (_("unsupported or unknown fork kind; cannot catch it"));
12014       break;
12015     }
12016 }
12017
12018 static void
12019 catch_exec_command_1 (char *arg, int from_tty, 
12020                       struct cmd_list_element *command)
12021 {
12022   struct exec_catchpoint *c;
12023   struct gdbarch *gdbarch = get_current_arch ();
12024   int tempflag;
12025   char *cond_string = NULL;
12026
12027   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12028
12029   if (!arg)
12030     arg = "";
12031   arg = skip_spaces (arg);
12032
12033   /* The allowed syntax is:
12034      catch exec
12035      catch exec if <cond>
12036
12037      First, check if there's an if clause.  */
12038   cond_string = ep_parse_optional_if_clause (&arg);
12039
12040   if ((*arg != '\0') && !isspace (*arg))
12041     error (_("Junk at end of arguments."));
12042
12043   c = XNEW (struct exec_catchpoint);
12044   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
12045                    &catch_exec_breakpoint_ops);
12046   c->exec_pathname = NULL;
12047
12048   install_breakpoint (0, &c->base, 1);
12049 }
12050
12051 void
12052 init_ada_exception_breakpoint (struct breakpoint *b,
12053                                struct gdbarch *gdbarch,
12054                                struct symtab_and_line sal,
12055                                char *addr_string,
12056                                const struct breakpoint_ops *ops,
12057                                int tempflag,
12058                                int enabled,
12059                                int from_tty)
12060 {
12061   if (from_tty)
12062     {
12063       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
12064       if (!loc_gdbarch)
12065         loc_gdbarch = gdbarch;
12066
12067       describe_other_breakpoints (loc_gdbarch,
12068                                   sal.pspace, sal.pc, sal.section, -1);
12069       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
12070          version for exception catchpoints, because two catchpoints
12071          used for different exception names will use the same address.
12072          In this case, a "breakpoint ... also set at..." warning is
12073          unproductive.  Besides, the warning phrasing is also a bit
12074          inappropriate, we should use the word catchpoint, and tell
12075          the user what type of catchpoint it is.  The above is good
12076          enough for now, though.  */
12077     }
12078
12079   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
12080
12081   b->enable_state = enabled ? bp_enabled : bp_disabled;
12082   b->disposition = tempflag ? disp_del : disp_donttouch;
12083   b->addr_string = addr_string;
12084   b->language = language_ada;
12085 }
12086
12087 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
12088    filter list, or NULL if no filtering is required.  */
12089 static VEC(int) *
12090 catch_syscall_split_args (char *arg)
12091 {
12092   VEC(int) *result = NULL;
12093   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
12094
12095   while (*arg != '\0')
12096     {
12097       int i, syscall_number;
12098       char *endptr;
12099       char cur_name[128];
12100       struct syscall s;
12101
12102       /* Skip whitespace.  */
12103       arg = skip_spaces (arg);
12104
12105       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
12106         cur_name[i] = arg[i];
12107       cur_name[i] = '\0';
12108       arg += i;
12109
12110       /* Check if the user provided a syscall name or a number.  */
12111       syscall_number = (int) strtol (cur_name, &endptr, 0);
12112       if (*endptr == '\0')
12113         get_syscall_by_number (syscall_number, &s);
12114       else
12115         {
12116           /* We have a name.  Let's check if it's valid and convert it
12117              to a number.  */
12118           get_syscall_by_name (cur_name, &s);
12119
12120           if (s.number == UNKNOWN_SYSCALL)
12121             /* Here we have to issue an error instead of a warning,
12122                because GDB cannot do anything useful if there's no
12123                syscall number to be caught.  */
12124             error (_("Unknown syscall name '%s'."), cur_name);
12125         }
12126
12127       /* Ok, it's valid.  */
12128       VEC_safe_push (int, result, s.number);
12129     }
12130
12131   discard_cleanups (cleanup);
12132   return result;
12133 }
12134
12135 /* Implement the "catch syscall" command.  */
12136
12137 static void
12138 catch_syscall_command_1 (char *arg, int from_tty, 
12139                          struct cmd_list_element *command)
12140 {
12141   int tempflag;
12142   VEC(int) *filter;
12143   struct syscall s;
12144   struct gdbarch *gdbarch = get_current_arch ();
12145
12146   /* Checking if the feature if supported.  */
12147   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
12148     error (_("The feature 'catch syscall' is not supported on \
12149 this architecture yet."));
12150
12151   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
12152
12153   arg = skip_spaces (arg);
12154
12155   /* We need to do this first "dummy" translation in order
12156      to get the syscall XML file loaded or, most important,
12157      to display a warning to the user if there's no XML file
12158      for his/her architecture.  */
12159   get_syscall_by_number (0, &s);
12160
12161   /* The allowed syntax is:
12162      catch syscall
12163      catch syscall <name | number> [<name | number> ... <name | number>]
12164
12165      Let's check if there's a syscall name.  */
12166
12167   if (arg != NULL)
12168     filter = catch_syscall_split_args (arg);
12169   else
12170     filter = NULL;
12171
12172   create_syscall_event_catchpoint (tempflag, filter,
12173                                    &catch_syscall_breakpoint_ops);
12174 }
12175
12176 static void
12177 catch_command (char *arg, int from_tty)
12178 {
12179   error (_("Catch requires an event name."));
12180 }
12181 \f
12182
12183 static void
12184 tcatch_command (char *arg, int from_tty)
12185 {
12186   error (_("Catch requires an event name."));
12187 }
12188
12189 /* A qsort comparison function that sorts breakpoints in order.  */
12190
12191 static int
12192 compare_breakpoints (const void *a, const void *b)
12193 {
12194   const breakpoint_p *ba = a;
12195   uintptr_t ua = (uintptr_t) *ba;
12196   const breakpoint_p *bb = b;
12197   uintptr_t ub = (uintptr_t) *bb;
12198
12199   if ((*ba)->number < (*bb)->number)
12200     return -1;
12201   else if ((*ba)->number > (*bb)->number)
12202     return 1;
12203
12204   /* Now sort by address, in case we see, e..g, two breakpoints with
12205      the number 0.  */
12206   if (ua < ub)
12207     return -1;
12208   return ua > ub ? 1 : 0;
12209 }
12210
12211 /* Delete breakpoints by address or line.  */
12212
12213 static void
12214 clear_command (char *arg, int from_tty)
12215 {
12216   struct breakpoint *b, *prev;
12217   VEC(breakpoint_p) *found = 0;
12218   int ix;
12219   int default_match;
12220   struct symtabs_and_lines sals;
12221   struct symtab_and_line sal;
12222   int i;
12223   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
12224
12225   if (arg)
12226     {
12227       sals = decode_line_with_current_source (arg,
12228                                               (DECODE_LINE_FUNFIRSTLINE
12229                                                | DECODE_LINE_LIST_MODE));
12230       make_cleanup (xfree, sals.sals);
12231       default_match = 0;
12232     }
12233   else
12234     {
12235       sals.sals = (struct symtab_and_line *)
12236         xmalloc (sizeof (struct symtab_and_line));
12237       make_cleanup (xfree, sals.sals);
12238       init_sal (&sal);          /* Initialize to zeroes.  */
12239
12240       /* Set sal's line, symtab, pc, and pspace to the values
12241          corresponding to the last call to print_frame_info.  If the
12242          codepoint is not valid, this will set all the fields to 0.  */
12243       get_last_displayed_sal (&sal);
12244       if (sal.symtab == 0)
12245         error (_("No source file specified."));
12246
12247       sals.sals[0] = sal;
12248       sals.nelts = 1;
12249
12250       default_match = 1;
12251     }
12252
12253   /* We don't call resolve_sal_pc here.  That's not as bad as it
12254      seems, because all existing breakpoints typically have both
12255      file/line and pc set.  So, if clear is given file/line, we can
12256      match this to existing breakpoint without obtaining pc at all.
12257
12258      We only support clearing given the address explicitly 
12259      present in breakpoint table.  Say, we've set breakpoint 
12260      at file:line.  There were several PC values for that file:line,
12261      due to optimization, all in one block.
12262
12263      We've picked one PC value.  If "clear" is issued with another
12264      PC corresponding to the same file:line, the breakpoint won't
12265      be cleared.  We probably can still clear the breakpoint, but 
12266      since the other PC value is never presented to user, user
12267      can only find it by guessing, and it does not seem important
12268      to support that.  */
12269
12270   /* For each line spec given, delete bps which correspond to it.  Do
12271      it in two passes, solely to preserve the current behavior that
12272      from_tty is forced true if we delete more than one
12273      breakpoint.  */
12274
12275   found = NULL;
12276   make_cleanup (VEC_cleanup (breakpoint_p), &found);
12277   for (i = 0; i < sals.nelts; i++)
12278     {
12279       const char *sal_fullname;
12280
12281       /* If exact pc given, clear bpts at that pc.
12282          If line given (pc == 0), clear all bpts on specified line.
12283          If defaulting, clear all bpts on default line
12284          or at default pc.
12285
12286          defaulting    sal.pc != 0    tests to do
12287
12288          0              1             pc
12289          1              1             pc _and_ line
12290          0              0             line
12291          1              0             <can't happen> */
12292
12293       sal = sals.sals[i];
12294       sal_fullname = (sal.symtab == NULL
12295                       ? NULL : symtab_to_fullname (sal.symtab));
12296
12297       /* Find all matching breakpoints and add them to 'found'.  */
12298       ALL_BREAKPOINTS (b)
12299         {
12300           int match = 0;
12301           /* Are we going to delete b?  */
12302           if (b->type != bp_none && !is_watchpoint (b))
12303             {
12304               struct bp_location *loc = b->loc;
12305               for (; loc; loc = loc->next)
12306                 {
12307                   /* If the user specified file:line, don't allow a PC
12308                      match.  This matches historical gdb behavior.  */
12309                   int pc_match = (!sal.explicit_line
12310                                   && sal.pc
12311                                   && (loc->pspace == sal.pspace)
12312                                   && (loc->address == sal.pc)
12313                                   && (!section_is_overlay (loc->section)
12314                                       || loc->section == sal.section));
12315                   int line_match = 0;
12316
12317                   if ((default_match || sal.explicit_line)
12318                       && loc->symtab != NULL
12319                       && sal_fullname != NULL
12320                       && sal.pspace == loc->pspace
12321                       && loc->line_number == sal.line
12322                       && filename_cmp (symtab_to_fullname (loc->symtab),
12323                                        sal_fullname) == 0)
12324                     line_match = 1;
12325
12326                   if (pc_match || line_match)
12327                     {
12328                       match = 1;
12329                       break;
12330                     }
12331                 }
12332             }
12333
12334           if (match)
12335             VEC_safe_push(breakpoint_p, found, b);
12336         }
12337     }
12338
12339   /* Now go thru the 'found' chain and delete them.  */
12340   if (VEC_empty(breakpoint_p, found))
12341     {
12342       if (arg)
12343         error (_("No breakpoint at %s."), arg);
12344       else
12345         error (_("No breakpoint at this line."));
12346     }
12347
12348   /* Remove duplicates from the vec.  */
12349   qsort (VEC_address (breakpoint_p, found),
12350          VEC_length (breakpoint_p, found),
12351          sizeof (breakpoint_p),
12352          compare_breakpoints);
12353   prev = VEC_index (breakpoint_p, found, 0);
12354   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
12355     {
12356       if (b == prev)
12357         {
12358           VEC_ordered_remove (breakpoint_p, found, ix);
12359           --ix;
12360         }
12361     }
12362
12363   if (VEC_length(breakpoint_p, found) > 1)
12364     from_tty = 1;       /* Always report if deleted more than one.  */
12365   if (from_tty)
12366     {
12367       if (VEC_length(breakpoint_p, found) == 1)
12368         printf_unfiltered (_("Deleted breakpoint "));
12369       else
12370         printf_unfiltered (_("Deleted breakpoints "));
12371     }
12372
12373   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
12374     {
12375       if (from_tty)
12376         printf_unfiltered ("%d ", b->number);
12377       delete_breakpoint (b);
12378     }
12379   if (from_tty)
12380     putchar_unfiltered ('\n');
12381
12382   do_cleanups (cleanups);
12383 }
12384 \f
12385 /* Delete breakpoint in BS if they are `delete' breakpoints and
12386    all breakpoints that are marked for deletion, whether hit or not.
12387    This is called after any breakpoint is hit, or after errors.  */
12388
12389 void
12390 breakpoint_auto_delete (bpstat bs)
12391 {
12392   struct breakpoint *b, *b_tmp;
12393
12394   for (; bs; bs = bs->next)
12395     if (bs->breakpoint_at
12396         && bs->breakpoint_at->disposition == disp_del
12397         && bs->stop)
12398       delete_breakpoint (bs->breakpoint_at);
12399
12400   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12401   {
12402     if (b->disposition == disp_del_at_next_stop)
12403       delete_breakpoint (b);
12404   }
12405 }
12406
12407 /* A comparison function for bp_location AP and BP being interfaced to
12408    qsort.  Sort elements primarily by their ADDRESS (no matter what
12409    does breakpoint_address_is_meaningful say for its OWNER),
12410    secondarily by ordering first bp_permanent OWNERed elements and
12411    terciarily just ensuring the array is sorted stable way despite
12412    qsort being an unstable algorithm.  */
12413
12414 static int
12415 bp_location_compare (const void *ap, const void *bp)
12416 {
12417   struct bp_location *a = *(void **) ap;
12418   struct bp_location *b = *(void **) bp;
12419   /* A and B come from existing breakpoints having non-NULL OWNER.  */
12420   int a_perm = a->owner->enable_state == bp_permanent;
12421   int b_perm = b->owner->enable_state == bp_permanent;
12422
12423   if (a->address != b->address)
12424     return (a->address > b->address) - (a->address < b->address);
12425
12426   /* Sort locations at the same address by their pspace number, keeping
12427      locations of the same inferior (in a multi-inferior environment)
12428      grouped.  */
12429
12430   if (a->pspace->num != b->pspace->num)
12431     return ((a->pspace->num > b->pspace->num)
12432             - (a->pspace->num < b->pspace->num));
12433
12434   /* Sort permanent breakpoints first.  */
12435   if (a_perm != b_perm)
12436     return (a_perm < b_perm) - (a_perm > b_perm);
12437
12438   /* Make the internal GDB representation stable across GDB runs
12439      where A and B memory inside GDB can differ.  Breakpoint locations of
12440      the same type at the same address can be sorted in arbitrary order.  */
12441
12442   if (a->owner->number != b->owner->number)
12443     return ((a->owner->number > b->owner->number)
12444             - (a->owner->number < b->owner->number));
12445
12446   return (a > b) - (a < b);
12447 }
12448
12449 /* Set bp_location_placed_address_before_address_max and
12450    bp_location_shadow_len_after_address_max according to the current
12451    content of the bp_location array.  */
12452
12453 static void
12454 bp_location_target_extensions_update (void)
12455 {
12456   struct bp_location *bl, **blp_tmp;
12457
12458   bp_location_placed_address_before_address_max = 0;
12459   bp_location_shadow_len_after_address_max = 0;
12460
12461   ALL_BP_LOCATIONS (bl, blp_tmp)
12462     {
12463       CORE_ADDR start, end, addr;
12464
12465       if (!bp_location_has_shadow (bl))
12466         continue;
12467
12468       start = bl->target_info.placed_address;
12469       end = start + bl->target_info.shadow_len;
12470
12471       gdb_assert (bl->address >= start);
12472       addr = bl->address - start;
12473       if (addr > bp_location_placed_address_before_address_max)
12474         bp_location_placed_address_before_address_max = addr;
12475
12476       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
12477
12478       gdb_assert (bl->address < end);
12479       addr = end - bl->address;
12480       if (addr > bp_location_shadow_len_after_address_max)
12481         bp_location_shadow_len_after_address_max = addr;
12482     }
12483 }
12484
12485 /* Download tracepoint locations if they haven't been.  */
12486
12487 static void
12488 download_tracepoint_locations (void)
12489 {
12490   struct breakpoint *b;
12491   struct cleanup *old_chain;
12492
12493   if (!target_can_download_tracepoint ())
12494     return;
12495
12496   old_chain = save_current_space_and_thread ();
12497
12498   ALL_TRACEPOINTS (b)
12499     {
12500       struct bp_location *bl;
12501       struct tracepoint *t;
12502       int bp_location_downloaded = 0;
12503
12504       if ((b->type == bp_fast_tracepoint
12505            ? !may_insert_fast_tracepoints
12506            : !may_insert_tracepoints))
12507         continue;
12508
12509       for (bl = b->loc; bl; bl = bl->next)
12510         {
12511           /* In tracepoint, locations are _never_ duplicated, so
12512              should_be_inserted is equivalent to
12513              unduplicated_should_be_inserted.  */
12514           if (!should_be_inserted (bl) || bl->inserted)
12515             continue;
12516
12517           switch_to_program_space_and_thread (bl->pspace);
12518
12519           target_download_tracepoint (bl);
12520
12521           bl->inserted = 1;
12522           bp_location_downloaded = 1;
12523         }
12524       t = (struct tracepoint *) b;
12525       t->number_on_target = b->number;
12526       if (bp_location_downloaded)
12527         observer_notify_breakpoint_modified (b);
12528     }
12529
12530   do_cleanups (old_chain);
12531 }
12532
12533 /* Swap the insertion/duplication state between two locations.  */
12534
12535 static void
12536 swap_insertion (struct bp_location *left, struct bp_location *right)
12537 {
12538   const int left_inserted = left->inserted;
12539   const int left_duplicate = left->duplicate;
12540   const int left_needs_update = left->needs_update;
12541   const struct bp_target_info left_target_info = left->target_info;
12542
12543   /* Locations of tracepoints can never be duplicated.  */
12544   if (is_tracepoint (left->owner))
12545     gdb_assert (!left->duplicate);
12546   if (is_tracepoint (right->owner))
12547     gdb_assert (!right->duplicate);
12548
12549   left->inserted = right->inserted;
12550   left->duplicate = right->duplicate;
12551   left->needs_update = right->needs_update;
12552   left->target_info = right->target_info;
12553   right->inserted = left_inserted;
12554   right->duplicate = left_duplicate;
12555   right->needs_update = left_needs_update;
12556   right->target_info = left_target_info;
12557 }
12558
12559 /* Force the re-insertion of the locations at ADDRESS.  This is called
12560    once a new/deleted/modified duplicate location is found and we are evaluating
12561    conditions on the target's side.  Such conditions need to be updated on
12562    the target.  */
12563
12564 static void
12565 force_breakpoint_reinsertion (struct bp_location *bl)
12566 {
12567   struct bp_location **locp = NULL, **loc2p;
12568   struct bp_location *loc;
12569   CORE_ADDR address = 0;
12570   int pspace_num;
12571
12572   address = bl->address;
12573   pspace_num = bl->pspace->num;
12574
12575   /* This is only meaningful if the target is
12576      evaluating conditions and if the user has
12577      opted for condition evaluation on the target's
12578      side.  */
12579   if (gdb_evaluates_breakpoint_condition_p ()
12580       || !target_supports_evaluation_of_breakpoint_conditions ())
12581     return;
12582
12583   /* Flag all breakpoint locations with this address and
12584      the same program space as the location
12585      as "its condition has changed".  We need to
12586      update the conditions on the target's side.  */
12587   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
12588     {
12589       loc = *loc2p;
12590
12591       if (!is_breakpoint (loc->owner)
12592           || pspace_num != loc->pspace->num)
12593         continue;
12594
12595       /* Flag the location appropriately.  We use a different state to
12596          let everyone know that we already updated the set of locations
12597          with addr bl->address and program space bl->pspace.  This is so
12598          we don't have to keep calling these functions just to mark locations
12599          that have already been marked.  */
12600       loc->condition_changed = condition_updated;
12601
12602       /* Free the agent expression bytecode as well.  We will compute
12603          it later on.  */
12604       if (loc->cond_bytecode)
12605         {
12606           free_agent_expr (loc->cond_bytecode);
12607           loc->cond_bytecode = NULL;
12608         }
12609     }
12610 }
12611 /* Called whether new breakpoints are created, or existing breakpoints
12612    deleted, to update the global location list and recompute which
12613    locations are duplicate of which.
12614
12615    The INSERT_MODE flag determines whether locations may not, may, or
12616    shall be inserted now.  See 'enum ugll_insert_mode' for more
12617    info.  */
12618
12619 static void
12620 update_global_location_list (enum ugll_insert_mode insert_mode)
12621 {
12622   struct breakpoint *b;
12623   struct bp_location **locp, *loc;
12624   struct cleanup *cleanups;
12625   /* Last breakpoint location address that was marked for update.  */
12626   CORE_ADDR last_addr = 0;
12627   /* Last breakpoint location program space that was marked for update.  */
12628   int last_pspace_num = -1;
12629
12630   /* Used in the duplicates detection below.  When iterating over all
12631      bp_locations, points to the first bp_location of a given address.
12632      Breakpoints and watchpoints of different types are never
12633      duplicates of each other.  Keep one pointer for each type of
12634      breakpoint/watchpoint, so we only need to loop over all locations
12635      once.  */
12636   struct bp_location *bp_loc_first;  /* breakpoint */
12637   struct bp_location *wp_loc_first;  /* hardware watchpoint */
12638   struct bp_location *awp_loc_first; /* access watchpoint */
12639   struct bp_location *rwp_loc_first; /* read watchpoint */
12640
12641   /* Saved former bp_location array which we compare against the newly
12642      built bp_location from the current state of ALL_BREAKPOINTS.  */
12643   struct bp_location **old_location, **old_locp;
12644   unsigned old_location_count;
12645
12646   old_location = bp_location;
12647   old_location_count = bp_location_count;
12648   bp_location = NULL;
12649   bp_location_count = 0;
12650   cleanups = make_cleanup (xfree, old_location);
12651
12652   ALL_BREAKPOINTS (b)
12653     for (loc = b->loc; loc; loc = loc->next)
12654       bp_location_count++;
12655
12656   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
12657   locp = bp_location;
12658   ALL_BREAKPOINTS (b)
12659     for (loc = b->loc; loc; loc = loc->next)
12660       *locp++ = loc;
12661   qsort (bp_location, bp_location_count, sizeof (*bp_location),
12662          bp_location_compare);
12663
12664   bp_location_target_extensions_update ();
12665
12666   /* Identify bp_location instances that are no longer present in the
12667      new list, and therefore should be freed.  Note that it's not
12668      necessary that those locations should be removed from inferior --
12669      if there's another location at the same address (previously
12670      marked as duplicate), we don't need to remove/insert the
12671      location.
12672      
12673      LOCP is kept in sync with OLD_LOCP, each pointing to the current
12674      and former bp_location array state respectively.  */
12675
12676   locp = bp_location;
12677   for (old_locp = old_location; old_locp < old_location + old_location_count;
12678        old_locp++)
12679     {
12680       struct bp_location *old_loc = *old_locp;
12681       struct bp_location **loc2p;
12682
12683       /* Tells if 'old_loc' is found among the new locations.  If
12684          not, we have to free it.  */
12685       int found_object = 0;
12686       /* Tells if the location should remain inserted in the target.  */
12687       int keep_in_target = 0;
12688       int removed = 0;
12689
12690       /* Skip LOCP entries which will definitely never be needed.
12691          Stop either at or being the one matching OLD_LOC.  */
12692       while (locp < bp_location + bp_location_count
12693              && (*locp)->address < old_loc->address)
12694         locp++;
12695
12696       for (loc2p = locp;
12697            (loc2p < bp_location + bp_location_count
12698             && (*loc2p)->address == old_loc->address);
12699            loc2p++)
12700         {
12701           /* Check if this is a new/duplicated location or a duplicated
12702              location that had its condition modified.  If so, we want to send
12703              its condition to the target if evaluation of conditions is taking
12704              place there.  */
12705           if ((*loc2p)->condition_changed == condition_modified
12706               && (last_addr != old_loc->address
12707                   || last_pspace_num != old_loc->pspace->num))
12708             {
12709               force_breakpoint_reinsertion (*loc2p);
12710               last_pspace_num = old_loc->pspace->num;
12711             }
12712
12713           if (*loc2p == old_loc)
12714             found_object = 1;
12715         }
12716
12717       /* We have already handled this address, update it so that we don't
12718          have to go through updates again.  */
12719       last_addr = old_loc->address;
12720
12721       /* Target-side condition evaluation: Handle deleted locations.  */
12722       if (!found_object)
12723         force_breakpoint_reinsertion (old_loc);
12724
12725       /* If this location is no longer present, and inserted, look if
12726          there's maybe a new location at the same address.  If so,
12727          mark that one inserted, and don't remove this one.  This is
12728          needed so that we don't have a time window where a breakpoint
12729          at certain location is not inserted.  */
12730
12731       if (old_loc->inserted)
12732         {
12733           /* If the location is inserted now, we might have to remove
12734              it.  */
12735
12736           if (found_object && should_be_inserted (old_loc))
12737             {
12738               /* The location is still present in the location list,
12739                  and still should be inserted.  Don't do anything.  */
12740               keep_in_target = 1;
12741             }
12742           else
12743             {
12744               /* This location still exists, but it won't be kept in the
12745                  target since it may have been disabled.  We proceed to
12746                  remove its target-side condition.  */
12747
12748               /* The location is either no longer present, or got
12749                  disabled.  See if there's another location at the
12750                  same address, in which case we don't need to remove
12751                  this one from the target.  */
12752
12753               /* OLD_LOC comes from existing struct breakpoint.  */
12754               if (breakpoint_address_is_meaningful (old_loc->owner))
12755                 {
12756                   for (loc2p = locp;
12757                        (loc2p < bp_location + bp_location_count
12758                         && (*loc2p)->address == old_loc->address);
12759                        loc2p++)
12760                     {
12761                       struct bp_location *loc2 = *loc2p;
12762
12763                       if (breakpoint_locations_match (loc2, old_loc))
12764                         {
12765                           /* Read watchpoint locations are switched to
12766                              access watchpoints, if the former are not
12767                              supported, but the latter are.  */
12768                           if (is_hardware_watchpoint (old_loc->owner))
12769                             {
12770                               gdb_assert (is_hardware_watchpoint (loc2->owner));
12771                               loc2->watchpoint_type = old_loc->watchpoint_type;
12772                             }
12773
12774                           /* loc2 is a duplicated location. We need to check
12775                              if it should be inserted in case it will be
12776                              unduplicated.  */
12777                           if (loc2 != old_loc
12778                               && unduplicated_should_be_inserted (loc2))
12779                             {
12780                               swap_insertion (old_loc, loc2);
12781                               keep_in_target = 1;
12782                               break;
12783                             }
12784                         }
12785                     }
12786                 }
12787             }
12788
12789           if (!keep_in_target)
12790             {
12791               if (remove_breakpoint (old_loc, mark_uninserted))
12792                 {
12793                   /* This is just about all we can do.  We could keep
12794                      this location on the global list, and try to
12795                      remove it next time, but there's no particular
12796                      reason why we will succeed next time.
12797                      
12798                      Note that at this point, old_loc->owner is still
12799                      valid, as delete_breakpoint frees the breakpoint
12800                      only after calling us.  */
12801                   printf_filtered (_("warning: Error removing "
12802                                      "breakpoint %d\n"), 
12803                                    old_loc->owner->number);
12804                 }
12805               removed = 1;
12806             }
12807         }
12808
12809       if (!found_object)
12810         {
12811           if (removed && non_stop
12812               && breakpoint_address_is_meaningful (old_loc->owner)
12813               && !is_hardware_watchpoint (old_loc->owner))
12814             {
12815               /* This location was removed from the target.  In
12816                  non-stop mode, a race condition is possible where
12817                  we've removed a breakpoint, but stop events for that
12818                  breakpoint are already queued and will arrive later.
12819                  We apply an heuristic to be able to distinguish such
12820                  SIGTRAPs from other random SIGTRAPs: we keep this
12821                  breakpoint location for a bit, and will retire it
12822                  after we see some number of events.  The theory here
12823                  is that reporting of events should, "on the average",
12824                  be fair, so after a while we'll see events from all
12825                  threads that have anything of interest, and no longer
12826                  need to keep this breakpoint location around.  We
12827                  don't hold locations forever so to reduce chances of
12828                  mistaking a non-breakpoint SIGTRAP for a breakpoint
12829                  SIGTRAP.
12830
12831                  The heuristic failing can be disastrous on
12832                  decr_pc_after_break targets.
12833
12834                  On decr_pc_after_break targets, like e.g., x86-linux,
12835                  if we fail to recognize a late breakpoint SIGTRAP,
12836                  because events_till_retirement has reached 0 too
12837                  soon, we'll fail to do the PC adjustment, and report
12838                  a random SIGTRAP to the user.  When the user resumes
12839                  the inferior, it will most likely immediately crash
12840                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12841                  corrupted, because of being resumed e.g., in the
12842                  middle of a multi-byte instruction, or skipped a
12843                  one-byte instruction.  This was actually seen happen
12844                  on native x86-linux, and should be less rare on
12845                  targets that do not support new thread events, like
12846                  remote, due to the heuristic depending on
12847                  thread_count.
12848
12849                  Mistaking a random SIGTRAP for a breakpoint trap
12850                  causes similar symptoms (PC adjustment applied when
12851                  it shouldn't), but then again, playing with SIGTRAPs
12852                  behind the debugger's back is asking for trouble.
12853
12854                  Since hardware watchpoint traps are always
12855                  distinguishable from other traps, so we don't need to
12856                  apply keep hardware watchpoint moribund locations
12857                  around.  We simply always ignore hardware watchpoint
12858                  traps we can no longer explain.  */
12859
12860               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12861               old_loc->owner = NULL;
12862
12863               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12864             }
12865           else
12866             {
12867               old_loc->owner = NULL;
12868               decref_bp_location (&old_loc);
12869             }
12870         }
12871     }
12872
12873   /* Rescan breakpoints at the same address and section, marking the
12874      first one as "first" and any others as "duplicates".  This is so
12875      that the bpt instruction is only inserted once.  If we have a
12876      permanent breakpoint at the same place as BPT, make that one the
12877      official one, and the rest as duplicates.  Permanent breakpoints
12878      are sorted first for the same address.
12879
12880      Do the same for hardware watchpoints, but also considering the
12881      watchpoint's type (regular/access/read) and length.  */
12882
12883   bp_loc_first = NULL;
12884   wp_loc_first = NULL;
12885   awp_loc_first = NULL;
12886   rwp_loc_first = NULL;
12887   ALL_BP_LOCATIONS (loc, locp)
12888     {
12889       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12890          non-NULL.  */
12891       struct bp_location **loc_first_p;
12892       b = loc->owner;
12893
12894       if (!unduplicated_should_be_inserted (loc)
12895           || !breakpoint_address_is_meaningful (b)
12896           /* Don't detect duplicate for tracepoint locations because they are
12897            never duplicated.  See the comments in field `duplicate' of
12898            `struct bp_location'.  */
12899           || is_tracepoint (b))
12900         {
12901           /* Clear the condition modification flag.  */
12902           loc->condition_changed = condition_unchanged;
12903           continue;
12904         }
12905
12906       /* Permanent breakpoint should always be inserted.  */
12907       if (b->enable_state == bp_permanent && ! loc->inserted)
12908         internal_error (__FILE__, __LINE__,
12909                         _("allegedly permanent breakpoint is not "
12910                         "actually inserted"));
12911
12912       if (b->type == bp_hardware_watchpoint)
12913         loc_first_p = &wp_loc_first;
12914       else if (b->type == bp_read_watchpoint)
12915         loc_first_p = &rwp_loc_first;
12916       else if (b->type == bp_access_watchpoint)
12917         loc_first_p = &awp_loc_first;
12918       else
12919         loc_first_p = &bp_loc_first;
12920
12921       if (*loc_first_p == NULL
12922           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12923           || !breakpoint_locations_match (loc, *loc_first_p))
12924         {
12925           *loc_first_p = loc;
12926           loc->duplicate = 0;
12927
12928           if (is_breakpoint (loc->owner) && loc->condition_changed)
12929             {
12930               loc->needs_update = 1;
12931               /* Clear the condition modification flag.  */
12932               loc->condition_changed = condition_unchanged;
12933             }
12934           continue;
12935         }
12936
12937
12938       /* This and the above ensure the invariant that the first location
12939          is not duplicated, and is the inserted one.
12940          All following are marked as duplicated, and are not inserted.  */
12941       if (loc->inserted)
12942         swap_insertion (loc, *loc_first_p);
12943       loc->duplicate = 1;
12944
12945       /* Clear the condition modification flag.  */
12946       loc->condition_changed = condition_unchanged;
12947
12948       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12949           && b->enable_state != bp_permanent)
12950         internal_error (__FILE__, __LINE__,
12951                         _("another breakpoint was inserted on top of "
12952                         "a permanent breakpoint"));
12953     }
12954
12955   if (insert_mode == UGLL_INSERT || breakpoints_should_be_inserted_now ())
12956     {
12957       if (insert_mode != UGLL_DONT_INSERT)
12958         insert_breakpoint_locations ();
12959       else
12960         {
12961           /* Even though the caller told us to not insert new
12962              locations, we may still need to update conditions on the
12963              target's side of breakpoints that were already inserted
12964              if the target is evaluating breakpoint conditions.  We
12965              only update conditions for locations that are marked
12966              "needs_update".  */
12967           update_inserted_breakpoint_locations ();
12968         }
12969     }
12970
12971   if (insert_mode != UGLL_DONT_INSERT)
12972     download_tracepoint_locations ();
12973
12974   do_cleanups (cleanups);
12975 }
12976
12977 void
12978 breakpoint_retire_moribund (void)
12979 {
12980   struct bp_location *loc;
12981   int ix;
12982
12983   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12984     if (--(loc->events_till_retirement) == 0)
12985       {
12986         decref_bp_location (&loc);
12987         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12988         --ix;
12989       }
12990 }
12991
12992 static void
12993 update_global_location_list_nothrow (enum ugll_insert_mode insert_mode)
12994 {
12995   volatile struct gdb_exception e;
12996
12997   TRY_CATCH (e, RETURN_MASK_ERROR)
12998     update_global_location_list (insert_mode);
12999 }
13000
13001 /* Clear BKP from a BPS.  */
13002
13003 static void
13004 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
13005 {
13006   bpstat bs;
13007
13008   for (bs = bps; bs; bs = bs->next)
13009     if (bs->breakpoint_at == bpt)
13010       {
13011         bs->breakpoint_at = NULL;
13012         bs->old_val = NULL;
13013         /* bs->commands will be freed later.  */
13014       }
13015 }
13016
13017 /* Callback for iterate_over_threads.  */
13018 static int
13019 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
13020 {
13021   struct breakpoint *bpt = data;
13022
13023   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
13024   return 0;
13025 }
13026
13027 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
13028    callbacks.  */
13029
13030 static void
13031 say_where (struct breakpoint *b)
13032 {
13033   struct value_print_options opts;
13034
13035   get_user_print_options (&opts);
13036
13037   /* i18n: cagney/2005-02-11: Below needs to be merged into a
13038      single string.  */
13039   if (b->loc == NULL)
13040     {
13041       printf_filtered (_(" (%s) pending."), b->addr_string);
13042     }
13043   else
13044     {
13045       if (opts.addressprint || b->loc->symtab == NULL)
13046         {
13047           printf_filtered (" at ");
13048           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
13049                           gdb_stdout);
13050         }
13051       if (b->loc->symtab != NULL)
13052         {
13053           /* If there is a single location, we can print the location
13054              more nicely.  */
13055           if (b->loc->next == NULL)
13056             printf_filtered (": file %s, line %d.",
13057                              symtab_to_filename_for_display (b->loc->symtab),
13058                              b->loc->line_number);
13059           else
13060             /* This is not ideal, but each location may have a
13061                different file name, and this at least reflects the
13062                real situation somewhat.  */
13063             printf_filtered (": %s.", b->addr_string);
13064         }
13065
13066       if (b->loc->next)
13067         {
13068           struct bp_location *loc = b->loc;
13069           int n = 0;
13070           for (; loc; loc = loc->next)
13071             ++n;
13072           printf_filtered (" (%d locations)", n);
13073         }
13074     }
13075 }
13076
13077 /* Default bp_location_ops methods.  */
13078
13079 static void
13080 bp_location_dtor (struct bp_location *self)
13081 {
13082   xfree (self->cond);
13083   if (self->cond_bytecode)
13084     free_agent_expr (self->cond_bytecode);
13085   xfree (self->function_name);
13086
13087   VEC_free (agent_expr_p, self->target_info.conditions);
13088   VEC_free (agent_expr_p, self->target_info.tcommands);
13089 }
13090
13091 static const struct bp_location_ops bp_location_ops =
13092 {
13093   bp_location_dtor
13094 };
13095
13096 /* Default breakpoint_ops methods all breakpoint_ops ultimately
13097    inherit from.  */
13098
13099 static void
13100 base_breakpoint_dtor (struct breakpoint *self)
13101 {
13102   decref_counted_command_line (&self->commands);
13103   xfree (self->cond_string);
13104   xfree (self->extra_string);
13105   xfree (self->addr_string);
13106   xfree (self->filter);
13107   xfree (self->addr_string_range_end);
13108 }
13109
13110 static struct bp_location *
13111 base_breakpoint_allocate_location (struct breakpoint *self)
13112 {
13113   struct bp_location *loc;
13114
13115   loc = XNEW (struct bp_location);
13116   init_bp_location (loc, &bp_location_ops, self);
13117   return loc;
13118 }
13119
13120 static void
13121 base_breakpoint_re_set (struct breakpoint *b)
13122 {
13123   /* Nothing to re-set. */
13124 }
13125
13126 #define internal_error_pure_virtual_called() \
13127   gdb_assert_not_reached ("pure virtual function called")
13128
13129 static int
13130 base_breakpoint_insert_location (struct bp_location *bl)
13131 {
13132   internal_error_pure_virtual_called ();
13133 }
13134
13135 static int
13136 base_breakpoint_remove_location (struct bp_location *bl)
13137 {
13138   internal_error_pure_virtual_called ();
13139 }
13140
13141 static int
13142 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
13143                                 struct address_space *aspace,
13144                                 CORE_ADDR bp_addr,
13145                                 const struct target_waitstatus *ws)
13146 {
13147   internal_error_pure_virtual_called ();
13148 }
13149
13150 static void
13151 base_breakpoint_check_status (bpstat bs)
13152 {
13153   /* Always stop.   */
13154 }
13155
13156 /* A "works_in_software_mode" breakpoint_ops method that just internal
13157    errors.  */
13158
13159 static int
13160 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
13161 {
13162   internal_error_pure_virtual_called ();
13163 }
13164
13165 /* A "resources_needed" breakpoint_ops method that just internal
13166    errors.  */
13167
13168 static int
13169 base_breakpoint_resources_needed (const struct bp_location *bl)
13170 {
13171   internal_error_pure_virtual_called ();
13172 }
13173
13174 static enum print_stop_action
13175 base_breakpoint_print_it (bpstat bs)
13176 {
13177   internal_error_pure_virtual_called ();
13178 }
13179
13180 static void
13181 base_breakpoint_print_one_detail (const struct breakpoint *self,
13182                                   struct ui_out *uiout)
13183 {
13184   /* nothing */
13185 }
13186
13187 static void
13188 base_breakpoint_print_mention (struct breakpoint *b)
13189 {
13190   internal_error_pure_virtual_called ();
13191 }
13192
13193 static void
13194 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
13195 {
13196   internal_error_pure_virtual_called ();
13197 }
13198
13199 static void
13200 base_breakpoint_create_sals_from_address (char **arg,
13201                                           struct linespec_result *canonical,
13202                                           enum bptype type_wanted,
13203                                           char *addr_start,
13204                                           char **copy_arg)
13205 {
13206   internal_error_pure_virtual_called ();
13207 }
13208
13209 static void
13210 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13211                                         struct linespec_result *c,
13212                                         char *cond_string,
13213                                         char *extra_string,
13214                                         enum bptype type_wanted,
13215                                         enum bpdisp disposition,
13216                                         int thread,
13217                                         int task, int ignore_count,
13218                                         const struct breakpoint_ops *o,
13219                                         int from_tty, int enabled,
13220                                         int internal, unsigned flags)
13221 {
13222   internal_error_pure_virtual_called ();
13223 }
13224
13225 static void
13226 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
13227                                  struct symtabs_and_lines *sals)
13228 {
13229   internal_error_pure_virtual_called ();
13230 }
13231
13232 /* The default 'explains_signal' method.  */
13233
13234 static int
13235 base_breakpoint_explains_signal (struct breakpoint *b, enum gdb_signal sig)
13236 {
13237   return 1;
13238 }
13239
13240 /* The default "after_condition_true" method.  */
13241
13242 static void
13243 base_breakpoint_after_condition_true (struct bpstats *bs)
13244 {
13245   /* Nothing to do.   */
13246 }
13247
13248 struct breakpoint_ops base_breakpoint_ops =
13249 {
13250   base_breakpoint_dtor,
13251   base_breakpoint_allocate_location,
13252   base_breakpoint_re_set,
13253   base_breakpoint_insert_location,
13254   base_breakpoint_remove_location,
13255   base_breakpoint_breakpoint_hit,
13256   base_breakpoint_check_status,
13257   base_breakpoint_resources_needed,
13258   base_breakpoint_works_in_software_mode,
13259   base_breakpoint_print_it,
13260   NULL,
13261   base_breakpoint_print_one_detail,
13262   base_breakpoint_print_mention,
13263   base_breakpoint_print_recreate,
13264   base_breakpoint_create_sals_from_address,
13265   base_breakpoint_create_breakpoints_sal,
13266   base_breakpoint_decode_linespec,
13267   base_breakpoint_explains_signal,
13268   base_breakpoint_after_condition_true,
13269 };
13270
13271 /* Default breakpoint_ops methods.  */
13272
13273 static void
13274 bkpt_re_set (struct breakpoint *b)
13275 {
13276   /* FIXME: is this still reachable?  */
13277   if (b->addr_string == NULL)
13278     {
13279       /* Anything without a string can't be re-set.  */
13280       delete_breakpoint (b);
13281       return;
13282     }
13283
13284   breakpoint_re_set_default (b);
13285 }
13286
13287 /* Copy SRC's shadow buffer and whatever else we'd set if we actually
13288    inserted DEST, so we can remove it later, in case SRC is removed
13289    first.  */
13290
13291 static void
13292 bp_target_info_copy_insertion_state (struct bp_target_info *dest,
13293                                      const struct bp_target_info *src)
13294 {
13295   dest->shadow_len = src->shadow_len;
13296   memcpy (dest->shadow_contents, src->shadow_contents, src->shadow_len);
13297   dest->placed_size = src->placed_size;
13298 }
13299
13300 static int
13301 bkpt_insert_location (struct bp_location *bl)
13302 {
13303   if (bl->loc_type == bp_loc_hardware_breakpoint)
13304     return target_insert_hw_breakpoint (bl->gdbarch,
13305                                         &bl->target_info);
13306   else
13307     {
13308       struct bp_target_info *bp_tgt = &bl->target_info;
13309       int ret;
13310       int sss_slot;
13311
13312       /* There is no need to insert a breakpoint if an unconditional
13313          raw/sss breakpoint is already inserted at that location.  */
13314       sss_slot = find_single_step_breakpoint (bp_tgt->placed_address_space,
13315                                               bp_tgt->placed_address);
13316       if (sss_slot >= 0)
13317         {
13318           struct bp_target_info *sss_bp_tgt = single_step_breakpoints[sss_slot];
13319
13320           bp_target_info_copy_insertion_state (bp_tgt, sss_bp_tgt);
13321           return 0;
13322         }
13323
13324       return target_insert_breakpoint (bl->gdbarch, bp_tgt);
13325     }
13326 }
13327
13328 static int
13329 bkpt_remove_location (struct bp_location *bl)
13330 {
13331   if (bl->loc_type == bp_loc_hardware_breakpoint)
13332     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
13333   else
13334     {
13335       struct bp_target_info *bp_tgt = &bl->target_info;
13336       struct address_space *aspace = bp_tgt->placed_address_space;
13337       CORE_ADDR address = bp_tgt->placed_address;
13338
13339       /* Only remove the breakpoint if there is no raw/sss breakpoint
13340          still inserted at this location.  Otherwise, we would be
13341          effectively disabling the raw/sss breakpoint.  */
13342       if (single_step_breakpoint_inserted_here_p (aspace, address))
13343         return 0;
13344
13345       return target_remove_breakpoint (bl->gdbarch, bp_tgt);
13346     }
13347 }
13348
13349 static int
13350 bkpt_breakpoint_hit (const struct bp_location *bl,
13351                      struct address_space *aspace, CORE_ADDR bp_addr,
13352                      const struct target_waitstatus *ws)
13353 {
13354   if (ws->kind != TARGET_WAITKIND_STOPPED
13355       || ws->value.sig != GDB_SIGNAL_TRAP)
13356     return 0;
13357
13358   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
13359                                  aspace, bp_addr))
13360     return 0;
13361
13362   if (overlay_debugging         /* unmapped overlay section */
13363       && section_is_overlay (bl->section)
13364       && !section_is_mapped (bl->section))
13365     return 0;
13366
13367   return 1;
13368 }
13369
13370 static int
13371 dprintf_breakpoint_hit (const struct bp_location *bl,
13372                         struct address_space *aspace, CORE_ADDR bp_addr,
13373                         const struct target_waitstatus *ws)
13374 {
13375   if (dprintf_style == dprintf_style_agent
13376       && target_can_run_breakpoint_commands ())
13377     {
13378       /* An agent-style dprintf never causes a stop.  If we see a trap
13379          for this address it must be for a breakpoint that happens to
13380          be set at the same address.  */
13381       return 0;
13382     }
13383
13384   return bkpt_breakpoint_hit (bl, aspace, bp_addr, ws);
13385 }
13386
13387 static int
13388 bkpt_resources_needed (const struct bp_location *bl)
13389 {
13390   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
13391
13392   return 1;
13393 }
13394
13395 static enum print_stop_action
13396 bkpt_print_it (bpstat bs)
13397 {
13398   struct breakpoint *b;
13399   const struct bp_location *bl;
13400   int bp_temp;
13401   struct ui_out *uiout = current_uiout;
13402
13403   gdb_assert (bs->bp_location_at != NULL);
13404
13405   bl = bs->bp_location_at;
13406   b = bs->breakpoint_at;
13407
13408   bp_temp = b->disposition == disp_del;
13409   if (bl->address != bl->requested_address)
13410     breakpoint_adjustment_warning (bl->requested_address,
13411                                    bl->address,
13412                                    b->number, 1);
13413   annotate_breakpoint (b->number);
13414   if (bp_temp)
13415     ui_out_text (uiout, "\nTemporary breakpoint ");
13416   else
13417     ui_out_text (uiout, "\nBreakpoint ");
13418   if (ui_out_is_mi_like_p (uiout))
13419     {
13420       ui_out_field_string (uiout, "reason",
13421                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
13422       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
13423     }
13424   ui_out_field_int (uiout, "bkptno", b->number);
13425   ui_out_text (uiout, ", ");
13426
13427   return PRINT_SRC_AND_LOC;
13428 }
13429
13430 static void
13431 bkpt_print_mention (struct breakpoint *b)
13432 {
13433   if (ui_out_is_mi_like_p (current_uiout))
13434     return;
13435
13436   switch (b->type)
13437     {
13438     case bp_breakpoint:
13439     case bp_gnu_ifunc_resolver:
13440       if (b->disposition == disp_del)
13441         printf_filtered (_("Temporary breakpoint"));
13442       else
13443         printf_filtered (_("Breakpoint"));
13444       printf_filtered (_(" %d"), b->number);
13445       if (b->type == bp_gnu_ifunc_resolver)
13446         printf_filtered (_(" at gnu-indirect-function resolver"));
13447       break;
13448     case bp_hardware_breakpoint:
13449       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
13450       break;
13451     case bp_dprintf:
13452       printf_filtered (_("Dprintf %d"), b->number);
13453       break;
13454     }
13455
13456   say_where (b);
13457 }
13458
13459 static void
13460 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13461 {
13462   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
13463     fprintf_unfiltered (fp, "tbreak");
13464   else if (tp->type == bp_breakpoint)
13465     fprintf_unfiltered (fp, "break");
13466   else if (tp->type == bp_hardware_breakpoint
13467            && tp->disposition == disp_del)
13468     fprintf_unfiltered (fp, "thbreak");
13469   else if (tp->type == bp_hardware_breakpoint)
13470     fprintf_unfiltered (fp, "hbreak");
13471   else
13472     internal_error (__FILE__, __LINE__,
13473                     _("unhandled breakpoint type %d"), (int) tp->type);
13474
13475   fprintf_unfiltered (fp, " %s", tp->addr_string);
13476   print_recreate_thread (tp, fp);
13477 }
13478
13479 static void
13480 bkpt_create_sals_from_address (char **arg,
13481                                struct linespec_result *canonical,
13482                                enum bptype type_wanted,
13483                                char *addr_start, char **copy_arg)
13484 {
13485   create_sals_from_address_default (arg, canonical, type_wanted,
13486                                     addr_start, copy_arg);
13487 }
13488
13489 static void
13490 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
13491                              struct linespec_result *canonical,
13492                              char *cond_string,
13493                              char *extra_string,
13494                              enum bptype type_wanted,
13495                              enum bpdisp disposition,
13496                              int thread,
13497                              int task, int ignore_count,
13498                              const struct breakpoint_ops *ops,
13499                              int from_tty, int enabled,
13500                              int internal, unsigned flags)
13501 {
13502   create_breakpoints_sal_default (gdbarch, canonical,
13503                                   cond_string, extra_string,
13504                                   type_wanted,
13505                                   disposition, thread, task,
13506                                   ignore_count, ops, from_tty,
13507                                   enabled, internal, flags);
13508 }
13509
13510 static void
13511 bkpt_decode_linespec (struct breakpoint *b, char **s,
13512                       struct symtabs_and_lines *sals)
13513 {
13514   decode_linespec_default (b, s, sals);
13515 }
13516
13517 /* Virtual table for internal breakpoints.  */
13518
13519 static void
13520 internal_bkpt_re_set (struct breakpoint *b)
13521 {
13522   switch (b->type)
13523     {
13524       /* Delete overlay event and longjmp master breakpoints; they
13525          will be reset later by breakpoint_re_set.  */
13526     case bp_overlay_event:
13527     case bp_longjmp_master:
13528     case bp_std_terminate_master:
13529     case bp_exception_master:
13530       delete_breakpoint (b);
13531       break;
13532
13533       /* This breakpoint is special, it's set up when the inferior
13534          starts and we really don't want to touch it.  */
13535     case bp_shlib_event:
13536
13537       /* Like bp_shlib_event, this breakpoint type is special.  Once
13538          it is set up, we do not want to touch it.  */
13539     case bp_thread_event:
13540       break;
13541     }
13542 }
13543
13544 static void
13545 internal_bkpt_check_status (bpstat bs)
13546 {
13547   if (bs->breakpoint_at->type == bp_shlib_event)
13548     {
13549       /* If requested, stop when the dynamic linker notifies GDB of
13550          events.  This allows the user to get control and place
13551          breakpoints in initializer routines for dynamically loaded
13552          objects (among other things).  */
13553       bs->stop = stop_on_solib_events;
13554       bs->print = stop_on_solib_events;
13555     }
13556   else
13557     bs->stop = 0;
13558 }
13559
13560 static enum print_stop_action
13561 internal_bkpt_print_it (bpstat bs)
13562 {
13563   struct breakpoint *b;
13564
13565   b = bs->breakpoint_at;
13566
13567   switch (b->type)
13568     {
13569     case bp_shlib_event:
13570       /* Did we stop because the user set the stop_on_solib_events
13571          variable?  (If so, we report this as a generic, "Stopped due
13572          to shlib event" message.) */
13573       print_solib_event (0);
13574       break;
13575
13576     case bp_thread_event:
13577       /* Not sure how we will get here.
13578          GDB should not stop for these breakpoints.  */
13579       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
13580       break;
13581
13582     case bp_overlay_event:
13583       /* By analogy with the thread event, GDB should not stop for these.  */
13584       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
13585       break;
13586
13587     case bp_longjmp_master:
13588       /* These should never be enabled.  */
13589       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
13590       break;
13591
13592     case bp_std_terminate_master:
13593       /* These should never be enabled.  */
13594       printf_filtered (_("std::terminate Master Breakpoint: "
13595                          "gdb should not stop!\n"));
13596       break;
13597
13598     case bp_exception_master:
13599       /* These should never be enabled.  */
13600       printf_filtered (_("Exception Master Breakpoint: "
13601                          "gdb should not stop!\n"));
13602       break;
13603     }
13604
13605   return PRINT_NOTHING;
13606 }
13607
13608 static void
13609 internal_bkpt_print_mention (struct breakpoint *b)
13610 {
13611   /* Nothing to mention.  These breakpoints are internal.  */
13612 }
13613
13614 /* Virtual table for momentary breakpoints  */
13615
13616 static void
13617 momentary_bkpt_re_set (struct breakpoint *b)
13618 {
13619   /* Keep temporary breakpoints, which can be encountered when we step
13620      over a dlopen call and solib_add is resetting the breakpoints.
13621      Otherwise these should have been blown away via the cleanup chain
13622      or by breakpoint_init_inferior when we rerun the executable.  */
13623 }
13624
13625 static void
13626 momentary_bkpt_check_status (bpstat bs)
13627 {
13628   /* Nothing.  The point of these breakpoints is causing a stop.  */
13629 }
13630
13631 static enum print_stop_action
13632 momentary_bkpt_print_it (bpstat bs)
13633 {
13634   struct ui_out *uiout = current_uiout;
13635
13636   if (ui_out_is_mi_like_p (uiout))
13637     {
13638       struct breakpoint *b = bs->breakpoint_at;
13639
13640       switch (b->type)
13641         {
13642         case bp_finish:
13643           ui_out_field_string
13644             (uiout, "reason",
13645              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
13646           break;
13647
13648         case bp_until:
13649           ui_out_field_string
13650             (uiout, "reason",
13651              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
13652           break;
13653         }
13654     }
13655
13656   return PRINT_UNKNOWN;
13657 }
13658
13659 static void
13660 momentary_bkpt_print_mention (struct breakpoint *b)
13661 {
13662   /* Nothing to mention.  These breakpoints are internal.  */
13663 }
13664
13665 /* Ensure INITIATING_FRAME is cleared when no such breakpoint exists.
13666
13667    It gets cleared already on the removal of the first one of such placed
13668    breakpoints.  This is OK as they get all removed altogether.  */
13669
13670 static void
13671 longjmp_bkpt_dtor (struct breakpoint *self)
13672 {
13673   struct thread_info *tp = find_thread_id (self->thread);
13674
13675   if (tp)
13676     tp->initiating_frame = null_frame_id;
13677
13678   momentary_breakpoint_ops.dtor (self);
13679 }
13680
13681 /* Specific methods for probe breakpoints.  */
13682
13683 static int
13684 bkpt_probe_insert_location (struct bp_location *bl)
13685 {
13686   int v = bkpt_insert_location (bl);
13687
13688   if (v == 0)
13689     {
13690       /* The insertion was successful, now let's set the probe's semaphore
13691          if needed.  */
13692       bl->probe.probe->pops->set_semaphore (bl->probe.probe,
13693                                             bl->probe.objfile,
13694                                             bl->gdbarch);
13695     }
13696
13697   return v;
13698 }
13699
13700 static int
13701 bkpt_probe_remove_location (struct bp_location *bl)
13702 {
13703   /* Let's clear the semaphore before removing the location.  */
13704   bl->probe.probe->pops->clear_semaphore (bl->probe.probe,
13705                                           bl->probe.objfile,
13706                                           bl->gdbarch);
13707
13708   return bkpt_remove_location (bl);
13709 }
13710
13711 static void
13712 bkpt_probe_create_sals_from_address (char **arg,
13713                                      struct linespec_result *canonical,
13714                                      enum bptype type_wanted,
13715                                      char *addr_start, char **copy_arg)
13716 {
13717   struct linespec_sals lsal;
13718
13719   lsal.sals = parse_probes (arg, canonical);
13720
13721   *copy_arg = xstrdup (canonical->addr_string);
13722   lsal.canonical = xstrdup (*copy_arg);
13723
13724   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13725 }
13726
13727 static void
13728 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
13729                             struct symtabs_and_lines *sals)
13730 {
13731   *sals = parse_probes (s, NULL);
13732   if (!sals->sals)
13733     error (_("probe not found"));
13734 }
13735
13736 /* The breakpoint_ops structure to be used in tracepoints.  */
13737
13738 static void
13739 tracepoint_re_set (struct breakpoint *b)
13740 {
13741   breakpoint_re_set_default (b);
13742 }
13743
13744 static int
13745 tracepoint_breakpoint_hit (const struct bp_location *bl,
13746                            struct address_space *aspace, CORE_ADDR bp_addr,
13747                            const struct target_waitstatus *ws)
13748 {
13749   /* By definition, the inferior does not report stops at
13750      tracepoints.  */
13751   return 0;
13752 }
13753
13754 static void
13755 tracepoint_print_one_detail (const struct breakpoint *self,
13756                              struct ui_out *uiout)
13757 {
13758   struct tracepoint *tp = (struct tracepoint *) self;
13759   if (tp->static_trace_marker_id)
13760     {
13761       gdb_assert (self->type == bp_static_tracepoint);
13762
13763       ui_out_text (uiout, "\tmarker id is ");
13764       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
13765                            tp->static_trace_marker_id);
13766       ui_out_text (uiout, "\n");
13767     }
13768 }
13769
13770 static void
13771 tracepoint_print_mention (struct breakpoint *b)
13772 {
13773   if (ui_out_is_mi_like_p (current_uiout))
13774     return;
13775
13776   switch (b->type)
13777     {
13778     case bp_tracepoint:
13779       printf_filtered (_("Tracepoint"));
13780       printf_filtered (_(" %d"), b->number);
13781       break;
13782     case bp_fast_tracepoint:
13783       printf_filtered (_("Fast tracepoint"));
13784       printf_filtered (_(" %d"), b->number);
13785       break;
13786     case bp_static_tracepoint:
13787       printf_filtered (_("Static tracepoint"));
13788       printf_filtered (_(" %d"), b->number);
13789       break;
13790     default:
13791       internal_error (__FILE__, __LINE__,
13792                       _("unhandled tracepoint type %d"), (int) b->type);
13793     }
13794
13795   say_where (b);
13796 }
13797
13798 static void
13799 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
13800 {
13801   struct tracepoint *tp = (struct tracepoint *) self;
13802
13803   if (self->type == bp_fast_tracepoint)
13804     fprintf_unfiltered (fp, "ftrace");
13805   if (self->type == bp_static_tracepoint)
13806     fprintf_unfiltered (fp, "strace");
13807   else if (self->type == bp_tracepoint)
13808     fprintf_unfiltered (fp, "trace");
13809   else
13810     internal_error (__FILE__, __LINE__,
13811                     _("unhandled tracepoint type %d"), (int) self->type);
13812
13813   fprintf_unfiltered (fp, " %s", self->addr_string);
13814   print_recreate_thread (self, fp);
13815
13816   if (tp->pass_count)
13817     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
13818 }
13819
13820 static void
13821 tracepoint_create_sals_from_address (char **arg,
13822                                      struct linespec_result *canonical,
13823                                      enum bptype type_wanted,
13824                                      char *addr_start, char **copy_arg)
13825 {
13826   create_sals_from_address_default (arg, canonical, type_wanted,
13827                                     addr_start, copy_arg);
13828 }
13829
13830 static void
13831 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
13832                                    struct linespec_result *canonical,
13833                                    char *cond_string,
13834                                    char *extra_string,
13835                                    enum bptype type_wanted,
13836                                    enum bpdisp disposition,
13837                                    int thread,
13838                                    int task, int ignore_count,
13839                                    const struct breakpoint_ops *ops,
13840                                    int from_tty, int enabled,
13841                                    int internal, unsigned flags)
13842 {
13843   create_breakpoints_sal_default (gdbarch, canonical,
13844                                   cond_string, extra_string,
13845                                   type_wanted,
13846                                   disposition, thread, task,
13847                                   ignore_count, ops, from_tty,
13848                                   enabled, internal, flags);
13849 }
13850
13851 static void
13852 tracepoint_decode_linespec (struct breakpoint *b, char **s,
13853                             struct symtabs_and_lines *sals)
13854 {
13855   decode_linespec_default (b, s, sals);
13856 }
13857
13858 struct breakpoint_ops tracepoint_breakpoint_ops;
13859
13860 /* The breakpoint_ops structure to be use on tracepoints placed in a
13861    static probe.  */
13862
13863 static void
13864 tracepoint_probe_create_sals_from_address (char **arg,
13865                                            struct linespec_result *canonical,
13866                                            enum bptype type_wanted,
13867                                            char *addr_start, char **copy_arg)
13868 {
13869   /* We use the same method for breakpoint on probes.  */
13870   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
13871                                        addr_start, copy_arg);
13872 }
13873
13874 static void
13875 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
13876                                   struct symtabs_and_lines *sals)
13877 {
13878   /* We use the same method for breakpoint on probes.  */
13879   bkpt_probe_decode_linespec (b, s, sals);
13880 }
13881
13882 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
13883
13884 /* Dprintf breakpoint_ops methods.  */
13885
13886 static void
13887 dprintf_re_set (struct breakpoint *b)
13888 {
13889   breakpoint_re_set_default (b);
13890
13891   /* This breakpoint could have been pending, and be resolved now, and
13892      if so, we should now have the extra string.  If we don't, the
13893      dprintf was malformed when created, but we couldn't tell because
13894      we can't extract the extra string until the location is
13895      resolved.  */
13896   if (b->loc != NULL && b->extra_string == NULL)
13897     error (_("Format string required"));
13898
13899   /* 1 - connect to target 1, that can run breakpoint commands.
13900      2 - create a dprintf, which resolves fine.
13901      3 - disconnect from target 1
13902      4 - connect to target 2, that can NOT run breakpoint commands.
13903
13904      After steps #3/#4, you'll want the dprintf command list to
13905      be updated, because target 1 and 2 may well return different
13906      answers for target_can_run_breakpoint_commands().
13907      Given absence of finer grained resetting, we get to do
13908      it all the time.  */
13909   if (b->extra_string != NULL)
13910     update_dprintf_command_list (b);
13911 }
13912
13913 /* Implement the "print_recreate" breakpoint_ops method for dprintf.  */
13914
13915 static void
13916 dprintf_print_recreate (struct breakpoint *tp, struct ui_file *fp)
13917 {
13918   fprintf_unfiltered (fp, "dprintf %s%s", tp->addr_string,
13919                       tp->extra_string);
13920   print_recreate_thread (tp, fp);
13921 }
13922
13923 /* Implement the "after_condition_true" breakpoint_ops method for
13924    dprintf.
13925
13926    dprintf's are implemented with regular commands in their command
13927    list, but we run the commands here instead of before presenting the
13928    stop to the user, as dprintf's don't actually cause a stop.  This
13929    also makes it so that the commands of multiple dprintfs at the same
13930    address are all handled.  */
13931
13932 static void
13933 dprintf_after_condition_true (struct bpstats *bs)
13934 {
13935   struct cleanup *old_chain;
13936   struct bpstats tmp_bs = { NULL };
13937   struct bpstats *tmp_bs_p = &tmp_bs;
13938
13939   /* dprintf's never cause a stop.  This wasn't set in the
13940      check_status hook instead because that would make the dprintf's
13941      condition not be evaluated.  */
13942   bs->stop = 0;
13943
13944   /* Run the command list here.  Take ownership of it instead of
13945      copying.  We never want these commands to run later in
13946      bpstat_do_actions, if a breakpoint that causes a stop happens to
13947      be set at same address as this dprintf, or even if running the
13948      commands here throws.  */
13949   tmp_bs.commands = bs->commands;
13950   bs->commands = NULL;
13951   old_chain = make_cleanup_decref_counted_command_line (&tmp_bs.commands);
13952
13953   bpstat_do_actions_1 (&tmp_bs_p);
13954
13955   /* 'tmp_bs.commands' will usually be NULL by now, but
13956      bpstat_do_actions_1 may return early without processing the whole
13957      list.  */
13958   do_cleanups (old_chain);
13959 }
13960
13961 /* The breakpoint_ops structure to be used on static tracepoints with
13962    markers (`-m').  */
13963
13964 static void
13965 strace_marker_create_sals_from_address (char **arg,
13966                                         struct linespec_result *canonical,
13967                                         enum bptype type_wanted,
13968                                         char *addr_start, char **copy_arg)
13969 {
13970   struct linespec_sals lsal;
13971
13972   lsal.sals = decode_static_tracepoint_spec (arg);
13973
13974   *copy_arg = savestring (addr_start, *arg - addr_start);
13975
13976   canonical->addr_string = xstrdup (*copy_arg);
13977   lsal.canonical = xstrdup (*copy_arg);
13978   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
13979 }
13980
13981 static void
13982 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
13983                                       struct linespec_result *canonical,
13984                                       char *cond_string,
13985                                       char *extra_string,
13986                                       enum bptype type_wanted,
13987                                       enum bpdisp disposition,
13988                                       int thread,
13989                                       int task, int ignore_count,
13990                                       const struct breakpoint_ops *ops,
13991                                       int from_tty, int enabled,
13992                                       int internal, unsigned flags)
13993 {
13994   int i;
13995   struct linespec_sals *lsal = VEC_index (linespec_sals,
13996                                           canonical->sals, 0);
13997
13998   /* If the user is creating a static tracepoint by marker id
13999      (strace -m MARKER_ID), then store the sals index, so that
14000      breakpoint_re_set can try to match up which of the newly
14001      found markers corresponds to this one, and, don't try to
14002      expand multiple locations for each sal, given than SALS
14003      already should contain all sals for MARKER_ID.  */
14004
14005   for (i = 0; i < lsal->sals.nelts; ++i)
14006     {
14007       struct symtabs_and_lines expanded;
14008       struct tracepoint *tp;
14009       struct cleanup *old_chain;
14010       char *addr_string;
14011
14012       expanded.nelts = 1;
14013       expanded.sals = &lsal->sals.sals[i];
14014
14015       addr_string = xstrdup (canonical->addr_string);
14016       old_chain = make_cleanup (xfree, addr_string);
14017
14018       tp = XCNEW (struct tracepoint);
14019       init_breakpoint_sal (&tp->base, gdbarch, expanded,
14020                            addr_string, NULL,
14021                            cond_string, extra_string,
14022                            type_wanted, disposition,
14023                            thread, task, ignore_count, ops,
14024                            from_tty, enabled, internal, flags,
14025                            canonical->special_display);
14026       /* Given that its possible to have multiple markers with
14027          the same string id, if the user is creating a static
14028          tracepoint by marker id ("strace -m MARKER_ID"), then
14029          store the sals index, so that breakpoint_re_set can
14030          try to match up which of the newly found markers
14031          corresponds to this one  */
14032       tp->static_trace_marker_id_idx = i;
14033
14034       install_breakpoint (internal, &tp->base, 0);
14035
14036       discard_cleanups (old_chain);
14037     }
14038 }
14039
14040 static void
14041 strace_marker_decode_linespec (struct breakpoint *b, char **s,
14042                                struct symtabs_and_lines *sals)
14043 {
14044   struct tracepoint *tp = (struct tracepoint *) b;
14045
14046   *sals = decode_static_tracepoint_spec (s);
14047   if (sals->nelts > tp->static_trace_marker_id_idx)
14048     {
14049       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
14050       sals->nelts = 1;
14051     }
14052   else
14053     error (_("marker %s not found"), tp->static_trace_marker_id);
14054 }
14055
14056 static struct breakpoint_ops strace_marker_breakpoint_ops;
14057
14058 static int
14059 strace_marker_p (struct breakpoint *b)
14060 {
14061   return b->ops == &strace_marker_breakpoint_ops;
14062 }
14063
14064 /* Delete a breakpoint and clean up all traces of it in the data
14065    structures.  */
14066
14067 void
14068 delete_breakpoint (struct breakpoint *bpt)
14069 {
14070   struct breakpoint *b;
14071
14072   gdb_assert (bpt != NULL);
14073
14074   /* Has this bp already been deleted?  This can happen because
14075      multiple lists can hold pointers to bp's.  bpstat lists are
14076      especial culprits.
14077
14078      One example of this happening is a watchpoint's scope bp.  When
14079      the scope bp triggers, we notice that the watchpoint is out of
14080      scope, and delete it.  We also delete its scope bp.  But the
14081      scope bp is marked "auto-deleting", and is already on a bpstat.
14082      That bpstat is then checked for auto-deleting bp's, which are
14083      deleted.
14084
14085      A real solution to this problem might involve reference counts in
14086      bp's, and/or giving them pointers back to their referencing
14087      bpstat's, and teaching delete_breakpoint to only free a bp's
14088      storage when no more references were extent.  A cheaper bandaid
14089      was chosen.  */
14090   if (bpt->type == bp_none)
14091     return;
14092
14093   /* At least avoid this stale reference until the reference counting
14094      of breakpoints gets resolved.  */
14095   if (bpt->related_breakpoint != bpt)
14096     {
14097       struct breakpoint *related;
14098       struct watchpoint *w;
14099
14100       if (bpt->type == bp_watchpoint_scope)
14101         w = (struct watchpoint *) bpt->related_breakpoint;
14102       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
14103         w = (struct watchpoint *) bpt;
14104       else
14105         w = NULL;
14106       if (w != NULL)
14107         watchpoint_del_at_next_stop (w);
14108
14109       /* Unlink bpt from the bpt->related_breakpoint ring.  */
14110       for (related = bpt; related->related_breakpoint != bpt;
14111            related = related->related_breakpoint);
14112       related->related_breakpoint = bpt->related_breakpoint;
14113       bpt->related_breakpoint = bpt;
14114     }
14115
14116   /* watch_command_1 creates a watchpoint but only sets its number if
14117      update_watchpoint succeeds in creating its bp_locations.  If there's
14118      a problem in that process, we'll be asked to delete the half-created
14119      watchpoint.  In that case, don't announce the deletion.  */
14120   if (bpt->number)
14121     observer_notify_breakpoint_deleted (bpt);
14122
14123   if (breakpoint_chain == bpt)
14124     breakpoint_chain = bpt->next;
14125
14126   ALL_BREAKPOINTS (b)
14127     if (b->next == bpt)
14128     {
14129       b->next = bpt->next;
14130       break;
14131     }
14132
14133   /* Be sure no bpstat's are pointing at the breakpoint after it's
14134      been freed.  */
14135   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
14136      in all threads for now.  Note that we cannot just remove bpstats
14137      pointing at bpt from the stop_bpstat list entirely, as breakpoint
14138      commands are associated with the bpstat; if we remove it here,
14139      then the later call to bpstat_do_actions (&stop_bpstat); in
14140      event-top.c won't do anything, and temporary breakpoints with
14141      commands won't work.  */
14142
14143   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
14144
14145   /* Now that breakpoint is removed from breakpoint list, update the
14146      global location list.  This will remove locations that used to
14147      belong to this breakpoint.  Do this before freeing the breakpoint
14148      itself, since remove_breakpoint looks at location's owner.  It
14149      might be better design to have location completely
14150      self-contained, but it's not the case now.  */
14151   update_global_location_list (UGLL_DONT_INSERT);
14152
14153   bpt->ops->dtor (bpt);
14154   /* On the chance that someone will soon try again to delete this
14155      same bp, we mark it as deleted before freeing its storage.  */
14156   bpt->type = bp_none;
14157   xfree (bpt);
14158 }
14159
14160 static void
14161 do_delete_breakpoint_cleanup (void *b)
14162 {
14163   delete_breakpoint (b);
14164 }
14165
14166 struct cleanup *
14167 make_cleanup_delete_breakpoint (struct breakpoint *b)
14168 {
14169   return make_cleanup (do_delete_breakpoint_cleanup, b);
14170 }
14171
14172 /* Iterator function to call a user-provided callback function once
14173    for each of B and its related breakpoints.  */
14174
14175 static void
14176 iterate_over_related_breakpoints (struct breakpoint *b,
14177                                   void (*function) (struct breakpoint *,
14178                                                     void *),
14179                                   void *data)
14180 {
14181   struct breakpoint *related;
14182
14183   related = b;
14184   do
14185     {
14186       struct breakpoint *next;
14187
14188       /* FUNCTION may delete RELATED.  */
14189       next = related->related_breakpoint;
14190
14191       if (next == related)
14192         {
14193           /* RELATED is the last ring entry.  */
14194           function (related, data);
14195
14196           /* FUNCTION may have deleted it, so we'd never reach back to
14197              B.  There's nothing left to do anyway, so just break
14198              out.  */
14199           break;
14200         }
14201       else
14202         function (related, data);
14203
14204       related = next;
14205     }
14206   while (related != b);
14207 }
14208
14209 static void
14210 do_delete_breakpoint (struct breakpoint *b, void *ignore)
14211 {
14212   delete_breakpoint (b);
14213 }
14214
14215 /* A callback for map_breakpoint_numbers that calls
14216    delete_breakpoint.  */
14217
14218 static void
14219 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
14220 {
14221   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
14222 }
14223
14224 void
14225 delete_command (char *arg, int from_tty)
14226 {
14227   struct breakpoint *b, *b_tmp;
14228
14229   dont_repeat ();
14230
14231   if (arg == 0)
14232     {
14233       int breaks_to_delete = 0;
14234
14235       /* Delete all breakpoints if no argument.  Do not delete
14236          internal breakpoints, these have to be deleted with an
14237          explicit breakpoint number argument.  */
14238       ALL_BREAKPOINTS (b)
14239         if (user_breakpoint_p (b))
14240           {
14241             breaks_to_delete = 1;
14242             break;
14243           }
14244
14245       /* Ask user only if there are some breakpoints to delete.  */
14246       if (!from_tty
14247           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
14248         {
14249           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14250             if (user_breakpoint_p (b))
14251               delete_breakpoint (b);
14252         }
14253     }
14254   else
14255     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14256 }
14257
14258 static int
14259 all_locations_are_pending (struct bp_location *loc)
14260 {
14261   for (; loc; loc = loc->next)
14262     if (!loc->shlib_disabled
14263         && !loc->pspace->executing_startup)
14264       return 0;
14265   return 1;
14266 }
14267
14268 /* Subroutine of update_breakpoint_locations to simplify it.
14269    Return non-zero if multiple fns in list LOC have the same name.
14270    Null names are ignored.  */
14271
14272 static int
14273 ambiguous_names_p (struct bp_location *loc)
14274 {
14275   struct bp_location *l;
14276   htab_t htab = htab_create_alloc (13, htab_hash_string,
14277                                    (int (*) (const void *, 
14278                                              const void *)) streq,
14279                                    NULL, xcalloc, xfree);
14280
14281   for (l = loc; l != NULL; l = l->next)
14282     {
14283       const char **slot;
14284       const char *name = l->function_name;
14285
14286       /* Allow for some names to be NULL, ignore them.  */
14287       if (name == NULL)
14288         continue;
14289
14290       slot = (const char **) htab_find_slot (htab, (const void *) name,
14291                                              INSERT);
14292       /* NOTE: We can assume slot != NULL here because xcalloc never
14293          returns NULL.  */
14294       if (*slot != NULL)
14295         {
14296           htab_delete (htab);
14297           return 1;
14298         }
14299       *slot = name;
14300     }
14301
14302   htab_delete (htab);
14303   return 0;
14304 }
14305
14306 /* When symbols change, it probably means the sources changed as well,
14307    and it might mean the static tracepoint markers are no longer at
14308    the same address or line numbers they used to be at last we
14309    checked.  Losing your static tracepoints whenever you rebuild is
14310    undesirable.  This function tries to resync/rematch gdb static
14311    tracepoints with the markers on the target, for static tracepoints
14312    that have not been set by marker id.  Static tracepoint that have
14313    been set by marker id are reset by marker id in breakpoint_re_set.
14314    The heuristic is:
14315
14316    1) For a tracepoint set at a specific address, look for a marker at
14317    the old PC.  If one is found there, assume to be the same marker.
14318    If the name / string id of the marker found is different from the
14319    previous known name, assume that means the user renamed the marker
14320    in the sources, and output a warning.
14321
14322    2) For a tracepoint set at a given line number, look for a marker
14323    at the new address of the old line number.  If one is found there,
14324    assume to be the same marker.  If the name / string id of the
14325    marker found is different from the previous known name, assume that
14326    means the user renamed the marker in the sources, and output a
14327    warning.
14328
14329    3) If a marker is no longer found at the same address or line, it
14330    may mean the marker no longer exists.  But it may also just mean
14331    the code changed a bit.  Maybe the user added a few lines of code
14332    that made the marker move up or down (in line number terms).  Ask
14333    the target for info about the marker with the string id as we knew
14334    it.  If found, update line number and address in the matching
14335    static tracepoint.  This will get confused if there's more than one
14336    marker with the same ID (possible in UST, although unadvised
14337    precisely because it confuses tools).  */
14338
14339 static struct symtab_and_line
14340 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
14341 {
14342   struct tracepoint *tp = (struct tracepoint *) b;
14343   struct static_tracepoint_marker marker;
14344   CORE_ADDR pc;
14345
14346   pc = sal.pc;
14347   if (sal.line)
14348     find_line_pc (sal.symtab, sal.line, &pc);
14349
14350   if (target_static_tracepoint_marker_at (pc, &marker))
14351     {
14352       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
14353         warning (_("static tracepoint %d changed probed marker from %s to %s"),
14354                  b->number,
14355                  tp->static_trace_marker_id, marker.str_id);
14356
14357       xfree (tp->static_trace_marker_id);
14358       tp->static_trace_marker_id = xstrdup (marker.str_id);
14359       release_static_tracepoint_marker (&marker);
14360
14361       return sal;
14362     }
14363
14364   /* Old marker wasn't found on target at lineno.  Try looking it up
14365      by string ID.  */
14366   if (!sal.explicit_pc
14367       && sal.line != 0
14368       && sal.symtab != NULL
14369       && tp->static_trace_marker_id != NULL)
14370     {
14371       VEC(static_tracepoint_marker_p) *markers;
14372
14373       markers
14374         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
14375
14376       if (!VEC_empty(static_tracepoint_marker_p, markers))
14377         {
14378           struct symtab_and_line sal2;
14379           struct symbol *sym;
14380           struct static_tracepoint_marker *tpmarker;
14381           struct ui_out *uiout = current_uiout;
14382
14383           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
14384
14385           xfree (tp->static_trace_marker_id);
14386           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
14387
14388           warning (_("marker for static tracepoint %d (%s) not "
14389                      "found at previous line number"),
14390                    b->number, tp->static_trace_marker_id);
14391
14392           init_sal (&sal2);
14393
14394           sal2.pc = tpmarker->address;
14395
14396           sal2 = find_pc_line (tpmarker->address, 0);
14397           sym = find_pc_sect_function (tpmarker->address, NULL);
14398           ui_out_text (uiout, "Now in ");
14399           if (sym)
14400             {
14401               ui_out_field_string (uiout, "func",
14402                                    SYMBOL_PRINT_NAME (sym));
14403               ui_out_text (uiout, " at ");
14404             }
14405           ui_out_field_string (uiout, "file",
14406                                symtab_to_filename_for_display (sal2.symtab));
14407           ui_out_text (uiout, ":");
14408
14409           if (ui_out_is_mi_like_p (uiout))
14410             {
14411               const char *fullname = symtab_to_fullname (sal2.symtab);
14412
14413               ui_out_field_string (uiout, "fullname", fullname);
14414             }
14415
14416           ui_out_field_int (uiout, "line", sal2.line);
14417           ui_out_text (uiout, "\n");
14418
14419           b->loc->line_number = sal2.line;
14420           b->loc->symtab = sym != NULL ? sal2.symtab : NULL;
14421
14422           xfree (b->addr_string);
14423           b->addr_string = xstrprintf ("%s:%d",
14424                                    symtab_to_filename_for_display (sal2.symtab),
14425                                        b->loc->line_number);
14426
14427           /* Might be nice to check if function changed, and warn if
14428              so.  */
14429
14430           release_static_tracepoint_marker (tpmarker);
14431         }
14432     }
14433   return sal;
14434 }
14435
14436 /* Returns 1 iff locations A and B are sufficiently same that
14437    we don't need to report breakpoint as changed.  */
14438
14439 static int
14440 locations_are_equal (struct bp_location *a, struct bp_location *b)
14441 {
14442   while (a && b)
14443     {
14444       if (a->address != b->address)
14445         return 0;
14446
14447       if (a->shlib_disabled != b->shlib_disabled)
14448         return 0;
14449
14450       if (a->enabled != b->enabled)
14451         return 0;
14452
14453       a = a->next;
14454       b = b->next;
14455     }
14456
14457   if ((a == NULL) != (b == NULL))
14458     return 0;
14459
14460   return 1;
14461 }
14462
14463 /* Create new breakpoint locations for B (a hardware or software breakpoint)
14464    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
14465    a ranged breakpoint.  */
14466
14467 void
14468 update_breakpoint_locations (struct breakpoint *b,
14469                              struct symtabs_and_lines sals,
14470                              struct symtabs_and_lines sals_end)
14471 {
14472   int i;
14473   struct bp_location *existing_locations = b->loc;
14474
14475   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
14476     {
14477       /* Ranged breakpoints have only one start location and one end
14478          location.  */
14479       b->enable_state = bp_disabled;
14480       update_global_location_list (UGLL_MAY_INSERT);
14481       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
14482                            "multiple locations found\n"),
14483                          b->number);
14484       return;
14485     }
14486
14487   /* If there's no new locations, and all existing locations are
14488      pending, don't do anything.  This optimizes the common case where
14489      all locations are in the same shared library, that was unloaded.
14490      We'd like to retain the location, so that when the library is
14491      loaded again, we don't loose the enabled/disabled status of the
14492      individual locations.  */
14493   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
14494     return;
14495
14496   b->loc = NULL;
14497
14498   for (i = 0; i < sals.nelts; ++i)
14499     {
14500       struct bp_location *new_loc;
14501
14502       switch_to_program_space_and_thread (sals.sals[i].pspace);
14503
14504       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
14505
14506       /* Reparse conditions, they might contain references to the
14507          old symtab.  */
14508       if (b->cond_string != NULL)
14509         {
14510           const char *s;
14511           volatile struct gdb_exception e;
14512
14513           s = b->cond_string;
14514           TRY_CATCH (e, RETURN_MASK_ERROR)
14515             {
14516               new_loc->cond = parse_exp_1 (&s, sals.sals[i].pc,
14517                                            block_for_pc (sals.sals[i].pc), 
14518                                            0);
14519             }
14520           if (e.reason < 0)
14521             {
14522               warning (_("failed to reevaluate condition "
14523                          "for breakpoint %d: %s"), 
14524                        b->number, e.message);
14525               new_loc->enabled = 0;
14526             }
14527         }
14528
14529       if (sals_end.nelts)
14530         {
14531           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
14532
14533           new_loc->length = end - sals.sals[0].pc + 1;
14534         }
14535     }
14536
14537   /* Update locations of permanent breakpoints.  */
14538   if (b->enable_state == bp_permanent)
14539     make_breakpoint_permanent (b);
14540
14541   /* If possible, carry over 'disable' status from existing
14542      breakpoints.  */
14543   {
14544     struct bp_location *e = existing_locations;
14545     /* If there are multiple breakpoints with the same function name,
14546        e.g. for inline functions, comparing function names won't work.
14547        Instead compare pc addresses; this is just a heuristic as things
14548        may have moved, but in practice it gives the correct answer
14549        often enough until a better solution is found.  */
14550     int have_ambiguous_names = ambiguous_names_p (b->loc);
14551
14552     for (; e; e = e->next)
14553       {
14554         if (!e->enabled && e->function_name)
14555           {
14556             struct bp_location *l = b->loc;
14557             if (have_ambiguous_names)
14558               {
14559                 for (; l; l = l->next)
14560                   if (breakpoint_locations_match (e, l))
14561                     {
14562                       l->enabled = 0;
14563                       break;
14564                     }
14565               }
14566             else
14567               {
14568                 for (; l; l = l->next)
14569                   if (l->function_name
14570                       && strcmp (e->function_name, l->function_name) == 0)
14571                     {
14572                       l->enabled = 0;
14573                       break;
14574                     }
14575               }
14576           }
14577       }
14578   }
14579
14580   if (!locations_are_equal (existing_locations, b->loc))
14581     observer_notify_breakpoint_modified (b);
14582
14583   update_global_location_list (UGLL_MAY_INSERT);
14584 }
14585
14586 /* Find the SaL locations corresponding to the given ADDR_STRING.
14587    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
14588
14589 static struct symtabs_and_lines
14590 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
14591 {
14592   char *s;
14593   struct symtabs_and_lines sals = {0};
14594   volatile struct gdb_exception e;
14595
14596   gdb_assert (b->ops != NULL);
14597   s = addr_string;
14598
14599   TRY_CATCH (e, RETURN_MASK_ERROR)
14600     {
14601       b->ops->decode_linespec (b, &s, &sals);
14602     }
14603   if (e.reason < 0)
14604     {
14605       int not_found_and_ok = 0;
14606       /* For pending breakpoints, it's expected that parsing will
14607          fail until the right shared library is loaded.  User has
14608          already told to create pending breakpoints and don't need
14609          extra messages.  If breakpoint is in bp_shlib_disabled
14610          state, then user already saw the message about that
14611          breakpoint being disabled, and don't want to see more
14612          errors.  */
14613       if (e.error == NOT_FOUND_ERROR
14614           && (b->condition_not_parsed 
14615               || (b->loc && b->loc->shlib_disabled)
14616               || (b->loc && b->loc->pspace->executing_startup)
14617               || b->enable_state == bp_disabled))
14618         not_found_and_ok = 1;
14619
14620       if (!not_found_and_ok)
14621         {
14622           /* We surely don't want to warn about the same breakpoint
14623              10 times.  One solution, implemented here, is disable
14624              the breakpoint on error.  Another solution would be to
14625              have separate 'warning emitted' flag.  Since this
14626              happens only when a binary has changed, I don't know
14627              which approach is better.  */
14628           b->enable_state = bp_disabled;
14629           throw_exception (e);
14630         }
14631     }
14632
14633   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
14634     {
14635       int i;
14636
14637       for (i = 0; i < sals.nelts; ++i)
14638         resolve_sal_pc (&sals.sals[i]);
14639       if (b->condition_not_parsed && s && s[0])
14640         {
14641           char *cond_string, *extra_string;
14642           int thread, task;
14643
14644           find_condition_and_thread (s, sals.sals[0].pc,
14645                                      &cond_string, &thread, &task,
14646                                      &extra_string);
14647           if (cond_string)
14648             b->cond_string = cond_string;
14649           b->thread = thread;
14650           b->task = task;
14651           if (extra_string)
14652             b->extra_string = extra_string;
14653           b->condition_not_parsed = 0;
14654         }
14655
14656       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
14657         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
14658
14659       *found = 1;
14660     }
14661   else
14662     *found = 0;
14663
14664   return sals;
14665 }
14666
14667 /* The default re_set method, for typical hardware or software
14668    breakpoints.  Reevaluate the breakpoint and recreate its
14669    locations.  */
14670
14671 static void
14672 breakpoint_re_set_default (struct breakpoint *b)
14673 {
14674   int found;
14675   struct symtabs_and_lines sals, sals_end;
14676   struct symtabs_and_lines expanded = {0};
14677   struct symtabs_and_lines expanded_end = {0};
14678
14679   sals = addr_string_to_sals (b, b->addr_string, &found);
14680   if (found)
14681     {
14682       make_cleanup (xfree, sals.sals);
14683       expanded = sals;
14684     }
14685
14686   if (b->addr_string_range_end)
14687     {
14688       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
14689       if (found)
14690         {
14691           make_cleanup (xfree, sals_end.sals);
14692           expanded_end = sals_end;
14693         }
14694     }
14695
14696   update_breakpoint_locations (b, expanded, expanded_end);
14697 }
14698
14699 /* Default method for creating SALs from an address string.  It basically
14700    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
14701
14702 static void
14703 create_sals_from_address_default (char **arg,
14704                                   struct linespec_result *canonical,
14705                                   enum bptype type_wanted,
14706                                   char *addr_start, char **copy_arg)
14707 {
14708   parse_breakpoint_sals (arg, canonical);
14709 }
14710
14711 /* Call create_breakpoints_sal for the given arguments.  This is the default
14712    function for the `create_breakpoints_sal' method of
14713    breakpoint_ops.  */
14714
14715 static void
14716 create_breakpoints_sal_default (struct gdbarch *gdbarch,
14717                                 struct linespec_result *canonical,
14718                                 char *cond_string,
14719                                 char *extra_string,
14720                                 enum bptype type_wanted,
14721                                 enum bpdisp disposition,
14722                                 int thread,
14723                                 int task, int ignore_count,
14724                                 const struct breakpoint_ops *ops,
14725                                 int from_tty, int enabled,
14726                                 int internal, unsigned flags)
14727 {
14728   create_breakpoints_sal (gdbarch, canonical, cond_string,
14729                           extra_string,
14730                           type_wanted, disposition,
14731                           thread, task, ignore_count, ops, from_tty,
14732                           enabled, internal, flags);
14733 }
14734
14735 /* Decode the line represented by S by calling decode_line_full.  This is the
14736    default function for the `decode_linespec' method of breakpoint_ops.  */
14737
14738 static void
14739 decode_linespec_default (struct breakpoint *b, char **s,
14740                          struct symtabs_and_lines *sals)
14741 {
14742   struct linespec_result canonical;
14743
14744   init_linespec_result (&canonical);
14745   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
14746                     (struct symtab *) NULL, 0,
14747                     &canonical, multiple_symbols_all,
14748                     b->filter);
14749
14750   /* We should get 0 or 1 resulting SALs.  */
14751   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
14752
14753   if (VEC_length (linespec_sals, canonical.sals) > 0)
14754     {
14755       struct linespec_sals *lsal;
14756
14757       lsal = VEC_index (linespec_sals, canonical.sals, 0);
14758       *sals = lsal->sals;
14759       /* Arrange it so the destructor does not free the
14760          contents.  */
14761       lsal->sals.sals = NULL;
14762     }
14763
14764   destroy_linespec_result (&canonical);
14765 }
14766
14767 /* Prepare the global context for a re-set of breakpoint B.  */
14768
14769 static struct cleanup *
14770 prepare_re_set_context (struct breakpoint *b)
14771 {
14772   struct cleanup *cleanups;
14773
14774   input_radix = b->input_radix;
14775   cleanups = save_current_space_and_thread ();
14776   if (b->pspace != NULL)
14777     switch_to_program_space_and_thread (b->pspace);
14778   set_language (b->language);
14779
14780   return cleanups;
14781 }
14782
14783 /* Reset a breakpoint given it's struct breakpoint * BINT.
14784    The value we return ends up being the return value from catch_errors.
14785    Unused in this case.  */
14786
14787 static int
14788 breakpoint_re_set_one (void *bint)
14789 {
14790   /* Get past catch_errs.  */
14791   struct breakpoint *b = (struct breakpoint *) bint;
14792   struct cleanup *cleanups;
14793
14794   cleanups = prepare_re_set_context (b);
14795   b->ops->re_set (b);
14796   do_cleanups (cleanups);
14797   return 0;
14798 }
14799
14800 /* Re-set all breakpoints after symbols have been re-loaded.  */
14801 void
14802 breakpoint_re_set (void)
14803 {
14804   struct breakpoint *b, *b_tmp;
14805   enum language save_language;
14806   int save_input_radix;
14807   struct cleanup *old_chain;
14808
14809   save_language = current_language->la_language;
14810   save_input_radix = input_radix;
14811   old_chain = save_current_program_space ();
14812
14813   ALL_BREAKPOINTS_SAFE (b, b_tmp)
14814   {
14815     /* Format possible error msg.  */
14816     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
14817                                 b->number);
14818     struct cleanup *cleanups = make_cleanup (xfree, message);
14819     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
14820     do_cleanups (cleanups);
14821   }
14822   set_language (save_language);
14823   input_radix = save_input_radix;
14824
14825   jit_breakpoint_re_set ();
14826
14827   do_cleanups (old_chain);
14828
14829   create_overlay_event_breakpoint ();
14830   create_longjmp_master_breakpoint ();
14831   create_std_terminate_master_breakpoint ();
14832   create_exception_master_breakpoint ();
14833 }
14834 \f
14835 /* Reset the thread number of this breakpoint:
14836
14837    - If the breakpoint is for all threads, leave it as-is.
14838    - Else, reset it to the current thread for inferior_ptid.  */
14839 void
14840 breakpoint_re_set_thread (struct breakpoint *b)
14841 {
14842   if (b->thread != -1)
14843     {
14844       if (in_thread_list (inferior_ptid))
14845         b->thread = pid_to_thread_id (inferior_ptid);
14846
14847       /* We're being called after following a fork.  The new fork is
14848          selected as current, and unless this was a vfork will have a
14849          different program space from the original thread.  Reset that
14850          as well.  */
14851       b->loc->pspace = current_program_space;
14852     }
14853 }
14854
14855 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14856    If from_tty is nonzero, it prints a message to that effect,
14857    which ends with a period (no newline).  */
14858
14859 void
14860 set_ignore_count (int bptnum, int count, int from_tty)
14861 {
14862   struct breakpoint *b;
14863
14864   if (count < 0)
14865     count = 0;
14866
14867   ALL_BREAKPOINTS (b)
14868     if (b->number == bptnum)
14869     {
14870       if (is_tracepoint (b))
14871         {
14872           if (from_tty && count != 0)
14873             printf_filtered (_("Ignore count ignored for tracepoint %d."),
14874                              bptnum);
14875           return;
14876         }
14877       
14878       b->ignore_count = count;
14879       if (from_tty)
14880         {
14881           if (count == 0)
14882             printf_filtered (_("Will stop next time "
14883                                "breakpoint %d is reached."),
14884                              bptnum);
14885           else if (count == 1)
14886             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
14887                              bptnum);
14888           else
14889             printf_filtered (_("Will ignore next %d "
14890                                "crossings of breakpoint %d."),
14891                              count, bptnum);
14892         }
14893       observer_notify_breakpoint_modified (b);
14894       return;
14895     }
14896
14897   error (_("No breakpoint number %d."), bptnum);
14898 }
14899
14900 /* Command to set ignore-count of breakpoint N to COUNT.  */
14901
14902 static void
14903 ignore_command (char *args, int from_tty)
14904 {
14905   char *p = args;
14906   int num;
14907
14908   if (p == 0)
14909     error_no_arg (_("a breakpoint number"));
14910
14911   num = get_number (&p);
14912   if (num == 0)
14913     error (_("bad breakpoint number: '%s'"), args);
14914   if (*p == 0)
14915     error (_("Second argument (specified ignore-count) is missing."));
14916
14917   set_ignore_count (num,
14918                     longest_to_int (value_as_long (parse_and_eval (p))),
14919                     from_tty);
14920   if (from_tty)
14921     printf_filtered ("\n");
14922 }
14923 \f
14924 /* Call FUNCTION on each of the breakpoints
14925    whose numbers are given in ARGS.  */
14926
14927 static void
14928 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
14929                                                       void *),
14930                         void *data)
14931 {
14932   int num;
14933   struct breakpoint *b, *tmp;
14934   int match;
14935   struct get_number_or_range_state state;
14936
14937   if (args == 0)
14938     error_no_arg (_("one or more breakpoint numbers"));
14939
14940   init_number_or_range (&state, args);
14941
14942   while (!state.finished)
14943     {
14944       const char *p = state.string;
14945
14946       match = 0;
14947
14948       num = get_number_or_range (&state);
14949       if (num == 0)
14950         {
14951           warning (_("bad breakpoint number at or near '%s'"), p);
14952         }
14953       else
14954         {
14955           ALL_BREAKPOINTS_SAFE (b, tmp)
14956             if (b->number == num)
14957               {
14958                 match = 1;
14959                 function (b, data);
14960                 break;
14961               }
14962           if (match == 0)
14963             printf_unfiltered (_("No breakpoint number %d.\n"), num);
14964         }
14965     }
14966 }
14967
14968 static struct bp_location *
14969 find_location_by_number (char *number)
14970 {
14971   char *dot = strchr (number, '.');
14972   char *p1;
14973   int bp_num;
14974   int loc_num;
14975   struct breakpoint *b;
14976   struct bp_location *loc;  
14977
14978   *dot = '\0';
14979
14980   p1 = number;
14981   bp_num = get_number (&p1);
14982   if (bp_num == 0)
14983     error (_("Bad breakpoint number '%s'"), number);
14984
14985   ALL_BREAKPOINTS (b)
14986     if (b->number == bp_num)
14987       {
14988         break;
14989       }
14990
14991   if (!b || b->number != bp_num)
14992     error (_("Bad breakpoint number '%s'"), number);
14993   
14994   p1 = dot+1;
14995   loc_num = get_number (&p1);
14996   if (loc_num == 0)
14997     error (_("Bad breakpoint location number '%s'"), number);
14998
14999   --loc_num;
15000   loc = b->loc;
15001   for (;loc_num && loc; --loc_num, loc = loc->next)
15002     ;
15003   if (!loc)
15004     error (_("Bad breakpoint location number '%s'"), dot+1);
15005     
15006   return loc;  
15007 }
15008
15009
15010 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
15011    If from_tty is nonzero, it prints a message to that effect,
15012    which ends with a period (no newline).  */
15013
15014 void
15015 disable_breakpoint (struct breakpoint *bpt)
15016 {
15017   /* Never disable a watchpoint scope breakpoint; we want to
15018      hit them when we leave scope so we can delete both the
15019      watchpoint and its scope breakpoint at that time.  */
15020   if (bpt->type == bp_watchpoint_scope)
15021     return;
15022
15023   /* You can't disable permanent breakpoints.  */
15024   if (bpt->enable_state == bp_permanent)
15025     return;
15026
15027   bpt->enable_state = bp_disabled;
15028
15029   /* Mark breakpoint locations modified.  */
15030   mark_breakpoint_modified (bpt);
15031
15032   if (target_supports_enable_disable_tracepoint ()
15033       && current_trace_status ()->running && is_tracepoint (bpt))
15034     {
15035       struct bp_location *location;
15036      
15037       for (location = bpt->loc; location; location = location->next)
15038         target_disable_tracepoint (location);
15039     }
15040
15041   update_global_location_list (UGLL_DONT_INSERT);
15042
15043   observer_notify_breakpoint_modified (bpt);
15044 }
15045
15046 /* A callback for iterate_over_related_breakpoints.  */
15047
15048 static void
15049 do_disable_breakpoint (struct breakpoint *b, void *ignore)
15050 {
15051   disable_breakpoint (b);
15052 }
15053
15054 /* A callback for map_breakpoint_numbers that calls
15055    disable_breakpoint.  */
15056
15057 static void
15058 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
15059 {
15060   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
15061 }
15062
15063 static void
15064 disable_command (char *args, int from_tty)
15065 {
15066   if (args == 0)
15067     {
15068       struct breakpoint *bpt;
15069
15070       ALL_BREAKPOINTS (bpt)
15071         if (user_breakpoint_p (bpt))
15072           disable_breakpoint (bpt);
15073     }
15074   else
15075     {
15076       char *num = extract_arg (&args);
15077
15078       while (num)
15079         {
15080           if (strchr (num, '.'))
15081             {
15082               struct bp_location *loc = find_location_by_number (num);
15083
15084               if (loc)
15085                 {
15086                   if (loc->enabled)
15087                     {
15088                       loc->enabled = 0;
15089                       mark_breakpoint_location_modified (loc);
15090                     }
15091                   if (target_supports_enable_disable_tracepoint ()
15092                       && current_trace_status ()->running && loc->owner
15093                       && is_tracepoint (loc->owner))
15094                     target_disable_tracepoint (loc);
15095                 }
15096               update_global_location_list (UGLL_DONT_INSERT);
15097             }
15098           else
15099             map_breakpoint_numbers (num, do_map_disable_breakpoint, NULL);
15100           num = extract_arg (&args);
15101         }
15102     }
15103 }
15104
15105 static void
15106 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
15107                         int count)
15108 {
15109   int target_resources_ok;
15110
15111   if (bpt->type == bp_hardware_breakpoint)
15112     {
15113       int i;
15114       i = hw_breakpoint_used_count ();
15115       target_resources_ok = 
15116         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
15117                                             i + 1, 0);
15118       if (target_resources_ok == 0)
15119         error (_("No hardware breakpoint support in the target."));
15120       else if (target_resources_ok < 0)
15121         error (_("Hardware breakpoints used exceeds limit."));
15122     }
15123
15124   if (is_watchpoint (bpt))
15125     {
15126       /* Initialize it just to avoid a GCC false warning.  */
15127       enum enable_state orig_enable_state = 0;
15128       volatile struct gdb_exception e;
15129
15130       TRY_CATCH (e, RETURN_MASK_ALL)
15131         {
15132           struct watchpoint *w = (struct watchpoint *) bpt;
15133
15134           orig_enable_state = bpt->enable_state;
15135           bpt->enable_state = bp_enabled;
15136           update_watchpoint (w, 1 /* reparse */);
15137         }
15138       if (e.reason < 0)
15139         {
15140           bpt->enable_state = orig_enable_state;
15141           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
15142                              bpt->number);
15143           return;
15144         }
15145     }
15146
15147   if (bpt->enable_state != bp_permanent)
15148     bpt->enable_state = bp_enabled;
15149
15150   bpt->enable_state = bp_enabled;
15151
15152   /* Mark breakpoint locations modified.  */
15153   mark_breakpoint_modified (bpt);
15154
15155   if (target_supports_enable_disable_tracepoint ()
15156       && current_trace_status ()->running && is_tracepoint (bpt))
15157     {
15158       struct bp_location *location;
15159
15160       for (location = bpt->loc; location; location = location->next)
15161         target_enable_tracepoint (location);
15162     }
15163
15164   bpt->disposition = disposition;
15165   bpt->enable_count = count;
15166   update_global_location_list (UGLL_MAY_INSERT);
15167
15168   observer_notify_breakpoint_modified (bpt);
15169 }
15170
15171
15172 void
15173 enable_breakpoint (struct breakpoint *bpt)
15174 {
15175   enable_breakpoint_disp (bpt, bpt->disposition, 0);
15176 }
15177
15178 static void
15179 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
15180 {
15181   enable_breakpoint (bpt);
15182 }
15183
15184 /* A callback for map_breakpoint_numbers that calls
15185    enable_breakpoint.  */
15186
15187 static void
15188 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
15189 {
15190   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
15191 }
15192
15193 /* The enable command enables the specified breakpoints (or all defined
15194    breakpoints) so they once again become (or continue to be) effective
15195    in stopping the inferior.  */
15196
15197 static void
15198 enable_command (char *args, int from_tty)
15199 {
15200   if (args == 0)
15201     {
15202       struct breakpoint *bpt;
15203
15204       ALL_BREAKPOINTS (bpt)
15205         if (user_breakpoint_p (bpt))
15206           enable_breakpoint (bpt);
15207     }
15208   else
15209     {
15210       char *num = extract_arg (&args);
15211
15212       while (num)
15213         {
15214           if (strchr (num, '.'))
15215             {
15216               struct bp_location *loc = find_location_by_number (num);
15217
15218               if (loc)
15219                 {
15220                   if (!loc->enabled)
15221                     {
15222                       loc->enabled = 1;
15223                       mark_breakpoint_location_modified (loc);
15224                     }
15225                   if (target_supports_enable_disable_tracepoint ()
15226                       && current_trace_status ()->running && loc->owner
15227                       && is_tracepoint (loc->owner))
15228                     target_enable_tracepoint (loc);
15229                 }
15230               update_global_location_list (UGLL_MAY_INSERT);
15231             }
15232           else
15233             map_breakpoint_numbers (num, do_map_enable_breakpoint, NULL);
15234           num = extract_arg (&args);
15235         }
15236     }
15237 }
15238
15239 /* This struct packages up disposition data for application to multiple
15240    breakpoints.  */
15241
15242 struct disp_data
15243 {
15244   enum bpdisp disp;
15245   int count;
15246 };
15247
15248 static void
15249 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
15250 {
15251   struct disp_data disp_data = *(struct disp_data *) arg;
15252
15253   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
15254 }
15255
15256 static void
15257 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
15258 {
15259   struct disp_data disp = { disp_disable, 1 };
15260
15261   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15262 }
15263
15264 static void
15265 enable_once_command (char *args, int from_tty)
15266 {
15267   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
15268 }
15269
15270 static void
15271 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
15272 {
15273   struct disp_data disp = { disp_disable, *(int *) countptr };
15274
15275   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15276 }
15277
15278 static void
15279 enable_count_command (char *args, int from_tty)
15280 {
15281   int count = get_number (&args);
15282
15283   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
15284 }
15285
15286 static void
15287 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
15288 {
15289   struct disp_data disp = { disp_del, 1 };
15290
15291   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
15292 }
15293
15294 static void
15295 enable_delete_command (char *args, int from_tty)
15296 {
15297   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
15298 }
15299 \f
15300 static void
15301 set_breakpoint_cmd (char *args, int from_tty)
15302 {
15303 }
15304
15305 static void
15306 show_breakpoint_cmd (char *args, int from_tty)
15307 {
15308 }
15309
15310 /* Invalidate last known value of any hardware watchpoint if
15311    the memory which that value represents has been written to by
15312    GDB itself.  */
15313
15314 static void
15315 invalidate_bp_value_on_memory_change (struct inferior *inferior,
15316                                       CORE_ADDR addr, ssize_t len,
15317                                       const bfd_byte *data)
15318 {
15319   struct breakpoint *bp;
15320
15321   ALL_BREAKPOINTS (bp)
15322     if (bp->enable_state == bp_enabled
15323         && bp->type == bp_hardware_watchpoint)
15324       {
15325         struct watchpoint *wp = (struct watchpoint *) bp;
15326
15327         if (wp->val_valid && wp->val)
15328           {
15329             struct bp_location *loc;
15330
15331             for (loc = bp->loc; loc != NULL; loc = loc->next)
15332               if (loc->loc_type == bp_loc_hardware_watchpoint
15333                   && loc->address + loc->length > addr
15334                   && addr + len > loc->address)
15335                 {
15336                   value_free (wp->val);
15337                   wp->val = NULL;
15338                   wp->val_valid = 0;
15339                 }
15340           }
15341       }
15342 }
15343
15344 /* Create and insert a raw software breakpoint at PC.  Return an
15345    identifier, which should be used to remove the breakpoint later.
15346    In general, places which call this should be using something on the
15347    breakpoint chain instead; this function should be eliminated
15348    someday.  */
15349
15350 void *
15351 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
15352                                   struct address_space *aspace, CORE_ADDR pc)
15353 {
15354   struct bp_target_info *bp_tgt;
15355   struct bp_location *bl;
15356
15357   bp_tgt = XCNEW (struct bp_target_info);
15358
15359   bp_tgt->placed_address_space = aspace;
15360   bp_tgt->placed_address = pc;
15361
15362   /* If an unconditional non-raw breakpoint is already inserted at
15363      that location, there's no need to insert another.  However, with
15364      target-side evaluation of breakpoint conditions, if the
15365      breakpoint that is currently inserted on the target is
15366      conditional, we need to make it unconditional.  Note that a
15367      breakpoint with target-side commands is not reported even if
15368      unconditional, so we need to remove the commands from the target
15369      as well.  */
15370   bl = find_non_raw_software_breakpoint_inserted_here (aspace, pc);
15371   if (bl != NULL
15372       && VEC_empty (agent_expr_p, bl->target_info.conditions)
15373       && VEC_empty (agent_expr_p, bl->target_info.tcommands))
15374     {
15375       bp_target_info_copy_insertion_state (bp_tgt, &bl->target_info);
15376       return bp_tgt;
15377     }
15378
15379   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
15380     {
15381       /* Could not insert the breakpoint.  */
15382       xfree (bp_tgt);
15383       return NULL;
15384     }
15385
15386   return bp_tgt;
15387 }
15388
15389 /* Remove a breakpoint BP inserted by
15390    deprecated_insert_raw_breakpoint.  */
15391
15392 int
15393 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
15394 {
15395   struct bp_target_info *bp_tgt = bp;
15396   struct address_space *aspace = bp_tgt->placed_address_space;
15397   CORE_ADDR address = bp_tgt->placed_address;
15398   struct bp_location *bl;
15399   int ret;
15400
15401   bl = find_non_raw_software_breakpoint_inserted_here (aspace, address);
15402
15403   /* Only remove the raw breakpoint if there are no other non-raw
15404      breakpoints still inserted at this location.  Otherwise, we would
15405      be effectively disabling those breakpoints.  */
15406   if (bl == NULL)
15407     ret = target_remove_breakpoint (gdbarch, bp_tgt);
15408   else if (!VEC_empty (agent_expr_p, bl->target_info.conditions)
15409            || !VEC_empty (agent_expr_p, bl->target_info.tcommands))
15410     {
15411       /* The target is evaluating conditions, and when we inserted the
15412          software single-step breakpoint, we had made the breakpoint
15413          unconditional and command-less on the target side.  Reinsert
15414          to restore the conditions/commands.  */
15415       ret = target_insert_breakpoint (bl->gdbarch, &bl->target_info);
15416     }
15417   else
15418     ret = 0;
15419
15420   xfree (bp_tgt);
15421
15422   return ret;
15423 }
15424
15425 /* Create and insert a breakpoint for software single step.  */
15426
15427 void
15428 insert_single_step_breakpoint (struct gdbarch *gdbarch,
15429                                struct address_space *aspace, 
15430                                CORE_ADDR next_pc)
15431 {
15432   void **bpt_p;
15433
15434   if (single_step_breakpoints[0] == NULL)
15435     {
15436       bpt_p = &single_step_breakpoints[0];
15437       single_step_gdbarch[0] = gdbarch;
15438     }
15439   else
15440     {
15441       gdb_assert (single_step_breakpoints[1] == NULL);
15442       bpt_p = &single_step_breakpoints[1];
15443       single_step_gdbarch[1] = gdbarch;
15444     }
15445
15446   /* NOTE drow/2006-04-11: A future improvement to this function would
15447      be to only create the breakpoints once, and actually put them on
15448      the breakpoint chain.  That would let us use set_raw_breakpoint.
15449      We could adjust the addresses each time they were needed.  Doing
15450      this requires corresponding changes elsewhere where single step
15451      breakpoints are handled, however.  So, for now, we use this.  */
15452
15453   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
15454   if (*bpt_p == NULL)
15455     error (_("Could not insert single-step breakpoint at %s"),
15456              paddress (gdbarch, next_pc));
15457 }
15458
15459 /* Check if the breakpoints used for software single stepping
15460    were inserted or not.  */
15461
15462 int
15463 single_step_breakpoints_inserted (void)
15464 {
15465   return (single_step_breakpoints[0] != NULL
15466           || single_step_breakpoints[1] != NULL);
15467 }
15468
15469 /* Remove and delete any breakpoints used for software single step.  */
15470
15471 void
15472 remove_single_step_breakpoints (void)
15473 {
15474   gdb_assert (single_step_breakpoints[0] != NULL);
15475
15476   /* See insert_single_step_breakpoint for more about this deprecated
15477      call.  */
15478   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
15479                                     single_step_breakpoints[0]);
15480   single_step_gdbarch[0] = NULL;
15481   single_step_breakpoints[0] = NULL;
15482
15483   if (single_step_breakpoints[1] != NULL)
15484     {
15485       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
15486                                         single_step_breakpoints[1]);
15487       single_step_gdbarch[1] = NULL;
15488       single_step_breakpoints[1] = NULL;
15489     }
15490 }
15491
15492 /* Delete software single step breakpoints without removing them from
15493    the inferior.  This is intended to be used if the inferior's address
15494    space where they were inserted is already gone, e.g. after exit or
15495    exec.  */
15496
15497 void
15498 cancel_single_step_breakpoints (void)
15499 {
15500   int i;
15501
15502   for (i = 0; i < 2; i++)
15503     if (single_step_breakpoints[i])
15504       {
15505         xfree (single_step_breakpoints[i]);
15506         single_step_breakpoints[i] = NULL;
15507         single_step_gdbarch[i] = NULL;
15508       }
15509 }
15510
15511 /* Detach software single-step breakpoints from INFERIOR_PTID without
15512    removing them.  */
15513
15514 static void
15515 detach_single_step_breakpoints (void)
15516 {
15517   int i;
15518
15519   for (i = 0; i < 2; i++)
15520     if (single_step_breakpoints[i])
15521       target_remove_breakpoint (single_step_gdbarch[i],
15522                                 single_step_breakpoints[i]);
15523 }
15524
15525 /* Find the software single-step breakpoint that inserted at PC.
15526    Returns its slot if found, and -1 if not found.  */
15527
15528 static int
15529 find_single_step_breakpoint (struct address_space *aspace,
15530                              CORE_ADDR pc)
15531 {
15532   int i;
15533
15534   for (i = 0; i < 2; i++)
15535     {
15536       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
15537       if (bp_tgt
15538           && breakpoint_address_match (bp_tgt->placed_address_space,
15539                                        bp_tgt->placed_address,
15540                                        aspace, pc))
15541         return i;
15542     }
15543
15544   return -1;
15545 }
15546
15547 /* Check whether a software single-step breakpoint is inserted at
15548    PC.  */
15549
15550 int
15551 single_step_breakpoint_inserted_here_p (struct address_space *aspace,
15552                                         CORE_ADDR pc)
15553 {
15554   return find_single_step_breakpoint (aspace, pc) >= 0;
15555 }
15556
15557 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
15558    non-zero otherwise.  */
15559 static int
15560 is_syscall_catchpoint_enabled (struct breakpoint *bp)
15561 {
15562   if (syscall_catchpoint_p (bp)
15563       && bp->enable_state != bp_disabled
15564       && bp->enable_state != bp_call_disabled)
15565     return 1;
15566   else
15567     return 0;
15568 }
15569
15570 int
15571 catch_syscall_enabled (void)
15572 {
15573   struct catch_syscall_inferior_data *inf_data
15574     = get_catch_syscall_inferior_data (current_inferior ());
15575
15576   return inf_data->total_syscalls_count != 0;
15577 }
15578
15579 int
15580 catching_syscall_number (int syscall_number)
15581 {
15582   struct breakpoint *bp;
15583
15584   ALL_BREAKPOINTS (bp)
15585     if (is_syscall_catchpoint_enabled (bp))
15586       {
15587         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
15588
15589         if (c->syscalls_to_be_caught)
15590           {
15591             int i, iter;
15592             for (i = 0;
15593                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
15594                  i++)
15595               if (syscall_number == iter)
15596                 return 1;
15597           }
15598         else
15599           return 1;
15600       }
15601
15602   return 0;
15603 }
15604
15605 /* Complete syscall names.  Used by "catch syscall".  */
15606 static VEC (char_ptr) *
15607 catch_syscall_completer (struct cmd_list_element *cmd,
15608                          const char *text, const char *word)
15609 {
15610   const char **list = get_syscall_names ();
15611   VEC (char_ptr) *retlist
15612     = (list == NULL) ? NULL : complete_on_enum (list, word, word);
15613
15614   xfree (list);
15615   return retlist;
15616 }
15617
15618 /* Tracepoint-specific operations.  */
15619
15620 /* Set tracepoint count to NUM.  */
15621 static void
15622 set_tracepoint_count (int num)
15623 {
15624   tracepoint_count = num;
15625   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
15626 }
15627
15628 static void
15629 trace_command (char *arg, int from_tty)
15630 {
15631   struct breakpoint_ops *ops;
15632   const char *arg_cp = arg;
15633
15634   if (arg && probe_linespec_to_ops (&arg_cp))
15635     ops = &tracepoint_probe_breakpoint_ops;
15636   else
15637     ops = &tracepoint_breakpoint_ops;
15638
15639   create_breakpoint (get_current_arch (),
15640                      arg,
15641                      NULL, 0, NULL, 1 /* parse arg */,
15642                      0 /* tempflag */,
15643                      bp_tracepoint /* type_wanted */,
15644                      0 /* Ignore count */,
15645                      pending_break_support,
15646                      ops,
15647                      from_tty,
15648                      1 /* enabled */,
15649                      0 /* internal */, 0);
15650 }
15651
15652 static void
15653 ftrace_command (char *arg, int from_tty)
15654 {
15655   create_breakpoint (get_current_arch (),
15656                      arg,
15657                      NULL, 0, NULL, 1 /* parse arg */,
15658                      0 /* tempflag */,
15659                      bp_fast_tracepoint /* type_wanted */,
15660                      0 /* Ignore count */,
15661                      pending_break_support,
15662                      &tracepoint_breakpoint_ops,
15663                      from_tty,
15664                      1 /* enabled */,
15665                      0 /* internal */, 0);
15666 }
15667
15668 /* strace command implementation.  Creates a static tracepoint.  */
15669
15670 static void
15671 strace_command (char *arg, int from_tty)
15672 {
15673   struct breakpoint_ops *ops;
15674
15675   /* Decide if we are dealing with a static tracepoint marker (`-m'),
15676      or with a normal static tracepoint.  */
15677   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
15678     ops = &strace_marker_breakpoint_ops;
15679   else
15680     ops = &tracepoint_breakpoint_ops;
15681
15682   create_breakpoint (get_current_arch (),
15683                      arg,
15684                      NULL, 0, NULL, 1 /* parse arg */,
15685                      0 /* tempflag */,
15686                      bp_static_tracepoint /* type_wanted */,
15687                      0 /* Ignore count */,
15688                      pending_break_support,
15689                      ops,
15690                      from_tty,
15691                      1 /* enabled */,
15692                      0 /* internal */, 0);
15693 }
15694
15695 /* Set up a fake reader function that gets command lines from a linked
15696    list that was acquired during tracepoint uploading.  */
15697
15698 static struct uploaded_tp *this_utp;
15699 static int next_cmd;
15700
15701 static char *
15702 read_uploaded_action (void)
15703 {
15704   char *rslt;
15705
15706   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
15707
15708   next_cmd++;
15709
15710   return rslt;
15711 }
15712
15713 /* Given information about a tracepoint as recorded on a target (which
15714    can be either a live system or a trace file), attempt to create an
15715    equivalent GDB tracepoint.  This is not a reliable process, since
15716    the target does not necessarily have all the information used when
15717    the tracepoint was originally defined.  */
15718   
15719 struct tracepoint *
15720 create_tracepoint_from_upload (struct uploaded_tp *utp)
15721 {
15722   char *addr_str, small_buf[100];
15723   struct tracepoint *tp;
15724
15725   if (utp->at_string)
15726     addr_str = utp->at_string;
15727   else
15728     {
15729       /* In the absence of a source location, fall back to raw
15730          address.  Since there is no way to confirm that the address
15731          means the same thing as when the trace was started, warn the
15732          user.  */
15733       warning (_("Uploaded tracepoint %d has no "
15734                  "source location, using raw address"),
15735                utp->number);
15736       xsnprintf (small_buf, sizeof (small_buf), "*%s", hex_string (utp->addr));
15737       addr_str = small_buf;
15738     }
15739
15740   /* There's not much we can do with a sequence of bytecodes.  */
15741   if (utp->cond && !utp->cond_string)
15742     warning (_("Uploaded tracepoint %d condition "
15743                "has no source form, ignoring it"),
15744              utp->number);
15745
15746   if (!create_breakpoint (get_current_arch (),
15747                           addr_str,
15748                           utp->cond_string, -1, NULL,
15749                           0 /* parse cond/thread */,
15750                           0 /* tempflag */,
15751                           utp->type /* type_wanted */,
15752                           0 /* Ignore count */,
15753                           pending_break_support,
15754                           &tracepoint_breakpoint_ops,
15755                           0 /* from_tty */,
15756                           utp->enabled /* enabled */,
15757                           0 /* internal */,
15758                           CREATE_BREAKPOINT_FLAGS_INSERTED))
15759     return NULL;
15760
15761   /* Get the tracepoint we just created.  */
15762   tp = get_tracepoint (tracepoint_count);
15763   gdb_assert (tp != NULL);
15764
15765   if (utp->pass > 0)
15766     {
15767       xsnprintf (small_buf, sizeof (small_buf), "%d %d", utp->pass,
15768                  tp->base.number);
15769
15770       trace_pass_command (small_buf, 0);
15771     }
15772
15773   /* If we have uploaded versions of the original commands, set up a
15774      special-purpose "reader" function and call the usual command line
15775      reader, then pass the result to the breakpoint command-setting
15776      function.  */
15777   if (!VEC_empty (char_ptr, utp->cmd_strings))
15778     {
15779       struct command_line *cmd_list;
15780
15781       this_utp = utp;
15782       next_cmd = 0;
15783
15784       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
15785
15786       breakpoint_set_commands (&tp->base, cmd_list);
15787     }
15788   else if (!VEC_empty (char_ptr, utp->actions)
15789            || !VEC_empty (char_ptr, utp->step_actions))
15790     warning (_("Uploaded tracepoint %d actions "
15791                "have no source form, ignoring them"),
15792              utp->number);
15793
15794   /* Copy any status information that might be available.  */
15795   tp->base.hit_count = utp->hit_count;
15796   tp->traceframe_usage = utp->traceframe_usage;
15797
15798   return tp;
15799 }
15800   
15801 /* Print information on tracepoint number TPNUM_EXP, or all if
15802    omitted.  */
15803
15804 static void
15805 tracepoints_info (char *args, int from_tty)
15806 {
15807   struct ui_out *uiout = current_uiout;
15808   int num_printed;
15809
15810   num_printed = breakpoint_1 (args, 0, is_tracepoint);
15811
15812   if (num_printed == 0)
15813     {
15814       if (args == NULL || *args == '\0')
15815         ui_out_message (uiout, 0, "No tracepoints.\n");
15816       else
15817         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
15818     }
15819
15820   default_collect_info ();
15821 }
15822
15823 /* The 'enable trace' command enables tracepoints.
15824    Not supported by all targets.  */
15825 static void
15826 enable_trace_command (char *args, int from_tty)
15827 {
15828   enable_command (args, from_tty);
15829 }
15830
15831 /* The 'disable trace' command disables tracepoints.
15832    Not supported by all targets.  */
15833 static void
15834 disable_trace_command (char *args, int from_tty)
15835 {
15836   disable_command (args, from_tty);
15837 }
15838
15839 /* Remove a tracepoint (or all if no argument).  */
15840 static void
15841 delete_trace_command (char *arg, int from_tty)
15842 {
15843   struct breakpoint *b, *b_tmp;
15844
15845   dont_repeat ();
15846
15847   if (arg == 0)
15848     {
15849       int breaks_to_delete = 0;
15850
15851       /* Delete all breakpoints if no argument.
15852          Do not delete internal or call-dummy breakpoints, these
15853          have to be deleted with an explicit breakpoint number 
15854          argument.  */
15855       ALL_TRACEPOINTS (b)
15856         if (is_tracepoint (b) && user_breakpoint_p (b))
15857           {
15858             breaks_to_delete = 1;
15859             break;
15860           }
15861
15862       /* Ask user only if there are some breakpoints to delete.  */
15863       if (!from_tty
15864           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
15865         {
15866           ALL_BREAKPOINTS_SAFE (b, b_tmp)
15867             if (is_tracepoint (b) && user_breakpoint_p (b))
15868               delete_breakpoint (b);
15869         }
15870     }
15871   else
15872     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
15873 }
15874
15875 /* Helper function for trace_pass_command.  */
15876
15877 static void
15878 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
15879 {
15880   tp->pass_count = count;
15881   observer_notify_breakpoint_modified (&tp->base);
15882   if (from_tty)
15883     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
15884                      tp->base.number, count);
15885 }
15886
15887 /* Set passcount for tracepoint.
15888
15889    First command argument is passcount, second is tracepoint number.
15890    If tracepoint number omitted, apply to most recently defined.
15891    Also accepts special argument "all".  */
15892
15893 static void
15894 trace_pass_command (char *args, int from_tty)
15895 {
15896   struct tracepoint *t1;
15897   unsigned int count;
15898
15899   if (args == 0 || *args == 0)
15900     error (_("passcount command requires an "
15901              "argument (count + optional TP num)"));
15902
15903   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
15904
15905   args = skip_spaces (args);
15906   if (*args && strncasecmp (args, "all", 3) == 0)
15907     {
15908       struct breakpoint *b;
15909
15910       args += 3;                        /* Skip special argument "all".  */
15911       if (*args)
15912         error (_("Junk at end of arguments."));
15913
15914       ALL_TRACEPOINTS (b)
15915       {
15916         t1 = (struct tracepoint *) b;
15917         trace_pass_set_count (t1, count, from_tty);
15918       }
15919     }
15920   else if (*args == '\0')
15921     {
15922       t1 = get_tracepoint_by_number (&args, NULL);
15923       if (t1)
15924         trace_pass_set_count (t1, count, from_tty);
15925     }
15926   else
15927     {
15928       struct get_number_or_range_state state;
15929
15930       init_number_or_range (&state, args);
15931       while (!state.finished)
15932         {
15933           t1 = get_tracepoint_by_number (&args, &state);
15934           if (t1)
15935             trace_pass_set_count (t1, count, from_tty);
15936         }
15937     }
15938 }
15939
15940 struct tracepoint *
15941 get_tracepoint (int num)
15942 {
15943   struct breakpoint *t;
15944
15945   ALL_TRACEPOINTS (t)
15946     if (t->number == num)
15947       return (struct tracepoint *) t;
15948
15949   return NULL;
15950 }
15951
15952 /* Find the tracepoint with the given target-side number (which may be
15953    different from the tracepoint number after disconnecting and
15954    reconnecting).  */
15955
15956 struct tracepoint *
15957 get_tracepoint_by_number_on_target (int num)
15958 {
15959   struct breakpoint *b;
15960
15961   ALL_TRACEPOINTS (b)
15962     {
15963       struct tracepoint *t = (struct tracepoint *) b;
15964
15965       if (t->number_on_target == num)
15966         return t;
15967     }
15968
15969   return NULL;
15970 }
15971
15972 /* Utility: parse a tracepoint number and look it up in the list.
15973    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
15974    If the argument is missing, the most recent tracepoint
15975    (tracepoint_count) is returned.  */
15976
15977 struct tracepoint *
15978 get_tracepoint_by_number (char **arg,
15979                           struct get_number_or_range_state *state)
15980 {
15981   struct breakpoint *t;
15982   int tpnum;
15983   char *instring = arg == NULL ? NULL : *arg;
15984
15985   if (state)
15986     {
15987       gdb_assert (!state->finished);
15988       tpnum = get_number_or_range (state);
15989     }
15990   else if (arg == NULL || *arg == NULL || ! **arg)
15991     tpnum = tracepoint_count;
15992   else
15993     tpnum = get_number (arg);
15994
15995   if (tpnum <= 0)
15996     {
15997       if (instring && *instring)
15998         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
15999                          instring);
16000       else
16001         printf_filtered (_("No previous tracepoint\n"));
16002       return NULL;
16003     }
16004
16005   ALL_TRACEPOINTS (t)
16006     if (t->number == tpnum)
16007     {
16008       return (struct tracepoint *) t;
16009     }
16010
16011   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
16012   return NULL;
16013 }
16014
16015 void
16016 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
16017 {
16018   if (b->thread != -1)
16019     fprintf_unfiltered (fp, " thread %d", b->thread);
16020
16021   if (b->task != 0)
16022     fprintf_unfiltered (fp, " task %d", b->task);
16023
16024   fprintf_unfiltered (fp, "\n");
16025 }
16026
16027 /* Save information on user settable breakpoints (watchpoints, etc) to
16028    a new script file named FILENAME.  If FILTER is non-NULL, call it
16029    on each breakpoint and only include the ones for which it returns
16030    non-zero.  */
16031
16032 static void
16033 save_breakpoints (char *filename, int from_tty,
16034                   int (*filter) (const struct breakpoint *))
16035 {
16036   struct breakpoint *tp;
16037   int any = 0;
16038   struct cleanup *cleanup;
16039   struct ui_file *fp;
16040   int extra_trace_bits = 0;
16041
16042   if (filename == 0 || *filename == 0)
16043     error (_("Argument required (file name in which to save)"));
16044
16045   /* See if we have anything to save.  */
16046   ALL_BREAKPOINTS (tp)
16047   {
16048     /* Skip internal and momentary breakpoints.  */
16049     if (!user_breakpoint_p (tp))
16050       continue;
16051
16052     /* If we have a filter, only save the breakpoints it accepts.  */
16053     if (filter && !filter (tp))
16054       continue;
16055
16056     any = 1;
16057
16058     if (is_tracepoint (tp))
16059       {
16060         extra_trace_bits = 1;
16061
16062         /* We can stop searching.  */
16063         break;
16064       }
16065   }
16066
16067   if (!any)
16068     {
16069       warning (_("Nothing to save."));
16070       return;
16071     }
16072
16073   filename = tilde_expand (filename);
16074   cleanup = make_cleanup (xfree, filename);
16075   fp = gdb_fopen (filename, "w");
16076   if (!fp)
16077     error (_("Unable to open file '%s' for saving (%s)"),
16078            filename, safe_strerror (errno));
16079   make_cleanup_ui_file_delete (fp);
16080
16081   if (extra_trace_bits)
16082     save_trace_state_variables (fp);
16083
16084   ALL_BREAKPOINTS (tp)
16085   {
16086     /* Skip internal and momentary breakpoints.  */
16087     if (!user_breakpoint_p (tp))
16088       continue;
16089
16090     /* If we have a filter, only save the breakpoints it accepts.  */
16091     if (filter && !filter (tp))
16092       continue;
16093
16094     tp->ops->print_recreate (tp, fp);
16095
16096     /* Note, we can't rely on tp->number for anything, as we can't
16097        assume the recreated breakpoint numbers will match.  Use $bpnum
16098        instead.  */
16099
16100     if (tp->cond_string)
16101       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
16102
16103     if (tp->ignore_count)
16104       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
16105
16106     if (tp->type != bp_dprintf && tp->commands)
16107       {
16108         volatile struct gdb_exception ex;       
16109
16110         fprintf_unfiltered (fp, "  commands\n");
16111         
16112         ui_out_redirect (current_uiout, fp);
16113         TRY_CATCH (ex, RETURN_MASK_ALL)
16114           {
16115             print_command_lines (current_uiout, tp->commands->commands, 2);
16116           }
16117         ui_out_redirect (current_uiout, NULL);
16118
16119         if (ex.reason < 0)
16120           throw_exception (ex);
16121
16122         fprintf_unfiltered (fp, "  end\n");
16123       }
16124
16125     if (tp->enable_state == bp_disabled)
16126       fprintf_unfiltered (fp, "disable\n");
16127
16128     /* If this is a multi-location breakpoint, check if the locations
16129        should be individually disabled.  Watchpoint locations are
16130        special, and not user visible.  */
16131     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
16132       {
16133         struct bp_location *loc;
16134         int n = 1;
16135
16136         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
16137           if (!loc->enabled)
16138             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
16139       }
16140   }
16141
16142   if (extra_trace_bits && *default_collect)
16143     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
16144
16145   if (from_tty)
16146     printf_filtered (_("Saved to file '%s'.\n"), filename);
16147   do_cleanups (cleanup);
16148 }
16149
16150 /* The `save breakpoints' command.  */
16151
16152 static void
16153 save_breakpoints_command (char *args, int from_tty)
16154 {
16155   save_breakpoints (args, from_tty, NULL);
16156 }
16157
16158 /* The `save tracepoints' command.  */
16159
16160 static void
16161 save_tracepoints_command (char *args, int from_tty)
16162 {
16163   save_breakpoints (args, from_tty, is_tracepoint);
16164 }
16165
16166 /* Create a vector of all tracepoints.  */
16167
16168 VEC(breakpoint_p) *
16169 all_tracepoints (void)
16170 {
16171   VEC(breakpoint_p) *tp_vec = 0;
16172   struct breakpoint *tp;
16173
16174   ALL_TRACEPOINTS (tp)
16175   {
16176     VEC_safe_push (breakpoint_p, tp_vec, tp);
16177   }
16178
16179   return tp_vec;
16180 }
16181
16182 \f
16183 /* This help string is used for the break, hbreak, tbreak and thbreak
16184    commands.  It is defined as a macro to prevent duplication.
16185    COMMAND should be a string constant containing the name of the
16186    command.  */
16187 #define BREAK_ARGS_HELP(command) \
16188 command" [PROBE_MODIFIER] [LOCATION] [thread THREADNUM] [if CONDITION]\n\
16189 PROBE_MODIFIER shall be present if the command is to be placed in a\n\
16190 probe point.  Accepted values are `-probe' (for a generic, automatically\n\
16191 guessed probe type) or `-probe-stap' (for a SystemTap probe).\n\
16192 LOCATION may be a line number, function name, or \"*\" and an address.\n\
16193 If a line number is specified, break at start of code for that line.\n\
16194 If a function is specified, break at start of code for that function.\n\
16195 If an address is specified, break at that exact address.\n\
16196 With no LOCATION, uses current execution address of the selected\n\
16197 stack frame.  This is useful for breaking on return to a stack frame.\n\
16198 \n\
16199 THREADNUM is the number from \"info threads\".\n\
16200 CONDITION is a boolean expression.\n\
16201 \n\
16202 Multiple breakpoints at one place are permitted, and useful if their\n\
16203 conditions are different.\n\
16204 \n\
16205 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
16206
16207 /* List of subcommands for "catch".  */
16208 static struct cmd_list_element *catch_cmdlist;
16209
16210 /* List of subcommands for "tcatch".  */
16211 static struct cmd_list_element *tcatch_cmdlist;
16212
16213 void
16214 add_catch_command (char *name, char *docstring,
16215                    cmd_sfunc_ftype *sfunc,
16216                    completer_ftype *completer,
16217                    void *user_data_catch,
16218                    void *user_data_tcatch)
16219 {
16220   struct cmd_list_element *command;
16221
16222   command = add_cmd (name, class_breakpoint, NULL, docstring,
16223                      &catch_cmdlist);
16224   set_cmd_sfunc (command, sfunc);
16225   set_cmd_context (command, user_data_catch);
16226   set_cmd_completer (command, completer);
16227
16228   command = add_cmd (name, class_breakpoint, NULL, docstring,
16229                      &tcatch_cmdlist);
16230   set_cmd_sfunc (command, sfunc);
16231   set_cmd_context (command, user_data_tcatch);
16232   set_cmd_completer (command, completer);
16233 }
16234
16235 static void
16236 clear_syscall_counts (struct inferior *inf)
16237 {
16238   struct catch_syscall_inferior_data *inf_data
16239     = get_catch_syscall_inferior_data (inf);
16240
16241   inf_data->total_syscalls_count = 0;
16242   inf_data->any_syscall_count = 0;
16243   VEC_free (int, inf_data->syscalls_counts);
16244 }
16245
16246 static void
16247 save_command (char *arg, int from_tty)
16248 {
16249   printf_unfiltered (_("\"save\" must be followed by "
16250                        "the name of a save subcommand.\n"));
16251   help_list (save_cmdlist, "save ", all_commands, gdb_stdout);
16252 }
16253
16254 struct breakpoint *
16255 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
16256                           void *data)
16257 {
16258   struct breakpoint *b, *b_tmp;
16259
16260   ALL_BREAKPOINTS_SAFE (b, b_tmp)
16261     {
16262       if ((*callback) (b, data))
16263         return b;
16264     }
16265
16266   return NULL;
16267 }
16268
16269 /* Zero if any of the breakpoint's locations could be a location where
16270    functions have been inlined, nonzero otherwise.  */
16271
16272 static int
16273 is_non_inline_function (struct breakpoint *b)
16274 {
16275   /* The shared library event breakpoint is set on the address of a
16276      non-inline function.  */
16277   if (b->type == bp_shlib_event)
16278     return 1;
16279
16280   return 0;
16281 }
16282
16283 /* Nonzero if the specified PC cannot be a location where functions
16284    have been inlined.  */
16285
16286 int
16287 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
16288                            const struct target_waitstatus *ws)
16289 {
16290   struct breakpoint *b;
16291   struct bp_location *bl;
16292
16293   ALL_BREAKPOINTS (b)
16294     {
16295       if (!is_non_inline_function (b))
16296         continue;
16297
16298       for (bl = b->loc; bl != NULL; bl = bl->next)
16299         {
16300           if (!bl->shlib_disabled
16301               && bpstat_check_location (bl, aspace, pc, ws))
16302             return 1;
16303         }
16304     }
16305
16306   return 0;
16307 }
16308
16309 /* Remove any references to OBJFILE which is going to be freed.  */
16310
16311 void
16312 breakpoint_free_objfile (struct objfile *objfile)
16313 {
16314   struct bp_location **locp, *loc;
16315
16316   ALL_BP_LOCATIONS (loc, locp)
16317     if (loc->symtab != NULL && loc->symtab->objfile == objfile)
16318       loc->symtab = NULL;
16319 }
16320
16321 void
16322 initialize_breakpoint_ops (void)
16323 {
16324   static int initialized = 0;
16325
16326   struct breakpoint_ops *ops;
16327
16328   if (initialized)
16329     return;
16330   initialized = 1;
16331
16332   /* The breakpoint_ops structure to be inherit by all kinds of
16333      breakpoints (real breakpoints, i.e., user "break" breakpoints,
16334      internal and momentary breakpoints, etc.).  */
16335   ops = &bkpt_base_breakpoint_ops;
16336   *ops = base_breakpoint_ops;
16337   ops->re_set = bkpt_re_set;
16338   ops->insert_location = bkpt_insert_location;
16339   ops->remove_location = bkpt_remove_location;
16340   ops->breakpoint_hit = bkpt_breakpoint_hit;
16341   ops->create_sals_from_address = bkpt_create_sals_from_address;
16342   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
16343   ops->decode_linespec = bkpt_decode_linespec;
16344
16345   /* The breakpoint_ops structure to be used in regular breakpoints.  */
16346   ops = &bkpt_breakpoint_ops;
16347   *ops = bkpt_base_breakpoint_ops;
16348   ops->re_set = bkpt_re_set;
16349   ops->resources_needed = bkpt_resources_needed;
16350   ops->print_it = bkpt_print_it;
16351   ops->print_mention = bkpt_print_mention;
16352   ops->print_recreate = bkpt_print_recreate;
16353
16354   /* Ranged breakpoints.  */
16355   ops = &ranged_breakpoint_ops;
16356   *ops = bkpt_breakpoint_ops;
16357   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
16358   ops->resources_needed = resources_needed_ranged_breakpoint;
16359   ops->print_it = print_it_ranged_breakpoint;
16360   ops->print_one = print_one_ranged_breakpoint;
16361   ops->print_one_detail = print_one_detail_ranged_breakpoint;
16362   ops->print_mention = print_mention_ranged_breakpoint;
16363   ops->print_recreate = print_recreate_ranged_breakpoint;
16364
16365   /* Internal breakpoints.  */
16366   ops = &internal_breakpoint_ops;
16367   *ops = bkpt_base_breakpoint_ops;
16368   ops->re_set = internal_bkpt_re_set;
16369   ops->check_status = internal_bkpt_check_status;
16370   ops->print_it = internal_bkpt_print_it;
16371   ops->print_mention = internal_bkpt_print_mention;
16372
16373   /* Momentary breakpoints.  */
16374   ops = &momentary_breakpoint_ops;
16375   *ops = bkpt_base_breakpoint_ops;
16376   ops->re_set = momentary_bkpt_re_set;
16377   ops->check_status = momentary_bkpt_check_status;
16378   ops->print_it = momentary_bkpt_print_it;
16379   ops->print_mention = momentary_bkpt_print_mention;
16380
16381   /* Momentary breakpoints for bp_longjmp and bp_exception.  */
16382   ops = &longjmp_breakpoint_ops;
16383   *ops = momentary_breakpoint_ops;
16384   ops->dtor = longjmp_bkpt_dtor;
16385
16386   /* Probe breakpoints.  */
16387   ops = &bkpt_probe_breakpoint_ops;
16388   *ops = bkpt_breakpoint_ops;
16389   ops->insert_location = bkpt_probe_insert_location;
16390   ops->remove_location = bkpt_probe_remove_location;
16391   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
16392   ops->decode_linespec = bkpt_probe_decode_linespec;
16393
16394   /* Watchpoints.  */
16395   ops = &watchpoint_breakpoint_ops;
16396   *ops = base_breakpoint_ops;
16397   ops->dtor = dtor_watchpoint;
16398   ops->re_set = re_set_watchpoint;
16399   ops->insert_location = insert_watchpoint;
16400   ops->remove_location = remove_watchpoint;
16401   ops->breakpoint_hit = breakpoint_hit_watchpoint;
16402   ops->check_status = check_status_watchpoint;
16403   ops->resources_needed = resources_needed_watchpoint;
16404   ops->works_in_software_mode = works_in_software_mode_watchpoint;
16405   ops->print_it = print_it_watchpoint;
16406   ops->print_mention = print_mention_watchpoint;
16407   ops->print_recreate = print_recreate_watchpoint;
16408   ops->explains_signal = explains_signal_watchpoint;
16409
16410   /* Masked watchpoints.  */
16411   ops = &masked_watchpoint_breakpoint_ops;
16412   *ops = watchpoint_breakpoint_ops;
16413   ops->insert_location = insert_masked_watchpoint;
16414   ops->remove_location = remove_masked_watchpoint;
16415   ops->resources_needed = resources_needed_masked_watchpoint;
16416   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
16417   ops->print_it = print_it_masked_watchpoint;
16418   ops->print_one_detail = print_one_detail_masked_watchpoint;
16419   ops->print_mention = print_mention_masked_watchpoint;
16420   ops->print_recreate = print_recreate_masked_watchpoint;
16421
16422   /* Tracepoints.  */
16423   ops = &tracepoint_breakpoint_ops;
16424   *ops = base_breakpoint_ops;
16425   ops->re_set = tracepoint_re_set;
16426   ops->breakpoint_hit = tracepoint_breakpoint_hit;
16427   ops->print_one_detail = tracepoint_print_one_detail;
16428   ops->print_mention = tracepoint_print_mention;
16429   ops->print_recreate = tracepoint_print_recreate;
16430   ops->create_sals_from_address = tracepoint_create_sals_from_address;
16431   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
16432   ops->decode_linespec = tracepoint_decode_linespec;
16433
16434   /* Probe tracepoints.  */
16435   ops = &tracepoint_probe_breakpoint_ops;
16436   *ops = tracepoint_breakpoint_ops;
16437   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
16438   ops->decode_linespec = tracepoint_probe_decode_linespec;
16439
16440   /* Static tracepoints with marker (`-m').  */
16441   ops = &strace_marker_breakpoint_ops;
16442   *ops = tracepoint_breakpoint_ops;
16443   ops->create_sals_from_address = strace_marker_create_sals_from_address;
16444   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
16445   ops->decode_linespec = strace_marker_decode_linespec;
16446
16447   /* Fork catchpoints.  */
16448   ops = &catch_fork_breakpoint_ops;
16449   *ops = base_breakpoint_ops;
16450   ops->insert_location = insert_catch_fork;
16451   ops->remove_location = remove_catch_fork;
16452   ops->breakpoint_hit = breakpoint_hit_catch_fork;
16453   ops->print_it = print_it_catch_fork;
16454   ops->print_one = print_one_catch_fork;
16455   ops->print_mention = print_mention_catch_fork;
16456   ops->print_recreate = print_recreate_catch_fork;
16457
16458   /* Vfork catchpoints.  */
16459   ops = &catch_vfork_breakpoint_ops;
16460   *ops = base_breakpoint_ops;
16461   ops->insert_location = insert_catch_vfork;
16462   ops->remove_location = remove_catch_vfork;
16463   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
16464   ops->print_it = print_it_catch_vfork;
16465   ops->print_one = print_one_catch_vfork;
16466   ops->print_mention = print_mention_catch_vfork;
16467   ops->print_recreate = print_recreate_catch_vfork;
16468
16469   /* Exec catchpoints.  */
16470   ops = &catch_exec_breakpoint_ops;
16471   *ops = base_breakpoint_ops;
16472   ops->dtor = dtor_catch_exec;
16473   ops->insert_location = insert_catch_exec;
16474   ops->remove_location = remove_catch_exec;
16475   ops->breakpoint_hit = breakpoint_hit_catch_exec;
16476   ops->print_it = print_it_catch_exec;
16477   ops->print_one = print_one_catch_exec;
16478   ops->print_mention = print_mention_catch_exec;
16479   ops->print_recreate = print_recreate_catch_exec;
16480
16481   /* Syscall catchpoints.  */
16482   ops = &catch_syscall_breakpoint_ops;
16483   *ops = base_breakpoint_ops;
16484   ops->dtor = dtor_catch_syscall;
16485   ops->insert_location = insert_catch_syscall;
16486   ops->remove_location = remove_catch_syscall;
16487   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
16488   ops->print_it = print_it_catch_syscall;
16489   ops->print_one = print_one_catch_syscall;
16490   ops->print_mention = print_mention_catch_syscall;
16491   ops->print_recreate = print_recreate_catch_syscall;
16492
16493   /* Solib-related catchpoints.  */
16494   ops = &catch_solib_breakpoint_ops;
16495   *ops = base_breakpoint_ops;
16496   ops->dtor = dtor_catch_solib;
16497   ops->insert_location = insert_catch_solib;
16498   ops->remove_location = remove_catch_solib;
16499   ops->breakpoint_hit = breakpoint_hit_catch_solib;
16500   ops->check_status = check_status_catch_solib;
16501   ops->print_it = print_it_catch_solib;
16502   ops->print_one = print_one_catch_solib;
16503   ops->print_mention = print_mention_catch_solib;
16504   ops->print_recreate = print_recreate_catch_solib;
16505
16506   ops = &dprintf_breakpoint_ops;
16507   *ops = bkpt_base_breakpoint_ops;
16508   ops->re_set = dprintf_re_set;
16509   ops->resources_needed = bkpt_resources_needed;
16510   ops->print_it = bkpt_print_it;
16511   ops->print_mention = bkpt_print_mention;
16512   ops->print_recreate = dprintf_print_recreate;
16513   ops->after_condition_true = dprintf_after_condition_true;
16514   ops->breakpoint_hit = dprintf_breakpoint_hit;
16515 }
16516
16517 /* Chain containing all defined "enable breakpoint" subcommands.  */
16518
16519 static struct cmd_list_element *enablebreaklist = NULL;
16520
16521 void
16522 _initialize_breakpoint (void)
16523 {
16524   struct cmd_list_element *c;
16525
16526   initialize_breakpoint_ops ();
16527
16528   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
16529   observer_attach_free_objfile (disable_breakpoints_in_freed_objfile);
16530   observer_attach_inferior_exit (clear_syscall_counts);
16531   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
16532
16533   breakpoint_objfile_key
16534     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
16535
16536   catch_syscall_inferior_data
16537     = register_inferior_data_with_cleanup (NULL,
16538                                            catch_syscall_inferior_data_cleanup);
16539
16540   breakpoint_chain = 0;
16541   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
16542      before a breakpoint is set.  */
16543   breakpoint_count = 0;
16544
16545   tracepoint_count = 0;
16546
16547   add_com ("ignore", class_breakpoint, ignore_command, _("\
16548 Set ignore-count of breakpoint number N to COUNT.\n\
16549 Usage is `ignore N COUNT'."));
16550   if (xdb_commands)
16551     add_com_alias ("bc", "ignore", class_breakpoint, 1);
16552
16553   add_com ("commands", class_breakpoint, commands_command, _("\
16554 Set commands to be executed when a breakpoint is hit.\n\
16555 Give breakpoint number as argument after \"commands\".\n\
16556 With no argument, the targeted breakpoint is the last one set.\n\
16557 The commands themselves follow starting on the next line.\n\
16558 Type a line containing \"end\" to indicate the end of them.\n\
16559 Give \"silent\" as the first line to make the breakpoint silent;\n\
16560 then no output is printed when it is hit, except what the commands print."));
16561
16562   c = add_com ("condition", class_breakpoint, condition_command, _("\
16563 Specify breakpoint number N to break only if COND is true.\n\
16564 Usage is `condition N COND', where N is an integer and COND is an\n\
16565 expression to be evaluated whenever breakpoint N is reached."));
16566   set_cmd_completer (c, condition_completer);
16567
16568   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
16569 Set a temporary breakpoint.\n\
16570 Like \"break\" except the breakpoint is only temporary,\n\
16571 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
16572 by using \"enable delete\" on the breakpoint number.\n\
16573 \n"
16574 BREAK_ARGS_HELP ("tbreak")));
16575   set_cmd_completer (c, location_completer);
16576
16577   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
16578 Set a hardware assisted breakpoint.\n\
16579 Like \"break\" except the breakpoint requires hardware support,\n\
16580 some target hardware may not have this support.\n\
16581 \n"
16582 BREAK_ARGS_HELP ("hbreak")));
16583   set_cmd_completer (c, location_completer);
16584
16585   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
16586 Set a temporary hardware assisted breakpoint.\n\
16587 Like \"hbreak\" except the breakpoint is only temporary,\n\
16588 so it will be deleted when hit.\n\
16589 \n"
16590 BREAK_ARGS_HELP ("thbreak")));
16591   set_cmd_completer (c, location_completer);
16592
16593   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
16594 Enable some breakpoints.\n\
16595 Give breakpoint numbers (separated by spaces) as arguments.\n\
16596 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16597 This is used to cancel the effect of the \"disable\" command.\n\
16598 With a subcommand you can enable temporarily."),
16599                   &enablelist, "enable ", 1, &cmdlist);
16600   if (xdb_commands)
16601     add_com ("ab", class_breakpoint, enable_command, _("\
16602 Enable some breakpoints.\n\
16603 Give breakpoint numbers (separated by spaces) as arguments.\n\
16604 With no subcommand, breakpoints are enabled until you command otherwise.\n\
16605 This is used to cancel the effect of the \"disable\" command.\n\
16606 With a subcommand you can enable temporarily."));
16607
16608   add_com_alias ("en", "enable", class_breakpoint, 1);
16609
16610   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
16611 Enable some breakpoints.\n\
16612 Give breakpoint numbers (separated by spaces) as arguments.\n\
16613 This is used to cancel the effect of the \"disable\" command.\n\
16614 May be abbreviated to simply \"enable\".\n"),
16615                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
16616
16617   add_cmd ("once", no_class, enable_once_command, _("\
16618 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16619 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16620            &enablebreaklist);
16621
16622   add_cmd ("delete", no_class, enable_delete_command, _("\
16623 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16624 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16625            &enablebreaklist);
16626
16627   add_cmd ("count", no_class, enable_count_command, _("\
16628 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16629 If a breakpoint is hit while enabled in this fashion,\n\
16630 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16631            &enablebreaklist);
16632
16633   add_cmd ("delete", no_class, enable_delete_command, _("\
16634 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
16635 If a breakpoint is hit while enabled in this fashion, it is deleted."),
16636            &enablelist);
16637
16638   add_cmd ("once", no_class, enable_once_command, _("\
16639 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
16640 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
16641            &enablelist);
16642
16643   add_cmd ("count", no_class, enable_count_command, _("\
16644 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
16645 If a breakpoint is hit while enabled in this fashion,\n\
16646 the count is decremented; when it reaches zero, the breakpoint is disabled."),
16647            &enablelist);
16648
16649   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
16650 Disable some breakpoints.\n\
16651 Arguments are breakpoint numbers with spaces in between.\n\
16652 To disable all breakpoints, give no argument.\n\
16653 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
16654                   &disablelist, "disable ", 1, &cmdlist);
16655   add_com_alias ("dis", "disable", class_breakpoint, 1);
16656   add_com_alias ("disa", "disable", class_breakpoint, 1);
16657   if (xdb_commands)
16658     add_com ("sb", 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
16664   add_cmd ("breakpoints", class_alias, disable_command, _("\
16665 Disable some breakpoints.\n\
16666 Arguments are breakpoint numbers with spaces in between.\n\
16667 To disable all breakpoints, give no argument.\n\
16668 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
16669 This command may be abbreviated \"disable\"."),
16670            &disablelist);
16671
16672   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
16673 Delete some breakpoints or auto-display expressions.\n\
16674 Arguments are breakpoint numbers with spaces in between.\n\
16675 To delete all breakpoints, give no argument.\n\
16676 \n\
16677 Also a prefix command for deletion of other GDB objects.\n\
16678 The \"unset\" command is also an alias for \"delete\"."),
16679                   &deletelist, "delete ", 1, &cmdlist);
16680   add_com_alias ("d", "delete", class_breakpoint, 1);
16681   add_com_alias ("del", "delete", class_breakpoint, 1);
16682   if (xdb_commands)
16683     add_com ("db", class_breakpoint, delete_command, _("\
16684 Delete some breakpoints.\n\
16685 Arguments are breakpoint numbers with spaces in between.\n\
16686 To delete all breakpoints, give no argument.\n"));
16687
16688   add_cmd ("breakpoints", class_alias, delete_command, _("\
16689 Delete some breakpoints or auto-display expressions.\n\
16690 Arguments are breakpoint numbers with spaces in between.\n\
16691 To delete all breakpoints, give no argument.\n\
16692 This command may be abbreviated \"delete\"."),
16693            &deletelist);
16694
16695   add_com ("clear", class_breakpoint, clear_command, _("\
16696 Clear breakpoint at specified line or function.\n\
16697 Argument may be line number, function name, or \"*\" and an address.\n\
16698 If line number is specified, all breakpoints in that line are cleared.\n\
16699 If function is specified, breakpoints at beginning of function are cleared.\n\
16700 If an address is specified, breakpoints at that address are cleared.\n\
16701 \n\
16702 With no argument, clears all breakpoints in the line that the selected frame\n\
16703 is executing in.\n\
16704 \n\
16705 See also the \"delete\" command which clears breakpoints by number."));
16706   add_com_alias ("cl", "clear", class_breakpoint, 1);
16707
16708   c = add_com ("break", class_breakpoint, break_command, _("\
16709 Set breakpoint at specified line or function.\n"
16710 BREAK_ARGS_HELP ("break")));
16711   set_cmd_completer (c, location_completer);
16712
16713   add_com_alias ("b", "break", class_run, 1);
16714   add_com_alias ("br", "break", class_run, 1);
16715   add_com_alias ("bre", "break", class_run, 1);
16716   add_com_alias ("brea", "break", class_run, 1);
16717
16718   if (xdb_commands)
16719    add_com_alias ("ba", "break", class_breakpoint, 1);
16720
16721   if (dbx_commands)
16722     {
16723       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
16724 Break in function/address or break at a line in the current file."),
16725                              &stoplist, "stop ", 1, &cmdlist);
16726       add_cmd ("in", class_breakpoint, stopin_command,
16727                _("Break in function or address."), &stoplist);
16728       add_cmd ("at", class_breakpoint, stopat_command,
16729                _("Break at a line in the current file."), &stoplist);
16730       add_com ("status", class_info, breakpoints_info, _("\
16731 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16732 The \"Type\" column indicates one of:\n\
16733 \tbreakpoint     - normal breakpoint\n\
16734 \twatchpoint     - watchpoint\n\
16735 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16736 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16737 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16738 address and file/line number respectively.\n\
16739 \n\
16740 Convenience variable \"$_\" and default examine address for \"x\"\n\
16741 are set to the address of the last breakpoint listed unless the command\n\
16742 is prefixed with \"server \".\n\n\
16743 Convenience variable \"$bpnum\" contains the number of the last\n\
16744 breakpoint set."));
16745     }
16746
16747   add_info ("breakpoints", breakpoints_info, _("\
16748 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
16749 The \"Type\" column indicates one of:\n\
16750 \tbreakpoint     - normal breakpoint\n\
16751 \twatchpoint     - watchpoint\n\
16752 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16753 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16754 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16755 address and file/line number respectively.\n\
16756 \n\
16757 Convenience variable \"$_\" and default examine address for \"x\"\n\
16758 are set to the address of the last breakpoint listed unless the command\n\
16759 is prefixed with \"server \".\n\n\
16760 Convenience variable \"$bpnum\" contains the number of the last\n\
16761 breakpoint set."));
16762
16763   add_info_alias ("b", "breakpoints", 1);
16764
16765   if (xdb_commands)
16766     add_com ("lb", class_breakpoint, breakpoints_info, _("\
16767 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
16768 The \"Type\" column indicates one of:\n\
16769 \tbreakpoint     - normal breakpoint\n\
16770 \twatchpoint     - watchpoint\n\
16771 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16772 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16773 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16774 address and file/line number respectively.\n\
16775 \n\
16776 Convenience variable \"$_\" and default examine address for \"x\"\n\
16777 are set to the address of the last breakpoint listed unless the command\n\
16778 is prefixed with \"server \".\n\n\
16779 Convenience variable \"$bpnum\" contains the number of the last\n\
16780 breakpoint set."));
16781
16782   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
16783 Status of all breakpoints, or breakpoint number NUMBER.\n\
16784 The \"Type\" column indicates one of:\n\
16785 \tbreakpoint     - normal breakpoint\n\
16786 \twatchpoint     - watchpoint\n\
16787 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
16788 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
16789 \tuntil          - internal breakpoint used by the \"until\" command\n\
16790 \tfinish         - internal breakpoint used by the \"finish\" command\n\
16791 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
16792 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
16793 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
16794 address and file/line number respectively.\n\
16795 \n\
16796 Convenience variable \"$_\" and default examine address for \"x\"\n\
16797 are set to the address of the last breakpoint listed unless the command\n\
16798 is prefixed with \"server \".\n\n\
16799 Convenience variable \"$bpnum\" contains the number of the last\n\
16800 breakpoint set."),
16801            &maintenanceinfolist);
16802
16803   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
16804 Set catchpoints to catch events."),
16805                   &catch_cmdlist, "catch ",
16806                   0/*allow-unknown*/, &cmdlist);
16807
16808   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
16809 Set temporary catchpoints to catch events."),
16810                   &tcatch_cmdlist, "tcatch ",
16811                   0/*allow-unknown*/, &cmdlist);
16812
16813   add_catch_command ("fork", _("Catch calls to fork."),
16814                      catch_fork_command_1,
16815                      NULL,
16816                      (void *) (uintptr_t) catch_fork_permanent,
16817                      (void *) (uintptr_t) catch_fork_temporary);
16818   add_catch_command ("vfork", _("Catch calls to vfork."),
16819                      catch_fork_command_1,
16820                      NULL,
16821                      (void *) (uintptr_t) catch_vfork_permanent,
16822                      (void *) (uintptr_t) catch_vfork_temporary);
16823   add_catch_command ("exec", _("Catch calls to exec."),
16824                      catch_exec_command_1,
16825                      NULL,
16826                      CATCH_PERMANENT,
16827                      CATCH_TEMPORARY);
16828   add_catch_command ("load", _("Catch loads of shared libraries.\n\
16829 Usage: catch load [REGEX]\n\
16830 If REGEX is given, only stop for libraries matching the regular expression."),
16831                      catch_load_command_1,
16832                      NULL,
16833                      CATCH_PERMANENT,
16834                      CATCH_TEMPORARY);
16835   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
16836 Usage: catch unload [REGEX]\n\
16837 If REGEX is given, only stop for libraries matching the regular expression."),
16838                      catch_unload_command_1,
16839                      NULL,
16840                      CATCH_PERMANENT,
16841                      CATCH_TEMPORARY);
16842   add_catch_command ("syscall", _("\
16843 Catch system calls by their names and/or numbers.\n\
16844 Arguments say which system calls to catch.  If no arguments\n\
16845 are given, every system call will be caught.\n\
16846 Arguments, if given, should be one or more system call names\n\
16847 (if your system supports that), or system call numbers."),
16848                      catch_syscall_command_1,
16849                      catch_syscall_completer,
16850                      CATCH_PERMANENT,
16851                      CATCH_TEMPORARY);
16852
16853   c = add_com ("watch", class_breakpoint, watch_command, _("\
16854 Set a watchpoint for an expression.\n\
16855 Usage: watch [-l|-location] EXPRESSION\n\
16856 A watchpoint stops execution of your program whenever the value of\n\
16857 an expression changes.\n\
16858 If -l or -location is given, this evaluates EXPRESSION and watches\n\
16859 the memory to which it refers."));
16860   set_cmd_completer (c, expression_completer);
16861
16862   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
16863 Set a read watchpoint for an expression.\n\
16864 Usage: rwatch [-l|-location] EXPRESSION\n\
16865 A watchpoint stops execution of your program whenever the value of\n\
16866 an expression is read.\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 ("awatch", class_breakpoint, awatch_command, _("\
16872 Set a watchpoint for an expression.\n\
16873 Usage: awatch [-l|-location] EXPRESSION\n\
16874 A watchpoint stops execution of your program whenever the value of\n\
16875 an expression is either read or written.\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   add_info ("watchpoints", watchpoints_info, _("\
16881 Status of specified watchpoints (all watchpoints if no argument)."));
16882
16883   /* XXX: cagney/2005-02-23: This should be a boolean, and should
16884      respond to changes - contrary to the description.  */
16885   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
16886                             &can_use_hw_watchpoints, _("\
16887 Set debugger's willingness to use watchpoint hardware."), _("\
16888 Show debugger's willingness to use watchpoint hardware."), _("\
16889 If zero, gdb will not use hardware for new watchpoints, even if\n\
16890 such is available.  (However, any hardware watchpoints that were\n\
16891 created before setting this to nonzero, will continue to use watchpoint\n\
16892 hardware.)"),
16893                             NULL,
16894                             show_can_use_hw_watchpoints,
16895                             &setlist, &showlist);
16896
16897   can_use_hw_watchpoints = 1;
16898
16899   /* Tracepoint manipulation commands.  */
16900
16901   c = add_com ("trace", class_breakpoint, trace_command, _("\
16902 Set a tracepoint at specified line or function.\n\
16903 \n"
16904 BREAK_ARGS_HELP ("trace") "\n\
16905 Do \"help tracepoints\" for info on other tracepoint commands."));
16906   set_cmd_completer (c, location_completer);
16907
16908   add_com_alias ("tp", "trace", class_alias, 0);
16909   add_com_alias ("tr", "trace", class_alias, 1);
16910   add_com_alias ("tra", "trace", class_alias, 1);
16911   add_com_alias ("trac", "trace", class_alias, 1);
16912
16913   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
16914 Set a fast tracepoint at specified line or function.\n\
16915 \n"
16916 BREAK_ARGS_HELP ("ftrace") "\n\
16917 Do \"help tracepoints\" for info on other tracepoint commands."));
16918   set_cmd_completer (c, location_completer);
16919
16920   c = add_com ("strace", class_breakpoint, strace_command, _("\
16921 Set a static tracepoint at specified line, function or marker.\n\
16922 \n\
16923 strace [LOCATION] [if CONDITION]\n\
16924 LOCATION may be a line number, function name, \"*\" and an address,\n\
16925 or -m MARKER_ID.\n\
16926 If a line number is specified, probe the marker at start of code\n\
16927 for that line.  If a function is specified, probe the marker at start\n\
16928 of code for that function.  If an address is specified, probe the marker\n\
16929 at that exact address.  If a marker id is specified, probe the marker\n\
16930 with that name.  With no LOCATION, uses current execution address of\n\
16931 the selected stack frame.\n\
16932 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
16933 This collects arbitrary user data passed in the probe point call to the\n\
16934 tracing library.  You can inspect it when analyzing the trace buffer,\n\
16935 by printing the $_sdata variable like any other convenience variable.\n\
16936 \n\
16937 CONDITION is a boolean expression.\n\
16938 \n\
16939 Multiple tracepoints at one place are permitted, and useful if their\n\
16940 conditions are different.\n\
16941 \n\
16942 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
16943 Do \"help tracepoints\" for info on other tracepoint commands."));
16944   set_cmd_completer (c, location_completer);
16945
16946   add_info ("tracepoints", tracepoints_info, _("\
16947 Status of specified tracepoints (all tracepoints if no argument).\n\
16948 Convenience variable \"$tpnum\" contains the number of the\n\
16949 last tracepoint set."));
16950
16951   add_info_alias ("tp", "tracepoints", 1);
16952
16953   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
16954 Delete specified tracepoints.\n\
16955 Arguments are tracepoint numbers, separated by spaces.\n\
16956 No argument means delete all tracepoints."),
16957            &deletelist);
16958   add_alias_cmd ("tr", "tracepoints", class_trace, 1, &deletelist);
16959
16960   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
16961 Disable specified tracepoints.\n\
16962 Arguments are tracepoint numbers, separated by spaces.\n\
16963 No argument means disable all tracepoints."),
16964            &disablelist);
16965   deprecate_cmd (c, "disable");
16966
16967   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
16968 Enable specified tracepoints.\n\
16969 Arguments are tracepoint numbers, separated by spaces.\n\
16970 No argument means enable all tracepoints."),
16971            &enablelist);
16972   deprecate_cmd (c, "enable");
16973
16974   add_com ("passcount", class_trace, trace_pass_command, _("\
16975 Set the passcount for a tracepoint.\n\
16976 The trace will end when the tracepoint has been passed 'count' times.\n\
16977 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
16978 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
16979
16980   add_prefix_cmd ("save", class_breakpoint, save_command,
16981                   _("Save breakpoint definitions as a script."),
16982                   &save_cmdlist, "save ",
16983                   0/*allow-unknown*/, &cmdlist);
16984
16985   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
16986 Save current breakpoint definitions as a script.\n\
16987 This includes all types of breakpoints (breakpoints, watchpoints,\n\
16988 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
16989 session to restore them."),
16990                &save_cmdlist);
16991   set_cmd_completer (c, filename_completer);
16992
16993   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
16994 Save current tracepoint definitions as a script.\n\
16995 Use the 'source' command in another debug session to restore them."),
16996                &save_cmdlist);
16997   set_cmd_completer (c, filename_completer);
16998
16999   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
17000   deprecate_cmd (c, "save tracepoints");
17001
17002   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
17003 Breakpoint specific settings\n\
17004 Configure various breakpoint-specific variables such as\n\
17005 pending breakpoint behavior"),
17006                   &breakpoint_set_cmdlist, "set breakpoint ",
17007                   0/*allow-unknown*/, &setlist);
17008   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
17009 Breakpoint specific settings\n\
17010 Configure various breakpoint-specific variables such as\n\
17011 pending breakpoint behavior"),
17012                   &breakpoint_show_cmdlist, "show breakpoint ",
17013                   0/*allow-unknown*/, &showlist);
17014
17015   add_setshow_auto_boolean_cmd ("pending", no_class,
17016                                 &pending_break_support, _("\
17017 Set debugger's behavior regarding pending breakpoints."), _("\
17018 Show debugger's behavior regarding pending breakpoints."), _("\
17019 If on, an unrecognized breakpoint location will cause gdb to create a\n\
17020 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
17021 an error.  If auto, an unrecognized breakpoint location results in a\n\
17022 user-query to see if a pending breakpoint should be created."),
17023                                 NULL,
17024                                 show_pending_break_support,
17025                                 &breakpoint_set_cmdlist,
17026                                 &breakpoint_show_cmdlist);
17027
17028   pending_break_support = AUTO_BOOLEAN_AUTO;
17029
17030   add_setshow_boolean_cmd ("auto-hw", no_class,
17031                            &automatic_hardware_breakpoints, _("\
17032 Set automatic usage of hardware breakpoints."), _("\
17033 Show automatic usage of hardware breakpoints."), _("\
17034 If set, the debugger will automatically use hardware breakpoints for\n\
17035 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
17036 a warning will be emitted for such breakpoints."),
17037                            NULL,
17038                            show_automatic_hardware_breakpoints,
17039                            &breakpoint_set_cmdlist,
17040                            &breakpoint_show_cmdlist);
17041
17042   add_setshow_boolean_cmd ("always-inserted", class_support,
17043                            &always_inserted_mode, _("\
17044 Set mode for inserting breakpoints."), _("\
17045 Show mode for inserting breakpoints."), _("\
17046 When this mode is on, breakpoints are inserted immediately as soon as\n\
17047 they're created, kept inserted even when execution stops, and removed\n\
17048 only when the user deletes them.  When this mode is off (the default),\n\
17049 breakpoints are inserted only when execution continues, and removed\n\
17050 when execution stops."),
17051                                 NULL,
17052                                 &show_always_inserted_mode,
17053                                 &breakpoint_set_cmdlist,
17054                                 &breakpoint_show_cmdlist);
17055
17056   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
17057                         condition_evaluation_enums,
17058                         &condition_evaluation_mode_1, _("\
17059 Set mode of breakpoint condition evaluation."), _("\
17060 Show mode of breakpoint condition evaluation."), _("\
17061 When this is set to \"host\", breakpoint conditions will be\n\
17062 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
17063 breakpoint conditions will be downloaded to the target (if the target\n\
17064 supports such feature) and conditions will be evaluated on the target's side.\n\
17065 If this is set to \"auto\" (default), this will be automatically set to\n\
17066 \"target\" if it supports condition evaluation, otherwise it will\n\
17067 be set to \"gdb\""),
17068                            &set_condition_evaluation_mode,
17069                            &show_condition_evaluation_mode,
17070                            &breakpoint_set_cmdlist,
17071                            &breakpoint_show_cmdlist);
17072
17073   add_com ("break-range", class_breakpoint, break_range_command, _("\
17074 Set a breakpoint for an address range.\n\
17075 break-range START-LOCATION, END-LOCATION\n\
17076 where START-LOCATION and END-LOCATION can be one of the following:\n\
17077   LINENUM, for that line in the current file,\n\
17078   FILE:LINENUM, for that line in that file,\n\
17079   +OFFSET, for that number of lines after the current line\n\
17080            or the start of the range\n\
17081   FUNCTION, for the first line in that function,\n\
17082   FILE:FUNCTION, to distinguish among like-named static functions.\n\
17083   *ADDRESS, for the instruction at that address.\n\
17084 \n\
17085 The breakpoint will stop execution of the inferior whenever it executes\n\
17086 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
17087 range (including START-LOCATION and END-LOCATION)."));
17088
17089   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
17090 Set a dynamic printf at specified line or function.\n\
17091 dprintf location,format string,arg1,arg2,...\n\
17092 location may be a line number, function name, or \"*\" and an address.\n\
17093 If a line number is specified, break at start of code for that line.\n\
17094 If a function is specified, break at start of code for that function."));
17095   set_cmd_completer (c, location_completer);
17096
17097   add_setshow_enum_cmd ("dprintf-style", class_support,
17098                         dprintf_style_enums, &dprintf_style, _("\
17099 Set the style of usage for dynamic printf."), _("\
17100 Show the style of usage for dynamic printf."), _("\
17101 This setting chooses how GDB will do a dynamic printf.\n\
17102 If the value is \"gdb\", then the printing is done by GDB to its own\n\
17103 console, as with the \"printf\" command.\n\
17104 If the value is \"call\", the print is done by calling a function in your\n\
17105 program; by default printf(), but you can choose a different function or\n\
17106 output stream by setting dprintf-function and dprintf-channel."),
17107                         update_dprintf_commands, NULL,
17108                         &setlist, &showlist);
17109
17110   dprintf_function = xstrdup ("printf");
17111   add_setshow_string_cmd ("dprintf-function", class_support,
17112                           &dprintf_function, _("\
17113 Set the function to use for dynamic printf"), _("\
17114 Show the function to use for dynamic printf"), NULL,
17115                           update_dprintf_commands, NULL,
17116                           &setlist, &showlist);
17117
17118   dprintf_channel = xstrdup ("");
17119   add_setshow_string_cmd ("dprintf-channel", class_support,
17120                           &dprintf_channel, _("\
17121 Set the channel to use for dynamic printf"), _("\
17122 Show the channel to use for dynamic printf"), NULL,
17123                           update_dprintf_commands, NULL,
17124                           &setlist, &showlist);
17125
17126   add_setshow_boolean_cmd ("disconnected-dprintf", no_class,
17127                            &disconnected_dprintf, _("\
17128 Set whether dprintf continues after GDB disconnects."), _("\
17129 Show whether dprintf continues after GDB disconnects."), _("\
17130 Use this to let dprintf commands continue to hit and produce output\n\
17131 even if GDB disconnects or detaches from the target."),
17132                            NULL,
17133                            NULL,
17134                            &setlist, &showlist);
17135
17136   add_com ("agent-printf", class_vars, agent_printf_command, _("\
17137 agent-printf \"printf format string\", arg1, arg2, arg3, ..., argn\n\
17138 (target agent only) This is useful for formatted output in user-defined commands."));
17139
17140   automatic_hardware_breakpoints = 1;
17141
17142   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
17143   observer_attach_thread_exit (remove_threaded_breakpoints);
17144 }